lint amnesty in monkey_patch,oauth_dispatch,olx_rest_api and password_policy (#26376)

This commit is contained in:
M. Zulqarnain
2021-02-04 17:10:16 +05:00
committed by GitHub
parent 96dd5855ca
commit 6e7af5eab6
25 changed files with 51 additions and 51 deletions

View File

@@ -1,4 +1,4 @@
"""
""" # lint-amnesty, pylint: disable=django-not-configured
Monkey-patch the edX platform
Here be dragons (and simians!)

View File

@@ -17,4 +17,4 @@ class EdxRateLimitedAllowAllUsersModelBackend(RateLimitMixin, UserModelBackend):
See: https://openedx.atlassian.net/browse/TNL-4516
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass

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)
super(EdxOAuth2Validator, self).save_bearer_token(token, request, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
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)
return super(EdxOAuth2AuthorizationView, self).get(request, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
scopes, credentials = self.validate_authorization_request(request)
all_scopes = get_scopes_backend().get_all_scopes()
@@ -59,7 +59,7 @@ class EdxOAuth2AuthorizationView(AuthorizationView):
kwargs['response_type'] = credentials['response_type']
kwargs['state'] = credentials['state']
self.oauth2_data = kwargs
self.oauth2_data = kwargs # lint-amnesty, pylint: disable=attribute-defined-outside-init
# following two loc are here only because of https://code.djangoproject.com/ticket/17795
form = self.get_form(self.get_form_class())
kwargs['form'] = form
@@ -69,7 +69,7 @@ class EdxOAuth2AuthorizationView(AuthorizationView):
# This is useful for in-house applications-> assume an in-house applications
# are already approved.
if application.skip_authorization:
uri, headers, body, status = self.create_authorization_response(
uri, headers, body, status = self.create_authorization_response( # lint-amnesty, pylint: disable=unused-variable
request=self.request, scopes=" ".join(scopes),
credentials=credentials, allow=True)
return OAuth2ResponseRedirect(uri, application.get_allowed_schemes())

View File

@@ -7,7 +7,7 @@ Also creates an oauth_dispatch application access if scopes are provided.
import logging
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.management.base import BaseCommand
from oauth2_provider.models import get_application_model

View File

@@ -17,7 +17,7 @@ from oauth2_provider.settings import oauth2_settings
logger = logging.getLogger(__name__)
class Command(BaseCommand):
class Command(BaseCommand): # lint-amnesty, pylint: disable=missing-class-docstring
help = "Clear expired access tokens and refresh tokens for Django OAuth Toolkit"
def add_arguments(self, parser):
@@ -41,7 +41,7 @@ class Command(BaseCommand):
default='',
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):
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__)
logger.info(message)
while query_set.exists():
@@ -53,14 +53,14 @@ class Command(BaseCommand):
if query_set.exists():
sleep(sleep_time)
def get_expiration_time(self, now):
def get_expiration_time(self, now): # lint-amnesty, pylint: disable=missing-function-docstring
refresh_token_expire_seconds = oauth2_settings.REFRESH_TOKEN_EXPIRE_SECONDS
if not isinstance(refresh_token_expire_seconds, timedelta):
try:
refresh_token_expire_seconds = timedelta(seconds=refresh_token_expire_seconds)
except TypeError:
e = "REFRESH_TOKEN_EXPIRE_SECONDS must be either a timedelta or seconds"
raise ImproperlyConfigured(e)
raise ImproperlyConfigured(e) # lint-amnesty, pylint: disable=raise-missing-from
return now - refresh_token_expire_seconds
def handle(self, *args, **options):

View File

