Merge pull request #26323 from edx/bom-2314

Applied pylint-amnesty to openedx/core/{djangolib, lib, tests, *.py
This commit is contained in:
Jawayria
2021-02-03 18:46:02 +05:00
committed by GitHub
51 changed files with 117 additions and 116 deletions

View File

@@ -1,4 +1,4 @@
"""
""" # lint-amnesty, pylint: disable=django-not-configured
Open API support.
"""

View File

@@ -102,7 +102,7 @@ class BundleCache(object):
cache.delete(cache_key)
def _construct_versioned_cache_key(bundle_uuid, version_num, key_parts, draft_name=None):
def _construct_versioned_cache_key(bundle_uuid, version_num, key_parts, draft_name=None): # lint-amnesty, pylint: disable=missing-function-docstring
cache_key = str(bundle_uuid)
if draft_name:
cache_key += ":" + draft_name

View File

@@ -48,7 +48,7 @@ class BigAutoField(models.AutoField):
elif "postgres" in conn_module:
return "bigserial"
else:
return super(BigAutoField, self).db_type(connection)
return super(BigAutoField, self).db_type(connection) # lint-amnesty, pylint: disable=super-with-arguments
def rel_db_type(self, connection):
"""

View File

@@ -69,7 +69,7 @@ def dump_js_escaped_json(obj, cls=EdxJSONEncoder):
(string) Escaped encoded JSON.
"""
obj = list(obj) if isinstance(obj, type({}.values())) else obj
obj = list(obj) if isinstance(obj, type({}.values())) else obj # lint-amnesty, pylint: disable=isinstance-second-argument-not-valid-type
json_string = json.dumps(obj, ensure_ascii=True, cls=cls)
json_string = _escape_json_for_js(json_string)
return json_string

View File

@@ -19,7 +19,7 @@ class TestGetMockRequest(TestCase):
"""
Validate the behavior of get_mock_request
"""
def setUp(self):
def setUp(self): # lint-amnesty, pylint: disable=super-method-not-called
self.addCleanup(set_current_request, None)
def test_mock_request_is_request(self):

View File

@@ -59,7 +59,7 @@ class CacheIsolationMixin(object):
super(CacheIsolationMixin, cls).tearDownClass()
def setUp(self):
super(CacheIsolationMixin, self).setUp()
super(CacheIsolationMixin, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.clear_caches()
self.addCleanup(self.clear_caches)
@@ -165,7 +165,7 @@ class _AssertNumQueriesContext(CaptureQueriesContext):
self.test_case = test_case
self.num = num
self.table_blacklist = table_blacklist
super(_AssertNumQueriesContext, self).__init__(connection)
super(_AssertNumQueriesContext, self).__init__(connection) # lint-amnesty, pylint: disable=super-with-arguments
def __exit__(self, exc_type, exc_value, traceback):
def is_unfiltered_query(query):
@@ -185,7 +185,7 @@ class _AssertNumQueriesContext(CaptureQueriesContext):
return False
return True
super(_AssertNumQueriesContext, self).__exit__(exc_type, exc_value, traceback)
super(_AssertNumQueriesContext, self).__exit__(exc_type, exc_value, traceback) # lint-amnesty, pylint: disable=super-with-arguments
if exc_type is not None:
return
filtered_queries = [query for query in self.captured_queries if is_unfiltered_query(query)]
@@ -207,7 +207,7 @@ class FilteredQueryCountMixin(object):
assertNumQueries with one that accepts a blacklist of tables to filter out
of the count.
"""
def assertNumQueries(self, num, func=None, table_blacklist=None, *args, **kwargs):
def assertNumQueries(self, num, func=None, table_blacklist=None, *args, **kwargs): # lint-amnesty, pylint: disable=keyword-arg-before-vararg
"""
Used to replace Django's assertNumQueries with the same capability, with
the addition of the following argument:

View File

@@ -1,4 +1,4 @@
# pylint: disable=unicode-format-string
# lint-amnesty, pylint: disable=bad-option-value, unicode-format-string
# -*- coding: utf-8 -*-
"""
Tests for js_utils.py
@@ -32,7 +32,7 @@ class TestJSUtils(TestCase):
A test encoder that is used to prove that the encoder does its job before the escaping.
"""
# pylint: disable=method-hidden
def default(self, noDefaultEncodingObj):
def default(self, noDefaultEncodingObj): # lint-amnesty, pylint: disable=arguments-differ
return noDefaultEncodingObj.value.replace("<script>", "sample-encoder-was-here")
def test_dump_js_escaped_json_escapes_unsafe_html(self):

View File

@@ -17,7 +17,7 @@ from common.djangoapps.student.tests.factories import UserFactory
from ..oauth2_retirement_utils import retire_dot_oauth2_models
class RetireDOTModelsTest(TestCase):
class RetireDOTModelsTest(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def test_delete_dot_models(self):
user = UserFactory.create()

View File

@@ -3,7 +3,7 @@ i18n utility functions
"""
from django.utils.translation import ugettext as _, override
from django.utils.translation import ugettext as _, override # lint-amnesty, pylint: disable=unused-import
from django.utils.formats import dateformat, get_format

View File

@@ -43,7 +43,7 @@ class BearerAuthentication(BaseAuthentication):
set_custom_attribute("BearerAuthentication", "Failed") # default value
auth = get_authorization_header(request).split()
if len(auth) == 1:
if len(auth) == 1: # lint-amnesty, pylint: disable=no-else-raise
raise AuthenticationFailed({
'error_code': OAUTH2_TOKEN_ERROR_NOT_PROVIDED,
'developer_message': 'Invalid token header. No credentials provided.'})
@@ -75,12 +75,12 @@ class BearerAuthentication(BaseAuthentication):
try:
token = self.get_access_token(access_token)
except AuthenticationFailed as exc:
raise AuthenticationFailed({
raise AuthenticationFailed({ # lint-amnesty, pylint: disable=raise-missing-from
u'error_code': OAUTH2_TOKEN_ERROR,
u'developer_message': exc.detail
})
if not token:
if not token: # lint-amnesty, pylint: disable=no-else-raise
raise AuthenticationFailed({
'error_code': OAUTH2_TOKEN_ERROR_NONEXISTENT,
'developer_message': 'The provided access token does not match any valid tokens.'
@@ -100,7 +100,7 @@ class BearerAuthentication(BaseAuthentication):
'developer_message': msg})
# Check to make sure the users have activated their account (by confirming their email)
if not self.allow_inactive_users and not user.is_active:
if not self.allow_inactive_users and not user.is_active: # lint-amnesty, pylint: disable=no-else-raise
set_custom_attribute("BearerAuthentication_user_active", False)
msg = 'User inactive or deleted: %s' % user.get_username()
raise AuthenticationFailed({

View File

@@ -3,7 +3,7 @@
from rest_framework.serializers import Field, URLField
class ExpandableField(Field):
class ExpandableField(Field): # lint-amnesty, pylint: disable=abstract-method
"""Field that can dynamically use a more detailed serializer based on a user-provided "expand" parameter.
Kwargs:
@@ -16,9 +16,9 @@ class ExpandableField(Field):
assert 'collapsed_serializer' in kwargs and 'expanded_serializer' in kwargs
self.collapsed = kwargs.pop('collapsed_serializer')
self.expanded = kwargs.pop('expanded_serializer')
super(ExpandableField, self).__init__(**kwargs)
super(ExpandableField, self).__init__(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def to_representation(self, obj):
def to_representation(self, obj): # lint-amnesty, pylint: disable=arguments-differ
"""
Return a representation of the field that is either expanded or collapsed.
"""

View File

@@ -22,11 +22,11 @@ class PutAsCreateMixin(CreateModelMixin):
# First, try to update the existing instance
try:
try:
return super(PutAsCreateMixin, self).update(request, *args, **kwargs)
return super(PutAsCreateMixin, self).update(request, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
except Http404:
# If no instance exists yet, create it.
# This is backwards-compatible with the behavior of DRF v2.
return super(PutAsCreateMixin, self).create(request, *args, **kwargs)
return super(PutAsCreateMixin, self).create(request, *args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
# Backwards compatibility with DRF v2 behavior, which would catch model-level
# validation errors and return a 400

View File

@@ -75,7 +75,7 @@ class TypedFileUploadParser(FileUploadParser):
u'Filename: "{filename}", Content-type: "{contenttype}"'
)
raise ParseError(errmsg.format(filename=filename, contenttype=media_type))
return super(TypedFileUploadParser, self).parse(stream, media_type, parser_context)
return super(TypedFileUploadParser, self).parse(stream, media_type, parser_context) # lint-amnesty, pylint: disable=super-with-arguments
class MergePatchParser(JSONParser):

View File

@@ -94,7 +94,7 @@ class IsMasterCourseStaffInstructor(permissions.BasePermission):
try:
course_key = CourseKey.from_string(master_course_id)
except InvalidKeyError:
raise Http404()
raise Http404() # lint-amnesty, pylint: disable=raise-missing-from
return (hasattr(request, 'user') and
(CourseInstructorRole(course_key).has_user(request.user) or
CourseStaffRole(course_key).has_user(request.user)))

View File

@@ -13,7 +13,7 @@ class CollapsedReferenceSerializer(serializers.HyperlinkedModelSerializer):
"""Serializes arbitrary models in a collapsed format, with just an id and url."""
url = serializers.HyperlinkedIdentityField(view_name='')
def __init__(self, model_class, view_name, id_source='id', lookup_field=None, *args, **kwargs):
def __init__(self, model_class, view_name, id_source='id', lookup_field=None, *args, **kwargs): # lint-amnesty, pylint: disable=keyword-arg-before-vararg
"""Configures the serializer.
Args:
@@ -32,7 +32,7 @@ class CollapsedReferenceSerializer(serializers.HyperlinkedModelSerializer):
self.Meta.model = model_class
super(CollapsedReferenceSerializer, self).__init__(*args, **kwargs)
super(CollapsedReferenceSerializer, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.fields[id_source] = serializers.CharField(read_only=True)
self.fields['url'].view_name = view_name
@@ -46,7 +46,7 @@ class CollapsedReferenceSerializer(serializers.HyperlinkedModelSerializer):
class CourseKeyField(serializers.Field):
""" Serializer field for a model CourseKey field. """
def to_representation(self, data):
def to_representation(self, data): # lint-amnesty, pylint: disable=arguments-differ
"""Convert a course key to unicode. """
return six.text_type(data)
@@ -55,13 +55,13 @@ class CourseKeyField(serializers.Field):
try:
return CourseKey.from_string(data)
except InvalidKeyError as ex:
raise serializers.ValidationError(u"Invalid course key: {msg}".format(msg=ex.msg))
raise serializers.ValidationError(u"Invalid course key: {msg}".format(msg=ex.msg)) # lint-amnesty, pylint: disable=no-member
class UsageKeyField(serializers.Field):
""" Serializer field for a model UsageKey field. """
def to_representation(self, data):
def to_representation(self, data): # lint-amnesty, pylint: disable=arguments-differ
"""Convert a usage key to unicode. """
return six.text_type(data)
@@ -70,4 +70,4 @@ class UsageKeyField(serializers.Field):
try:
return UsageKey.from_string(data)
except InvalidKeyError as ex:
raise serializers.ValidationError(u"Invalid usage key: {msg}".format(msg=ex.msg))
raise serializers.ValidationError(u"Invalid usage key: {msg}".format(msg=ex.msg)) # lint-amnesty, pylint: disable=no-member

View File

@@ -11,8 +11,8 @@ from datetime import timedelta
import ddt
from django.conf import settings
from django.conf.urls import include, url
from django.contrib.auth.models import User
from django.conf.urls import include, url # lint-amnesty, pylint: disable=unused-import
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.http import HttpResponse
from django.test import TestCase
from django.test.utils import override_settings
@@ -58,11 +58,11 @@ urlpatterns = [
@ddt.ddt # pylint: disable=missing-docstring
@unittest.skipUnless(settings.FEATURES.get("ENABLE_OAUTH2_PROVIDER"), "OAuth2 not enabled")
@override_settings(ROOT_URLCONF=__name__)
class OAuth2AllowInActiveUsersTests(TestCase):
class OAuth2AllowInActiveUsersTests(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
OAUTH2_BASE_TESTING_URL = '/oauth2-inactive-test/'
def setUp(self):
super(OAuth2AllowInActiveUsersTests, self).setUp()
super(OAuth2AllowInActiveUsersTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.dot_adapter = adapters.DOTAdapter()
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.username = 'john'
@@ -219,12 +219,12 @@ class OAuth2AllowInActiveUsersTests(TestCase):
self.check_error_codes(response, status_code=status.HTTP_401_UNAUTHORIZED, error_code=token_error.error_code)
class BearerAuthenticationTests(OAuth2AllowInActiveUsersTests): # pylint: disable=test-inherits-tests
class BearerAuthenticationTests(OAuth2AllowInActiveUsersTests): # lint-amnesty, pylint: disable=missing-class-docstring, test-inherits-tests
OAUTH2_BASE_TESTING_URL = '/oauth2-test/'
def setUp(self):
super(BearerAuthenticationTests, self).setUp()
super(BearerAuthenticationTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
# Since this is testing back to previous version, user should be set to true
self.user.is_active = True
self.user.save()

View File

@@ -20,7 +20,7 @@ class AbsoluteURLFieldTests(TestCase):
""" Tests for the AbsoluteURLField. """
def setUp(self):
super(AbsoluteURLFieldTests, self).setUp()
super(AbsoluteURLFieldTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.field = AbsoluteURLField()
self.field._context = {'request': MockRequest()} # pylint:disable=protected-access

View File

@@ -18,7 +18,7 @@ class TestTypedFileUploadParser(APITestCase):
"""
def setUp(self):
super(TestTypedFileUploadParser, self).setUp()
super(TestTypedFileUploadParser, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.parser = parsers.TypedFileUploadParser()
self.request_factory = APIRequestFactory()
upload_media_types = {'image/png', 'image/jpeg', 'application/octet-stream'}
@@ -86,8 +86,8 @@ class TestTypedFileUploadParser(APITestCase):
context = {'view': self.view, 'request': request}
with self.assertRaises(exceptions.ParseError) as err:
self.parser.parse(stream=BytesIO(b'abcdefgh'), media_type='image/png', parser_context=context)
self.assertIn('developer_message', err.detail)
self.assertNotIn('user_message', err.detail)
self.assertIn('developer_message', err.detail) # lint-amnesty, pylint: disable=no-member
self.assertNotIn('user_message', err.detail) # lint-amnesty, pylint: disable=no-member
def test_no_acceptable_types(self):
"""
@@ -105,5 +105,5 @@ class TestTypedFileUploadParser(APITestCase):
context = {'view': view, 'request': request}
with self.assertRaises(exceptions.UnsupportedMediaType) as err:
self.parser.parse(stream=BytesIO(b'abcdefgh'), media_type='image/png', parser_context=context)
self.assertIn('developer_message', err.detail)
self.assertIn('user_message', err.detail)
self.assertIn('developer_message', err.detail) # lint-amnesty, pylint: disable=no-member
self.assertIn('user_message', err.detail) # lint-amnesty, pylint: disable=no-member

View File

@@ -23,7 +23,7 @@ class TestObject(object):
class TestCcxObject(TestObject):
""" Fake class for object permission for CCX Courses """
def __init__(self, user=None, course_id=None):
super(TestCcxObject, self).__init__(user, course_id)
super(TestCcxObject, self).__init__(user, course_id) # lint-amnesty, pylint: disable=super-with-arguments
self.coach = user
@@ -31,7 +31,7 @@ class IsCourseStaffInstructorTests(TestCase):
""" Test for IsCourseStaffInstructor permission class. """
def setUp(self):
super(IsCourseStaffInstructorTests, self).setUp()
super(IsCourseStaffInstructorTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.permission = IsCourseStaffInstructor()
self.coach = UserFactory()
self.user = UserFactory()
@@ -64,7 +64,7 @@ class IsMasterCourseStaffInstructorTests(TestCase):
""" Test for IsMasterCourseStaffInstructorTests permission class. """
def setUp(self):
super(IsMasterCourseStaffInstructorTests, self).setUp()
super(IsMasterCourseStaffInstructorTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.permission = IsMasterCourseStaffInstructor()
master_course_id = 'edx/test123/run'
self.user = UserFactory()
@@ -109,7 +109,7 @@ class IsStaffOrOwnerTests(TestCase):
""" Tests for IsStaffOrOwner permission class. """
def setUp(self):
super(IsStaffOrOwnerTests, self).setUp()
super(IsStaffOrOwnerTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.permission = IsStaffOrOwner()
self.request = RequestFactory().get('/')
self.obj = TestObject()

View File

@@ -2,7 +2,7 @@
Utilities related to API views
"""
from collections import Sequence
from collections import Sequence # lint-amnesty, pylint: disable=no-name-in-module
from functools import wraps
from django.core.exceptions import NON_FIELD_ERRORS, ObjectDoesNotExist, ValidationError
@@ -35,7 +35,7 @@ class DeveloperErrorResponseException(Exception):
Intended to be used with and by DeveloperErrorViewMixin.
"""
def __init__(self, response):
super(DeveloperErrorResponseException, self).__init__()
super(DeveloperErrorResponseException, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self.response = response
@@ -92,12 +92,12 @@ class DeveloperErrorViewMixin(object):
return exc.response
elif isinstance(exc, APIException):
return self._make_error_response(exc.status_code, exc.detail)
elif isinstance(exc, Http404) or isinstance(exc, ObjectDoesNotExist):
elif isinstance(exc, Http404) or isinstance(exc, ObjectDoesNotExist): # lint-amnesty, pylint: disable=consider-merging-isinstance
return self._make_error_response(404, text_type(exc) or "Not found.")
elif isinstance(exc, ValidationError):
return self._make_validation_error_response(exc)
else:
raise
raise # lint-amnesty, pylint: disable=misplaced-bare-raise
class ExpandableFieldViewMixin(object):
@@ -105,7 +105,7 @@ class ExpandableFieldViewMixin(object):
def get_serializer_context(self):
"""Adds expand information from query parameters to the serializer context to support expandable fields."""
result = super(ExpandableFieldViewMixin, self).get_serializer_context()
result = super(ExpandableFieldViewMixin, self).get_serializer_context() # lint-amnesty, pylint: disable=super-with-arguments
result['expand'] = [x for x in self.request.query_params.get('expand', '').split(',') if x]
return result
@@ -156,7 +156,7 @@ def add_serializer_errors(serializer, data, field_errors):
for key, error in iteritems(errors):
error = clean_errors(error)
if key == 'bio':
user_message = _(u"The about me field must be at most {} characters long.".format(BIO_MAX_LENGTH))
user_message = _(u"The about me field must be at most {} characters long.".format(BIO_MAX_LENGTH)) # lint-amnesty, pylint: disable=translation-of-non-string
else:
user_message = _(u"This value is invalid.")
@@ -180,7 +180,7 @@ def build_api_error(message, **kwargs):
"""
return {
'developer_message': message.format(**kwargs),
'user_message': _(message).format(**kwargs),
'user_message': _(message).format(**kwargs), # lint-amnesty, pylint: disable=translation-of-non-string
}
@@ -290,7 +290,7 @@ class LazySequence(Sequence):
self._data.append(next(self.iterable))
except StopIteration:
self._exhausted = True
raise IndexError("Underlying sequence exhausted")
raise IndexError("Underlying sequence exhausted") # lint-amnesty, pylint: disable=raise-missing-from
return self._data[index]
elif isinstance(index, slice):
@@ -346,10 +346,10 @@ class PaginatedAPIView(APIView):
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
if self.pagination_class is None: # lint-amnesty, pylint: disable=no-member
self._paginator = None
else:
self._paginator = self.pagination_class()
self._paginator = self.pagination_class() # lint-amnesty, pylint: disable=no-member
return self._paginator
def paginate_queryset(self, queryset):
@@ -417,7 +417,7 @@ def verify_course_exists(view_func):
try:
course_key = get_course_key(request, kwargs.get('course_id'))
except InvalidKeyError:
raise self.api_error(
raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from
status_code=status.HTTP_404_NOT_FOUND,
developer_message='The provided course key cannot be parsed.',
error_code='invalid_course_key'

View File

@@ -115,7 +115,7 @@ def get_collection(collection_uuid):
try:
data = api_request('get', api_url('collections', str(collection_uuid)))
except NotFound:
raise CollectionNotFound("Collection {} does not exist.".format(collection_uuid))
raise CollectionNotFound("Collection {} does not exist.".format(collection_uuid)) # lint-amnesty, pylint: disable=raise-missing-from
return _collection_from_response(data)
@@ -170,7 +170,7 @@ def get_bundle(bundle_uuid):
try:
data = api_request('get', api_url('bundles', str(bundle_uuid)))
except NotFound:
raise BundleNotFound("Bundle {} does not exist.".format(bundle_uuid))
raise BundleNotFound("Bundle {} does not exist.".format(bundle_uuid)) # lint-amnesty, pylint: disable=raise-missing-from
return _bundle_from_response(data)
@@ -224,7 +224,7 @@ def get_draft(draft_uuid):
try:
data = api_request('get', api_url('drafts', str(draft_uuid)))
except NotFound:
raise DraftNotFound("Draft does not exist: {}".format(draft_uuid))
raise DraftNotFound("Draft does not exist: {}".format(draft_uuid)) # lint-amnesty, pylint: disable=raise-missing-from
return _draft_from_response(data)
@@ -353,7 +353,7 @@ def get_bundle_file_metadata(bundle_uuid, path, use_draft=None):
try:
return files_dict[path]
except KeyError:
raise BundleFileNotFound(
raise BundleFileNotFound( # lint-amnesty, pylint: disable=raise-missing-from
"Bundle {} (draft: {}) does not contain a file {}".format(bundle_uuid, use_draft, path)
)

View File

@@ -47,4 +47,4 @@ def parse_course_keys(course_key_strings):
try:
return [CourseKey.from_string(course_key_string) for course_key_string in course_key_strings]
except InvalidKeyError as error:
raise CommandError(u'Invalid key specified: {}'.format(text_type(error)))
raise CommandError(u'Invalid key specified: {}'.format(text_type(error))) # lint-amnesty, pylint: disable=raise-missing-from

View File

@@ -3,7 +3,7 @@ Tabs for courseware.
"""
from edx_django_utils.plugins import PluginManager
from functools import cmp_to_key
from functools import cmp_to_key # lint-amnesty, pylint: disable=wrong-import-order
# Stevedore extension point namespaces

View File

@@ -76,7 +76,7 @@ def clean_course_id(model_form, is_required=True):
course_key = CourseKey.from_string(cleaned_id)
except InvalidKeyError:
msg = u'Course id invalid. Entered course id was: "{0}".'.format(cleaned_id)
raise forms.ValidationError(msg)
raise forms.ValidationError(msg) # lint-amnesty, pylint: disable=raise-missing-from
if not modulestore().has_course(course_key):
msg = u'Course not found. Entered course id was: "{0}".'.format(text_type(course_key))

View File

@@ -47,7 +47,7 @@ def derive_settings(module_name):
module_name (str): Name of module to which the derived settings will be added.
"""
module = sys.modules[module_name]
for derived in __DERIVED:
for derived in __DERIVED: # lint-amnesty, pylint: disable=redefined-outer-name
if isinstance(derived, six.string_types):
setting = getattr(module, derived)
if callable(setting):

View File

@@ -12,4 +12,4 @@ class OptimizedCachedRequireJsStorage(OptimizedFilesMixin, PipelineForgivingMixi
"""
Custom storage backend that is used by Django-require.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass

View File

@@ -9,18 +9,18 @@ class CourseNotFoundError(ObjectDoesNotExist):
"""
Course was not found.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class PageNotFoundError(ObjectDoesNotExist):
"""
Page was not found. Used for paginated endpoint.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class DiscussionNotFoundError(ObjectDoesNotExist):
"""
Discussion Module was not found.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass

View File

@@ -51,7 +51,7 @@ def safemembers(members, base):
raise SuspiciousOperation("Attempted to import course outside of data dir")
for finfo in members:
if _is_bad_path(finfo.name, base):
if _is_bad_path(finfo.name, base): # lint-amnesty, pylint: disable=no-else-raise
log.debug(u"File %r is blocked (illegal path)", finfo.name)
raise SuspiciousOperation("Illegal path")
elif finfo.issym() and _is_bad_link(finfo, base):

View File

@@ -6,7 +6,7 @@ import json
import logging
from completion.models import BlockCompletion
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.urls import reverse
from django.utils.translation import ugettext as _
from milestones import api as milestones_api
@@ -72,7 +72,7 @@ def _validate_min_score(min_score):
try:
min_score = int(min_score)
except ValueError:
raise GatingValidationError(message)
raise GatingValidationError(message) # lint-amnesty, pylint: disable=raise-missing-from
if min_score < 0 or min_score > 100:
raise GatingValidationError(message)

View File

@@ -7,4 +7,4 @@ class GatingValidationError(Exception):
"""
Exception class for validation errors related to course gating information
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass

View File

@@ -37,7 +37,7 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
"""
Initial data setup
"""
super(TestGatingApi, self).setUp()
super(TestGatingApi, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
# create course
self.course = CourseFactory.create(

View File

@@ -116,7 +116,7 @@ from collections import deque
def traverse_topologically(
start_node,
get_parents,
get_children,
get_children, # lint-amnesty, pylint: disable=redefined-outer-name
filter_func=None,
yield_descendants_of_unyielded=False,
):
@@ -161,7 +161,7 @@ def traverse_topologically(
)
def traverse_pre_order(start_node, get_children, filter_func=None):
def traverse_pre_order(start_node, get_children, filter_func=None): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Generator for yielding nodes of a tree (or directed acyclic graph)
in a pre-order sort.
@@ -178,7 +178,7 @@ def traverse_pre_order(start_node, get_children, filter_func=None):
)
def traverse_post_order(start_node, get_children, filter_func=None):
def traverse_post_order(start_node, get_children, filter_func=None): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Generator for yielding nodes of a tree (or directed acyclic graph)
in a post-order sort.
@@ -192,7 +192,7 @@ def traverse_post_order(start_node, get_children, filter_func=None):
An active iterator is needed in order to determine when all
children are visited and so the node itself should be visited.
"""
def __init__(self, node, get_children):
def __init__(self, node, get_children): # lint-amnesty, pylint: disable=redefined-outer-name
self.node = node
self.children = iter(get_children(node))
@@ -237,7 +237,7 @@ def traverse_post_order(start_node, get_children, filter_func=None):
def _traverse_generic(
start_node,
get_parents,
get_children,
get_children, # lint-amnesty, pylint: disable=redefined-outer-name
filter_func=None,
yield_descendants_of_unyielded=False,
):

View File

@@ -28,4 +28,4 @@ class EdxJSONEncoder(DjangoJSONEncoder):
else:
return o.isoformat()
else:
return super(EdxJSONEncoder, self).default(o)
return super(EdxJSONEncoder, self).default(o) # lint-amnesty, pylint: disable=super-with-arguments

View File

@@ -1,2 +1,3 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from .mixin import LicenseMixin
from .wrapper import wrap_with_license

View File

@@ -10,7 +10,7 @@ from logging.handlers import SysLogHandler
LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
def get_logger_config(log_dir,
def get_logger_config(log_dir, # lint-amnesty, pylint: disable=unused-argument
logging_env="no_env",
local_loglevel='INFO',
service_variant=""):

View File

@@ -2,7 +2,7 @@
Custom session serializer to deal with going from python2 and python3.
"""
import pickle
import six
import six # lint-amnesty, pylint: disable=unused-import
class PickleSerializer(object):

View File

@@ -148,7 +148,7 @@ class TeamsConfig(object):
try:
teamset = self.teamsets_by_id[teamset_id]
except KeyError:
raise ValueError("Team-set {!r} does not exist.".format(teamset_id))
raise ValueError("Team-set {!r} does not exist.".format(teamset_id)) # lint-amnesty, pylint: disable=raise-missing-from
if teamset.teamset_type != TeamsetType.open:
return MANAGED_TEAM_MAX_TEAM_SIZE
if teamset.max_team_size:

View File

@@ -18,7 +18,7 @@ class TestRequestCachedDecorator(TestCase):
"""
Test the request_cached decorator.
"""
def setUp(self):
def setUp(self): # lint-amnesty, pylint: disable=super-method-not-called
RequestCache.clear_all_namespaces()
def test_request_cached_miss_and_then_hit(self):
@@ -33,7 +33,7 @@ class TestRequestCachedDecorator(TestCase):
"""Simple wrapper to let us decorate our mock."""
return to_be_wrapped(*args, **kwargs)
wrapped = request_cached()(mock_wrapper)
wrapped = request_cached()(mock_wrapper) # lint-amnesty, pylint: disable=no-value-for-parameter
result = wrapped()
self.assertEqual(result, 42)
self.assertEqual(to_be_wrapped.call_count, 1)
@@ -54,7 +54,7 @@ class TestRequestCachedDecorator(TestCase):
"""Simple wrapper to let us decorate our mock."""
return to_be_wrapped(*args, **kwargs)
wrapped = request_cached()(mock_wrapper)
wrapped = request_cached()(mock_wrapper) # lint-amnesty, pylint: disable=no-value-for-parameter
result = wrapped()
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 1)
@@ -88,7 +88,7 @@ class TestRequestCachedDecorator(TestCase):
"""Simple wrapper to let us decorate our mock."""
return to_be_wrapped(*args, **kwargs)
wrapped = request_cached()(mock_wrapper)
wrapped = request_cached()(mock_wrapper) # lint-amnesty, pylint: disable=no-value-for-parameter
# This will be a miss, and make an underlying call.
result = wrapped(1)
@@ -127,7 +127,7 @@ class TestRequestCachedDecorator(TestCase):
"""Simple wrapper to let us decorate our mock."""
return to_be_wrapped(*args, **kwargs)
wrapped = request_cached()(mock_wrapper)
wrapped = request_cached()(mock_wrapper) # lint-amnesty, pylint: disable=no-value-for-parameter
# This will be a miss, and make an underlying call.
result = wrapped(1, foo=1)
@@ -183,7 +183,7 @@ class TestRequestCachedDecorator(TestCase):
self.assertTrue(dummy_function('Hello', u'World'), 'Should be callable with ASCII chars')
self.assertTrue(dummy_function('H∂llå', u'Wørld'), 'Should be callable with non-ASCII chars')
wrapped = request_cached()(dummy_function)
wrapped = request_cached()(dummy_function) # lint-amnesty, pylint: disable=no-value-for-parameter
self.assertTrue(wrapped('Hello', u'World'), 'Wrapper should handle ASCII only chars')
self.assertTrue(wrapped('H∂llå', u'Wørld'), 'Wrapper should handle non-ASCII chars')
@@ -202,7 +202,7 @@ class TestRequestCachedDecorator(TestCase):
"""Simple wrapper to let us decorate our mock."""
return to_be_wrapped(*args, **kwargs)
wrapped = request_cached()(mock_wrapper)
wrapped = request_cached()(mock_wrapper) # lint-amnesty, pylint: disable=no-value-for-parameter
# This will be a miss, and make an underlying call.
result = wrapped(1)
@@ -242,7 +242,7 @@ class TestRequestCachedDecorator(TestCase):
return to_be_wrapped(*args, **kwargs)
request_cache_getter = lambda args, kwargs: RequestCache('test')
wrapped = request_cached(request_cache_getter=request_cache_getter)(mock_wrapper)
wrapped = request_cached(request_cache_getter=request_cache_getter)(mock_wrapper) # lint-amnesty, pylint: disable=no-value-for-parameter
# This will be a miss, and make an underlying call.
result = wrapped(1)
@@ -277,7 +277,7 @@ class TestRequestCachedDecorator(TestCase):
return to_be_wrapped(*args, **kwargs)
arg_map_function = lambda arg: six.text_type(arg == 1)
wrapped = request_cached(arg_map_function=arg_map_function)(mock_wrapper)
wrapped = request_cached(arg_map_function=arg_map_function)(mock_wrapper) # lint-amnesty, pylint: disable=no-value-for-parameter
# This will be a miss, and make an underlying call.
result = wrapped(1)

View File

@@ -42,7 +42,7 @@ class KeyCheckerTestCase(TestCase):
"""Test cases for KeyChecker class"""
def setUp(self):
super(KeyCheckerTestCase, self).setUp()
super(KeyCheckerTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.valid_keys = ['a', 'b']
self.invalid_keys = ['a', 'v', 'g']
@@ -60,7 +60,7 @@ class NeedNameTestCase(TestCase):
"""Test cases for NeedName validator"""
def setUp(self):
super(NeedNameTestCase, self).setUp()
super(NeedNameTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.valid_dict1 = {'a': 1, 'name': 2}
self.valid_dict2 = {'name': 1}

View File

@@ -13,7 +13,7 @@ class TestDerivedSettings(TestCase):
Test settings that are derived from other settings.
"""
def setUp(self):
super(TestDerivedSettings, self).setUp()
super(TestDerivedSettings, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
clear_for_tests()
self.module = sys.modules[__name__]
self.module.SIMPLE_VALUE = 'paneer'

View File

@@ -26,7 +26,7 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
ENABLED_CACHES = ['default']
def setUp(self):
super(TestGetEdxApiData, self).setUp()
super(TestGetEdxApiData, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory()

View File

@@ -31,7 +31,7 @@ class TestGraphTraversals(TestCase):
# e1 e2
# |
# f1
super(TestGraphTraversals, self).setUp()
super(TestGraphTraversals, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.parent_to_children_map = {
'a1': ['b1'],
'a2': ['b2'],

View File

@@ -21,12 +21,12 @@ class RequestUtilTestCase(unittest.TestCase):
Tests for request_utils module.
"""
def setUp(self):
super(RequestUtilTestCase, self).setUp()
super(RequestUtilTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.old_site_name = settings.SITE_NAME
self.old_allowed_hosts = settings.ALLOWED_HOSTS
def tearDown(self):
super(RequestUtilTestCase, self).tearDown()
super(RequestUtilTestCase, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments
settings.SITE_NAME = self.old_site_name
settings.ALLOWED_HOSTS = self.old_allowed_hosts

View File

@@ -17,7 +17,7 @@ class TestTimeZoneUtils(TestCase):
"""
Sets up user for testing with time zone utils.
"""
super(TestTimeZoneUtils, self).setUp()
super(TestTimeZoneUtils, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user = UserFactory.build()
self.user.save()

View File

@@ -14,7 +14,7 @@ class XForwardedForMiddleware(MiddlewareMixin):
"""
def process_request(self, request):
def process_request(self, request): # lint-amnesty, pylint: disable=useless-return
"""
Process the given request, update the value of REMOTE_ADDR, SERVER_NAME and SERVER_PORT based
on X-Forwarded-For, HTTP_HOST and X-Forwarded-Port headers

View File

@@ -66,7 +66,7 @@ class DiscussionXBlockImportExportTests(TestCase):
"""
Set up method
"""
super(DiscussionXBlockImportExportTests, self).setUp()
super(DiscussionXBlockImportExportTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.keys = ScopeIds("any_user", "discussion", "def_id", "usage_id")
self.runtime_mock = mock.Mock(spec=Runtime)
self.runtime_mock.construct_xblock_from_class = mock.Mock(side_effect=self._construct_xblock_mock)

View File

@@ -36,7 +36,7 @@ def _(text):
@XBlock.needs('user') # pylint: disable=abstract-method
@XBlock.needs('i18n')
class DiscussionXBlock(XBlock, StudioEditableXBlockMixin, XmlParserMixin):
class DiscussionXBlock(XBlock, StudioEditableXBlockMixin, XmlParserMixin): # lint-amnesty, pylint: disable=abstract-method
"""
Provides a discussion forum that is inline with other content in the courseware.
"""

View File

@@ -27,7 +27,7 @@ class XBlockPackageStorage(Storage):
"""
Returns a static file storage if available in the given app.
"""
super(XBlockPackageStorage, self).__init__(*args, **kwargs)
super(XBlockPackageStorage, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.module = module
self.base_dir = base_dir
@@ -40,7 +40,7 @@ class XBlockPackageStorage(Storage):
"""
return resource_filename(self.module, os.path.join(self.base_dir, name))
def exists(self, path):
def exists(self, path): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns True if the specified path exists.
"""
@@ -108,7 +108,7 @@ class XBlockPackageStorage(Storage):
raise NotImplementedError("Deleting files from a package is not supported")
class XBlockPipelineFinder(BaseFinder):
class XBlockPipelineFinder(BaseFinder): # lint-amnesty, pylint: disable=abstract-method
"""
A static files finder that gets static assets from xblocks.
"""
@@ -119,7 +119,7 @@ class XBlockPipelineFinder(BaseFinder):
initialization happens, we just proxy all list()/find() requests by
iterating through the XBlockPackageStorage objects.
"""
super(XBlockPipelineFinder, self).__init__(*args, **kwargs)
super(XBlockPipelineFinder, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
# xblock_resource_info holds (package_name, resources_dir) tuples. While
# it never happens in practice, the XBlock API does allow different

View File

@@ -15,7 +15,7 @@ import six
import webpack_loader.utils
from contracts import contract
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.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from django.utils.html import escape
@@ -438,7 +438,7 @@ def get_course_update_items(course_updates, provided_index=0):
try:
course_html_parsed = html.fromstring(course_updates.data)
except (etree.XMLSyntaxError, etree.ParserError):
log.error("Cannot parse: " + course_updates.data)
log.error("Cannot parse: " + course_updates.data) # lint-amnesty, pylint: disable=logging-not-lazy
escaped = escape(course_updates.data)
# xss-lint: disable=python-concat-html
course_html_parsed = html.fromstring("<ol><li>" + escaped + "</li></ol>")

View File

@@ -19,9 +19,9 @@ class PipelineForgivingMixin(object):
"""
An extension of the django-pipeline storage backend which forgives missing files.
"""
def hashed_name(self, name, content=None, **kwargs):
def hashed_name(self, name, content=None, **kwargs): # lint-amnesty, pylint: disable=missing-function-docstring
try:
out = super(PipelineForgivingMixin, self).hashed_name(name, content, **kwargs)
out = super(PipelineForgivingMixin, self).hashed_name(name, content, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
except ValueError:
# This means that a file could not be found, and normally this would
# cause a fatal error, which seems rather excessive given that
@@ -29,9 +29,9 @@ class PipelineForgivingMixin(object):
out = name
return out
def stored_name(self, name):
def stored_name(self, name): # lint-amnesty, pylint: disable=missing-function-docstring
try:
out = super(PipelineForgivingMixin, self).stored_name(name)
out = super(PipelineForgivingMixin, self).stored_name(name) # lint-amnesty, pylint: disable=super-with-arguments
except ValueError:
# This means that a file could not be found, and normally this would
# cause a fatal error, which seems rather excessive given that
@@ -54,7 +54,7 @@ class ProductionMixin(
"""
def __init__(self, *args, **kwargs):
kwargs.update(settings.STATICFILES_STORAGE_KWARGS.get(settings.STATICFILES_STORAGE, {}))
super(ProductionMixin, self).__init__(*args, **kwargs)
super(ProductionMixin, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
class ProductionStorage(ProductionMixin, StaticFilesStorage):
@@ -76,7 +76,7 @@ class DevelopmentStorage(
that provide additional functionality. We use this version for development,
so that we can skip packaging and optimization.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@deconstructible

View File

@@ -17,7 +17,7 @@ class TestAdminView(TestCase):
Tests of the admin view
"""
def setUp(self):
super(TestAdminView, self).setUp()
super(TestAdminView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.client = Client()
def test_admin_view_loads_for_is_staff(self):