From dfe6f21e4a4218f4ca4d629714b2c6a98d522514 Mon Sep 17 00:00:00 2001 From: "M. Zulqarnain" Date: Tue, 16 Mar 2021 14:37:08 +0500 Subject: [PATCH] refactor: pyupgrade in monkey_patch, oauth_dispatch, olx_rest_api (#26917) --- .../djangoapps/oauth_dispatch/adapters/dot.py | 4 +- .../core/djangoapps/oauth_dispatch/admin.py | 38 +++++++++--------- .../core/djangoapps/oauth_dispatch/apps.py | 2 +- .../dot_overrides/validators.py | 2 +- .../oauth_dispatch/dot_overrides/views.py | 2 +- .../commands/edx_clear_expired_tokens.py | 2 +- .../commands/generate_jwt_signing_key.py | 15 ++++--- .../tests/test_clear_expired_tokens.py | 8 ++-- .../tests/test_create_dot_application.py | 4 +- .../tests/test_generate_jwt_signing_key.py | 4 +- .../oauth_dispatch/migrations/0001_initial.py | 3 -- ...plication_scopedapplicationorganization.py | 3 +- .../migrations/0003_application_data.py | 1 - .../migrations/0004_auto_20180626_1349.py | 5 +-- .../migrations/0005_applicationaccess_type.py | 1 - .../0006_drop_application_id_constraints.py | 1 - ...0007_restore_application_id_constraints.py | 1 - .../0008_applicationaccess_filters.py | 1 - ...0009_delete_enable_scopes_waffle_switch.py | 1 - .../core/djangoapps/oauth_dispatch/models.py | 6 +-- .../oauth_dispatch/tests/constants.py | 4 +- .../oauth_dispatch/tests/factories.py | 10 ++--- .../djangoapps/oauth_dispatch/tests/mixins.py | 2 +- .../oauth_dispatch/tests/test_api.py | 12 +++--- .../tests/test_client_credentials.py | 2 +- .../oauth_dispatch/tests/test_dot_adapter.py | 9 ++--- .../tests/test_dot_overrides.py | 6 +-- .../oauth_dispatch/tests/test_factories.py | 6 +-- .../oauth_dispatch/tests/test_jwt.py | 4 +- .../oauth_dispatch/tests/test_scopes.py | 2 +- .../oauth_dispatch/tests/test_views.py | 40 +++++++++---------- .../core/djangoapps/oauth_dispatch/views.py | 6 +-- openedx/core/djangoapps/olx_rest_api/apps.py | 1 - .../olx_rest_api/block_serializer.py | 2 +- .../djangoapps/olx_rest_api/test_views.py | 2 +- openedx/core/djangoapps/olx_rest_api/views.py | 2 +- 36 files changed, 100 insertions(+), 114 deletions(-) diff --git a/openedx/core/djangoapps/oauth_dispatch/adapters/dot.py b/openedx/core/djangoapps/oauth_dispatch/adapters/dot.py index 5d513585cb..6912ecb439 100644 --- a/openedx/core/djangoapps/oauth_dispatch/adapters/dot.py +++ b/openedx/core/djangoapps/oauth_dispatch/adapters/dot.py @@ -8,13 +8,13 @@ from oauth2_provider import models from openedx.core.djangoapps.oauth_dispatch.models import RestrictedApplication -class DOTAdapter(object): +class DOTAdapter: """ Standard interface for working with django-oauth-toolkit """ backend = object() - FILTER_USER_ME = u'user:me' + FILTER_USER_ME = 'user:me' def create_confidential_client(self, name, diff --git a/openedx/core/djangoapps/oauth_dispatch/admin.py b/openedx/core/djangoapps/oauth_dispatch/admin.py index 5401a81a8e..333d4a3d4f 100644 --- a/openedx/core/djangoapps/oauth_dispatch/admin.py +++ b/openedx/core/djangoapps/oauth_dispatch/admin.py @@ -35,11 +35,11 @@ class DOTAccessTokenAdmin(ModelAdmin): """ Custom AccessToken Admin """ - date_hierarchy = u'expires' - list_display = [u'token', u'user', u'application', u'expires'] - list_filter = [u'application'] - raw_id_fields = [u'user'] - search_fields = [u'token', u'user__username'] + date_hierarchy = 'expires' + list_display = ['token', 'user', 'application', 'expires'] + list_filter = ['application'] + raw_id_fields = ['user'] + search_fields = ['token', 'user__username'] @reregister(models.RefreshToken) @@ -47,10 +47,10 @@ class DOTRefreshTokenAdmin(ModelAdmin): """ Custom AccessToken Admin """ - list_display = [u'token', u'user', u'application', u'access_token'] - list_filter = [u'application'] - raw_id_fields = [u'user', u'access_token'] - search_fields = [u'token', u'user__username', u'access_token__token'] + list_display = ['token', 'user', 'application', 'access_token'] + list_filter = ['application'] + raw_id_fields = ['user', 'access_token'] + search_fields = ['token', 'user__username', 'access_token__token'] @reregister(models.Grant) @@ -58,11 +58,11 @@ class DOTGrantAdmin(ModelAdmin): """ Custom Grant Admin """ - date_hierarchy = u'expires' - list_display = [u'code', u'user', u'application', u'expires'] - list_filter = [u'application'] - raw_id_fields = [u'user'] - search_fields = [u'code', u'user__username'] + date_hierarchy = 'expires' + list_display = ['code', 'user', 'application', 'expires'] + list_filter = ['application'] + raw_id_fields = ['user'] + search_fields = ['code', 'user__username'] @reregister(models.get_application_model()) @@ -70,10 +70,10 @@ class DOTApplicationAdmin(ModelAdmin): """ Custom Application Admin """ - list_display = [u'name', u'user', u'client_type', u'authorization_grant_type', u'client_id'] - list_filter = [u'client_type', u'authorization_grant_type', u'skip_authorization'] - raw_id_fields = [u'user'] - search_fields = [u'name', u'user__username', u'client_id'] + list_display = ['name', 'user', 'client_type', 'authorization_grant_type', 'client_id'] + list_filter = ['client_type', 'authorization_grant_type', 'skip_authorization'] + raw_id_fields = ['user'] + search_fields = ['name', 'user__username', 'client_id'] class ApplicationAccessAdmin(ModelAdmin): @@ -87,7 +87,7 @@ class RestrictedApplicationAdmin(ModelAdmin): """ ModelAdmin for the Restricted Application """ - list_display = [u'application'] + list_display = ['application'] site.register(ApplicationAccess, ApplicationAccessAdmin) diff --git a/openedx/core/djangoapps/oauth_dispatch/apps.py b/openedx/core/djangoapps/oauth_dispatch/apps.py index 00209df813..4bb88d682f 100644 --- a/openedx/core/djangoapps/oauth_dispatch/apps.py +++ b/openedx/core/djangoapps/oauth_dispatch/apps.py @@ -10,4 +10,4 @@ class OAuthDispatchAppConfig(AppConfig): """ OAuthDispatch Configuration """ - name = u'openedx.core.djangoapps.oauth_dispatch' + name = 'openedx.core.djangoapps.oauth_dispatch' diff --git a/openedx/core/djangoapps/oauth_dispatch/dot_overrides/validators.py b/openedx/core/djangoapps/oauth_dispatch/dot_overrides/validators.py index 356b7ace23..0b2ad35b2f 100644 --- a/openedx/core/djangoapps/oauth_dispatch/dot_overrides/validators.py +++ b/openedx/core/djangoapps/oauth_dispatch/dot_overrides/validators.py @@ -81,7 +81,7 @@ class EdxOAuth2Validator(OAuth2Validator): # associate access tokens issued with the client_credentials grant to users. request.user = request.client.user - super(EdxOAuth2Validator, self).save_bearer_token(token, request, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + super().save_bearer_token(token, request, *args, **kwargs) is_restricted_client = self._update_token_expiry_if_restricted_client(token, request.client) if not is_restricted_client: diff --git a/openedx/core/djangoapps/oauth_dispatch/dot_overrides/views.py b/openedx/core/djangoapps/oauth_dispatch/dot_overrides/views.py index cb10bf70d4..9720240fc6 100644 --- a/openedx/core/djangoapps/oauth_dispatch/dot_overrides/views.py +++ b/openedx/core/djangoapps/oauth_dispatch/dot_overrides/views.py @@ -36,7 +36,7 @@ class EdxOAuth2AuthorizationView(AuthorizationView): oauth2_settings.REQUEST_APPROVAL_PROMPT, ) if require_approval != 'auto_even_if_expired': - return super(EdxOAuth2AuthorizationView, self).get(request, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + return super().get(request, *args, **kwargs) scopes, credentials = self.validate_authorization_request(request) all_scopes = get_scopes_backend().get_all_scopes() diff --git a/openedx/core/djangoapps/oauth_dispatch/management/commands/edx_clear_expired_tokens.py b/openedx/core/djangoapps/oauth_dispatch/management/commands/edx_clear_expired_tokens.py index e224beb56e..9b820ea1d4 100644 --- a/openedx/core/djangoapps/oauth_dispatch/management/commands/edx_clear_expired_tokens.py +++ b/openedx/core/djangoapps/oauth_dispatch/management/commands/edx_clear_expired_tokens.py @@ -42,7 +42,7 @@ class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docst help='Comma-separated list of application IDs for which tokens will NOT be removed') def clear_table_data(self, query_set, batch_size, model, sleep_time): # lint-amnesty, pylint: disable=missing-function-docstring - message = 'Cleaning {} rows from {} table'.format(query_set.count(), model.__name__) + message = f'Cleaning {query_set.count()} rows from {model.__name__} table' logger.info(message) while query_set.exists(): qs = query_set[:batch_size] diff --git a/openedx/core/djangoapps/oauth_dispatch/management/commands/generate_jwt_signing_key.py b/openedx/core/djangoapps/oauth_dispatch/management/commands/generate_jwt_signing_key.py index 56b9c8f8f3..944eec839a 100644 --- a/openedx/core/djangoapps/oauth_dispatch/management/commands/generate_jwt_signing_key.py +++ b/openedx/core/djangoapps/oauth_dispatch/management/commands/generate_jwt_signing_key.py @@ -15,7 +15,6 @@ from Cryptodome.PublicKey import RSA from django.conf import settings from django.core.management.base import BaseCommand from jwkest import jwk -from six.moves import range log = logging.getLogger(__name__) @@ -40,7 +39,7 @@ class Command(BaseCommand): ''' def create_parser(self, *args, **kwargs): # pylint: disable=arguments-differ - parser = super(Command, self).create_parser(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + parser = super().create_parser(*args, **kwargs) parser.formatter_class = RawTextHelpFormatter return parser @@ -135,7 +134,7 @@ class Command(BaseCommand): serialized_public_keys = public_keys.dump_jwks() prefix = '' if strip_prefix else 'COMMON_' - public_signing_key = '{}JWT_PUBLIC_SIGNING_JWK_SET'.format(prefix) + public_signing_key = f'{prefix}JWT_PUBLIC_SIGNING_JWK_SET' log.info('New JWT_PUBLIC_SIGNING_JWK_SET: %s.', serialized_public_keys) print(" ") @@ -149,7 +148,7 @@ class Command(BaseCommand): "docs/decisions/0008-use-asymmetric-jwts.rst" ) print(" ") - print(" {}: '{}'".format(public_signing_key, serialized_public_keys)) + print(f" {public_signing_key}: '{serialized_public_keys}'") return {public_signing_key: serialized_public_keys} def _add_previous_public_keys(self, public_keys): @@ -163,8 +162,8 @@ class Command(BaseCommand): serialized_keypair_json = json.dumps(serialized_keypair) prefix = '' if strip_prefix else 'EDXAPP_' - private_signing_key = '{}JWT_PRIVATE_SIGNING_JWK'.format(prefix) - algorithm_key = '{}JWT_SIGNING_ALGORITHM'.format(prefix) + private_signing_key = f'{prefix}JWT_PRIVATE_SIGNING_JWK' + algorithm_key = f'{prefix}JWT_SIGNING_ALGORITHM' print(" ") print(" ") @@ -177,9 +176,9 @@ class Command(BaseCommand): "docs/decisions/0008-use-asymmetric-jwts.rst" ) print(" ") - print(" {}: '{}'".format(private_signing_key, serialized_keypair_json)) + print(f" {private_signing_key}: '{serialized_keypair_json}'") print(" ") - print(" {}: 'RS512'".format(algorithm_key)) + print(f" {algorithm_key}: 'RS512'") return { private_signing_key: serialized_keypair_json, algorithm_key: 'RS512', diff --git a/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_clear_expired_tokens.py b/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_clear_expired_tokens.py index c57d50a9f7..889316b6ea 100644 --- a/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_clear_expired_tokens.py +++ b/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_clear_expired_tokens.py @@ -5,8 +5,9 @@ Tests the ``edx_clear_expired_tokens`` management command. import unittest from datetime import timedelta -import pytest +from unittest.mock import patch +import pytest from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.management import call_command @@ -14,7 +15,6 @@ from django.db.models import QuerySet from django.test import TestCase from django.test.utils import override_settings from django.utils import timezone -from mock import patch from oauth2_provider.models import AccessToken, RefreshToken from testfixtures import LogCapture @@ -67,12 +67,12 @@ class EdxClearExpiredTokensTests(TestCase): # lint-amnesty, pylint: disable=mis ( LOGGER_NAME, 'INFO', - u'Cleaning {} rows from {} table'.format(0, RefreshToken.__name__) + 'Cleaning {} rows from {} table'.format(0, RefreshToken.__name__) ), ( LOGGER_NAME, 'INFO', - u'Cleaning {} rows from {} table'.format(0, AccessToken.__name__), + 'Cleaning {} rows from {} table'.format(0, AccessToken.__name__), ), ( LOGGER_NAME, diff --git a/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_create_dot_application.py b/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_create_dot_application.py index 7d705eed68..f30e8bb614 100644 --- a/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_create_dot_application.py +++ b/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_create_dot_application.py @@ -21,11 +21,11 @@ class TestCreateDotApplication(TestCase): Tests the ``create_dot_application`` management command. """ def setUp(self): - super(TestCreateDotApplication, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create() def tearDown(self): - super(TestCreateDotApplication, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments + super().tearDown() Application.objects.filter(user=self.user).delete() def test_update_dot_application(self): diff --git a/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_generate_jwt_signing_key.py b/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_generate_jwt_signing_key.py index 6848c4c65f..75d45fe883 100644 --- a/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_generate_jwt_signing_key.py +++ b/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_generate_jwt_signing_key.py @@ -8,13 +8,13 @@ import os import sys import tempfile from contextlib import contextmanager -from six import StringIO +from io import StringIO +from unittest.mock import patch import ddt import yaml from django.core.management import call_command from django.test import TestCase -from mock import patch from openedx.core.djangolib.testing.utils import skip_unless_lms diff --git a/openedx/core/djangoapps/oauth_dispatch/migrations/0001_initial.py b/openedx/core/djangoapps/oauth_dispatch/migrations/0001_initial.py index babaaa7830..a446d1c4d1 100644 --- a/openedx/core/djangoapps/oauth_dispatch/migrations/0001_initial.py +++ b/openedx/core/djangoapps/oauth_dispatch/migrations/0001_initial.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - from django.conf import settings from django.db import migrations, models diff --git a/openedx/core/djangoapps/oauth_dispatch/migrations/0002_scopedapplication_scopedapplicationorganization.py b/openedx/core/djangoapps/oauth_dispatch/migrations/0002_scopedapplication_scopedapplicationorganization.py index 3a785ffe24..e5ee43423f 100644 --- a/openedx/core/djangoapps/oauth_dispatch/migrations/0002_scopedapplication_scopedapplicationorganization.py +++ b/openedx/core/djangoapps/oauth_dispatch/migrations/0002_scopedapplication_scopedapplicationorganization.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-20 18:22 @@ -38,7 +37,7 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('short_name', models.CharField(help_text='The short_name of an existing Organization.', max_length=255)), - ('provider_type', models.CharField(choices=[(u'content_org', 'Content Provider')], default=u'content_org', max_length=32)), + ('provider_type', models.CharField(choices=[('content_org', 'Content Provider')], default='content_org', max_length=32)), ('application', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='organizations', to=settings.OAUTH2_PROVIDER_APPLICATION_MODEL)), ], ), diff --git a/openedx/core/djangoapps/oauth_dispatch/migrations/0003_application_data.py b/openedx/core/djangoapps/oauth_dispatch/migrations/0003_application_data.py index 18cb2fb735..b55bee3752 100644 --- a/openedx/core/djangoapps/oauth_dispatch/migrations/0003_application_data.py +++ b/openedx/core/djangoapps/oauth_dispatch/migrations/0003_application_data.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-05 13:19 diff --git a/openedx/core/djangoapps/oauth_dispatch/migrations/0004_auto_20180626_1349.py b/openedx/core/djangoapps/oauth_dispatch/migrations/0004_auto_20180626_1349.py index eab45180f1..61dda22b4c 100644 --- a/openedx/core/djangoapps/oauth_dispatch/migrations/0004_auto_20180626_1349.py +++ b/openedx/core/djangoapps/oauth_dispatch/migrations/0004_auto_20180626_1349.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-26 17:49 @@ -29,7 +28,7 @@ class Migration(migrations.Migration): name='ApplicationOrganization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('relation_type', models.CharField(choices=[(u'content_org', 'Content Provider')], default=u'content_org', max_length=32)), + ('relation_type', models.CharField(choices=[('content_org', 'Content Provider')], default='content_org', max_length=32)), ('application', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='organizations', to=settings.OAUTH2_PROVIDER_APPLICATION_MODEL)), ('organization', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='organizations.Organization')), ], @@ -50,6 +49,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='applicationorganization', - unique_together=set([('application', 'relation_type', 'organization')]), + unique_together={('application', 'relation_type', 'organization')}, ), ] diff --git a/openedx/core/djangoapps/oauth_dispatch/migrations/0005_applicationaccess_type.py b/openedx/core/djangoapps/oauth_dispatch/migrations/0005_applicationaccess_type.py index 2143b75bdb..0934d60771 100644 --- a/openedx/core/djangoapps/oauth_dispatch/migrations/0005_applicationaccess_type.py +++ b/openedx/core/djangoapps/oauth_dispatch/migrations/0005_applicationaccess_type.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-29 18:18 diff --git a/openedx/core/djangoapps/oauth_dispatch/migrations/0006_drop_application_id_constraints.py b/openedx/core/djangoapps/oauth_dispatch/migrations/0006_drop_application_id_constraints.py index 2228f97023..c2c8fc3765 100644 --- a/openedx/core/djangoapps/oauth_dispatch/migrations/0006_drop_application_id_constraints.py +++ b/openedx/core/djangoapps/oauth_dispatch/migrations/0006_drop_application_id_constraints.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2018-07-23 14:58 diff --git a/openedx/core/djangoapps/oauth_dispatch/migrations/0007_restore_application_id_constraints.py b/openedx/core/djangoapps/oauth_dispatch/migrations/0007_restore_application_id_constraints.py index dc52ecc8ad..25fc535440 100644 --- a/openedx/core/djangoapps/oauth_dispatch/migrations/0007_restore_application_id_constraints.py +++ b/openedx/core/djangoapps/oauth_dispatch/migrations/0007_restore_application_id_constraints.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2018-07-23 15:12 diff --git a/openedx/core/djangoapps/oauth_dispatch/migrations/0008_applicationaccess_filters.py b/openedx/core/djangoapps/oauth_dispatch/migrations/0008_applicationaccess_filters.py index 991e64ce4d..846f00e32a 100644 --- a/openedx/core/djangoapps/oauth_dispatch/migrations/0008_applicationaccess_filters.py +++ b/openedx/core/djangoapps/oauth_dispatch/migrations/0008_applicationaccess_filters.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-02-14 21:30 diff --git a/openedx/core/djangoapps/oauth_dispatch/migrations/0009_delete_enable_scopes_waffle_switch.py b/openedx/core/djangoapps/oauth_dispatch/migrations/0009_delete_enable_scopes_waffle_switch.py index fe022ec4f7..bd4cef97b1 100644 --- a/openedx/core/djangoapps/oauth_dispatch/migrations/0009_delete_enable_scopes_waffle_switch.py +++ b/openedx/core/djangoapps/oauth_dispatch/migrations/0009_delete_enable_scopes_waffle_switch.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-03-04 15:19 """ diff --git a/openedx/core/djangoapps/oauth_dispatch/models.py b/openedx/core/djangoapps/oauth_dispatch/models.py index 85bfc41ccf..014a820c01 100644 --- a/openedx/core/djangoapps/oauth_dispatch/models.py +++ b/openedx/core/djangoapps/oauth_dispatch/models.py @@ -38,7 +38,7 @@ class RestrictedApplication(models.Model): """ Return a unicode representation of this object """ - return HTML(u"").format( + return HTML("").format( name=HTML(self.application.name) ) @@ -116,7 +116,7 @@ class ApplicationAccess(models.Model): """ Return a unicode representation of this object. """ - return u"{application_name}:{scopes}:{filters}".format( + return "{application_name}:{scopes}:{filters}".format( application_name=self.application.name, scopes=self.scopes, filters=self.filters, @@ -139,7 +139,7 @@ class ApplicationOrganization(models.Model): .. no_pii: """ - RELATION_TYPE_CONTENT_ORG = u'content_org' + RELATION_TYPE_CONTENT_ORG = 'content_org' RELATION_TYPES = ( (RELATION_TYPE_CONTENT_ORG, _('Content Provider')), ) diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/constants.py b/openedx/core/djangoapps/oauth_dispatch/tests/constants.py index 598e7278cc..abe0a55c09 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/constants.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/constants.py @@ -2,5 +2,5 @@ Constants for testing purposes """ -DUMMY_REDIRECT_URL = u'https://example.com/edx/redirect' -DUMMY_REDIRECT_URL2 = u'https://example.com/edx/other-redirect' +DUMMY_REDIRECT_URL = 'https://example.com/edx/redirect' +DUMMY_REDIRECT_URL2 = 'https://example.com/edx/other-redirect' diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/factories.py b/openedx/core/djangoapps/oauth_dispatch/tests/factories.py index a0ca20aa0a..473bcd4ced 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/factories.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/factories.py @@ -14,11 +14,11 @@ from common.djangoapps.student.tests.factories import UserFactory class ApplicationFactory(DjangoModelFactory): - class Meta(object): + class Meta: model = Application user = factory.SubFactory(UserFactory) - client_id = factory.Sequence(u'client_{0}'.format) + client_id = factory.Sequence('client_{}'.format) client_secret = 'some_secret' client_type = 'confidential' authorization_grant_type = Application.CLIENT_CONFIDENTIAL @@ -26,7 +26,7 @@ class ApplicationFactory(DjangoModelFactory): class ApplicationAccessFactory(DjangoModelFactory): - class Meta(object): + class Meta: model = ApplicationAccess application = factory.SubFactory(ApplicationFactory) @@ -34,7 +34,7 @@ class ApplicationAccessFactory(DjangoModelFactory): class AccessTokenFactory(DjangoModelFactory): - class Meta(object): + class Meta: model = AccessToken django_get_or_create = ('user', 'application') @@ -43,7 +43,7 @@ class AccessTokenFactory(DjangoModelFactory): class RefreshTokenFactory(DjangoModelFactory): - class Meta(object): + class Meta: model = RefreshToken django_get_or_create = ('user', 'application') diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/mixins.py b/openedx/core/djangoapps/oauth_dispatch/tests/mixins.py index 315f38b19e..67cf1ed99b 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/mixins.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/mixins.py @@ -12,7 +12,7 @@ from jwt.exceptions import ExpiredSignatureError from common.djangoapps.student.models import UserProfile, anonymous_id_for_user -class AccessTokenMixin(object): +class AccessTokenMixin: """ Mixin for tests dealing with OAuth 2 access tokens. """ def assert_valid_jwt_access_token(self, access_token, user, scopes=None, should_be_expired=False, filters=None, diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_api.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_api.py index aa8dadf1eb..3c064cc63c 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/test_api.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_api.py @@ -23,7 +23,7 @@ EXPECTED_DEFAULT_EXPIRES_IN = 36000 class TestOAuthDispatchAPI(TestCase): """ Tests for oauth_dispatch's api.py module. """ def setUp(self): - super(TestOAuthDispatchAPI, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.adapter = DOTAdapter() self.user = UserFactory() self.client = self.adapter.create_public_client( @@ -45,9 +45,9 @@ class TestOAuthDispatchAPI(TestCase): assert token['refresh_token'] self.assertDictContainsSubset( { - u'token_type': u'Bearer', - u'expires_in': EXPECTED_DEFAULT_EXPIRES_IN, - u'scope': u'', + 'token_type': 'Bearer', + 'expires_in': EXPECTED_DEFAULT_EXPIRES_IN, + 'scope': '', }, token, ) @@ -63,5 +63,5 @@ class TestOAuthDispatchAPI(TestCase): token = api.create_dot_access_token( HttpRequest(), self.user, self.client, expires_in=expires_in, scopes=['profile'], ) - self.assertDictContainsSubset({u'scope': u'profile'}, token) - self.assertDictContainsSubset({u'expires_in': expires_in}, token) + self.assertDictContainsSubset({'scope': 'profile'}, token) + self.assertDictContainsSubset({'expires_in': expires_in}, token) diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_client_credentials.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_client_credentials.py index 5c1c938d76..9bdc27618e 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/test_client_credentials.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_client_credentials.py @@ -21,7 +21,7 @@ class ClientCredentialsTest(mixins.AccessTokenMixin, TestCase): """ Tests validating the client credentials grant behavior. """ def setUp(self): - super(ClientCredentialsTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory() def test_jwt_access_token(self): diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_adapter.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_adapter.py index 3abc0fcb70..8992139df5 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_adapter.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_adapter.py @@ -7,7 +7,6 @@ from datetime import timedelta import pytest import ddt -import six from django.conf import settings from django.test import TestCase from django.utils.timezone import now @@ -29,7 +28,7 @@ class DOTAdapterTestCase(TestCase): Test class for DOTAdapter. """ def setUp(self): - super(DOTAdapterTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.adapter = DOTAdapter() self.user = UserFactory() self.public_client = self.adapter.create_public_client( @@ -56,7 +55,7 @@ class DOTAdapterTestCase(TestCase): """ Make sure unicode representation of RestrictedApplication is correct """ - assert six.text_type(self.restricted_app) == ""\ + assert str(self.restricted_app) == ""\ .format(name=self.restricted_client.name) @ddt.data( @@ -65,9 +64,9 @@ class DOTAdapterTestCase(TestCase): ) @ddt.unpack def test_create_client(self, client_name, client_type): - client = getattr(self, '{}_client'.format(client_name)) + client = getattr(self, f'{client_name}_client') assert isinstance(client, models.Application) - assert client.client_id == '{}-client-id'.format(client_name) + assert client.client_id == f'{client_name}-client-id' assert client.client_type == client_type def test_get_client(self): diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_overrides.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_overrides.py index b7ea105296..01ddeb3bd1 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_overrides.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_overrides.py @@ -32,7 +32,7 @@ class AuthenticateTestCase(TestCase): """ def setUp(self): - super(AuthenticateTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = User.objects.create_user( username='darkhelmet', password='12345', @@ -57,7 +57,7 @@ class CustomValidationTestCase(TestCase): In particular, inactive users should be able to validate. """ def setUp(self): - super(CustomValidationTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = User.objects.create_user( username='darkhelmet', password='12345', @@ -88,7 +88,7 @@ class CustomAuthorizationViewTestCase(TestCase): (This is a temporary override until Auth Scopes is implemented.) """ def setUp(self): - super(CustomAuthorizationViewTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.dot_adapter = adapters.DOTAdapter() self.user = UserFactory() self.client.login(username=self.user.username, password='test') diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_factories.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_factories.py index 44fec815a4..f784d3d178 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/test_factories.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_factories.py @@ -14,7 +14,7 @@ from common.djangoapps.student.tests.factories import UserFactory @unittest.skipUnless(settings.FEATURES.get("ENABLE_OAUTH2_PROVIDER"), "OAuth2 not enabled") class TestClientFactory(TestCase): def setUp(self): - super(TestClientFactory, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create() def test_client_factory(self): @@ -26,7 +26,7 @@ class TestClientFactory(TestCase): @unittest.skipUnless(settings.FEATURES.get("ENABLE_OAUTH2_PROVIDER"), "OAuth2 not enabled") class TestAccessTokenFactory(TestCase): def setUp(self): - super(TestAccessTokenFactory, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create() def test_access_token_client_factory(self): @@ -39,7 +39,7 @@ class TestAccessTokenFactory(TestCase): @unittest.skipUnless(settings.FEATURES.get("ENABLE_OAUTH2_PROVIDER"), "OAuth2 not enabled") class TestRefreshTokenFactory(TestCase): def setUp(self): - super(TestRefreshTokenFactory, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create() def test_refresh_token_factory(self): diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_jwt.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_jwt.py index e38ee11bdf..3eeae45d4f 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/test_jwt.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_jwt.py @@ -3,11 +3,11 @@ import itertools # lint-amnesty, pylint: disable=unused-import from datetime import timedelta +from unittest.mock import patch import ddt from django.test import TestCase from django.utils.timezone import now -from mock import patch from openedx.core.djangoapps.oauth_dispatch import jwt as jwt_api from openedx.core.djangoapps.oauth_dispatch.adapters import DOTAdapter @@ -20,7 +20,7 @@ from common.djangoapps.student.tests.factories import UserFactory class TestCreateJWTs(AccessTokenMixin, TestCase): """ Tests for oauth_dispatch's jwt creation functionality. """ def setUp(self): - super(TestCreateJWTs, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory() self.default_scopes = ['email', 'profile'] diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_scopes.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_scopes.py index 1cfcc12de5..5b68f6f14c 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/test_scopes.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_scopes.py @@ -30,4 +30,4 @@ class ApplicationModelScopesTestCase(TestCase): application_access = ApplicationAccessFactory(scopes=application_scopes) scopes = ApplicationModelScopes() assert set(scopes.get_available_scopes(application_access.application)) == \ - set((list(settings.OAUTH2_DEFAULT_SCOPES.keys()) + expected_additional_scopes)) + set(list(settings.OAUTH2_DEFAULT_SCOPES.keys()) + expected_additional_scopes) diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_views.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_views.py index 7eb41a6498..183efc5047 100644 --- a/openedx/core/djangoapps/oauth_dispatch/tests/test_views.py +++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_views.py @@ -5,6 +5,7 @@ Tests for Blocks Views import json import unittest +from unittest.mock import call, patch import ddt import httpretty @@ -13,7 +14,6 @@ from django.conf import settings from django.test import RequestFactory, TestCase from django.urls import reverse from jwkest import jwk -from mock import call, patch from oauth2_provider import models as dot_models from common.djangoapps.student.tests.factories import UserFactory @@ -38,7 +38,7 @@ if OAUTH_PROVIDER_ENABLED: from .. import views -class AccessTokenLoginMixin(object): +class AccessTokenLoginMixin: """ Shared helper class to assert proper access levels when using access_tokens """ @@ -47,7 +47,7 @@ class AccessTokenLoginMixin(object): """ Initialize mixin """ - super(AccessTokenLoginMixin, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.login_with_access_token_url = reverse("login_with_access_token") def login_with_access_token(self, access_token=None): @@ -59,7 +59,7 @@ class AccessTokenLoginMixin(object): return self.client.post( self.login_with_access_token_url, - HTTP_AUTHORIZATION=u"Bearer {0}".format(access_token if access_token else self.access_token).encode('utf-8') + HTTP_AUTHORIZATION="Bearer {}".format(access_token if access_token else self.access_token).encode('utf-8') ) def _assert_access_token_is_valid(self, access_token=None): @@ -83,7 +83,7 @@ class _DispatchingViewTestCase(TestCase): Subclasses need to define self.url. """ def setUp(self): - super(_DispatchingViewTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.dot_adapter = adapters.DOTAdapter() self.user = UserFactory() self.dot_app = self.dot_adapter.create_public_client( @@ -129,7 +129,7 @@ class TestAccessTokenView(AccessTokenLoginMixin, mixins.AccessTokenMixin, _Dispa """ def setUp(self): - super(TestAccessTokenView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.url = reverse('access_token') self.view_class = views.AccessTokenView @@ -309,7 +309,7 @@ class TestAccessTokenView(AccessTokenLoginMixin, mixins.AccessTokenMixin, _Dispa name='test dot application', user=self.user, redirect_uri=DUMMY_REDIRECT_URL, - client_id='dot-app-client-id-{grant_type}'.format(grant_type=grant_type), + client_id=f'dot-app-client-id-{grant_type}', grant_type=grant_type, ) dot_app_access = models.ApplicationAccess.objects.create( @@ -342,7 +342,7 @@ class TestAccessTokenExchangeView(ThirdPartyOAuthTestMixinGoogle, ThirdPartyOAut def setUp(self): self.url = reverse('exchange_access_token', kwargs={'backend': 'google-oauth2'}) self.view_class = views.AccessTokenExchangeView - super(TestAccessTokenExchangeView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() def _post_body(self, user, client, token_type=None, scope=None): return { @@ -367,7 +367,7 @@ class TestAuthorizationView(_DispatchingViewTestCase): """ def setUp(self): - super(TestAuthorizationView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory() self.dot_app = self.dot_adapter.create_confidential_client( name='test dot application', @@ -390,7 +390,7 @@ class TestAuthorizationView(_DispatchingViewTestCase): ) @ddt.unpack def test_post_authorization_view(self, client_type, allow_field): - oauth_application = getattr(self, '{}_app'.format(client_type)) + oauth_application = getattr(self, f'{client_type}_app') self.client.login(username=self.user.username, password='test') response = self.client.post( '/oauth2/authorize/', @@ -405,7 +405,7 @@ class TestAuthorizationView(_DispatchingViewTestCase): follow=True, ) - check_response = getattr(self, '_check_{}_response'.format(client_type)) + check_response = getattr(self, f'_check_{client_type}_response') check_response(response) def test_check_dot_authorization_page_get(self): @@ -437,7 +437,7 @@ class TestAuthorizationView(_DispatchingViewTestCase): # is the application name specified? self.assertContains( response, - u"Authorize {name}".format(name=self.dot_app.name) + f"Authorize {self.dot_app.name}" ) # are the cancel and allow buttons on the page? @@ -469,14 +469,14 @@ class TestAuthorizationView(_DispatchingViewTestCase): # django-oauth-toolkit tries to redirect to the user's redirect URL assert response.status_code == 404 # We used a non-existent redirect url. - expected_redirect_prefix = u'{}?'.format(DUMMY_REDIRECT_URL) + expected_redirect_prefix = f'{DUMMY_REDIRECT_URL}?' self._assert_startswith(self._redirect_destination(response), expected_redirect_prefix) def _assert_startswith(self, string, prefix): """ Assert that the string starts with the specified prefix. """ - assert string.startswith(prefix), u'{} does not start with {}'.format(string, prefix) + assert string.startswith(prefix), f'{string} does not start with {prefix}' @staticmethod def _redirect_destination(response): @@ -493,7 +493,7 @@ class TestViewDispatch(TestCase): """ def setUp(self): - super(TestViewDispatch, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.dot_adapter = adapters.DOTAdapter() self.user = UserFactory() self.view = views._DispatchingView() # pylint: disable=protected-access @@ -511,9 +511,9 @@ class TestViewDispatch(TestCase): could take any name, this assertion requires the argument to be named `request`. This is good practice. You should do it anyway. """ - _msg_base = u'{view} is not a view: {reason}' - msg_not_callable = _msg_base.format(view=view_candidate, reason=u'it is not callable') - msg_no_request = _msg_base.format(view=view_candidate, reason=u'it has no request argument') + _msg_base = '{view} is not a view: {reason}' + msg_not_callable = _msg_base.format(view=view_candidate, reason='it is not callable') + msg_no_request = _msg_base.format(view=view_candidate, reason='it has no request argument') assert hasattr(view_candidate, '__call__'), msg_not_callable args = view_candidate.__code__.co_varnames assert args, msg_no_request @@ -529,7 +529,7 @@ class TestViewDispatch(TestCase): """ Return a request with the specified client_id in the get parameters """ - return RequestFactory().get('/?client_id={}'.format(client_id)) + return RequestFactory().get(f'/?client_id={client_id}') def test_dispatching_post_to_dot(self): request = self._post_request('dot-id') @@ -565,7 +565,7 @@ class TestRevokeTokenView(AccessTokenLoginMixin, _DispatchingViewTestCase): # p self.revoke_token_url = reverse('revoke_token') self.access_token_url = reverse('access_token') - super(TestRevokeTokenView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() response = self.client.post(self.access_token_url, self.access_token_post_body_with_password()) access_token_data = json.loads(response.content.decode('utf-8')) self.access_token = access_token_data['access_token'] diff --git a/openedx/core/djangoapps/oauth_dispatch/views.py b/openedx/core/djangoapps/oauth_dispatch/views.py index e2206b9ee3..ef5a1d93d7 100644 --- a/openedx/core/djangoapps/oauth_dispatch/views.py +++ b/openedx/core/djangoapps/oauth_dispatch/views.py @@ -63,13 +63,13 @@ class _DispatchingView(View): if backend == self.dot_adapter.backend: return self.dot_view.as_view() # lint-amnesty, pylint: disable=no-member else: - raise KeyError('Failed to dispatch view. Invalid backend {}'.format(backend)) + raise KeyError(f'Failed to dispatch view. Invalid backend {backend}') def _get_client_id(self, request): """ Return the client_id from the provided request """ - if request.method == u'GET': + if request.method == 'GET': return request.GET.get('client_id') else: return request.POST.get('client_id') @@ -88,7 +88,7 @@ class AccessTokenView(_DispatchingView): dot_view = dot_views.TokenView def dispatch(self, request, *args, **kwargs): - response = super(AccessTokenView, self).dispatch(request, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + response = super().dispatch(request, *args, **kwargs) token_type = request.POST.get('token_type', request.META.get('HTTP_X_TOKEN_TYPE', 'no_token_type_supplied')).lower() diff --git a/openedx/core/djangoapps/olx_rest_api/apps.py b/openedx/core/djangoapps/olx_rest_api/apps.py index 5a4d056eec..0aa921017c 100644 --- a/openedx/core/djangoapps/olx_rest_api/apps.py +++ b/openedx/core/djangoapps/olx_rest_api/apps.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ olx_rest_api Django application initialization. """ diff --git a/openedx/core/djangoapps/olx_rest_api/block_serializer.py b/openedx/core/djangoapps/olx_rest_api/block_serializer.py index 36ed6a59c7..2a2d002f96 100644 --- a/openedx/core/djangoapps/olx_rest_api/block_serializer.py +++ b/openedx/core/djangoapps/olx_rest_api/block_serializer.py @@ -36,7 +36,7 @@ def blockstore_def_key_from_modulestore_usage_key(usage_key): return block_type + "/" + usage_key.block_id -class XBlockSerializer(object): +class XBlockSerializer: """ This class will serialize an XBlock, producing: (1) A new definition ID for use in Blockstore diff --git a/openedx/core/djangoapps/olx_rest_api/test_views.py b/openedx/core/djangoapps/olx_rest_api/test_views.py index 07a0a7bf15..24b318ca12 100644 --- a/openedx/core/djangoapps/olx_rest_api/test_views.py +++ b/openedx/core/djangoapps/olx_rest_api/test_views.py @@ -53,7 +53,7 @@ class OlxRestApiTestCase(SharedModuleStoreTestCase): assert clean(xml_str_a) == clean(xml_str_b) def get_olx_response_for_block(self, block_id): - return self.client.get('/api/olx-export/v1/xblock/{}/'.format(block_id)) + return self.client.get(f'/api/olx-export/v1/xblock/{block_id}/') # Actual tests: diff --git a/openedx/core/djangoapps/olx_rest_api/views.py b/openedx/core/djangoapps/olx_rest_api/views.py index 816954c669..bb1caa3061 100644 --- a/openedx/core/djangoapps/olx_rest_api/views.py +++ b/openedx/core/djangoapps/olx_rest_api/views.py @@ -113,5 +113,5 @@ def get_block_exportfs_file(request, usage_key_str, path): raise NotFound response = HttpResponse(static_file.data, content_type='application/octet-stream') - response['Content-Disposition'] = 'attachment; filename="{}"'.format(path) + response['Content-Disposition'] = f'attachment; filename="{path}"' return response