@@ -40,7 +40,7 @@ class Command(BaseCommand):
'''
def create_parser(self, *args, **kwargs): # pylint: disable=arguments-differ
parser = super(Command, self).create_parser(*args, **kwargs)
parser = super(Command, self).create_parser(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
parser.formatter_class = RawTextHelpFormatter
return parser
@@ -115,7 +115,7 @@ class Command(BaseCommand):
'JWT_AUTH': public_keys,
}
jwt_auth_data['JWT_AUTH'].update(private_keys)
with open(options['output_file'], 'w') as f_out: # pylint: disable=open-builtin
with open(options['output_file'], 'w') as f_out: # lint-amnesty, pylint: disable=bad-option-value, open-builtin
yaml.safe_dump(jwt_auth_data, stream=f_out)
def _generate_key_id(self, size, chars=string.ascii_uppercase + string.digits):

View File

@@ -38,7 +38,7 @@ def counter(fn):
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
class EdxClearExpiredTokensTests(TestCase):
class EdxClearExpiredTokensTests(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
# patching REFRESH_TOKEN_EXPIRE_SECONDS because override_settings not working.
@patch('oauth2_provider.settings.oauth2_settings.REFRESH_TOKEN_EXPIRE_SECONDS', 'xyz')

View File

@@ -21,11 +21,11 @@ class TestCreateDotApplication(TestCase):
Tests the ``create_dot_application`` management command.
"""
def setUp(self):
super(TestCreateDotApplication, self).setUp()
super(TestCreateDotApplication, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create()
def tearDown(self):
super(TestCreateDotApplication, self).tearDown()
super(TestCreateDotApplication, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments
Application.objects.filter(user=self.user).delete()
def test_update_dot_application(self):

View File

@@ -55,7 +55,7 @@ class TestGenerateJwtSigningKey(TestCase):
for expected in expected_in_output:
assert expected in output_stream.getvalue()
with open(filename) as file_obj: # pylint: disable=open-builtin
with open(filename) as file_obj: # lint-amnesty, pylint: disable=bad-option-value, open-builtin
output_from_yaml = yaml.safe_load(file_obj)
for expected in expected_in_output:
assert expected in output_from_yaml['JWT_AUTH']

View File

@@ -34,7 +34,7 @@ class RestrictedApplication(models.Model):
class Meta:
app_label = 'oauth_dispatch'
def __str__(self):
def __str__(self): # lint-amnesty, pylint: disable=invalid-str-returned
"""
Return a unicode representation of this object
"""
@@ -104,7 +104,7 @@ class ApplicationAccess(models.Model):
return cls.objects.get(application=application).filters
@classmethod
def get_filter_values(cls, application, filter_name):
def get_filter_values(cls, application, filter_name): # lint-amnesty, pylint: disable=missing-function-docstring
filters = cls.get_filters(application=application)
if filters:
for filter_constraint in filters:

View File

@@ -12,7 +12,7 @@ class ApplicationModelScopes(SettingsScopes):
"""
Scopes backend that determines available scopes using the ApplicationAccess model.
"""
def get_available_scopes(self, application=None, request=None, *args, **kwargs):
def get_available_scopes(self, application=None, request=None, *args, **kwargs): # lint-amnesty, pylint: disable=keyword-arg-before-vararg
""" Returns valid scopes configured for the given application. """
try:
application_scopes = ApplicationAccess.get_scopes(application)

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()
super(TestOAuthDispatchAPI, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.adapter = DOTAdapter()
self.user = UserFactory()
self.client = self.adapter.create_public_client(

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()
super(ClientCredentialsTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory()
def test_jwt_access_token(self):

View File

@@ -29,7 +29,7 @@ class DOTAdapterTestCase(TestCase):
Test class for DOTAdapter.
"""
def setUp(self):
super(DOTAdapterTestCase, self).setUp()
super(DOTAdapterTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.adapter = DOTAdapter()
self.user = UserFactory()
self.public_client = self.adapter.create_public_client(

View File

@@ -9,7 +9,7 @@ import datetime
import unittest
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.test import RequestFactory, TestCase
from django.utils import timezone
@@ -32,7 +32,7 @@ class AuthenticateTestCase(TestCase):
"""
def setUp(self):
super(AuthenticateTestCase, self).setUp()
super(AuthenticateTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
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()
super(CustomValidationTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
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()
super(CustomAuthorizationViewTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.dot_adapter = adapters.DOTAdapter()
self.user = UserFactory()
self.client.login(username=self.user.username, password='test')
@@ -96,7 +96,7 @@ class CustomAuthorizationViewTestCase(TestCase):
self.restricted_dot_app = self._create_restricted_app()
self._create_expired_token(self.restricted_dot_app)
def _create_restricted_app(self):
def _create_restricted_app(self): # lint-amnesty, pylint: disable=missing-function-docstring
restricted_app = self.dot_adapter.create_confidential_client(
name='test restricted dot application',
user=self.user,

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()
super(TestClientFactory, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
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()
super(TestAccessTokenFactory, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
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()
super(TestRefreshTokenFactory, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.create()
def test_refresh_token_factory(self):

View File

@@ -1,7 +1,7 @@
""" Tests for OAuth Dispatch's jwt module. """
import itertools
import itertools # lint-amnesty, pylint: disable=unused-import
from datetime import timedelta
import ddt
@@ -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()
super(TestCreateJWTs, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory()
self.default_scopes = ['email', 'profile']

View File

@@ -47,7 +47,7 @@ class AccessTokenLoginMixin(object):
"""
Initialize mixin
"""
super(AccessTokenLoginMixin, self).setUp()
super(AccessTokenLoginMixin, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.login_with_access_token_url = reverse("login_with_access_token")
def login_with_access_token(self, access_token=None):
@@ -83,7 +83,7 @@ class _DispatchingViewTestCase(TestCase):
Subclasses need to define self.url.
"""
def setUp(self):
super(_DispatchingViewTestCase, self).setUp()
super(_DispatchingViewTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
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()
super(TestAccessTokenView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.url = reverse('access_token')
self.view_class = views.AccessTokenView
@@ -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()
super(TestAccessTokenExchangeView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
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()
super(TestAuthorizationView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory()
self.dot_app = self.dot_adapter.create_confidential_client(
name='test dot application',
@@ -493,7 +493,7 @@ class TestViewDispatch(TestCase):
"""
def setUp(self):
super(TestViewDispatch, self).setUp()
super(TestViewDispatch, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.dot_adapter = adapters.DOTAdapter()
self.user = UserFactory()
self.view = views._DispatchingView() # pylint: disable=protected-access
@@ -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()
super(TestRevokeTokenView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
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

@@ -61,7 +61,7 @@ class _DispatchingView(View):
Return the appropriate view from the requested backend.
"""
if backend == self.dot_adapter.backend:
return self.dot_view.as_view()
return self.dot_view.as_view() # lint-amnesty, pylint: disable=no-member
else:
raise KeyError('Failed to dispatch view. Invalid backend {}'.format(backend))
@@ -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)
response = super(AccessTokenView, self).dispatch(request, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
token_type = request.POST.get('token_type',
request.META.get('HTTP_X_TOKEN_TYPE', 'no_token_type_supplied')).lower()

View File

@@ -28,7 +28,7 @@ def get_block_olx(request, usage_key_str):
try:
usage_key = UsageKey.from_string(usage_key_str)
except (ValueError, InvalidKeyError):
raise ValidationError('Invalid usage key')
raise ValidationError('Invalid usage key') # lint-amnesty, pylint: disable=raise-missing-from
if usage_key.block_type in ('course', 'chapter', 'sequential'):
raise ValidationError('Requested XBlock tree is too large - export verticals or their children only')
course_key = usage_key.context_key
@@ -92,7 +92,7 @@ def get_block_exportfs_file(request, usage_key_str, path):
try:
usage_key = UsageKey.from_string(usage_key_str)
except (ValueError, InvalidKeyError):
raise ValidationError('Invalid usage key')
raise ValidationError('Invalid usage key') # lint-amnesty, pylint: disable=raise-missing-from
if usage_key.block_type in ('course', 'chapter', 'sequential'):
raise ValidationError('Requested XBlock tree is too large - export verticals or their children only')
course_key = usage_key.context_key

View File

@@ -18,7 +18,7 @@ class NonCompliantPasswordException(Exception):
Exception that should be raised when a user who is required to be compliant with password policy requirements
is found to have a non-compliant password.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class NonCompliantPasswordWarning(Exception):
@@ -26,7 +26,7 @@ class NonCompliantPasswordWarning(Exception):
Exception that should be raised when a user who will soon be required to be compliant with password policy
requirements is found to have a non-compliant password.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def should_enforce_compliance_on_login():
@@ -70,7 +70,7 @@ def enforce_compliance_on_login(user, password):
return
now = datetime.now(pytz.UTC)
if now >= deadline:
if now >= deadline: # lint-amnesty, pylint: disable=no-else-raise
raise NonCompliantPasswordException(
HTML(_(
u'{strong_tag_open}We recently changed our password requirements{strong_tag_close}{break_line_tag}'

View File

@@ -21,7 +21,7 @@ class PasswordPolicyAwareAdminAuthForm(AdminAuthenticationForm):
"""
Overrides the clean method to allow for the enforcement of password policy requirements.
"""
cleaned_data = super(PasswordPolicyAwareAdminAuthForm, self).clean()
cleaned_data = super(PasswordPolicyAwareAdminAuthForm, self).clean() # lint-amnesty, pylint: disable=super-with-arguments
if password_policy_compliance.should_enforce_compliance_on_login():
try:
@@ -31,6 +31,6 @@ class PasswordPolicyAwareAdminAuthForm(AdminAuthenticationForm):
messages.warning(self.request, six.text_type(e))
except password_policy_compliance.NonCompliantPasswordException as e:
# Prevent the login attempt.
raise ValidationError(six.text_type(e))
raise ValidationError(six.text_type(e)) # lint-amnesty, pylint: disable=raise-missing-from
return cleaned_data

View File

@@ -7,4 +7,4 @@ def plugin_settings(settings): # pylint: disable=unused-argument
"""
Override the default password_policy app settings with development settings.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass

View File

@@ -20,7 +20,7 @@ class PasswordPolicyAwareAdminAuthFormTests(TestCase):
Tests the custom form for enforcing password policy rules
"""
def setUp(self):
super(PasswordPolicyAwareAdminAuthFormTests, self).setUp()
super(PasswordPolicyAwareAdminAuthFormTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.auth_form = PasswordPolicyAwareAdminAuthForm()
self.user = UserFactory.create(username='test_user', password='test_password', is_staff=True)
self.auth_form.cleaned_data = {