refactor: ran pyupgrade on openedx/core/djangoapps/credentials (#26847)

This commit is contained in:
Usama Sadiq
2021-03-15 18:09:56 +05:00
committed by GitHub
parent 8813a61da2
commit 7108562c87
14 changed files with 64 additions and 73 deletions

View File

@@ -20,22 +20,22 @@ class CredentialsConfig(AppConfig):
plugin_app = {
PluginSettings.CONFIG: {
ProjectType.LMS: {
SettingsType.PRODUCTION: {PluginSettings.RELATIVE_PATH: u'settings.production'},
SettingsType.COMMON: {PluginSettings.RELATIVE_PATH: u'settings.common'},
SettingsType.DEVSTACK: {PluginSettings.RELATIVE_PATH: u'settings.devstack'},
SettingsType.TEST: {PluginSettings.RELATIVE_PATH: u'settings.test'},
SettingsType.PRODUCTION: {PluginSettings.RELATIVE_PATH: 'settings.production'},
SettingsType.COMMON: {PluginSettings.RELATIVE_PATH: 'settings.common'},
SettingsType.DEVSTACK: {PluginSettings.RELATIVE_PATH: 'settings.devstack'},
SettingsType.TEST: {PluginSettings.RELATIVE_PATH: 'settings.test'},
}
},
PluginSignals.CONFIG: {
ProjectType.LMS: {
PluginSignals.RECEIVERS: [
{
PluginSignals.RECEIVER_FUNC_NAME: u'handle_grade_change',
PluginSignals.SIGNAL_PATH: u'openedx.core.djangoapps.signals.signals.COURSE_GRADE_CHANGED',
PluginSignals.RECEIVER_FUNC_NAME: 'handle_grade_change',
PluginSignals.SIGNAL_PATH: 'openedx.core.djangoapps.signals.signals.COURSE_GRADE_CHANGED',
},
{
PluginSignals.RECEIVER_FUNC_NAME: u'handle_cert_change',
PluginSignals.SIGNAL_PATH: u'openedx.core.djangoapps.signals.signals.COURSE_CERT_CHANGED',
PluginSignals.RECEIVER_FUNC_NAME: 'handle_cert_change',
PluginSignals.SIGNAL_PATH: 'openedx.core.djangoapps.signals.signals.COURSE_CERT_CHANGED',
},
],
},

View File

@@ -24,7 +24,6 @@ from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from pytz import UTC
from six.moves import range
from lms.djangoapps.certificates.api import get_recently_modified_certificates
from lms.djangoapps.grades.api import get_recently_modified_grades
@@ -39,11 +38,11 @@ log = logging.getLogger(__name__)
def certstr(cert):
return '{} for user {}'.format(cert.course_id, cert.user.username)
return f'{cert.course_id} for user {cert.user.username}'
def gradestr(grade):
return '{} for user {}'.format(grade.course_id, grade.user_id)
return f'{grade.course_id} for user {grade.user_id}'
def parsetime(timestr):
@@ -99,8 +98,8 @@ class Command(BaseCommand):
course-v1:edX+RecordsSelfPaced+1 for user 18
"""
help = (
u"Simulate certificate/grade changes without actually modifying database "
u"content. Specifically, trigger the handlers that send data to Credentials."
"Simulate certificate/grade changes without actually modifying database "
"content. Specifically, trigger the handlers that send data to Credentials."
)
def add_arguments(self, parser):
@@ -189,8 +188,8 @@ class Command(BaseCommand):
options['start_date'] = options['end_date'] - timedelta(hours=4)
log.info(
u"notify_credentials starting, dry-run=%s, site=%s, delay=%d seconds, page_size=%d, "
u"from=%s, to=%s, notify_programs=%s, user_ids=%s, execution=%s",
"notify_credentials starting, dry-run=%s, site=%s, delay=%d seconds, page_size=%d, "
"from=%s, to=%s, notify_programs=%s, user_ids=%s, execution=%s",
options['dry_run'],
options['site'],
options['delay'],
@@ -205,7 +204,7 @@ class Command(BaseCommand):
try:
site_config = SiteConfiguration.objects.get(site__domain=options['site']) if options['site'] else None
except SiteConfiguration.DoesNotExist:
log.error(u'No site configuration found for site %s', options['site'])
log.error('No site configuration found for site %s', options['site'])
course_keys = self.get_course_keys(options['courses'])
if not (course_keys or options['start_date'] or options['end_date'] or options['user_ids']):
@@ -250,11 +249,11 @@ class Command(BaseCommand):
# First, do certs
for i, cert in paged_query(certs, delay, page_size):
if site_config and not site_config.has_org(cert.course_id.org):
log.info(u"Skipping credential changes %d for certificate %s", i, certstr(cert))
log.info("Skipping credential changes %d for certificate %s", i, certstr(cert))
continue
log.info(
u"Handling credential changes %d for certificate %s",
"Handling credential changes %d for certificate %s",
i, certstr(cert),
)
@@ -280,11 +279,11 @@ class Command(BaseCommand):
# Then do grades
for i, grade in paged_query(grades, delay, page_size):
if site_config and not site_config.has_org(grade.course_id.org):
log.info(u"Skipping grade changes %d for grade %s", i, gradestr(grade))
log.info("Skipping grade changes %d for grade %s", i, gradestr(grade))
continue
log.info(
u"Handling grade changes %d for grade %s",
"Handling grade changes %d for grade %s",
i, gradestr(grade),
)
@@ -321,12 +320,12 @@ class Command(BaseCommand):
courses = []
course_keys = []
log.info(u"%d courses specified: %s", len(courses), ", ".join(courses))
log.info("%d courses specified: %s", len(courses), ", ".join(courses))
for course_id in courses:
try:
course_keys.append(CourseKey.from_string(course_id))
except InvalidKeyError:
log.fatal(u"%s is not a parseable CourseKey", course_id)
log.fatal("%s is not a parseable CourseKey", course_id)
sys.exit(1)
return course_keys
@@ -340,10 +339,10 @@ class Command(BaseCommand):
for cert in certs[:ITEMS_TO_SHOW]:
print(" ", certstr(cert))
if certs.count() > ITEMS_TO_SHOW:
print(u" (+ {} more)".format(certs.count() - ITEMS_TO_SHOW))
print(" (+ {} more)".format(certs.count() - ITEMS_TO_SHOW))
print(grades.count(), "Grades:")
for grade in grades[:ITEMS_TO_SHOW]:
print(" ", gradestr(grade))
if grades.count() > ITEMS_TO_SHOW:
print(u" (+ {} more)".format(grades.count() - ITEMS_TO_SHOW))
print(" (+ {} more)".format(grades.count() - ITEMS_TO_SHOW))

View File

@@ -4,7 +4,7 @@ Tests the ``notify_credentials`` management command.
from datetime import datetime
import mock
from unittest import mock
from django.core.management import call_command
from django.core.management.base import CommandError
@@ -31,7 +31,7 @@ class TestNotifyCredentials(TestCase):
Tests the ``notify_credentials`` management command.
"""
def setUp(self):
super(TestNotifyCredentials, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.user = UserFactory.create()
self.user2 = UserFactory.create()

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import migrations, models

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import migrations, models
@@ -14,11 +11,11 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='credentialsapiconfig',
name='internal_service_url',
field=models.URLField(help_text=u'DEPRECATED: Use the setting CREDENTIALS_INTERNAL_SERVICE_URL.', verbose_name='Internal Service URL'),
field=models.URLField(help_text='DEPRECATED: Use the setting CREDENTIALS_INTERNAL_SERVICE_URL.', verbose_name='Internal Service URL'),
),
migrations.AlterField(
model_name='credentialsapiconfig',
name='public_service_url',
field=models.URLField(help_text=u'DEPRECATED: Use the setting CREDENTIALS_PUBLIC_SERVICE_URL.', verbose_name='Public Service URL'),
field=models.URLField(help_text='DEPRECATED: Use the setting CREDENTIALS_PUBLIC_SERVICE_URL.', verbose_name='Public Service URL'),
),
]

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-08-17 18:14

View File

@@ -3,13 +3,13 @@ Models for credentials support for the LMS and Studio.
"""
import six
from urllib.parse import urljoin # pylint: disable=import-error
from config_models.models import ConfigurationModel
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from six.moves.urllib.parse import urljoin # pylint: disable=import-error
from openedx.core.djangoapps.site_configuration import helpers
@@ -27,7 +27,7 @@ class CredentialsApiConfig(ConfigurationModel):
.. no_pii:
"""
class Meta(object):
class Meta:
app_label = 'credentials'
OAUTH2_CLIENT_NAME = 'credentials'
@@ -36,11 +36,11 @@ class CredentialsApiConfig(ConfigurationModel):
internal_service_url = models.URLField(
verbose_name=_('Internal Service URL'),
help_text=u'DEPRECATED: Use the setting CREDENTIALS_INTERNAL_SERVICE_URL.'
help_text='DEPRECATED: Use the setting CREDENTIALS_INTERNAL_SERVICE_URL.'
)
public_service_url = models.URLField(
verbose_name=_('Public Service URL'),
help_text=u'DEPRECATED: Use the setting CREDENTIALS_PUBLIC_SERVICE_URL.'
help_text='DEPRECATED: Use the setting CREDENTIALS_PUBLIC_SERVICE_URL.'
)
enable_learner_issuance = models.BooleanField(
@@ -74,7 +74,7 @@ class CredentialsApiConfig(ConfigurationModel):
Internally-accessible API URL root, looked up based on the current request.
"""
root = helpers.get_value('CREDENTIALS_INTERNAL_SERVICE_URL', settings.CREDENTIALS_INTERNAL_SERVICE_URL)
return urljoin(root, '/api/{}/'.format(API_VERSION))
return urljoin(root, f'/api/{API_VERSION}/')
@staticmethod
def get_internal_api_url_for_org(org):
@@ -83,7 +83,7 @@ class CredentialsApiConfig(ConfigurationModel):
"""
root = helpers.get_value_for_org(org, 'CREDENTIALS_INTERNAL_SERVICE_URL',
settings.CREDENTIALS_INTERNAL_SERVICE_URL)
return urljoin(root, '/api/{}/'.format(API_VERSION))
return urljoin(root, f'/api/{API_VERSION}/')
@property
def public_api_url(self):
@@ -91,7 +91,7 @@ class CredentialsApiConfig(ConfigurationModel):
Publicly-accessible API URL root.
"""
root = helpers.get_value('CREDENTIALS_PUBLIC_SERVICE_URL', settings.CREDENTIALS_PUBLIC_SERVICE_URL)
return urljoin(root, '/api/{}/'.format(API_VERSION))
return urljoin(root, f'/api/{API_VERSION}/')
@property
def public_records_url(self):
@@ -125,7 +125,7 @@ class NotifyCredentialsConfig(ConfigurationModel):
.. no_pii:
"""
class Meta(object):
class Meta:
app_label = 'credentials'
verbose_name = 'notify_credentials argument'
@@ -136,4 +136,4 @@ class NotifyCredentialsConfig(ConfigurationModel):
)
def __str__(self):
return six.text_type(self.arguments)
return str(self.arguments)

View File

@@ -49,14 +49,14 @@ def send_grade_if_interesting(user, course_run_key, mode, status, letter_grade,
""" Checks if grade is interesting to Credentials and schedules a Celery task if so. """
if verbose:
msg = u"Starting send_grade_if_interesting with params: "\
u"user [{username}], "\
u"course_run_key [{key}], "\
u"mode [{mode}], "\
u"status [{status}], "\
u"letter_grade [{letter_grade}], "\
u"percent_grade [{percent_grade}], "\
u"verbose [{verbose}]"\
msg = "Starting send_grade_if_interesting with params: "\
"user [{username}], "\
"course_run_key [{key}], "\
"mode [{mode}], "\
"status [{status}], "\
"letter_grade [{letter_grade}], "\
"percent_grade [{percent_grade}], "\
"verbose [{verbose}]"\
.format(
username=getattr(user, 'username', None),
key=str(course_run_key),
@@ -77,7 +77,7 @@ def send_grade_if_interesting(user, course_run_key, mode, status, letter_grade,
if not is_learner_records_enabled_for_org(course_run_key.org):
if verbose:
log.info(
u"Skipping send grade: ENABLE_LEARNER_RECORDS False for org [{org}]".format(
"Skipping send grade: ENABLE_LEARNER_RECORDS False for org [{org}]".format(
org=course_run_key.org
)
)
@@ -93,7 +93,7 @@ def send_grade_if_interesting(user, course_run_key, mode, status, letter_grade,
# We only care about grades for which there is a certificate.
if verbose:
log.info(
u"Skipping send grade: no cert for user [{username}] & course_id [{course_id}]".format(
"Skipping send grade: no cert for user [{username}] & course_id [{course_id}]".format(
username=getattr(user, 'username', None),
course_id=str(course_run_key)
)
@@ -106,7 +106,7 @@ def send_grade_if_interesting(user, course_run_key, mode, status, letter_grade,
if mode not in INTERESTING_MODES or status not in INTERESTING_STATUSES:
if verbose:
log.info(
u"Skipping send grade: mode/status uninteresting for mode [{mode}] & status [{status}]".format(
"Skipping send grade: mode/status uninteresting for mode [{mode}] & status [{status}]".format(
mode=mode,
status=status
)
@@ -118,7 +118,7 @@ def send_grade_if_interesting(user, course_run_key, mode, status, letter_grade,
if not is_course_run_in_a_program(course_run_key):
if verbose:
log.info(
u"Skipping send grade: course run not in a program. [{course_id}]".format(course_id=str(course_run_key))
"Skipping send grade: course run not in a program. [{course_id}]".format(course_id=str(course_run_key))
)
return
@@ -128,7 +128,7 @@ def send_grade_if_interesting(user, course_run_key, mode, status, letter_grade,
if grade is None:
if verbose:
log.info(
u"Skipping send grade: No grade found for user [{username}] & course_id [{course_id}]".format(
"Skipping send grade: No grade found for user [{username}] & course_id [{course_id}]".format(
username=getattr(user, 'username', None),
course_id=str(course_run_key)
)

View File

@@ -4,7 +4,7 @@
from openedx.core.djangoapps.credentials.models import CredentialsApiConfig
class CredentialsApiConfigMixin(object):
class CredentialsApiConfigMixin:
""" Utilities for working with Credentials configuration during testing."""
CREDENTIALS_DEFAULTS = {

View File

@@ -1,8 +1,9 @@
"""Tests covering Credentials signals."""
from unittest import mock
import ddt
import mock
from django.conf import settings
from django.test import TestCase, override_settings
from opaque_keys.edx.keys import CourseKey
@@ -35,7 +36,7 @@ class TestCredentialsSignalsSendGrade(TestCase):
""" Tests for send_grade_if_interesting, the main utility function that sends a grade """
def setUp(self):
super(TestCredentialsSignalsSendGrade, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.user = UserFactory()
self.key = CourseKey.from_string(CourseRunFactory()['key'])
@@ -141,7 +142,7 @@ class TestCredentialsSignalsUtils(TestCase):
""" Tests helper utility functions in our signal handling. """
def setUp(self):
super(TestCredentialsSignalsUtils, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.site = SiteFactory()
self.course_run = CourseRunFactory()
course = CourseFactory(course_runs=[self.course_run])

View File

@@ -2,8 +2,9 @@
Test credentials tasks
"""
from unittest import mock
import pytest
import mock
from django.conf import settings
from django.test import TestCase, override_settings
@@ -27,7 +28,7 @@ class TestSendGradeToCredentialTask(TestCase):
Tests for the 'send_grade_to_credentials' method.
"""
def setUp(self):
super(TestSendGradeToCredentialTask, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
self.user = UserFactory.create(username=settings.CREDENTIALS_SERVICE_USERNAME)
def test_happy_path(self, mock_get_api_client):

View File

@@ -3,7 +3,7 @@
import uuid
import mock
from unittest import mock
from openedx.core.djangoapps.credentials.models import CredentialsApiConfig
from openedx.core.djangoapps.credentials.tests import factories
@@ -24,7 +24,7 @@ class TestGetCredentials(CredentialsApiConfigMixin, CacheIsolationTestCase):
ENABLED_CACHES = ['default']
def setUp(self):
super(TestGetCredentials, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp()
ApplicationFactory(name=CredentialsApiConfig.OAUTH2_CLIENT_NAME)
@@ -46,7 +46,7 @@ class TestGetCredentials(CredentialsApiConfigMixin, CacheIsolationTestCase):
'status': 'awarded',
'only_visible': 'True',
}
cache_key = '{}.{}'.format(self.credentials_config.CACHE_KEY, self.user.username)
cache_key = f'{self.credentials_config.CACHE_KEY}.{self.user.username}'
assert kwargs['querystring'] == querystring
assert kwargs['cache_key'] == cache_key
@@ -69,7 +69,7 @@ class TestGetCredentials(CredentialsApiConfigMixin, CacheIsolationTestCase):
'only_visible': 'True',
'program_uuid': program_uuid,
}
cache_key = '{}.{}.{}'.format(self.credentials_config.CACHE_KEY, self.user.username, program_uuid)
cache_key = f'{self.credentials_config.CACHE_KEY}.{self.user.username}.{program_uuid}'
assert kwargs['querystring'] == querystring
assert kwargs['cache_key'] == cache_key

View File

@@ -71,9 +71,9 @@ def get_credentials(user, program_uuid=None, credential_type=None):
# Bypass caching for staff users, who may be generating credentials and
# want to see them displayed immediately.
use_cache = credential_configuration.is_cache_enabled and not user.is_staff
cache_key = '{}.{}'.format(credential_configuration.CACHE_KEY, user.username) if use_cache else None
cache_key = f'{credential_configuration.CACHE_KEY}.{user.username}' if use_cache else None
if cache_key and program_uuid:
cache_key = '{}.{}'.format(cache_key, program_uuid)
cache_key = f'{cache_key}.{program_uuid}'
api = get_credentials_api_client(user)
return get_edx_api_data(