refactor: pyupgrade in monkey_patch, oauth_dispatch, olx_rest_api (#26917)

This commit is contained in:
M. Zulqarnain
2021-03-16 14:37:08 +05:00
committed by GitHub
parent cf10b29a3e
commit dfe6f21e4a
36 changed files with 100 additions and 114 deletions

View File

@@ -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,

View File

@@ -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)

View File

@@ -10,4 +10,4 @@ class OAuthDispatchAppConfig(AppConfig):
"""
OAuthDispatch Configuration
"""
name = u'openedx.core.djangoapps.oauth_dispatch'
name = 'openedx.core.djangoapps.oauth_dispatch'

View File

@@ -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:

View File

@@ -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()

View File

@@ -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]

View File

@@ -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',

View File

@@ -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,

View File

@@ -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):

View File

@@ -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

View File

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

View File

@@ -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)),
],
),

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-05 13:19

View File

@@ -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')},
),
]

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-29 18:18

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-23 14:58

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-23 15:12

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-02-14 21:30

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-03-04 15:19
"""

View File

@@ -38,7 +38,7 @@ class RestrictedApplication(models.Model):
"""
Return a unicode representation of this object
"""
return HTML(u"<RestrictedApplication '{name}'>").format(
return HTML("<RestrictedApplication '{name}'>").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')),
)

View File

@@ -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'

View File

@@ -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')

View File

@@ -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,

View File

@@ -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)

View File

@@ -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):

View File

@@ -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) == "<RestrictedApplication '{name}'>"\
assert str(self.restricted_app) == "<RestrictedApplication '{name}'>"\
.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):

View File

@@ -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')

View File

@@ -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):

View File

@@ -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']

View File

@@ -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)

View File

@@ -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']

View File

@@ -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()

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
olx_rest_api Django application initialization.
"""

View File

@@ -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

View File

@@ -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:

View File

@@ -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