BOM-2320 : Pylint amnesty in course apps under openedx (#26348)

* pylint amnesty in course apps under openedx
This commit is contained in:
M. Zulqarnain
2021-02-04 15:34:14 +05:00
committed by GitHub
parent 355423d322
commit 96ff0734f7
19 changed files with 62 additions and 61 deletions

View File

@@ -1,4 +1,4 @@
"""
""" # lint-amnesty, pylint: disable=django-not-configured
Django app to manage course content dates, and ingesting them into edx-when for later use by the LMS.
"""

View File

@@ -5,11 +5,11 @@ Django App Configuration for the course_date_signals app
from django.apps import AppConfig
class CourseDatesSignalsConfig(AppConfig):
class CourseDatesSignalsConfig(AppConfig): # lint-amnesty, pylint: disable=missing-class-docstring
name = 'openedx.core.djangoapps.course_date_signals'
def ready(self):
"""
Connect handlers to signals.
"""
from . import handlers # pylint: disable=unused-variable
from . import handlers # lint-amnesty, pylint: disable=unused-import, unused-variable

View File

@@ -9,7 +9,7 @@ from six import text_type
from common.lib.xmodule.xmodule.util.misc import is_xblock_an_assignment
from openedx.core.lib.graph_traversals import get_children, leaf_filter, traverse_pre_order
from xblock.fields import Scope
from xblock.fields import Scope # lint-amnesty, pylint: disable=wrong-import-order
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import SignalHandler, modulestore
@@ -37,7 +37,7 @@ def _field_values(fields, xblock):
location=text_type(xblock.location),
field_name=field.name
)
raise TypeError(exception_message)
raise TypeError(exception_message) # lint-amnesty, pylint: disable=raise-missing-from
return result
@@ -52,7 +52,7 @@ def _has_assignment_blocks(item):
)
def _gather_graded_items(root, due):
def _gather_graded_items(root, due): # lint-amnesty, pylint: disable=missing-function-docstring
items = [root]
has_non_ora_scored_content = False
collected_items = []

View File

@@ -1,6 +1,7 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from datetime import timedelta
import ddt
from unittest.mock import patch
from unittest.mock import patch # lint-amnesty, pylint: disable=wrong-import-order
from openedx.core.djangoapps.course_date_signals.handlers import _gather_graded_items, _has_assignment_blocks
from xmodule.modulestore.django import modulestore
@@ -10,7 +11,7 @@ from . import utils
@ddt.ddt
class SelfPacedDueDatesTests(ModuleStoreTestCase):
class SelfPacedDueDatesTests(ModuleStoreTestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def setUp(self):
super().setUp()
self.course = CourseFactory.create()
@@ -25,7 +26,7 @@ class SelfPacedDueDatesTests(ModuleStoreTestCase):
(3, 'Section 3', timedelta(days=28)),
]
with patch.object(utils, 'get_expected_duration', return_value=timedelta(weeks=4)):
actual = [(idx, section.display_name, offset) for (idx, section, offset) in utils.spaced_out_sections(self.course)]
actual = [(idx, section.display_name, offset) for (idx, section, offset) in utils.spaced_out_sections(self.course)] # lint-amnesty, pylint: disable=line-too-long
self.assertEqual(actual, expected_sections)
@@ -39,7 +40,7 @@ class SelfPacedDueDatesTests(ModuleStoreTestCase):
(3, 'Section 3', timedelta(days=28)),
]
with patch.object(utils, 'get_expected_duration', return_value=timedelta(weeks=4)):
actual = [(idx, section.display_name, offset) for (idx, section, offset) in utils.spaced_out_sections(self.course)]
actual = [(idx, section.display_name, offset) for (idx, section, offset) in utils.spaced_out_sections(self.course)] # lint-amnesty, pylint: disable=line-too-long
self.assertEqual(actual, expected_sections)

View File

@@ -3,7 +3,7 @@ course_groups API
"""
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from openedx.core.djangoapps.course_groups.models import CohortMembership

View File

@@ -8,7 +8,7 @@ import logging
import random
import six
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.db import IntegrityError
@@ -37,7 +37,7 @@ log = logging.getLogger(__name__)
@receiver(post_save, sender=CourseUserGroup)
def _cohort_added(sender, **kwargs):
def _cohort_added(sender, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""Emits a tracking log event each time a cohort is created"""
instance = kwargs["instance"]
if kwargs["created"] and instance.group_type == CourseUserGroup.COHORT:
@@ -48,7 +48,7 @@ def _cohort_added(sender, **kwargs):
@receiver(m2m_changed, sender=CourseUserGroup.users.through)
def _cohort_membership_changed(sender, **kwargs):
def _cohort_membership_changed(sender, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""Emits a tracking log event each time cohort membership is modified"""
def get_event_iter(user_id_iter, cohort_iter):
"""
@@ -390,7 +390,7 @@ def add_cohort(course_key, name, assignment_type):
try:
course = courses.get_course_by_id(course_key)
except Http404:
raise ValueError("Invalid course_key")
raise ValueError("Invalid course_key") # lint-amnesty, pylint: disable=raise-missing-from
cohort = CourseCohort.create(
cohort_name=name,
@@ -432,7 +432,7 @@ def remove_user_from_cohort(cohort, username_or_email):
membership.delete()
COHORT_MEMBERSHIP_UPDATED.send(sender=None, user=user, course_key=course_key)
except CohortMembership.DoesNotExist:
raise ValueError(u"User {} was not present in cohort {}".format(username_or_email, cohort))
raise ValueError(u"User {} was not present in cohort {}".format(username_or_email, cohort)) # lint-amnesty, pylint: disable=raise-missing-from
def add_user_to_cohort(cohort, username_or_email_or_user):
@@ -504,10 +504,10 @@ def add_user_to_cohort(cohort, username_or_email_or_user):
return (None, None, True)
except ValidationError as invalid:
if "@" in username_or_email_or_user:
if "@" in username_or_email_or_user: # lint-amnesty, pylint: disable=no-else-raise
raise invalid
else:
raise ex
raise ex # lint-amnesty, pylint: disable=raise-missing-from
def get_group_info_for_cohort(cohort, use_cached=False):
@@ -599,7 +599,7 @@ def _get_course_cohort_settings(course_key):
return course_cohort_settings
def get_legacy_discussion_settings(course_key):
def get_legacy_discussion_settings(course_key): # lint-amnesty, pylint: disable=missing-function-docstring
try:
course_cohort_settings = CourseCohortsSettings.objects.get(course_id=course_key)

View File

@@ -6,7 +6,7 @@ Django models related to course groups functionality.
import json
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.exceptions import ValidationError
from django.db import models, transaction
from django.db.models.signals import pre_delete
@@ -84,10 +84,10 @@ class CohortMembership(models.Model):
class Meta(object):
unique_together = (('user', 'course_id'), )
def clean_fields(self, *args, **kwargs):
def clean_fields(self, *args, **kwargs): # lint-amnesty, pylint: disable=signature-differs
if self.course_id is None:
self.course_id = self.course_user_group.course_id
super(CohortMembership, self).clean_fields(*args, **kwargs)
super(CohortMembership, self).clean_fields(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def clean(self):
if self.course_user_group.group_type != CourseUserGroup.COHORT:
@@ -131,7 +131,7 @@ class CohortMembership(models.Model):
self.full_clean(validate_unique=False)
log.info(u"Saving CohortMembership for user '%s' in '%s'", self.user.id, self.course_id)
return super(CohortMembership, self).save(force_insert=force_insert,
return super(CohortMembership, self).save(force_insert=force_insert, # lint-amnesty, pylint: disable=super-with-arguments
force_update=force_update,
using=using,
update_fields=update_fields)

View File

@@ -3,7 +3,7 @@ Cohorts API serializers.
"""
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from rest_framework import serializers

View File

@@ -35,8 +35,8 @@ class CohortFactory(DjangoModelFactory):
Returns the users associated with the cohort.
"""
if extracted:
self.users.add(*extracted)
for user in self.users.all():
self.users.add(*extracted) # lint-amnesty, pylint: disable=no-member
for user in self.users.all(): # lint-amnesty, pylint: disable=no-member
CohortMembership.objects.create(
user=user,
course_user_group=self,

View File

@@ -5,7 +5,7 @@ Tests for cohorts
import ddt
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.auth.models import AnonymousUser, User # lint-amnesty, pylint: disable=imported-auth-user
from django.db import IntegrityError
from django.http import Http404
from django.test import TestCase
@@ -33,7 +33,7 @@ class TestCohortSignals(TestCase):
"""
def setUp(self):
super(TestCohortSignals, self).setUp()
super(TestCohortSignals, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course_key = CourseLocator("dummy", "dummy", "dummy")
def test_cohort_added(self, mock_tracker):
@@ -143,7 +143,7 @@ class TestCohorts(ModuleStoreTestCase):
"""
Make sure that course is reloaded every time--clear out the modulestore.
"""
super(TestCohorts, self).setUp()
super(TestCohorts, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.toy_course_key = ToyCourseFactory.create().id
def _create_cohort(self, course_id, cohort_name, assignment_type):
@@ -713,7 +713,7 @@ class TestCohortsAndPartitionGroups(ModuleStoreTestCase):
"""
Regenerate a test course and cohorts for each test
"""
super(TestCohortsAndPartitionGroups, self).setUp()
super(TestCohortsAndPartitionGroups, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.test_course_key = ToyCourseFactory.create().id
self.course = modulestore().get_course(self.test_course_key)
@@ -857,7 +857,7 @@ class TestUnregisteredLearnerCohortAssignments(TestCase):
"""
def setUp(self):
super(TestUnregisteredLearnerCohortAssignments, self).setUp()
super(TestUnregisteredLearnerCohortAssignments, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course_key = CourseKey.from_string('course-v1:edX+DemoX+Demo_Course')
self.cohort = CourseUserGroup.objects.create(
name="TestCohort",

View File

@@ -35,7 +35,7 @@ class TestCohortPartitionScheme(ModuleStoreTestCase):
Regenerate a course with cohort configuration, partition and groups,
and a student for each test.
"""
super(TestCohortPartitionScheme, self).setUp()
super(TestCohortPartitionScheme, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course_key = ToyCourseFactory.create().id
self.course = modulestore().get_course(self.course_key)
@@ -280,7 +280,7 @@ class TestGetCohortedUserPartition(ModuleStoreTestCase):
Regenerate a course with cohort configuration, partition and groups,
and a student for each test.
"""
super(TestGetCohortedUserPartition, self).setUp()
super(TestGetCohortedUserPartition, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course_key = ToyCourseFactory.create().id
self.course = modulestore().get_course(self.course_key)
self.student = UserFactory.create()
@@ -331,7 +331,7 @@ class TestMasqueradedGroup(StaffMasqueradeTestCase):
Check for staff being able to masquerade as belonging to a group.
"""
def setUp(self):
super(TestMasqueradedGroup, self).setUp()
super(TestMasqueradedGroup, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user_partition = UserPartition(
0, 'Test User Partition', '',
[Group(0, 'Group 1'), Group(1, 'Group 2')],

View File

@@ -10,7 +10,7 @@ from collections import namedtuple
import six
from six.moves import range
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.http import Http404
from django.test.client import RequestFactory
from opaque_keys.edx.locator import CourseLocator
@@ -41,7 +41,7 @@ class CohortViewsTestCase(ModuleStoreTestCase):
Base class which sets up a course and staff/non-staff users.
"""
def setUp(self):
super(CohortViewsTestCase, self).setUp()
super(CohortViewsTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course = CourseFactory.create()
self.staff_user = UserFactory(is_staff=True, username="staff")
self.non_staff_user = UserFactory(username="nonstaff")
@@ -241,7 +241,7 @@ class CohortHandlerTestCase(CohortViewsTestCase):
Tests the `cohort_handler` view.
"""
def setUp(self):
super(CohortHandlerTestCase, self).setUp()
super(CohortHandlerTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.course_staff_user = StaffFactory(
username="coursestaff",
course_key=self.course.id
@@ -742,7 +742,7 @@ class AddUsersToCohortTestCase(CohortViewsTestCase):
Tests the `add_users_to_cohort` view.
"""
def setUp(self):
super(AddUsersToCohortTestCase, self).setUp()
super(AddUsersToCohortTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self._create_cohorts()
def request_add_users_to_cohort(self, users_string, cohort, course, should_raise_404=False):

View File

@@ -8,7 +8,7 @@ import re
import six
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.exceptions import ValidationError
from django.core.paginator import EmptyPage, Paginator
from django.http import Http404, HttpResponseBadRequest
@@ -309,7 +309,7 @@ def add_users_to_cohort(request, course_key_string, cohort_id):
try:
cohort = cohorts.get_cohort_by_id(course_key, cohort_id)
except CourseUserGroup.DoesNotExist:
raise Http404(u"Cohort (ID {cohort_id}) not found for {course_key_string}".format(
raise Http404(u"Cohort (ID {cohort_id}) not found for {course_key_string}".format( # lint-amnesty, pylint: disable=raise-missing-from
cohort_id=cohort_id,
course_key_string=course_key_string
))
@@ -358,7 +358,7 @@ def add_users_to_cohort(request, course_key_string, cohort_id):
@ensure_csrf_cookie
@require_POST
def remove_user_from_cohort(request, course_key_string, cohort_id):
def remove_user_from_cohort(request, course_key_string, cohort_id): # lint-amnesty, pylint: disable=unused-argument
"""
Expects 'username': username in POST data.
@@ -673,7 +673,7 @@ class CohortUsers(DeveloperErrorViewMixin, APIPermissions):
cohort_id=cohort_id,
course_key_string=course_key_string
)
raise self.api_error(status.HTTP_404_NOT_FOUND, msg, 'cohort-not-found')
raise self.api_error(status.HTTP_404_NOT_FOUND, msg, 'cohort-not-found') # lint-amnesty, pylint: disable=raise-missing-from
return course_key, cohort
def get(self, request, course_key_string, cohort_id, username=None): # pylint: disable=unused-argument
@@ -706,9 +706,9 @@ class CohortUsers(DeveloperErrorViewMixin, APIPermissions):
try:
api.remove_user_from_cohort(course_key, username, cohort.id)
except User.DoesNotExist:
raise self.api_error(status.HTTP_404_NOT_FOUND, 'User does not exist.', 'user-not-found')
raise self.api_error(status.HTTP_404_NOT_FOUND, 'User does not exist.', 'user-not-found') # lint-amnesty, pylint: disable=raise-missing-from
except CohortMembership.DoesNotExist: # pylint: disable=duplicate-except
raise self.api_error(
raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from
status.HTTP_400_BAD_REQUEST,
'User not assigned to the given cohort.',
'user-not-in-cohort'

View File

@@ -105,7 +105,7 @@ class TestDumpToNeo4jCommandBase(SharedModuleStoreTestCase):
number_commits: number of commits we expect against the graph
number_rollbacks: number of commit rollbacks we expect
"""
courses = set([node['course_key'] for node in mock_graph.nodes])
courses = set([node['course_key'] for node in mock_graph.nodes]) # lint-amnesty, pylint: disable=consider-using-set-comprehension
self.assertEqual(len(courses), number_of_courses)
self.assertEqual(mock_graph.number_commits, number_commits)
self.assertEqual(mock_graph.number_rollbacks, number_rollbacks)
@@ -362,7 +362,7 @@ class TestModuleStoreSerializer(TestDumpToNeo4jCommandBase):
"""
Test that we add index values on nodes
"""
nodes, relationships = serialize_course(self.course.id)
nodes, relationships = serialize_course(self.course.id) # lint-amnesty, pylint: disable=unused-variable
# the html node should have 0 index, and the problem should have 1
html_nodes = [node for node in nodes if node['block_type'] == 'html']
@@ -410,7 +410,7 @@ class TestModuleStoreSerializer(TestDumpToNeo4jCommandBase):
# mocking is thorwing error in kombu serialzier and its not require here any more.
credentials = {}
submitted, skipped = self.mss.dump_courses_to_neo4j(credentials)
submitted, skipped = self.mss.dump_courses_to_neo4j(credentials) # lint-amnesty, pylint: disable=unused-variable
self.assertCourseDump(
mock_graph,
@@ -438,7 +438,7 @@ class TestModuleStoreSerializer(TestDumpToNeo4jCommandBase):
# mocking is thorwing error in kombu serialzier and its not require here any more.
credentials = {}
submitted, skipped = self.mss.dump_courses_to_neo4j(credentials)
submitted, skipped = self.mss.dump_courses_to_neo4j(credentials) # lint-amnesty, pylint: disable=unused-variable
self.assertCourseDump(
mock_graph,
@@ -496,7 +496,7 @@ class TestModuleStoreSerializer(TestDumpToNeo4jCommandBase):
credentials = {}
# run once to warm the cache
submitted, skipped = self.mss.dump_courses_to_neo4j(credentials)
submitted, skipped = self.mss.dump_courses_to_neo4j(credentials) # lint-amnesty, pylint: disable=unused-variable
self.assertEqual(len(submitted), len(self.course_strings))
# simulate one of the courses being published

View File

@@ -50,7 +50,7 @@ class MockTransaction(object):
end = query.find("'")
course_key = query[:end]
self.graph.nodes = set([
self.graph.nodes = set([ # lint-amnesty, pylint: disable=consider-using-set-comprehension
node for node in self.graph.nodes if node['course_key'] != course_key
])

View File

@@ -7,7 +7,7 @@ neo4j, a graph database.
import logging
from celery import task
from django.conf import settings
from django.conf import settings # lint-amnesty, pylint: disable=unused-import
from django.utils import six, timezone
from edx_django_utils.cache import RequestCache
from edx_django_utils.monitoring import set_code_owner_attribute

View File

@@ -14,7 +14,7 @@ class _MediaSerializer(serializers.Serializer): # pylint: disable=abstract-meth
"""
def __init__(self, uri_attribute, *args, **kwargs):
super(_MediaSerializer, self).__init__(*args, **kwargs)
super(_MediaSerializer, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.uri_attribute = uri_attribute
uri = serializers.SerializerMethodField(source='*')
@@ -56,7 +56,7 @@ class _CourseApiMediaCollectionSerializer(serializers.Serializer): # pylint: di
ref_name = 'courseware_api'
class CourseProgramSerializer(serializers.Serializer):
class CourseProgramSerializer(serializers.Serializer): # lint-amnesty, pylint: disable=abstract-method, missing-class-docstring
progress = serializers.SerializerMethodField()
slug = serializers.CharField()
title = serializers.CharField()

View File

@@ -10,7 +10,7 @@ import mock
from completion.test_utils import CompletionWaffleTestMixin, submit_completions_for_testing
from django.conf import settings
from django.test.client import RequestFactory
from django.urls import reverse
from django.urls import reverse # lint-amnesty, pylint: disable=unused-import
from lms.djangoapps.certificates.api import get_certificate_url
from lms.djangoapps.certificates.tests.factories import (
@@ -131,7 +131,7 @@ class CourseApiTestViews(BaseCoursewareTests):
'The audit track does not include a certificate.')
assert response.data['certificate_data']['msg'] == expected_audit_message
assert response.data['verify_identity_url'] is None
assert response.data['verification_status'] is 'none'
assert response.data['verification_status'] is 'none' # lint-amnesty, pylint: disable=literal-comparison
assert response.data['linkedin_add_to_profile_url'] is None
else:
assert response.data['certificate_data']['cert_status'] == 'earned_but_not_available'
@@ -140,7 +140,7 @@ class CourseApiTestViews(BaseCoursewareTests):
)
# The response contains an absolute URL so this is only checking the path of the final
assert expected_verify_identity_url in response.data['verify_identity_url']
assert response.data['verification_status'] is 'none'
assert response.data['verification_status'] is 'none' # lint-amnesty, pylint: disable=literal-comparison
request = RequestFactory().request()
cert_url = get_certificate_url(course_id=self.course.id, uuid=cert.verify_uuid)

View File

@@ -145,7 +145,7 @@ class CoursewareMeta:
return course.license
@property
def can_load_courseware(self):
def can_load_courseware(self): # lint-amnesty, pylint: disable=missing-function-docstring
access_response = check_course_access(
self.overview,
self.effective_user,
@@ -470,14 +470,14 @@ class SequenceMetadata(DeveloperErrorViewMixin, APIView):
SessionAuthenticationAllowInactiveUser,
)
def get(self, request, usage_key_string, *args, **kwargs):
def get(self, request, usage_key_string, *args, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
Return response to a GET request.
"""
try:
usage_key = UsageKey.from_string(usage_key_string)
except InvalidKeyError:
raise NotFound("Invalid usage key: '{}'.".format(usage_key_string))
raise NotFound("Invalid usage key: '{}'.".format(usage_key_string)) # lint-amnesty, pylint: disable=raise-missing-from
sequence, _ = get_module_by_usage_id(
self.request,
@@ -527,7 +527,7 @@ class Resume(DeveloperErrorViewMixin, APIView):
)
permission_classes = (IsAuthenticated, )
def get(self, request, course_key_string, *args, **kwargs):
def get(self, request, course_key_string, *args, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
Return response to a GET request.
"""
@@ -581,7 +581,7 @@ class Celebration(DeveloperErrorViewMixin, APIView):
permission_classes = (IsAuthenticated, )
http_method_names = ['post']
def post(self, request, course_key_string, *args, **kwargs):
def post(self, request, course_key_string, *args, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
Handle a POST request.
"""