diff --git a/cms/__init__.py b/cms/__init__.py
index 34c8992065be..4e39b8279b02 100644
--- a/cms/__init__.py
+++ b/cms/__init__.py
@@ -21,4 +21,4 @@
# This will make sure the app is always imported when Django starts so
# that shared_task will use this app, and also ensures that the celery
# singleton is always configured for the CMS.
-from .celery import APP as CELERY_APP # lint-amnesty, pylint: disable=wrong-import-position
+from .celery import APP as CELERY_APP # lint-amnesty, pylint: disable=wrong-import-position # noqa: F401
diff --git a/cms/celery.py b/cms/celery.py
index a7166feb1c27..fbcfe36e4e8c 100644
--- a/cms/celery.py
+++ b/cms/celery.py
@@ -16,4 +16,4 @@
# Set the default Django settings module for the 'celery' program
# and then instantiate the Celery singleton.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cms.envs.production')
-from openedx.core.lib.celery import APP # pylint: disable=wrong-import-position,unused-import
+from openedx.core.lib.celery import APP # pylint: disable=wrong-import-position,unused-import # noqa: F401
diff --git a/cms/conftest.py b/cms/conftest.py
index ee83fb8c420e..5fee284ed88c 100644
--- a/cms/conftest.py
+++ b/cms/conftest.py
@@ -28,7 +28,7 @@ def pytest_configure(config):
logging.info("pytest did not register json_report correctly")
-@pytest.fixture(autouse=True, scope='function')
+@pytest.fixture(autouse=True, scope='function') # noqa: PT003
def _django_clear_site_cache():
"""
pytest-django uses this fixture to automatically clear the Site object
diff --git a/cms/djangoapps/api/v1/serializers/course_runs.py b/cms/djangoapps/api/v1/serializers/course_runs.py
index 36598b025073..ab56ea40d341 100644
--- a/cms/djangoapps/api/v1/serializers/course_runs.py
+++ b/cms/djangoapps/api/v1/serializers/course_runs.py
@@ -45,7 +45,7 @@ def to_internal_value(self, data):
try:
User.objects.get(username=member['user'])
except User.DoesNotExist:
- raise serializers.ValidationError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise serializers.ValidationError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
_('Course team user does not exist')
)
@@ -171,7 +171,7 @@ def validate(self, attrs):
with store.default_store('split'):
new_course_run_key = store.make_course_key(course_run_key.org, number, run)
except InvalidKeyError:
- raise serializers.ValidationError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise serializers.ValidationError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
'Invalid key supplied. Ensure there are no special characters in the Course Number.'
)
if store.has_course(new_course_run_key, ignore_case=True):
diff --git a/cms/djangoapps/api/v1/tests/test_views/test_course_runs.py b/cms/djangoapps/api/v1/tests/test_views/test_course_runs.py
index 40d25cf901a2..4de6209e3729 100644
--- a/cms/djangoapps/api/v1/tests/test_views/test_course_runs.py
+++ b/cms/djangoapps/api/v1/tests/test_views/test_course_runs.py
@@ -2,7 +2,7 @@
import datetime
-from unittest.mock import patch # lint-amnesty, pylint: disable=unused-import
+from unittest.mock import patch # lint-amnesty, pylint: disable=unused-import # noqa: F401
import ddt
import pytz
@@ -266,15 +266,15 @@ def test_create(self, pacing_type, expected_self_paced_value):
data = self.get_course_run_data(user, start, end, pacing_type, role)
response = self.client.post(self.list_url, data, format='json')
- self.assertEqual(response.status_code, 201)
+ self.assertEqual(response.status_code, 201) # noqa: PT009
course_run_key = CourseKey.from_string(response.data['id'])
course_run = modulestore().get_course(course_run_key)
- self.assertEqual(course_run.display_name, data['title'])
- self.assertEqual(course_run.id.org, data['org'])
- self.assertEqual(course_run.id.course, data['number'])
- self.assertEqual(course_run.id.run, data['run'])
- self.assertEqual(course_run.self_paced, expected_self_paced_value)
+ self.assertEqual(course_run.display_name, data['title']) # noqa: PT009
+ self.assertEqual(course_run.id.org, data['org']) # noqa: PT009
+ self.assertEqual(course_run.id.course, data['number']) # noqa: PT009
+ self.assertEqual(course_run.id.run, data['run']) # noqa: PT009
+ self.assertEqual(course_run.self_paced, expected_self_paced_value) # noqa: PT009
self.assert_course_run_schedule(course_run, start, end)
self.assert_access_role(course_run, user, role)
self.assert_course_access_role_count(course_run, 1)
@@ -290,8 +290,8 @@ def test_create_with_invalid_course_team(self):
data = self.get_course_run_data(user, start, end, 'self-paced')
data['team'] = [{'user': 'invalid-username'}]
response = self.client.post(self.list_url, data, format='json')
- self.assertEqual(response.status_code, 400)
- self.assertEqual(response.data.get('team'), ['Course team user does not exist'])
+ self.assertEqual(response.status_code, 400) # noqa: PT009
+ self.assertEqual(response.data.get('team'), ['Course team user does not exist']) # noqa: PT009
def test_images_upload(self):
# http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser
@@ -382,8 +382,8 @@ def test_rerun(self, pacing_type, expected_self_paced_value, number):
self.assert_access_role(course_run, user, role)
self.assert_course_access_role_count(course_run, 1)
course_orgs = get_course_organizations(course_run_key)
- self.assertEqual(len(course_orgs), 1)
- self.assertEqual(course_orgs[0]['short_name'], original_course_run.id.org) # lint-amnesty, pylint: disable=no-member
+ self.assertEqual(len(course_orgs), 1) # noqa: PT009
+ self.assertEqual(course_orgs[0]['short_name'], original_course_run.id.org) # lint-amnesty, pylint: disable=no-member # noqa: PT009
def test_rerun_duplicate_run(self):
course_run = ToyCourseFactory()
@@ -417,7 +417,7 @@ def test_clone_course(self):
}
response = self.client.post(url, data, format='json')
assert response.status_code == 201
- self.assertEqual(response.data, {"message": "Course cloned successfully."})
+ self.assertEqual(response.data, {"message": "Course cloned successfully."}) # noqa: PT009
def test_clone_course_with_missing_source_id(self):
url = reverse('api:v1:course_run-clone')
@@ -426,7 +426,7 @@ def test_clone_course_with_missing_source_id(self):
}
response = self.client.post(url, data, format='json')
assert response.status_code == 400
- self.assertEqual(response.data, {'source_course_id': ['This field is required.']})
+ self.assertEqual(response.data, {'source_course_id': ['This field is required.']}) # noqa: PT009
def test_clone_course_with_missing_dest_id(self):
url = reverse('api:v1:course_run-clone')
@@ -435,7 +435,7 @@ def test_clone_course_with_missing_dest_id(self):
}
response = self.client.post(url, data, format='json')
assert response.status_code == 400
- self.assertEqual(response.data, {'destination_course_id': ['This field is required.']})
+ self.assertEqual(response.data, {'destination_course_id': ['This field is required.']}) # noqa: PT009
def test_clone_course_with_nonexistent_source_course(self):
url = reverse('api:v1:course_run-clone')
diff --git a/cms/djangoapps/api/v1/views/course_runs.py b/cms/djangoapps/api/v1/views/course_runs.py
index 9752e0ff074b..065714a51218 100644
--- a/cms/djangoapps/api/v1/views/course_runs.py
+++ b/cms/djangoapps/api/v1/views/course_runs.py
@@ -29,7 +29,7 @@ def get_object(self):
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
assert lookup_url_kwarg in self.kwargs, (
- 'Expected view %s to be called with a URL keyword argument '
+ 'Expected view %s to be called with a URL keyword argument ' # noqa: UP031
'named "%s". Fix your URL conf, or set the `.lookup_field` '
'attribute on the view correctly.' %
(self.__class__.__name__, lookup_url_kwarg)
diff --git a/cms/djangoapps/cms_user_tasks/apps.py b/cms/djangoapps/cms_user_tasks/apps.py
index c4ac938c6e5d..390fa453db58 100644
--- a/cms/djangoapps/cms_user_tasks/apps.py
+++ b/cms/djangoapps/cms_user_tasks/apps.py
@@ -17,4 +17,4 @@ def ready(self):
"""
Connect signal handlers.
"""
- from . import signals # pylint: disable=unused-import
+ from . import signals # pylint: disable=unused-import # noqa: F401
diff --git a/cms/djangoapps/cms_user_tasks/tests.py b/cms/djangoapps/cms_user_tasks/tests.py
index 8a9bc5532101..b01fe1a35e4f 100644
--- a/cms/djangoapps/cms_user_tasks/tests.py
+++ b/cms/djangoapps/cms_user_tasks/tests.py
@@ -176,15 +176,15 @@ def create_olx_validation_artifact(self):
def assert_msg_subject(self, msg):
"""Verify that msg subject is in expected format."""
- subject = "{platform_name} {studio_name}: Task Status Update".format(
+ subject = "{platform_name} {studio_name}: Task Status Update".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME, studio_name=settings.STUDIO_NAME
)
- self.assertEqual(msg.subject, subject)
+ self.assertEqual(msg.subject, subject) # noqa: PT009
def assert_msg_body_fragments(self, msg, body_fragments):
"""Verify that email body contains expected fragments"""
for fragment in body_fragments:
- self.assertIn(fragment, msg.body)
+ self.assertIn(fragment, msg.body) # noqa: PT009
def test_email_sent_with_site(self):
"""
@@ -201,7 +201,7 @@ def test_email_sent_with_site(self):
reverse('usertaskstatus-detail', args=[self.status.uuid])
]
- self.assertEqual(len(mail.outbox), 1)
+ self.assertEqual(len(mail.outbox), 1) # noqa: PT009
msg = mail.outbox[0]
@@ -216,7 +216,7 @@ def test_email_not_sent_with_libary_import_task(self):
end_of_task_status.name = "bulk_migrate_from_modulestore"
user_task_stopped.send(sender=UserTaskStatus, status=end_of_task_status)
- self.assertEqual(len(mail.outbox), 0)
+ self.assertEqual(len(mail.outbox), 0) # noqa: PT009
def test_email_not_sent_with_libary_content_update(self):
"""
@@ -229,7 +229,7 @@ def test_email_not_sent_with_libary_content_update(self):
end_of_task_status.name = "updating block-v1:course+type@library_content+block@uuid from library"
user_task_stopped.send(sender=UserTaskStatus, status=end_of_task_status)
- self.assertEqual(len(mail.outbox), 0)
+ self.assertEqual(len(mail.outbox), 0) # noqa: PT009
def test_email_not_sent_with_legacy_libary_content_ref_update(self):
"""
@@ -239,7 +239,7 @@ def test_email_not_sent_with_legacy_libary_content_ref_update(self):
end_of_task_status.name = "Updating legacy library content blocks references of course-v1:UNIX+UN1+2025_T4"
user_task_stopped.send(sender=UserTaskStatus, status=end_of_task_status)
- self.assertEqual(len(mail.outbox), 0)
+ self.assertEqual(len(mail.outbox), 0) # noqa: PT009
def test_email_sent_with_olx_validations_with_config_enabled(self):
"""
@@ -258,7 +258,7 @@ def test_email_sent_with_olx_validations_with_config_enabled(self):
user_task_stopped.send(sender=UserTaskStatus, status=self.status)
msg = mail.outbox[0]
- self.assertEqual(len(mail.outbox), 1)
+ self.assertEqual(len(mail.outbox), 1) # noqa: PT009
self.assert_msg_subject(msg)
self.assert_msg_body_fragments(msg, body_fragments_with_validation)
@@ -277,8 +277,8 @@ def test_email_sent_with_olx_validations_with_default_config(self):
msg = mail.outbox[0]
# Verify olx validation is not enabled out of the box.
- self.assertFalse(settings.FEATURES.get('ENABLE_COURSE_OLX_VALIDATION'))
- self.assertEqual(len(mail.outbox), 1)
+ self.assertFalse(settings.FEATURES.get('ENABLE_COURSE_OLX_VALIDATION')) # noqa: PT009
+ self.assertEqual(len(mail.outbox), 1) # noqa: PT009
self.assert_msg_subject(msg)
self.assert_msg_body_fragments(msg, body_fragments)
@@ -298,11 +298,11 @@ def test_email_sent_with_olx_validations_with_bypass_flag(self):
user_task_stopped.send(sender=UserTaskStatus, status=self.status)
- self.assertEqual(len(mail.outbox), 1)
+ self.assertEqual(len(mail.outbox), 1) # noqa: PT009
msg = mail.outbox[0]
self.assert_msg_subject(msg)
self.assert_msg_body_fragments(msg, body_fragments)
- self.assertNotIn("Here are some validations we found with your course content.", msg.body)
+ self.assertNotIn("Here are some validations we found with your course content.", msg.body) # noqa: PT009
def test_email_not_sent_for_child(self):
"""
@@ -312,7 +312,7 @@ def test_email_not_sent_for_child(self):
user=self.user, task_id=str(uuid4()), task_class='test_rest_api.sample_task', name='SampleTask 2',
total_steps=5, parent=self.status)
user_task_stopped.send(sender=UserTaskStatus, status=child_status)
- self.assertEqual(len(mail.outbox), 0)
+ self.assertEqual(len(mail.outbox), 0) # noqa: PT009
def test_email_sent_without_site(self):
"""
@@ -325,7 +325,7 @@ def test_email_sent_without_site(self):
"Sign in to view the details of your task or download any files created."
]
- self.assertEqual(len(mail.outbox), 1)
+ self.assertEqual(len(mail.outbox), 1) # noqa: PT009
msg = mail.outbox[0]
self.assert_msg_subject(msg)
@@ -342,7 +342,7 @@ def test_email_retries(self):
with mock.patch('cms.djangoapps.cms_user_tasks.tasks.send_task_complete_email.retry') as mock_retry:
user_task_stopped.send(sender=UserTaskStatus, status=self.status)
- self.assertTrue(mock_retry.called)
+ self.assertTrue(mock_retry.called) # noqa: PT009
def test_queue_email_failure(self):
logger = logging.getLogger("cms.djangoapps.cms_user_tasks.signals")
@@ -354,5 +354,5 @@ def test_queue_email_failure(self):
{'error_response': 'error occurred'}, {'operation_name': 'test'}
)
user_task_stopped.send(sender=UserTaskStatus, status=self.status)
- self.assertTrue(mock_delay.called)
- self.assertEqual(hdlr.messages['error'][0], 'Unable to queue send_task_complete_email')
+ self.assertTrue(mock_delay.called) # noqa: PT009
+ self.assertEqual(hdlr.messages['error'][0], 'Unable to queue send_task_complete_email') # noqa: PT009
diff --git a/cms/djangoapps/contentstore/api/__init__.py b/cms/djangoapps/contentstore/api/__init__.py
index da36a1afe4d8..bbd94880dad0 100644
--- a/cms/djangoapps/contentstore/api/__init__.py
+++ b/cms/djangoapps/contentstore/api/__init__.py
@@ -1,2 +1,2 @@
"""Contentstore API"""
-from .views.utils import course_author_access_required, get_ready_to_migrate_legacy_library_content_blocks
+from .views.utils import course_author_access_required, get_ready_to_migrate_legacy_library_content_blocks # noqa: F401
diff --git a/cms/djangoapps/contentstore/api/tests/base.py b/cms/djangoapps/contentstore/api/tests/base.py
index 36e87ea7eba8..086ac06ac5fb 100644
--- a/cms/djangoapps/contentstore/api/tests/base.py
+++ b/cms/djangoapps/contentstore/api/tests/base.py
@@ -66,7 +66,7 @@ def initialize_course(cls, course):
parent_location=cls.section.location,
category="sequential",
)
- unit2 = BlockFactory.create(
+ unit2 = BlockFactory.create( # noqa: F841
parent_location=cls.subsection2.location,
category="vertical",
)
diff --git a/cms/djangoapps/contentstore/api/tests/test_import.py b/cms/djangoapps/contentstore/api/tests/test_import.py
index 3ed98b3fe353..74236d8f5c54 100644
--- a/cms/djangoapps/contentstore/api/tests/test_import.py
+++ b/cms/djangoapps/contentstore/api/tests/test_import.py
@@ -73,7 +73,7 @@ def test_anonymous_import_fails(self):
"""
with open(self.good_tar_fullpath, 'rb') as fp:
resp = self.client.post(self.get_url(self.course_key), {'course_data': fp}, format='multipart')
- self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_student_import_fails(self):
"""
@@ -82,7 +82,7 @@ def test_student_import_fails(self):
self.client.login(username=self.student.username, password=self.password)
with open(self.good_tar_fullpath, 'rb') as fp:
resp = self.client.post(self.get_url(self.course_key), {'course_data': fp}, format='multipart')
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_staff_with_access_import_succeeds(self):
"""
@@ -91,7 +91,7 @@ def test_staff_with_access_import_succeeds(self):
self.client.login(username=self.staff.username, password=self.password)
with open(self.good_tar_fullpath, 'rb') as fp:
resp = self.client.post(self.get_url(self.course_key), {'course_data': fp}, format='multipart')
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_staff_has_no_access_import_fails(self):
"""
@@ -100,7 +100,7 @@ def test_staff_has_no_access_import_fails(self):
self.client.login(username=self.staff.username, password=self.password)
with open(self.good_tar_fullpath, 'rb') as fp:
resp = self.client.post(self.get_url(self.restricted_course_key), {'course_data': fp}, format='multipart')
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_student_get_status_fails(self):
"""
@@ -108,14 +108,14 @@ def test_student_get_status_fails(self):
"""
self.client.login(username=self.student.username, password=self.password)
resp = self.client.get(self.get_url(self.course_key), {'task_id': '1234', 'filename': self.good_tar_filename})
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_anonymous_get_status_fails(self):
"""
Test that an anonymous user cannot access the API and an error is received.
"""
resp = self.client.get(self.get_url(self.course_key), {'task_id': '1234', 'filename': self.good_tar_filename})
- self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_staff_get_status_succeeds(self):
"""
@@ -126,13 +126,13 @@ def test_staff_get_status_succeeds(self):
self.client.login(username=self.staff.username, password=self.password)
with open(self.good_tar_fullpath, 'rb') as fp:
resp = self.client.post(self.get_url(self.course_key), {'course_data': fp}, format='multipart')
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
resp = self.client.get(
self.get_url(self.course_key),
{'task_id': resp.data['task_id'], 'filename': self.good_tar_filename},
format='multipart'
)
- self.assertEqual(resp.data['state'], UserTaskStatus.SUCCEEDED)
+ self.assertEqual(resp.data['state'], UserTaskStatus.SUCCEEDED) # noqa: PT009
def test_staff_no_access_get_status_fails(self):
"""
@@ -143,7 +143,7 @@ def test_staff_no_access_get_status_fails(self):
self.client.login(username=self.staff.username, password=self.password)
with open(self.good_tar_fullpath, 'rb') as fp:
resp = self.client.post(self.get_url(self.course_key), {'course_data': fp}, format='multipart')
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
task_id = resp.data['task_id']
resp = self.client.get(
@@ -151,7 +151,7 @@ def test_staff_no_access_get_status_fails(self):
{'task_id': task_id, 'filename': self.good_tar_filename},
format='multipart'
)
- self.assertEqual(resp.data['state'], UserTaskStatus.SUCCEEDED)
+ self.assertEqual(resp.data['state'], UserTaskStatus.SUCCEEDED) # noqa: PT009
self.client.logout()
@@ -161,7 +161,7 @@ def test_staff_no_access_get_status_fails(self):
{'task_id': task_id, 'filename': self.good_tar_filename},
format='multipart'
)
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_course_task_mismatch_get_status_fails(self):
"""
@@ -172,7 +172,7 @@ def test_course_task_mismatch_get_status_fails(self):
self.client.login(username=self.staff.username, password=self.password)
with open(self.good_tar_fullpath, 'rb') as fp:
resp = self.client.post(self.get_url(self.course_key), {'course_data': fp}, format='multipart')
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
task_id = resp.data['task_id']
resp = self.client.get(
@@ -180,4 +180,4 @@ def test_course_task_mismatch_get_status_fails(self):
{'task_id': task_id, 'filename': self.good_tar_filename},
format='multipart'
)
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/api/tests/test_quality.py b/cms/djangoapps/contentstore/api/tests/test_quality.py
index 46450c297e71..0efab43972f6 100644
--- a/cms/djangoapps/contentstore/api/tests/test_quality.py
+++ b/cms/djangoapps/contentstore/api/tests/test_quality.py
@@ -21,7 +21,7 @@ class CourseQualityViewTest(BaseCourseViewTest):
def test_staff_succeeds(self):
self.client.login(username=self.staff.username, password=self.password)
resp = self.client.get(self.get_url(self.course_key), {'all': 'true'})
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
expected_data = {
'units': {
'num_blocks': {
@@ -65,12 +65,12 @@ def test_staff_succeeds(self):
},
'is_self_paced': True,
}
- self.assertDictEqual(resp.data, expected_data)
+ self.assertDictEqual(resp.data, expected_data) # noqa: PT009
def test_student_fails(self):
self.client.login(username=self.student.username, password=self.password)
resp = self.client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
class CourseQualityAuthzTest(CourseAuthzTestMixin, BaseCourseViewTest):
@@ -85,19 +85,19 @@ class CourseQualityAuthzTest(CourseAuthzTestMixin, BaseCourseViewTest):
def test_authorized_user_can_access(self):
"""User with COURSE_STAFF role can access."""
resp = self.authorized_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_unauthorized_user_cannot_access(self):
"""User without role cannot access."""
resp = self.unauthorized_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_role_scoped_to_course(self):
"""Authorization should only apply to the assigned course."""
other_course = self.store.create_course("OtherOrg", "OtherCourse", "Run", self.staff.id)
resp = self.authorized_client.get(self.get_url(other_course.id))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_staff_user_allowed_via_legacy(self):
"""
@@ -106,7 +106,7 @@ def test_staff_user_allowed_via_legacy(self):
self.client.login(username=self.staff.username, password=self.password)
resp = self.client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_superuser_allowed(self):
"""Superusers should always be allowed."""
@@ -116,7 +116,7 @@ def test_superuser_allowed(self):
client.force_authenticate(user=superuser)
resp = client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_non_staff_user_cannot_access(self):
"""
@@ -130,4 +130,4 @@ def test_non_staff_user_cannot_access(self):
non_staff_client.force_authenticate(user=non_staff_user)
resp = non_staff_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/api/tests/test_validation.py b/cms/djangoapps/contentstore/api/tests/test_validation.py
index fab2089af8f1..012a5b00559d 100644
--- a/cms/djangoapps/contentstore/api/tests/test_validation.py
+++ b/cms/djangoapps/contentstore/api/tests/test_validation.py
@@ -96,7 +96,7 @@ def get_url(self, course_id):
def test_student_fails(self):
self.client.login(username=self.student.username, password=self.password)
resp = self.client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
@ddt.data(
(False, False),
@@ -116,7 +116,7 @@ def test_staff_succeeds(self, certs_html_view, with_modes):
)
self.client.login(username=self.staff.username, password=self.password)
resp = self.client.get(self.get_url(self.course_key), {'all': 'true'})
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
expected_data = {
'assignments': {
'total_number': 1,
@@ -148,7 +148,7 @@ def test_staff_succeeds(self, certs_html_view, with_modes):
},
'is_self_paced': True,
}
- self.assertDictEqual(resp.data, expected_data)
+ self.assertDictEqual(resp.data, expected_data) # noqa: PT009
class TestMigrationViewSetCreate(SharedModuleStoreTestCase, APITestCase):
@@ -270,7 +270,7 @@ def test_list_ready_to_update_reference_success(self, mock_block, mock_auth):
assert response.status_code == status.HTTP_200_OK
data = response.json()
- self.assertListEqual(data, [
+ self.assertListEqual(data, [ # noqa: PT009
{'usage_key': str(self.block1.location)},
{'usage_key': str(self.block2.location)},
])
@@ -292,7 +292,7 @@ def test_authorized_user_can_access(self):
"""
resp = self.authorized_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_unauthorized_user_cannot_access(self):
"""
@@ -300,7 +300,7 @@ def test_unauthorized_user_cannot_access(self):
"""
resp = self.unauthorized_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_role_scoped_to_course(self):
"""
@@ -315,7 +315,7 @@ def test_role_scoped_to_course(self):
resp = self.authorized_client.get(self.get_url(other_course.id))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_staff_user_allowed_via_legacy(self):
"""
@@ -325,7 +325,7 @@ def test_staff_user_allowed_via_legacy(self):
resp = self.client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_superuser_allowed(self):
"""
@@ -338,7 +338,7 @@ def test_superuser_allowed(self):
resp = client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_non_staff_user_cannot_access(self):
"""
@@ -352,4 +352,4 @@ def test_non_staff_user_cannot_access(self):
non_staff_client.force_authenticate(user=non_staff_user)
resp = non_staff_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/api/views/course_import.py b/cms/djangoapps/contentstore/api/views/course_import.py
index 3027b1926d0f..f2f8f168df50 100644
--- a/cms/djangoapps/contentstore/api/views/course_import.py
+++ b/cms/djangoapps/contentstore/api/views/course_import.py
@@ -155,7 +155,7 @@ def post(self, request, course_key):
})
except Exception as e:
log.exception(f'Course import {course_key}: Unknown error in import')
- raise self.api_error(
+ raise self.api_error( # noqa: B904
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
developer_message=str(e),
error_code='internal_error'
@@ -177,7 +177,7 @@ def get(self, request, course_key):
})
except Exception as e:
log.exception(str(e))
- raise self.api_error(
+ raise self.api_error( # noqa: B904
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
developer_message=str(e),
error_code='internal_error'
diff --git a/cms/djangoapps/contentstore/apps.py b/cms/djangoapps/contentstore/apps.py
index a1ff02e4cabc..93818066a3ee 100644
--- a/cms/djangoapps/contentstore/apps.py
+++ b/cms/djangoapps/contentstore/apps.py
@@ -20,4 +20,4 @@ def ready(self):
"""
# Can't import models at module level in AppConfigs, and models get
# included from the signal handlers
- from .signals import handlers # pylint: disable=unused-import
+ from .signals import handlers # pylint: disable=unused-import # noqa: F401
diff --git a/cms/djangoapps/contentstore/asset_storage_handlers.py b/cms/djangoapps/contentstore/asset_storage_handlers.py
index 402ef9d70062..06a76a904fcf 100644
--- a/cms/djangoapps/contentstore/asset_storage_handlers.py
+++ b/cms/djangoapps/contentstore/asset_storage_handlers.py
@@ -330,7 +330,7 @@ def _get_error_if_invalid_parameters(requested_filter):
if invalid_filters:
error_message = {
'error_code': 'invalid_asset_type_filter',
- 'developer_message': 'The asset_type parameter to the request is invalid. '
+ 'developer_message': 'The asset_type parameter to the request is invalid. ' # noqa: UP032
'The {} filters are not described in the settings.FILES_AND_UPLOAD_TYPE_FILTERS '
'dictionary.'.format(invalid_filters)
}
@@ -732,7 +732,7 @@ def _check_existence_and_get_asset_content(asset_key): # lint-amnesty, pylint:
content = contentstore().find(asset_key)
return content
except NotFoundError:
- raise AssetNotFoundException # lint-amnesty, pylint: disable=raise-missing-from
+ raise AssetNotFoundException # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def _delete_thumbnail(thumbnail_location, course_key, asset_key): # lint-amnesty, pylint: disable=missing-function-docstring
diff --git a/cms/djangoapps/contentstore/core/tests/test_course_optimizer_provider.py b/cms/djangoapps/contentstore/core/tests/test_course_optimizer_provider.py
index 274f45fef705..d4d1a8d6ee63 100644
--- a/cms/djangoapps/contentstore/core/tests/test_course_optimizer_provider.py
+++ b/cms/djangoapps/contentstore/core/tests/test_course_optimizer_provider.py
@@ -73,7 +73,7 @@ def test_update_node_tree_and_dictionary_returns_node_tree(self):
self.mock_block, 'example_link', LinkState.LOCKED, {}, {}
)
- self.assertEqual(expected_tree, result_tree)
+ self.assertEqual(expected_tree, result_tree) # noqa: PT009
def test_update_node_tree_and_dictionary_returns_dictionary(self):
"""
@@ -104,7 +104,7 @@ def test_update_node_tree_and_dictionary_returns_dictionary(self):
self.mock_block, 'example_link', LinkState.LOCKED, {}, {}
)
- self.assertEqual(expected_dictionary, result_dictionary)
+ self.assertEqual(expected_dictionary, result_dictionary) # noqa: PT009
def test_create_dto_recursive_returns_for_empty_node(self):
"""
@@ -112,7 +112,7 @@ def test_create_dto_recursive_returns_for_empty_node(self):
Function should return None when given empty node tree and empty dictionary.
"""
expected = _create_dto_recursive({}, {})
- self.assertEqual(None, expected)
+ self.assertEqual(None, expected) # noqa: PT009
def test_create_dto_recursive_returns_for_leaf_node(self):
"""
@@ -159,7 +159,7 @@ def test_create_dto_recursive_returns_for_leaf_node(self):
}
}
expected = _create_dto_recursive(mock_node_tree, mock_dictionary)
- self.assertEqual(expected_result, expected)
+ self.assertEqual(expected_result, expected) # noqa: PT009
def test_create_dto_recursive_returns_for_full_tree(self):
"""
@@ -231,7 +231,7 @@ def test_create_dto_recursive_returns_for_full_tree(self):
}
expected = _create_dto_recursive(mock_node_tree, mock_dictionary)
- self.assertEqual(expected_result, expected)
+ self.assertEqual(expected_result, expected) # noqa: PT009
@mock.patch('cms.djangoapps.contentstore.core.course_optimizer_provider.modulestore', autospec=True)
def test_returns_unchanged_data_if_no_course_blocks(self, mock_modulestore):
@@ -306,7 +306,7 @@ def test_sorts_sections_correctly(self, mock_modulestore):
{"id": "section3", "name": "Bonus"},
{"id": "section1", "name": "Intro"},
]
- self.assertEqual(result["LinkCheckOutput"]["sections"], expected_sections)
+ self.assertEqual(result["LinkCheckOutput"]["sections"], expected_sections) # noqa: PT009
def test_prev_run_link_detection(self):
"""Test the core logic of separating previous run links from regular links."""
@@ -330,7 +330,7 @@ def test_prev_run_link_detection(self):
for url, expected_match in test_cases:
with self.subTest(url=url, expected=expected_match):
result = contains_course_reference(url, previous_course_key)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
result,
expected_match,
f"URL '{url}' should {'match' if expected_match else 'not match'} previous course",
@@ -362,7 +362,7 @@ def test_enhanced_url_detection_edge_cases(self):
with self.subTest(content=content):
urls = extract_content_URLs_from_course(content)
for expected_url in expected_urls:
- self.assertIn(
+ self.assertIn( # noqa: PT009
expected_url,
urls,
f"Should find '{expected_url}' in content: {content}",
@@ -459,19 +459,19 @@ def test_course_updates_and_custom_pages_structure(self):
)
# Verify top-level structure
- self.assertIn("sections", result)
- self.assertIn("course_updates", result)
- self.assertIn("custom_pages", result)
- self.assertNotIn("handouts", result)
+ self.assertIn("sections", result) # noqa: PT009
+ self.assertIn("course_updates", result) # noqa: PT009
+ self.assertIn("custom_pages", result) # noqa: PT009
+ self.assertNotIn("handouts", result) # noqa: PT009
# Course updates should include both updates and handouts
- self.assertGreaterEqual(
+ self.assertGreaterEqual( # noqa: PT009
len(result["course_updates"]),
1,
"Should have course updates/handouts",
)
# Custom pages should have custom pages data
- self.assertGreaterEqual(
+ self.assertGreaterEqual( # noqa: PT009
len(result["custom_pages"]), 1, "Should have custom pages"
)
diff --git a/cms/djangoapps/contentstore/course_group_config.py b/cms/djangoapps/contentstore/course_group_config.py
index 02757176ae80..2cbab53a6e6e 100644
--- a/cms/djangoapps/contentstore/course_group_config.py
+++ b/cms/djangoapps/contentstore/course_group_config.py
@@ -18,7 +18,7 @@
COHORT_SCHEME,
CONTENT_GROUP_CONFIGURATION_DESCRIPTION,
CONTENT_GROUP_CONFIGURATION_NAME,
- ENROLLMENT_SCHEME,
+ ENROLLMENT_SCHEME, # noqa: F401
RANDOM_SCHEME,
)
from openedx.core.djangoapps.course_groups.partition_scheme import get_cohorted_user_partition
@@ -67,7 +67,7 @@ def parse(json_string):
try:
configuration = json.loads(json_string.decode("utf-8"))
except ValueError:
- raise GroupConfigurationsValidationError(_("invalid JSON")) # lint-amnesty, pylint: disable=raise-missing-from
+ raise GroupConfigurationsValidationError(_("invalid JSON")) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
configuration["version"] = UserPartition.VERSION
return configuration
@@ -116,7 +116,7 @@ def get_user_partition(self):
try:
return UserPartition.from_json(self.configuration)
except ReadOnlyUserPartitionError:
- raise GroupConfigurationsValidationError(_("unable to load this type of group configuration")) # lint-amnesty, pylint: disable=raise-missing-from
+ raise GroupConfigurationsValidationError(_("unable to load this type of group configuration")) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
@staticmethod
def _get_usage_dict(course, unit, block, scheme_name=None):
diff --git a/cms/djangoapps/contentstore/courseware_index.py b/cms/djangoapps/contentstore/courseware_index.py
index b7b74992035a..3061907a847d 100644
--- a/cms/djangoapps/contentstore/courseware_index.py
+++ b/cms/djangoapps/contentstore/courseware_index.py
@@ -313,7 +313,7 @@ def fetch_group_usage(cls, modulestore, structure): # pylint: disable=unused-ar
"""
return None
- @classmethod
+ @classmethod # noqa: B027
def supplemental_index_information(cls, modulestore, structure):
"""
Perform any supplemental indexing given that the structure object has
diff --git a/cms/djangoapps/contentstore/exams.py b/cms/djangoapps/contentstore/exams.py
index 8a4ddc09425e..5a35d3fbe9f8 100644
--- a/cms/djangoapps/contentstore/exams.py
+++ b/cms/djangoapps/contentstore/exams.py
@@ -58,7 +58,7 @@ def register_exams(course_key):
for timed_exam in timed_exams:
location = str(timed_exam.location)
msg = (
- 'Found {location} as an exam in course structure.'.format(
+ 'Found {location} as an exam in course structure.'.format( # noqa: UP032
location=location
)
)
diff --git a/cms/djangoapps/contentstore/git_export_utils.py b/cms/djangoapps/contentstore/git_export_utils.py
index e0ac80a4627f..5f1c7877c4b2 100644
--- a/cms/djangoapps/contentstore/git_export_utils.py
+++ b/cms/djangoapps/contentstore/git_export_utils.py
@@ -136,7 +136,7 @@ def export_to_git(course_id, repo, user='', rdir=None):
root_dir, course_dir)
except (OSError, AttributeError):
log.exception('Failed export to xml')
- raise GitExportError(GitExportError.XML_EXPORT_FAIL) # lint-amnesty, pylint: disable=raise-missing-from
+ raise GitExportError(GitExportError.XML_EXPORT_FAIL) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
# Get current branch if not already set
if not branch:
@@ -160,7 +160,7 @@ def export_to_git(course_id, repo, user='', rdir=None):
ident = GIT_EXPORT_DEFAULT_IDENT
time_stamp = timezone.now()
cwd = os.path.abspath(rdirp)
- commit_msg = "Export from Studio at {time_stamp}".format(
+ commit_msg = "Export from Studio at {time_stamp}".format( # noqa: UP032
time_stamp=time_stamp,
)
try:
diff --git a/cms/djangoapps/contentstore/management/commands/backfill_orgs_and_org_courses.py b/cms/djangoapps/contentstore/management/commands/backfill_orgs_and_org_courses.py
index cba7ab452b0a..1c9426182cd3 100644
--- a/cms/djangoapps/contentstore/management/commands/backfill_orgs_and_org_courses.py
+++ b/cms/djangoapps/contentstore/management/commands/backfill_orgs_and_org_courses.py
@@ -5,7 +5,7 @@
For full context, see:
https://github.com/openedx/edx-organizations/blob/master/docs/decisions/0001-phase-in-db-backed-organizations-to-all.rst
"""
-from typing import Dict, List, Set, Tuple
+from typing import Dict, List, Set, Tuple # noqa: UP035
from django.core.management import BaseCommand, CommandError
from organizations import api as organizations_api
@@ -151,9 +151,9 @@ def handle(self, *args, **options):
def confirm_changes(
- options: Dict[str, str],
- orgs: List[dict],
- org_courseid_pairs: List[Tuple[dict, str]],
+ options: Dict[str, str], # noqa: UP006
+ orgs: List[dict], # noqa: UP006
+ org_courseid_pairs: List[Tuple[dict, str]], # noqa: UP006
) -> bool:
"""
Should we apply the changes to the database?
@@ -192,8 +192,8 @@ def confirm_changes(
def bulk_add_data(
- orgs: List[dict],
- org_courseid_pairs: List[Tuple[dict, str]],
+ orgs: List[dict], # noqa: UP006
+ org_courseid_pairs: List[Tuple[dict, str]], # noqa: UP006
dry_run: bool,
activate: bool,
):
@@ -246,7 +246,7 @@ def bulk_add_data(
print("------------------------------------------------------")
-def find_orgslug_courseid_pairs() -> Set[Tuple[str, str]]:
+def find_orgslug_courseid_pairs() -> Set[Tuple[str, str]]: # noqa: UP006
"""
Returns the unique pairs of (organization short name, course run key string)
from the CourseOverviews table, which should contain all course runs in the
@@ -266,7 +266,7 @@ def find_orgslug_courseid_pairs() -> Set[Tuple[str, str]]:
}
-def find_orgslug_libraryid_pairs() -> Set[Tuple[str, str]]:
+def find_orgslug_libraryid_pairs() -> Set[Tuple[str, str]]: # noqa: UP006
"""
Returns the unique pairs of (organization short name, content library key string)
from the modulestore.
diff --git a/cms/djangoapps/contentstore/management/commands/clean_cert_name.py b/cms/djangoapps/contentstore/management/commands/clean_cert_name.py
index 087a3a4a7245..9c4e761c5b46 100644
--- a/cms/djangoapps/contentstore/management/commands/clean_cert_name.py
+++ b/cms/djangoapps/contentstore/management/commands/clean_cert_name.py
@@ -158,14 +158,14 @@ def _display(self, results):
col_format = "| {{:>{}}} |"
self.stdout.write(id_format.format(""), ending='')
- for header, width in zip(headers, col_widths):
+ for header, width in zip(headers, col_widths): # noqa: B905
self.stdout.write(col_format.format(width).format(header), ending='')
self.stdout.write('')
for idx, result in enumerate(results):
self.stdout.write(id_format.format(idx), ending='')
- for col, width in zip(result, col_widths):
+ for col, width in zip(result, col_widths): # noqa: B905
self.stdout.write(col_format.format(width).format(str(col)), ending='')
self.stdout.write("")
diff --git a/cms/djangoapps/contentstore/management/commands/create_course.py b/cms/djangoapps/contentstore/management/commands/create_course.py
index 9ff8b0abca5c..86e88beef774 100644
--- a/cms/djangoapps/contentstore/management/commands/create_course.py
+++ b/cms/djangoapps/contentstore/management/commands/create_course.py
@@ -52,7 +52,7 @@ def get_user(self, user):
try:
user_object = user_from_str(user)
except User.DoesNotExist:
- raise CommandError(f"No user {user} found.") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(f"No user {user} found.") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return user_object
def handle(self, *args, **options):
diff --git a/cms/djangoapps/contentstore/management/commands/delete_course.py b/cms/djangoapps/contentstore/management/commands/delete_course.py
index 7e9e053443f2..8a64c64e26fe 100644
--- a/cms/djangoapps/contentstore/management/commands/delete_course.py
+++ b/cms/djangoapps/contentstore/management/commands/delete_course.py
@@ -67,12 +67,12 @@ def handle(self, *args, **options):
course_key = str(options['course_key'])
course_key = CourseKey.from_string(course_key)
except InvalidKeyError:
- raise CommandError('Invalid course_key: {}'.format(options['course_key'])) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError('Invalid course_key: {}'.format(options['course_key'])) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not modulestore().get_course(course_key):
raise CommandError('Course not found: {}'.format(options['course_key']))
- print('Preparing to delete course %s from module store....' % options['course_key'])
+ print('Preparing to delete course %s from module store....' % options['course_key']) # noqa: UP031
if query_yes_no(f'Are you sure you want to delete course {course_key}?', default='no'):
if query_yes_no('Are you sure? This action cannot be undone!', default='no'):
diff --git a/cms/djangoapps/contentstore/management/commands/delete_orphans.py b/cms/djangoapps/contentstore/management/commands/delete_orphans.py
index 1994adcde90f..5fd53bb9338e 100644
--- a/cms/djangoapps/contentstore/management/commands/delete_orphans.py
+++ b/cms/djangoapps/contentstore/management/commands/delete_orphans.py
@@ -25,7 +25,7 @@ def handle(self, *args, **options):
try:
course_key = CourseKey.from_string(options['course_id'])
except InvalidKeyError:
- raise CommandError("Invalid course key.") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError("Invalid course key.") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if options['commit']:
print('Deleting orphans from the course:')
diff --git a/cms/djangoapps/contentstore/management/commands/edit_course_tabs.py b/cms/djangoapps/contentstore/management/commands/edit_course_tabs.py
index 529d2f881e2f..52d12c66e6ea 100644
--- a/cms/djangoapps/contentstore/management/commands/edit_course_tabs.py
+++ b/cms/djangoapps/contentstore/management/commands/edit_course_tabs.py
@@ -98,4 +98,4 @@ def handle(self, *args, **options):
tabs.primitive_insert(course, num - 1, tab_type, name) # -1 as above
except ValueError as e:
# Cute: translate to CommandError so the CLI error prints nicely.
- raise CommandError(e) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(e) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
diff --git a/cms/djangoapps/contentstore/management/commands/export.py b/cms/djangoapps/contentstore/management/commands/export.py
index 68f35826905a..76644d2d650b 100644
--- a/cms/djangoapps/contentstore/management/commands/export.py
+++ b/cms/djangoapps/contentstore/management/commands/export.py
@@ -32,10 +32,10 @@ def handle(self, *args, **options):
try:
course_key = CourseKey.from_string(options['course_id'])
except InvalidKeyError:
- raise CommandError("Invalid course_key: '%s'." % options['course_id']) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError("Invalid course_key: '%s'." % options['course_id']) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904, UP031
if not modulestore().get_course(course_key):
- raise CommandError("Course with %s key not found." % options['course_id'])
+ raise CommandError("Course with %s key not found." % options['course_id']) # noqa: UP031
output_path = options['output_path']
diff --git a/cms/djangoapps/contentstore/management/commands/export_content_library.py b/cms/djangoapps/contentstore/management/commands/export_content_library.py
index b56c172e374e..7a6d4cfd2599 100644
--- a/cms/djangoapps/contentstore/management/commands/export_content_library.py
+++ b/cms/djangoapps/contentstore/management/commands/export_content_library.py
@@ -34,7 +34,7 @@ def handle(self, *args, **options):
try:
library_key = CourseKey.from_string(options['library_id'])
except InvalidKeyError:
- raise CommandError('Invalid library ID: "{}".'.format(options['library_id'])) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError('Invalid library ID: "{}".'.format(options['library_id'])) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not isinstance(library_key, LibraryLocator):
raise CommandError('Argument "{}" is not a library key'.format(options['library_id']))
@@ -50,7 +50,7 @@ def handle(self, *args, **options):
# Generate archive using the handy tasks implementation
tarball = tasks.create_export_tarball(library, library_key, {}, None)
except Exception as e:
- raise CommandError(f'Failed to export "{library_key}" with "{e}"') # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(f'Failed to export "{library_key}" with "{e}"') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
with tarball:
# Save generated archive with keyed filename
prefix, suffix, n = str(library_key).replace(':', '+'), '.tar.gz', 0
diff --git a/cms/djangoapps/contentstore/management/commands/export_olx.py b/cms/djangoapps/contentstore/management/commands/export_olx.py
index 68b291c01342..6abed6bd043a 100644
--- a/cms/djangoapps/contentstore/management/commands/export_olx.py
+++ b/cms/djangoapps/contentstore/management/commands/export_olx.py
@@ -47,9 +47,9 @@ def handle(self, *args, **options):
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError:
- raise CommandError("Unparsable course_id") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError("Unparsable course_id") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except IndexError:
- raise CommandError("Insufficient arguments") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError("Insufficient arguments") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
filename = options['output']
pipe_results = False
diff --git a/cms/djangoapps/contentstore/management/commands/force_publish.py b/cms/djangoapps/contentstore/management/commands/force_publish.py
index bacf496f68ed..eac84efe4acd 100644
--- a/cms/djangoapps/contentstore/management/commands/force_publish.py
+++ b/cms/djangoapps/contentstore/management/commands/force_publish.py
@@ -36,7 +36,7 @@ def handle(self, *args, **options):
try:
course_key = CourseKey.from_string(options['course_key'])
except InvalidKeyError:
- raise CommandError("Invalid course key.") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError("Invalid course key.") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not modulestore().get_course(course_key):
raise CommandError("Course not found.")
diff --git a/cms/djangoapps/contentstore/management/commands/generate_courses.py b/cms/djangoapps/contentstore/management/commands/generate_courses.py
index 935dfe014f32..b1a2889a31a5 100644
--- a/cms/djangoapps/contentstore/management/commands/generate_courses.py
+++ b/cms/djangoapps/contentstore/management/commands/generate_courses.py
@@ -33,9 +33,9 @@ def handle(self, *args, **options):
try:
courses = json.loads(options["courses_json"])["courses"]
except ValueError:
- raise CommandError("Invalid JSON object") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError("Invalid JSON object") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except KeyError:
- raise CommandError("JSON object is missing courses list") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError("JSON object is missing courses list") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
for course_settings in courses:
# Validate course
diff --git a/cms/djangoapps/contentstore/management/commands/git_export.py b/cms/djangoapps/contentstore/management/commands/git_export.py
index d422cbe2b1fc..a8193f8e3409 100644
--- a/cms/djangoapps/contentstore/management/commands/git_export.py
+++ b/cms/djangoapps/contentstore/management/commands/git_export.py
@@ -50,7 +50,7 @@ def handle(self, *args, **options):
try:
course_key = CourseKey.from_string(options['course_loc'])
except InvalidKeyError:
- raise CommandError(str(git_export_utils.GitExportError.BAD_COURSE)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(str(git_export_utils.GitExportError.BAD_COURSE)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
try:
git_export_utils.export_to_git(
@@ -60,4 +60,4 @@ def handle(self, *args, **options):
options.get('rdir', None)
)
except git_export_utils.GitExportError as ex:
- raise CommandError(str(ex)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(str(ex)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
diff --git a/cms/djangoapps/contentstore/management/commands/import.py b/cms/djangoapps/contentstore/management/commands/import.py
index 346f10d933b1..f53a06ee25aa 100644
--- a/cms/djangoapps/contentstore/management/commands/import.py
+++ b/cms/djangoapps/contentstore/management/commands/import.py
@@ -49,7 +49,7 @@ def handle(self, *args, **options):
do_import_python_lib = do_import_static or not options.get('nopythonlib', False)
python_lib_filename = options.get('python_lib_filename')
- output = (
+ output = ( # noqa: UP032
"Importing...\n"
" data_dir={data}, source_dirs={courses}\n"
" Importing static content? {import_static}\n"
diff --git a/cms/djangoapps/contentstore/management/commands/prompt.py b/cms/djangoapps/contentstore/management/commands/prompt.py
index b53be18c9ec7..51512c304690 100644
--- a/cms/djangoapps/contentstore/management/commands/prompt.py
+++ b/cms/djangoapps/contentstore/management/commands/prompt.py
@@ -30,7 +30,7 @@ def query_yes_no(question, default="yes"):
elif default == "no":
prompt = " [y/N] "
else:
- raise ValueError("invalid default answer: '%s'" % default)
+ raise ValueError("invalid default answer: '%s'" % default) # noqa: UP031
while True:
sys.stdout.write(question + prompt)
diff --git a/cms/djangoapps/contentstore/management/commands/recreate_upstream_links.py b/cms/djangoapps/contentstore/management/commands/recreate_upstream_links.py
index a0f04bb279e9..7234f21ed3ce 100644
--- a/cms/djangoapps/contentstore/management/commands/recreate_upstream_links.py
+++ b/cms/djangoapps/contentstore/management/commands/recreate_upstream_links.py
@@ -75,7 +75,7 @@ def handle(self, *args, **options):
should_process_all = options['all']
force = options['force']
replace = options['replace']
- time_now = datetime.now(tz=timezone.utc)
+ time_now = datetime.now(tz=timezone.utc) # noqa: UP017
if not courses and not should_process_all:
raise CommandError('Either --course or --all argument should be provided.')
diff --git a/cms/djangoapps/contentstore/management/commands/reindex_course.py b/cms/djangoapps/contentstore/management/commands/reindex_course.py
index 557267986a9b..e9d97ab91c33 100644
--- a/cms/djangoapps/contentstore/management/commands/reindex_course.py
+++ b/cms/djangoapps/contentstore/management/commands/reindex_course.py
@@ -60,7 +60,7 @@ def _parse_course_key(self, raw_value):
try:
result = CourseKey.from_string(raw_value)
except InvalidKeyError:
- raise CommandError("Invalid course_key: '%s'." % raw_value) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError("Invalid course_key: '%s'." % raw_value) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904, UP031
if not isinstance(result, CourseLocator):
raise CommandError(f"Argument {raw_value} is not a course key")
@@ -83,7 +83,7 @@ def handle(self, *args, **options): # pylint: disable=too-many-statements
course_option_flag_option = index_all_courses_option or active_option or inclusion_date_option
if (not course_ids and not course_option_flag_option) or (course_ids and course_option_flag_option):
- raise CommandError((
+ raise CommandError(( # noqa: UP034
"reindex_course requires one or more s"
" OR the --all, --active, --setup, or --from_inclusion_date flags."
))
diff --git a/cms/djangoapps/contentstore/management/commands/replace_v1_lib_refs_with_v2_in_courses.py b/cms/djangoapps/contentstore/management/commands/replace_v1_lib_refs_with_v2_in_courses.py
index 13ffa9494de0..20d9e11bb14e 100644
--- a/cms/djangoapps/contentstore/management/commands/replace_v1_lib_refs_with_v2_in_courses.py
+++ b/cms/djangoapps/contentstore/management/commands/replace_v1_lib_refs_with_v2_in_courses.py
@@ -107,7 +107,7 @@ def handle(self, *args, **kwargs):
file_path = kwargs['file_path']
v1_to_v2_lib_map = {}
try:
- with open(file_path, 'r', encoding='utf-8') as csvfile:
+ with open(file_path, 'r', encoding='utf-8') as csvfile: # noqa: UP015
if not file_path.endswith('.csv'):
raise CommandError('Invalid file format. Only CSV files are supported.')
diff --git a/cms/djangoapps/contentstore/management/commands/sync_courses.py b/cms/djangoapps/contentstore/management/commands/sync_courses.py
index 3fa3a4aede61..75b4e4988a92 100644
--- a/cms/djangoapps/contentstore/management/commands/sync_courses.py
+++ b/cms/djangoapps/contentstore/management/commands/sync_courses.py
@@ -36,7 +36,7 @@ def get_user(self, user):
try:
user_object = user_from_str(user)
except User.DoesNotExist:
- raise CommandError(f"No user {user} found.") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(f"No user {user} found.") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return user_object
def handle(self, *args, **options):
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_backfill_course_tabs.py b/cms/djangoapps/contentstore/management/commands/tests/test_backfill_course_tabs.py
index 8af72088b16b..7d72020e1bd0 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_backfill_course_tabs.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_backfill_course_tabs.py
@@ -140,7 +140,7 @@ def test_command_logs_exception_on_error(self, mock_logger):
updated_course = CourseFactory()
updated_course.tabs = [tab for tab in updated_course.tabs if tab.type != 'dates']
self.update_course(updated_course, ModuleStoreEnum.UserID.test)
- updated_course_tabs_before = updated_course.tabs
+ updated_course_tabs_before = updated_course.tabs # noqa: F841
with mock.patch(
'lms.djangoapps.ccx.modulestore.CCXModulestoreWrapper.update_item', side_effect=[ValueError, None]
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_backfill_orgs_and_org_courses.py b/cms/djangoapps/contentstore/management/commands/tests/test_backfill_orgs_and_org_courses.py
index 461db23169de..12ecddf85d31 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_backfill_orgs_and_org_courses.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_backfill_orgs_and_org_courses.py
@@ -241,5 +241,5 @@ def test_conflicting_arguments(self):
"""
Test that calling the command with both "--dry" and "--apply" raises an exception.
"""
- with self.assertRaises(CommandError):
+ with self.assertRaises(CommandError): # noqa: PT027
call_command("backfill_orgs_and_org_courses", "--dry", "--apply")
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_clean_stale_certificate_availability_dates.py b/cms/djangoapps/contentstore/management/commands/tests/test_clean_stale_certificate_availability_dates.py
index e9548be04c79..6cd722d34d67 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_clean_stale_certificate_availability_dates.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_clean_stale_certificate_availability_dates.py
@@ -89,7 +89,7 @@ def test_remove_certificate_available_date_from_instructor_paced_course_expect_e
"date can be adjusted via Studio in the UI. Aborting operation."
)
- with self.assertRaises(CommandError) as error:
+ with self.assertRaises(CommandError) as error: # noqa: PT027
call_command(
"clean_stale_certificate_available_dates",
"--course-runs",
@@ -109,7 +109,7 @@ def test_remove_certificate_available_date_with_args_from_database(self):
expected_error_message = (
"CleanStaleCertificateAvailabilityDatesConfig is disabled, but --args-from-database was requested."
)
- with self.assertRaises(CommandError) as error:
+ with self.assertRaises(CommandError) as error: # noqa: PT027
call_command("clean_stale_certificate_available_dates", "--args-from-database")
assert str(error.exception) == expected_error_message
@@ -133,7 +133,7 @@ def test_remove_certificate_available_date_with_args_from_database(self):
config.enabled = False
config.save()
- with self.assertRaises(CommandError) as disabled_error:
+ with self.assertRaises(CommandError) as disabled_error: # noqa: F841, PT027
call_command("clean_stale_certificate_available_dates", "--args-from-database")
assert str(error.exception) == expected_error_message
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_cleanup_assets.py b/cms/djangoapps/contentstore/management/commands/tests/test_cleanup_assets.py
index 049652fac857..d5850c065f71 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_cleanup_assets.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_cleanup_assets.py
@@ -56,12 +56,12 @@ def test_export_all_courses(self):
)
course = self.module_store.get_course(CourseKey.from_string('/'.join(['edX', 'course_ignore', '2014_Fall'])))
- self.assertIsNotNone(course)
+ self.assertIsNotNone(course) # noqa: PT009
# check that there are two assets ['example.txt', '.example.txt'] in contentstore for imported course
all_assets, count = self.content_store.get_all_content_for_course(course.id)
- self.assertEqual(count, 2)
- self.assertEqual({asset['_id']['name'] for asset in all_assets}, {'.example.txt', 'example.txt'})
+ self.assertEqual(count, 2) # noqa: PT009
+ self.assertEqual({asset['_id']['name'] for asset in all_assets}, {'.example.txt', 'example.txt'}) # noqa: PT009
# manually add redundant assets (file ".DS_Store" and filename starts with "._")
course_filter = course.id.make_asset_key("asset", None)
@@ -75,13 +75,13 @@ def test_export_all_courses(self):
# check that now course has four assets
all_assets, count = self.content_store.get_all_content_for_course(course.id)
- self.assertEqual(count, 4)
- self.assertEqual(
+ self.assertEqual(count, 4) # noqa: PT009
+ self.assertEqual( # noqa: PT009
{asset['_id']['name'] for asset in all_assets},
{'.example.txt', 'example.txt', '._example_test.txt', '.DS_Store'}
)
# now call asset_cleanup command and check that there is only two proper assets in contentstore for the course
call_command('cleanup_assets')
all_assets, count = self.content_store.get_all_content_for_course(course.id)
- self.assertEqual(count, 2)
- self.assertEqual({asset['_id']['name'] for asset in all_assets}, {'.example.txt', 'example.txt'})
+ self.assertEqual(count, 2) # noqa: PT009
+ self.assertEqual({asset['_id']['name'] for asset in all_assets}, {'.example.txt', 'example.txt'}) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_create_course.py b/cms/djangoapps/contentstore/management/commands/tests/test_create_course.py
index f821c8a6d561..028b048f7e92 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_create_course.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_create_course.py
@@ -21,21 +21,21 @@ def setUp(self): # lint-amnesty, pylint: disable=useless-super-delegation
def test_no_args(self):
errstring = "Error: the following arguments are required: modulestore, user, org, number, run"
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('create_course')
def test_invalid_store(self):
- with self.assertRaises(CommandError):
+ with self.assertRaises(CommandError): # noqa: PT027
call_command('create_course', "foo", "user@foo.org", "org", "course", "run")
def test_nonexistent_user_id(self):
errstring = "No user 99 found"
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('create_course', "split", "99", "org", "course", "run")
def test_nonexistent_user_email(self):
errstring = "No user fake@example.com found"
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('create_course', "mongo", "fake@example.com", "org", "course", "run")
@@ -52,12 +52,12 @@ def test_all_stores_user_email(self):
"org", "course", "run", "dummy-course-name"
)
new_key = modulestore().make_course_key("org", "course", "run")
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
modulestore().has_course(new_key),
f"Could not find course in {ModuleStoreEnum.Type.split}"
)
# pylint: disable=protected-access
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
ModuleStoreEnum.Type.split,
modulestore()._get_modulestore_for_courselike(new_key).get_modulestore_type()
)
@@ -83,7 +83,7 @@ def test_duplicate_course(self):
stderr=out
)
expected = "Course already exists"
- self.assertIn(out.getvalue().strip(), expected)
+ self.assertIn(out.getvalue().strip(), expected) # noqa: PT009
def test_get_course_with_different_case(self):
"""
@@ -107,10 +107,10 @@ def test_get_course_with_different_case(self):
self.user.id
)
course = self.store.get_course(lowercase_course_id)
- self.assertIsNotNone(course, 'Course not found using lowercase course key.')
- self.assertEqual(str(course.id), str(lowercase_course_id))
+ self.assertIsNotNone(course, 'Course not found using lowercase course key.') # noqa: PT009
+ self.assertEqual(str(course.id), str(lowercase_course_id)) # noqa: PT009
# Verify store does not return course with different case.
uppercase_course_id = self.store.make_course_key(org.upper(), number.upper(), run.upper())
course = self.store.get_course(uppercase_course_id)
- self.assertIsNone(course, 'Course should not be accessed with uppercase course id.')
+ self.assertIsNone(course, 'Course should not be accessed with uppercase course id.') # noqa: PT009
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_delete_course.py b/cms/djangoapps/contentstore/management/commands/tests/test_delete_course.py
index 4df8ca479ec5..504c5ac06291 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_delete_course.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_delete_course.py
@@ -25,18 +25,18 @@ class DeleteCourseTests(ModuleStoreTestCase):
def test_invalid_course_key(self):
course_run_key = 'foo/TestX/TS01/2015_Q7'
expected_error_message = 'Invalid course_key: ' + course_run_key
- with self.assertRaisesRegex(CommandError, expected_error_message):
+ with self.assertRaisesRegex(CommandError, expected_error_message): # noqa: PT027
call_command('delete_course', course_run_key)
def test_course_not_found(self):
course_run_key = 'TestX/TS01/2015_Q7'
expected_error_message = 'Course not found: ' + course_run_key
- with self.assertRaisesRegex(CommandError, expected_error_message):
+ with self.assertRaisesRegex(CommandError, expected_error_message): # noqa: PT027
call_command('delete_course', course_run_key)
def test_asset_and_course_deletion(self):
course_run = CourseFactory()
- self.assertIsNotNone(modulestore().get_course(course_run.id))
+ self.assertIsNotNone(modulestore().get_course(course_run.id)) # noqa: PT009
store = contentstore()
asset_key = course_run.id.make_asset_key('asset', 'test.txt')
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_delete_orphans.py b/cms/djangoapps/contentstore/management/commands/tests/test_delete_orphans.py
index 75650d41dcb2..31d5296408df 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_delete_orphans.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_delete_orphans.py
@@ -18,7 +18,7 @@ def test_no_args(self):
Test delete_orphans command with no arguments
"""
errstring = 'Error: the following arguments are required: course_id'
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('delete_orphans')
def test_delete_orphans_no_commit(self):
@@ -28,10 +28,10 @@ def test_delete_orphans_no_commit(self):
"""
course = self.create_course_with_orphans(ModuleStoreEnum.Type.split)
call_command('delete_orphans', str(course.id))
- self.assertTrue(self.store.has_item(course.id.make_usage_key('html', 'multi_parent_html')))
- self.assertTrue(self.store.has_item(course.id.make_usage_key('vertical', 'OrphanVert')))
- self.assertTrue(self.store.has_item(course.id.make_usage_key('chapter', 'OrphanChapter')))
- self.assertTrue(self.store.has_item(course.id.make_usage_key('html', 'OrphanHtml')))
+ self.assertTrue(self.store.has_item(course.id.make_usage_key('html', 'multi_parent_html'))) # noqa: PT009
+ self.assertTrue(self.store.has_item(course.id.make_usage_key('vertical', 'OrphanVert'))) # noqa: PT009
+ self.assertTrue(self.store.has_item(course.id.make_usage_key('chapter', 'OrphanChapter'))) # noqa: PT009
+ self.assertTrue(self.store.has_item(course.id.make_usage_key('html', 'OrphanHtml'))) # noqa: PT009
def test_delete_orphans_commit(self):
"""
@@ -43,12 +43,12 @@ def test_delete_orphans_commit(self):
call_command('delete_orphans', str(course.id), '--commit')
# make sure this block wasn't deleted
- self.assertTrue(self.store.has_item(course.id.make_usage_key('html', 'multi_parent_html')))
+ self.assertTrue(self.store.has_item(course.id.make_usage_key('html', 'multi_parent_html'))) # noqa: PT009
# and make sure that these were
- self.assertFalse(self.store.has_item(course.id.make_usage_key('vertical', 'OrphanVert')))
- self.assertFalse(self.store.has_item(course.id.make_usage_key('chapter', 'OrphanChapter')))
- self.assertFalse(self.store.has_item(course.id.make_usage_key('html', 'OrphanHtml')))
+ self.assertFalse(self.store.has_item(course.id.make_usage_key('vertical', 'OrphanVert'))) # noqa: PT009
+ self.assertFalse(self.store.has_item(course.id.make_usage_key('chapter', 'OrphanChapter'))) # noqa: PT009
+ self.assertFalse(self.store.has_item(course.id.make_usage_key('html', 'OrphanHtml'))) # noqa: PT009
def test_delete_orphans_published_branch_split(self):
"""
@@ -69,14 +69,14 @@ def test_delete_orphans_published_branch_split(self):
# now all orphans should be deleted
self.assertOrphanCount(course.id, 0)
self.assertOrphanCount(published_branch, 0)
- self.assertNotIn(orphan, self.store.get_items(published_branch))
+ self.assertNotIn(orphan, self.store.get_items(published_branch)) # noqa: PT009
# we should have one fewer item in the published branch of the course
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
len(items_in_published) - 1,
len(self.store.get_items(published_branch)),
)
# and the same amount of items in the draft branch of the course
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
len(items_in_draft_preferred),
len(self.store.get_items(course.id)),
)
@@ -111,6 +111,6 @@ def create_split_course_with_published_orphan(self):
# there should be one in published
self.assertOrphanCount(course.id, 0)
self.assertOrphanCount(published_branch, 1)
- self.assertIn(orphan.location, [x.location for x in self.store.get_items(published_branch)])
+ self.assertIn(orphan.location, [x.location for x in self.store.get_items(published_branch)]) # noqa: PT009
return course, orphan
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_export.py b/cms/djangoapps/contentstore/management/commands/tests/test_export.py
index b467fd558f09..d4c7a8fbcc1c 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_export.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_export.py
@@ -24,7 +24,7 @@ def test_no_args(self):
Test export command with no arguments
"""
errstring = "Error: the following arguments are required: course_id, output_path"
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('export')
@@ -49,13 +49,13 @@ def test_export_course_with_directory_name(self):
"""
course = CourseFactory.create(default_store=ModuleStoreEnum.Type.split)
course_id = str(course.id)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
modulestore().has_course(course.id),
f"Could not find course in {ModuleStoreEnum.Type.split}"
)
# Test `export` management command with invalid course_id
errstring = "Invalid course_key: 'InvalidCourseID'."
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('export', "InvalidCourseID", self.temp_dir_1)
# Test `export` management command with correct course_id
@@ -67,5 +67,5 @@ def test_course_key_not_found(self):
Test export command with a valid course key that doesn't exist
"""
errstring = "Course with x/y/z key not found."
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('export', "x/y/z", self.temp_dir_1)
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_export_all_courses.py b/cms/djangoapps/contentstore/management/commands/tests/test_export_all_courses.py
index 027455a73547..71904e997c15 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_export_all_courses.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_export_all_courses.py
@@ -43,8 +43,8 @@ def test_export_all_courses(self):
"""
# check that both courses exported successfully
courses, failed_export_courses = export_courses_to_output_path(self.temp_dir)
- self.assertEqual(len(courses), 2)
- self.assertEqual(len(failed_export_courses), 0)
+ self.assertEqual(len(courses), 2) # noqa: PT009
+ self.assertEqual(len(failed_export_courses), 0) # noqa: PT009
# manually make second course faulty and check that it fails on export
second_course_id = self.second_course.id
@@ -53,6 +53,6 @@ def test_export_all_courses(self):
{'$set': {'metadata.tags': 'crash'}}
)
courses, failed_export_courses = export_courses_to_output_path(self.temp_dir)
- self.assertEqual(len(courses), 2)
- self.assertEqual(len(failed_export_courses), 1)
- self.assertEqual(failed_export_courses[0], str(second_course_id))
+ self.assertEqual(len(courses), 2) # noqa: PT009
+ self.assertEqual(len(failed_export_courses), 1) # noqa: PT009
+ self.assertEqual(failed_export_courses[0], str(second_course_id)) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_export_olx.py b/cms/djangoapps/contentstore/management/commands/tests/test_export_olx.py
index 49ba208b11e5..e8c001a2469f 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_export_olx.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_export_olx.py
@@ -28,7 +28,7 @@ def test_no_args(self):
Test export command with no arguments
"""
errstring = "Error: the following arguments are required: course_id"
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('export_olx')
@@ -42,7 +42,7 @@ def test_invalid_course_key(self):
Test export command with an invalid course key.
"""
errstring = "Unparsable course_id"
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('export_olx', 'InvalidCourseID')
def test_course_key_not_found(self):
@@ -50,13 +50,13 @@ def test_course_key_not_found(self):
Test export command with a valid course key that doesn't exist.
"""
errstring = "Invalid course_id"
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('export_olx', 'x/y/z')
def create_dummy_course(self, store_type):
"""Create small course."""
course = CourseFactory.create(default_store=store_type)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
modulestore().has_course(course.id),
f"Could not find course in {store_type}"
)
@@ -65,17 +65,17 @@ def create_dummy_course(self, store_type):
def check_export_file(self, tar_file, course_key, with_tags=False):
"""Check content of export file."""
names = tar_file.getnames()
- dirname = "{0.org}-{0.course}-{0.run}".format(course_key)
- self.assertIn(dirname, names)
+ dirname = "{0.org}-{0.course}-{0.run}".format(course_key) # noqa: UP032
+ self.assertIn(dirname, names) # noqa: PT009
# Check if some of the files are present, without being exhaustive.
- self.assertIn(f"{dirname}/about", names)
- self.assertIn(f"{dirname}/about/overview.html", names)
- self.assertIn(f"{dirname}/assets/assets.xml", names)
- self.assertIn(f"{dirname}/policies", names)
+ self.assertIn(f"{dirname}/about", names) # noqa: PT009
+ self.assertIn(f"{dirname}/about/overview.html", names) # noqa: PT009
+ self.assertIn(f"{dirname}/assets/assets.xml", names) # noqa: PT009
+ self.assertIn(f"{dirname}/policies", names) # noqa: PT009
if with_tags:
- self.assertIn(f"{dirname}/tags.csv", names)
+ self.assertIn(f"{dirname}/tags.csv", names) # noqa: PT009
else:
- self.assertNotIn(f"{dirname}/tags.csv", names)
+ self.assertNotIn(f"{dirname}/tags.csv", names) # noqa: PT009
def test_export_course(self):
test_course_key = self.create_dummy_course(ModuleStoreEnum.Type.split)
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_fix_not_found.py b/cms/djangoapps/contentstore/management/commands/tests/test_fix_not_found.py
index b957e95eae88..e17ea55ee98f 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_fix_not_found.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_fix_not_found.py
@@ -20,7 +20,7 @@ def test_no_args(self):
"""
msg = "Error: the following arguments are required: course_id"
- with self.assertRaisesRegex(CommandError, msg):
+ with self.assertRaisesRegex(CommandError, msg): # noqa: PT027
call_command('fix_not_found')
def test_fix_not_found(self):
@@ -38,13 +38,13 @@ def test_fix_not_found(self):
# the course block should now point to two children, one of which
# doesn't actually exist
- self.assertEqual(len(course.children), 2)
- self.assertIn(dangling_pointer, course.children)
+ self.assertEqual(len(course.children), 2) # noqa: PT009
+ self.assertIn(dangling_pointer, course.children) # noqa: PT009
call_command("fix_not_found", str(course.id))
# make sure the dangling pointer was removed from
# the course block's children
course = self.store.get_course(course.id)
- self.assertEqual(len(course.children), 1)
- self.assertNotIn(dangling_pointer, course.children)
+ self.assertEqual(len(course.children), 1) # noqa: PT009
+ self.assertNotIn(dangling_pointer, course.children) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_force_publish.py b/cms/djangoapps/contentstore/management/commands/tests/test_force_publish.py
index bfe123010f90..b51aa3977c9d 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_force_publish.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_force_publish.py
@@ -37,7 +37,7 @@ def test_no_args(self):
"""
errstring = "Error: the following arguments are required: course_key"
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('force_publish')
def test_invalid_course_key(self):
@@ -45,7 +45,7 @@ def test_invalid_course_key(self):
Test 'force_publish' command with invalid course key
"""
errstring = "Invalid course key."
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('force_publish', 'TestX/TS01')
def test_too_many_arguments(self):
@@ -53,7 +53,7 @@ def test_too_many_arguments(self):
Test 'force_publish' command with more than 2 arguments
"""
errstring = "Error: unrecognized arguments: invalid-arg"
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('force_publish', str(self.course.id), '--commit', 'invalid-arg')
def test_course_key_not_found(self):
@@ -61,7 +61,7 @@ def test_course_key_not_found(self):
Test 'force_publish' command with non-existing course key
"""
errstring = "Course not found."
- with self.assertRaisesRegex(CommandError, errstring):
+ with self.assertRaisesRegex(CommandError, errstring): # noqa: PT027
call_command('force_publish', 'course-v1:org+course+run')
@@ -91,7 +91,7 @@ def test_force_publish(self):
)
# verify that course has changes.
- self.assertTrue(self.store.has_changes(self.store.get_item(self.course.location)))
+ self.assertTrue(self.store.has_changes(self.store.get_item(self.course.location))) # noqa: PT009
# get draft and publish branch versions
versions = get_course_versions(str(self.course.id))
@@ -99,7 +99,7 @@ def test_force_publish(self):
published_version = versions['published-branch']
# verify that draft and publish point to different versions
- self.assertNotEqual(draft_version, published_version)
+ self.assertNotEqual(draft_version, published_version) # noqa: PT009
with mock.patch('cms.djangoapps.contentstore.management.commands.force_publish.query_yes_no') as patched_yes_no:
patched_yes_no.return_value = True
@@ -108,7 +108,7 @@ def test_force_publish(self):
call_command('force_publish', str(self.course.id), '--commit')
# verify that course has no changes
- self.assertFalse(self.store.has_changes(self.store.get_item(self.course.location)))
+ self.assertFalse(self.store.has_changes(self.store.get_item(self.course.location))) # noqa: PT009
# get new draft and publish branch versions
versions = get_course_versions(str(self.course.id))
@@ -116,8 +116,8 @@ def test_force_publish(self):
new_published_version = versions['published-branch']
# verify that the draft branch didn't change while the published branch did
- self.assertEqual(draft_version, new_draft_version)
- self.assertNotEqual(published_version, new_published_version)
+ self.assertEqual(draft_version, new_draft_version) # noqa: PT009
+ self.assertNotEqual(published_version, new_published_version) # noqa: PT009
# verify that draft and publish point to same versions now
- self.assertEqual(new_draft_version, new_published_version)
+ self.assertEqual(new_draft_version, new_published_version) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_generate_courses.py b/cms/djangoapps/contentstore/management/commands/tests/test_generate_courses.py
index aa3abf777682..e5398a5e6313 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_generate_courses.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_generate_courses.py
@@ -34,7 +34,7 @@ def test_generate_course_in_stores(self, mock_logger):
arg = json.dumps(settings)
call_command("generate_courses", arg)
key = modulestore().make_course_key("test-course-generator", "1", "1")
- self.assertTrue(modulestore().has_course(key))
+ self.assertTrue(modulestore().has_course(key)) # noqa: PT009
mock_logger.info.assert_any_call("Created course-v1:test-course-generator+1+1")
mock_logger.info.assert_any_call("announcement has been set to 2010-04-20T20:08:21.634121")
mock_logger.info.assert_any_call("display_name has been set to test-course")
@@ -43,7 +43,7 @@ def test_invalid_json(self):
"""
Test that providing an invalid JSON object will result in the appropriate command error
"""
- with self.assertRaisesRegex(CommandError, "Invalid JSON object"):
+ with self.assertRaisesRegex(CommandError, "Invalid JSON object"): # noqa: PT027
arg = "invalid_json"
call_command("generate_courses", arg)
@@ -51,7 +51,7 @@ def test_missing_courses_list(self):
"""
Test that a missing list of courses in json will result in the appropriate command error
"""
- with self.assertRaisesRegex(CommandError, "JSON object is missing courses list"):
+ with self.assertRaisesRegex(CommandError, "JSON object is missing courses list"): # noqa: PT027
settings = {}
arg = json.dumps(settings)
call_command("generate_courses", arg)
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_git_export.py b/cms/djangoapps/contentstore/management/commands/tests/test_git_export.py
index 8a2334b34375..b38ec8e55a1d 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_git_export.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_git_export.py
@@ -24,7 +24,7 @@
FEATURES_WITH_EXPORT_GIT = settings.FEATURES.copy()
FEATURES_WITH_EXPORT_GIT['ENABLE_EXPORT_GIT'] = True
TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
-TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex
+TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex # noqa: UP031
@override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE)
@@ -44,7 +44,7 @@ def setUp(self):
os.mkdir(git_export_utils.GIT_REPO_EXPORT_DIR)
self.addCleanup(shutil.rmtree, git_export_utils.GIT_REPO_EXPORT_DIR)
- self.bare_repo_dir = '{}/data/test_bare.git'.format(
+ self.bare_repo_dir = '{}/data/test_bare.git'.format( # noqa: UP032
os.path.abspath(settings.TEST_ROOT))
if not os.path.isdir(self.bare_repo_dir):
os.mkdir(self.bare_repo_dir)
@@ -57,7 +57,7 @@ def test_command(self):
Test that the command interface works. Ignore stderr for clean
test output.
"""
- with self.assertRaisesRegex(CommandError, 'Error: unrecognized arguments:*'):
+ with self.assertRaisesRegex(CommandError, 'Error: unrecognized arguments:*'): # noqa: PT027
call_command('git_export', 'blah', 'blah', 'blah', stderr=StringIO())
with self.assertRaisesMessage(
@@ -67,23 +67,23 @@ def test_command(self):
call_command('git_export', stderr=StringIO())
# Send bad url to get course not exported
- with self.assertRaisesRegex(CommandError, str(GitExportError.URL_BAD)):
+ with self.assertRaisesRegex(CommandError, str(GitExportError.URL_BAD)): # noqa: PT027
call_command('git_export', 'foo/bar/baz', 'silly', stderr=StringIO())
# Send bad course_id to get course not exported
- with self.assertRaisesRegex(CommandError, str(GitExportError.BAD_COURSE)):
+ with self.assertRaisesRegex(CommandError, str(GitExportError.BAD_COURSE)): # noqa: PT027
call_command('git_export', 'foo/bar:baz', 'silly', stderr=StringIO())
def test_error_output(self):
"""
Verify that error output is actually resolved as the correct string
"""
- with self.assertRaisesRegex(CommandError, str(GitExportError.BAD_COURSE)):
+ with self.assertRaisesRegex(CommandError, str(GitExportError.BAD_COURSE)): # noqa: PT027
call_command(
'git_export', 'foo/bar:baz', 'silly'
)
- with self.assertRaisesRegex(CommandError, str(GitExportError.URL_BAD)):
+ with self.assertRaisesRegex(CommandError, str(GitExportError.URL_BAD)): # noqa: PT027
call_command(
'git_export', 'foo/bar/baz', 'silly'
)
@@ -93,13 +93,13 @@ def test_bad_git_url(self):
Test several bad URLs for validation
"""
course_key = CourseLocator('org', 'course', 'run')
- with self.assertRaisesRegex(GitExportError, str(GitExportError.URL_BAD)):
+ with self.assertRaisesRegex(GitExportError, str(GitExportError.URL_BAD)): # noqa: PT027
git_export_utils.export_to_git(course_key, 'Sillyness')
- with self.assertRaisesRegex(GitExportError, str(GitExportError.URL_BAD)):
+ with self.assertRaisesRegex(GitExportError, str(GitExportError.URL_BAD)): # noqa: PT027
git_export_utils.export_to_git(course_key, 'example.com:edx/notreal')
- with self.assertRaisesRegex(GitExportError, str(GitExportError.URL_NO_AUTH)):
+ with self.assertRaisesRegex(GitExportError, str(GitExportError.URL_NO_AUTH)): # noqa: PT027
git_export_utils.export_to_git(course_key, 'http://blah')
def test_bad_git_repos(self):
@@ -107,23 +107,23 @@ def test_bad_git_repos(self):
Test invalid git repos
"""
test_repo_path = f'{git_export_utils.GIT_REPO_EXPORT_DIR}/test_repo'
- self.assertFalse(os.path.isdir(test_repo_path))
+ self.assertFalse(os.path.isdir(test_repo_path)) # noqa: PT009
course_key = CourseLocator('foo', 'blah', '100-')
# Test bad clones
- with self.assertRaisesRegex(GitExportError, str(GitExportError.CANNOT_PULL)):
+ with self.assertRaisesRegex(GitExportError, str(GitExportError.CANNOT_PULL)): # noqa: PT027
git_export_utils.export_to_git(
course_key,
'https://user:blah@example.com/test_repo.git')
- self.assertFalse(os.path.isdir(test_repo_path))
+ self.assertFalse(os.path.isdir(test_repo_path)) # noqa: PT009
# Setup good repo with bad course to test xml export
- with self.assertRaisesRegex(GitExportError, str(GitExportError.XML_EXPORT_FAIL)):
+ with self.assertRaisesRegex(GitExportError, str(GitExportError.XML_EXPORT_FAIL)): # noqa: PT027
git_export_utils.export_to_git(
course_key,
f'file://{self.bare_repo_dir}')
# Test bad git remote after successful clone
- with self.assertRaisesRegex(GitExportError, str(GitExportError.CANNOT_PULL)):
+ with self.assertRaisesRegex(GitExportError, str(GitExportError.CANNOT_PULL)): # noqa: PT027
git_export_utils.export_to_git(
course_key,
'https://user:blah@example.com/r.git')
@@ -153,7 +153,7 @@ def test_git_ident(self):
cwd = os.path.abspath(git_export_utils.GIT_REPO_EXPORT_DIR / 'test_bare')
git_log = subprocess.check_output(['git', 'log', '-1',
'--format=%an|%ae'], cwd=cwd).decode('utf-8')
- self.assertEqual(expect_string, git_log)
+ self.assertEqual(expect_string, git_log) # noqa: PT009
# Make changes to course so there is something to commit
self.populate_course()
@@ -162,13 +162,13 @@ def test_git_ident(self):
f'file://{self.bare_repo_dir}',
self.user.username
)
- expect_string = '{}|{}\n'.format(
+ expect_string = '{}|{}\n'.format( # noqa: UP032
self.user.username,
self.user.email,
)
git_log = subprocess.check_output(
['git', 'log', '-1', '--format=%an|%ae'], cwd=cwd).decode('utf-8')
- self.assertEqual(expect_string, git_log)
+ self.assertEqual(expect_string, git_log) # noqa: PT009
def test_no_change(self):
"""
@@ -179,6 +179,6 @@ def test_no_change(self):
f'file://{self.bare_repo_dir}'
)
- with self.assertRaisesRegex(GitExportError, str(GitExportError.CANNOT_COMMIT)):
+ with self.assertRaisesRegex(GitExportError, str(GitExportError.CANNOT_COMMIT)): # noqa: PT027
git_export_utils.export_to_git(
self.course.id, f'file://{self.bare_repo_dir}')
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_import.py b/cms/djangoapps/contentstore/management/commands/tests/test_import.py
index 900a1e25ead7..ef3cefcab11c 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_import.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_import.py
@@ -26,7 +26,7 @@ def create_course_xml(self, content_dir, course_id): # lint-amnesty, pylint: di
directory = tempfile.mkdtemp(dir=content_dir)
os.makedirs(os.path.join(directory, "course"))
with open(os.path.join(directory, "course.xml"), "w+") as f:
- f.write(''.format(course_id))
+ f.write(''.format(course_id)) # noqa: UP032
with open(os.path.join(directory, "course", f"{course_id.run}.xml"), "w+") as f:
f.write('')
@@ -55,9 +55,9 @@ def test_forum_seed(self):
"""
Tests that forum roles were created with import.
"""
- self.assertFalse(are_permissions_roles_seeded(self.base_course_key))
+ self.assertFalse(are_permissions_roles_seeded(self.base_course_key)) # noqa: PT009
call_command('import', self.content_dir, self.good_dir)
- self.assertTrue(are_permissions_roles_seeded(self.base_course_key))
+ self.assertTrue(are_permissions_roles_seeded(self.base_course_key)) # noqa: PT009
def test_truncated_course_with_url(self):
"""
@@ -69,8 +69,8 @@ def test_truncated_course_with_url(self):
# Load up base course and verify it is available
call_command('import', self.content_dir, self.good_dir)
store = modulestore()
- self.assertIsNotNone(store.get_course(self.base_course_key))
+ self.assertIsNotNone(store.get_course(self.base_course_key)) # noqa: PT009
# Now load up the course with a similar course_id and verify it loads
call_command('import', self.content_dir, self.course_dir)
- self.assertIsNotNone(store.get_course(self.truncated_key))
+ self.assertIsNotNone(store.get_course(self.truncated_key)) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_reindex_courses.py b/cms/djangoapps/contentstore/management/commands/tests/test_reindex_courses.py
index c7fb4249b0b4..f9de0833f11c 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_reindex_courses.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_reindex_courses.py
@@ -66,25 +66,25 @@ def _build_calls(self, *courses):
def test_given_no_arguments_raises_command_error(self):
""" Test that raises CommandError for incorrect arguments """
- with self.assertRaisesRegex(CommandError, ".* requires one or more *"):
+ with self.assertRaisesRegex(CommandError, ".* requires one or more *"): # noqa: PT027
call_command('reindex_course')
@ddt.data('qwerty', 'invalid_key', 'xblockv1:qwerty')
def test_given_invalid_course_key_raises_not_found(self, invalid_key):
""" Test that raises InvalidKeyError for invalid keys """
err_string = f"Invalid course_key: '{invalid_key}'"
- with self.assertRaisesRegex(CommandError, err_string):
+ with self.assertRaisesRegex(CommandError, err_string): # noqa: PT027
call_command('reindex_course', invalid_key)
def test_given_library_key_raises_command_error(self):
""" Test that raises CommandError if library key is passed """
- with self.assertRaisesRegex(CommandError, ".* is not a course key"):
+ with self.assertRaisesRegex(CommandError, ".* is not a course key"): # noqa: PT027
call_command('reindex_course', str(self._get_lib_key(self.first_lib)))
- with self.assertRaisesRegex(CommandError, ".* is not a course key"):
+ with self.assertRaisesRegex(CommandError, ".* is not a course key"): # noqa: PT027
call_command('reindex_course', str(self._get_lib_key(self.second_lib)))
- with self.assertRaisesRegex(CommandError, ".* is not a course key"):
+ with self.assertRaisesRegex(CommandError, ".* is not a course key"): # noqa: PT027
call_command(
'reindex_course',
str(self.second_course.id),
@@ -96,11 +96,11 @@ def test_given_id_list_indexes_courses(self):
with mock.patch(self.REINDEX_PATH_LOCATION) as patched_index, \
mock.patch(self.MODULESTORE_PATCH_LOCATION, mock.Mock(return_value=self.store)):
call_command('reindex_course', str(self.first_course.id))
- self.assertEqual(patched_index.mock_calls, self._build_calls(self.first_course))
+ self.assertEqual(patched_index.mock_calls, self._build_calls(self.first_course)) # noqa: PT009
patched_index.reset_mock()
call_command('reindex_course', str(self.second_course.id))
- self.assertEqual(patched_index.mock_calls, self._build_calls(self.second_course))
+ self.assertEqual(patched_index.mock_calls, self._build_calls(self.second_course)) # noqa: PT009
patched_index.reset_mock()
call_command(
@@ -109,7 +109,7 @@ def test_given_id_list_indexes_courses(self):
str(self.second_course.id)
)
expected_calls = self._build_calls(self.first_course, self.second_course)
- self.assertEqual(patched_index.mock_calls, expected_calls)
+ self.assertEqual(patched_index.mock_calls, expected_calls) # noqa: PT009
def test_given_all_key_prompts_and_reindexes_all_courses(self):
""" Test that reindexes all courses when --all key is given and confirmed """
@@ -123,7 +123,7 @@ def test_given_all_key_prompts_and_reindexes_all_courses(self):
expected_calls = self._build_calls(
self.first_course, self.second_course, self.third_course, self.fourth_course
)
- self.assertCountEqual(patched_index.mock_calls, expected_calls)
+ self.assertCountEqual(patched_index.mock_calls, expected_calls) # noqa: PT009
def test_given_all_key_prompts_and_reindexes_all_courses_cancelled(self):
""" Test that does not reindex anything when --all key is given and cancelled """
@@ -146,7 +146,7 @@ def test_given_active_key_prompt(self):
call_command('reindex_course', active=True)
expected_calls = self._build_calls(self.first_course, self.fourth_course)
- self.assertCountEqual(patched_index.mock_calls, expected_calls)
+ self.assertCountEqual(patched_index.mock_calls, expected_calls) # noqa: PT009
@mock.patch.dict(
'django.conf.settings.FEATURES',
@@ -162,4 +162,4 @@ def test_given_from_inclusion_date_key_prompt(self):
call_command('reindex_course', from_inclusion_date=True)
expected_calls = self._build_calls(self.first_course, self.second_course)
- self.assertCountEqual(patched_index.mock_calls, expected_calls)
+ self.assertCountEqual(patched_index.mock_calls, expected_calls) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_reindex_library.py b/cms/djangoapps/contentstore/management/commands/tests/test_reindex_library.py
index 6ba5ac63625f..0c3086ce7901 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_reindex_library.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_reindex_library.py
@@ -57,24 +57,24 @@ def _build_calls(self, *libraries):
def test_given_no_arguments_raises_command_error(self):
""" Test that raises CommandError for incorrect arguments """
- with self.assertRaisesRegex(CommandError, ".* requires one or more *"):
+ with self.assertRaisesRegex(CommandError, ".* requires one or more *"): # noqa: PT027
call_command('reindex_library')
@ddt.data('qwerty', 'invalid_key', 'xblock-v1:qwe+rty')
def test_given_invalid_lib_key_raises_not_found(self, invalid_key):
""" Test that raises InvalidKeyError for invalid keys """
- with self.assertRaises(InvalidKeyError):
+ with self.assertRaises(InvalidKeyError): # noqa: PT027
call_command('reindex_library', invalid_key)
def test_given_course_key_raises_command_error(self):
""" Test that raises CommandError if course key is passed """
- with self.assertRaisesRegex(CommandError, ".* is not a library key"):
+ with self.assertRaisesRegex(CommandError, ".* is not a library key"): # noqa: PT027
call_command('reindex_library', str(self.first_course.id))
- with self.assertRaisesRegex(CommandError, ".* is not a library key"):
+ with self.assertRaisesRegex(CommandError, ".* is not a library key"): # noqa: PT027
call_command('reindex_library', str(self.second_course.id))
- with self.assertRaisesRegex(CommandError, ".* is not a library key"):
+ with self.assertRaisesRegex(CommandError, ".* is not a library key"): # noqa: PT027
call_command(
'reindex_library',
str(self.second_course.id),
@@ -86,11 +86,11 @@ def test_given_id_list_indexes_libraries(self):
with mock.patch(self.REINDEX_PATH_LOCATION) as patched_index, \
mock.patch(self.MODULESTORE_PATCH_LOCATION, mock.Mock(return_value=self.store)):
call_command('reindex_library', str(self._get_lib_key(self.first_lib)))
- self.assertEqual(patched_index.mock_calls, self._build_calls(self.first_lib))
+ self.assertEqual(patched_index.mock_calls, self._build_calls(self.first_lib)) # noqa: PT009
patched_index.reset_mock()
call_command('reindex_library', str(self._get_lib_key(self.second_lib)))
- self.assertEqual(patched_index.mock_calls, self._build_calls(self.second_lib))
+ self.assertEqual(patched_index.mock_calls, self._build_calls(self.second_lib)) # noqa: PT009
patched_index.reset_mock()
call_command(
@@ -99,7 +99,7 @@ def test_given_id_list_indexes_libraries(self):
str(self._get_lib_key(self.second_lib))
)
expected_calls = self._build_calls(self.first_lib, self.second_lib)
- self.assertEqual(patched_index.mock_calls, expected_calls)
+ self.assertEqual(patched_index.mock_calls, expected_calls) # noqa: PT009
def test_given_all_key_prompts_and_reindexes_all_libraries(self):
""" Test that reindexes all libraries when --all key is given and confirmed """
@@ -111,7 +111,7 @@ def test_given_all_key_prompts_and_reindexes_all_libraries(self):
patched_yes_no.assert_called_once_with(ReindexCommand.CONFIRMATION_PROMPT, default='no')
expected_calls = self._build_calls(self.first_lib, self.second_lib)
- self.assertCountEqual(patched_index.mock_calls, expected_calls)
+ self.assertCountEqual(patched_index.mock_calls, expected_calls) # noqa: PT009
def test_given_all_key_prompts_and_reindexes_all_libraries_cancelled(self):
""" Test that does not reindex anything when --all key is given and cancelled """
@@ -129,5 +129,5 @@ def test_fail_fast_if_reindex_fails(self):
with mock.patch(self.REINDEX_PATH_LOCATION) as patched_index:
patched_index.side_effect = SearchIndexingError("message", [])
- with self.assertRaises(SearchIndexingError):
+ with self.assertRaises(SearchIndexingError): # noqa: PT027
call_command('reindex_library', str(self._get_lib_key(self.second_lib)))
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_reset_course_content.py b/cms/djangoapps/contentstore/management/commands/tests/test_reset_course_content.py
index 73a00f36b3c9..843a2795507a 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_reset_course_content.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_reset_course_content.py
@@ -21,15 +21,15 @@ class TestCommand(TestCase):
"""
def test_bad_course_id(self):
- with self.assertRaises(InvalidKeyError):
+ with self.assertRaises(InvalidKeyError): # noqa: PT027
call_command("reset_course_content", "not_a_course_id", "0123456789abcdef01234567")
def test_wrong_length_version_guid(self):
- with self.assertRaises(CommandError):
+ with self.assertRaises(CommandError): # noqa: PT027
call_command("reset_course_content", "course-v1:a+b+c", "0123456789abcdef")
def test_non_hex_version_guid(self):
- with self.assertRaises(CommandError):
+ with self.assertRaises(CommandError): # noqa: PT027
call_command("reset_course_content", "course-v1:a+b+c", "0123456789abcdefghijklmn")
@mock.patch.object(MixedModuleStore, "reset_course_to_version")
diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_sync_courses.py b/cms/djangoapps/contentstore/management/commands/tests/test_sync_courses.py
index a58c891c4730..b4c3ba9b0df4 100644
--- a/cms/djangoapps/contentstore/management/commands/tests/test_sync_courses.py
+++ b/cms/djangoapps/contentstore/management/commands/tests/test_sync_courses.py
@@ -36,7 +36,7 @@ def setUp(self):
def _validate_courses(self):
for run in self.catalog_course_runs:
course_key = CourseKey.from_string(run.get('key')) # lint-amnesty, pylint: disable=no-member
- self.assertTrue(modulestore().has_course(course_key))
+ self.assertTrue(modulestore().has_course(course_key)) # noqa: PT009
CourseOverview.objects.get(id=run.get('key')) # lint-amnesty, pylint: disable=no-member
def test_courses_sync(self, mock_catalog_course_runs):
@@ -65,7 +65,7 @@ def test_duplicate_courses_skipped(self, mock_catalog_course_runs):
with LogCapture() as capture:
call_command('sync_courses', self.user.email)
- expected_message = "Course already exists for {}, {}, {}. Skipping".format(
+ expected_message = "Course already exists for {}, {}, {}. Skipping".format( # noqa: UP032
course_key.org,
course_key.course,
course_key.run,
@@ -77,4 +77,4 @@ def test_duplicate_courses_skipped(self, mock_catalog_course_runs):
self._validate_courses()
course = modulestore().get_course(course_key)
- self.assertEqual(course.display_name, initial_display_name)
+ self.assertEqual(course.display_name, initial_display_name) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/management/commands/xlint.py b/cms/djangoapps/contentstore/management/commands/xlint.py
index d7e93d44de0a..24e0abd05e68 100644
--- a/cms/djangoapps/contentstore/management/commands/xlint.py
+++ b/cms/djangoapps/contentstore/management/commands/xlint.py
@@ -27,7 +27,7 @@ def handle(self, *args, **options):
data_dir = options['data_dir']
source_dirs = options['source_dirs']
- print("Importing. Data_dir={data}, source_dirs={courses}".format(
+ print("Importing. Data_dir={data}, source_dirs={courses}".format( # noqa: UP032
data=data_dir,
courses=source_dirs))
diff --git a/cms/djangoapps/contentstore/models.py b/cms/djangoapps/contentstore/models.py
index b1910750541f..9bc241e5b34f 100644
--- a/cms/djangoapps/contentstore/models.py
+++ b/cms/djangoapps/contentstore/models.py
@@ -127,7 +127,7 @@ def published_at(self) -> str | None:
"""
raise NotImplementedError
- class Meta:
+ class Meta: # noqa: DJ012
abstract = True
@classmethod
@@ -265,7 +265,7 @@ def update_or_create(
Update or create entity link. This will only update `updated` field if something has changed.
"""
if not created:
- created = datetime.now(tz=timezone.utc)
+ created = datetime.now(tz=timezone.utc) # noqa: UP017
top_level_parent = None
if top_level_parent_usage_key is not None:
try:
@@ -501,7 +501,7 @@ def update_or_create(
Update or create entity link. This will only update `updated` field if something has changed.
"""
if not created:
- created = datetime.now(tz=timezone.utc)
+ created = datetime.now(tz=timezone.utc) # noqa: UP017
top_level_parent = None
if top_level_parent_usage_key is not None:
try:
@@ -589,7 +589,7 @@ def get_or_create(cls, context_key: str, created: datetime | None = None) -> "Le
LearningContextLinksStatus object
"""
if not created:
- created = datetime.now(tz=timezone.utc)
+ created = datetime.now(tz=timezone.utc) # noqa: UP017
status, _ = cls.objects.get_or_create(
context_key=context_key,
defaults={
@@ -609,5 +609,5 @@ def update_status(
Updates entity links processing status of given learning context.
"""
self.status = status
- self.updated = updated or datetime.now(tz=timezone.utc)
+ self.updated = updated or datetime.now(tz=timezone.utc) # noqa: UP017
self.save()
diff --git a/cms/djangoapps/contentstore/outlines.py b/cms/djangoapps/contentstore/outlines.py
index aad3b378a6f0..1fe159913955 100644
--- a/cms/djangoapps/contentstore/outlines.py
+++ b/cms/djangoapps/contentstore/outlines.py
@@ -4,7 +4,7 @@
learning_sequences at publish time.
"""
from datetime import timezone
-from typing import List, Tuple
+from typing import List, Tuple # noqa: UP035
from edx_django_utils.monitoring import function_trace, set_custom_attribute
@@ -321,7 +321,7 @@ def _make_section_data(section, unique_sequences):
@function_trace('get_outline_from_modulestore')
-def get_outline_from_modulestore(course_key) -> Tuple[CourseOutlineData, List[ContentErrorData]]:
+def get_outline_from_modulestore(course_key) -> Tuple[CourseOutlineData, List[ContentErrorData]]: # noqa: UP006
"""
Return a CourseOutlineData and list of ContentErrorData for param:course_key
@@ -352,7 +352,7 @@ def get_outline_from_modulestore(course_key) -> Tuple[CourseOutlineData, List[Co
# maps to UTC), but for consistency, we're going to use the standard
# python timezone.utc (which is what the learning_sequence app will
# return from MySQL). They will compare as equal.
- published_at=course.subtree_edited_on.replace(tzinfo=timezone.utc),
+ published_at=course.subtree_edited_on.replace(tzinfo=timezone.utc), # noqa: UP017
# .course_version is a BSON obj, so we convert to str (MongoDB-
# specific objects don't go into CourseOutlineData).
diff --git a/cms/djangoapps/contentstore/proctoring.py b/cms/djangoapps/contentstore/proctoring.py
index 31042c249c50..7a6e120c9721 100644
--- a/cms/djangoapps/contentstore/proctoring.py
+++ b/cms/djangoapps/contentstore/proctoring.py
@@ -70,7 +70,7 @@ def register_special_exams(course_key):
# add/update any exam entries in edx-proctoring
for timed_exam in timed_exams:
msg = (
- 'Found {location} as a timed-exam in course structure. Inspecting...'.format(
+ 'Found {location} as a timed-exam in course structure. Inspecting...'.format( # noqa: UP032
location=str(timed_exam.location)
)
)
diff --git a/cms/djangoapps/contentstore/rest_api/serializers/__init__.py b/cms/djangoapps/contentstore/rest_api/serializers/__init__.py
index 9d207ee767ea..0f2da7e95365 100644
--- a/cms/djangoapps/contentstore/rest_api/serializers/__init__.py
+++ b/cms/djangoapps/contentstore/rest_api/serializers/__init__.py
@@ -1,4 +1,4 @@
"""
Serializers for all contentstore API versions
"""
-from .common import StrictSerializer
+from .common import StrictSerializer # noqa: F401
diff --git a/cms/djangoapps/contentstore/rest_api/v0/__init__.py b/cms/djangoapps/contentstore/rest_api/v0/__init__.py
index 1af3b679fc9f..90b9707d8612 100644
--- a/cms/djangoapps/contentstore/rest_api/v0/__init__.py
+++ b/cms/djangoapps/contentstore/rest_api/v0/__init__.py
@@ -2,5 +2,8 @@
Views for v0 contentstore API.
"""
-from cms.djangoapps.contentstore.rest_api.v0.views.assets import AssetsCreateRetrieveView, AssetsUpdateDestroyView
-from cms.djangoapps.contentstore.rest_api.v0.views.xblock import XblockCreateView, XblockView
+from cms.djangoapps.contentstore.rest_api.v0.views.assets import ( # noqa: F401
+ AssetsCreateRetrieveView,
+ AssetsUpdateDestroyView,
+)
+from cms.djangoapps.contentstore.rest_api.v0.views.xblock import XblockCreateView, XblockView # noqa: F401
diff --git a/cms/djangoapps/contentstore/rest_api/v0/serializers/__init__.py b/cms/djangoapps/contentstore/rest_api/v0/serializers/__init__.py
index 171f746be438..65e71ea67cb5 100644
--- a/cms/djangoapps/contentstore/rest_api/v0/serializers/__init__.py
+++ b/cms/djangoapps/contentstore/rest_api/v0/serializers/__init__.py
@@ -1,10 +1,14 @@
"""
Serializers for v0 contentstore API.
"""
-from .advanced_settings import AdvancedSettingsFieldSerializer, CourseAdvancedSettingsSerializer
-from .assets import AssetSerializer
-from .authoring_grading import CourseGradingModelSerializer
-from .course_optimizer import LinkCheckSerializer
-from .tabs import CourseTabSerializer, CourseTabUpdateSerializer, TabIDLocatorSerializer
-from .transcripts import TranscriptSerializer, YoutubeTranscriptCheckSerializer, YoutubeTranscriptUploadSerializer
-from .xblock import XblockSerializer
+from .advanced_settings import AdvancedSettingsFieldSerializer, CourseAdvancedSettingsSerializer # noqa: F401
+from .assets import AssetSerializer # noqa: F401
+from .authoring_grading import CourseGradingModelSerializer # noqa: F401
+from .course_optimizer import LinkCheckSerializer # noqa: F401
+from .tabs import CourseTabSerializer, CourseTabUpdateSerializer, TabIDLocatorSerializer # noqa: F401
+from .transcripts import ( # noqa: F401
+ TranscriptSerializer,
+ YoutubeTranscriptCheckSerializer,
+ YoutubeTranscriptUploadSerializer,
+)
+from .xblock import XblockSerializer # noqa: F401
diff --git a/cms/djangoapps/contentstore/rest_api/v0/serializers/advanced_settings.py b/cms/djangoapps/contentstore/rest_api/v0/serializers/advanced_settings.py
index 31b3d27d08ea..a17c625a0fe0 100644
--- a/cms/djangoapps/contentstore/rest_api/v0/serializers/advanced_settings.py
+++ b/cms/djangoapps/contentstore/rest_api/v0/serializers/advanced_settings.py
@@ -1,6 +1,6 @@
""" Serializers for course advanced settings"""
-from typing import Dict as DictType
-from typing import Type
+from typing import Dict as DictType # noqa: UP035
+from typing import Type # noqa: UP035
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
@@ -51,7 +51,7 @@ class CourseAdvancedSettingsSerializer(serializers.Serializer): # pylint: disab
"""
@staticmethod
- def _get_drf_field_type_from_xblock_field(xblock_field: XBlockField) -> Type[SerializerField]:
+ def _get_drf_field_type_from_xblock_field(xblock_field: XBlockField) -> Type[SerializerField]: # noqa: UP006
"""
Return the corresponding DRF Serializer field for an XBlock field.
@@ -67,7 +67,7 @@ def _get_drf_field_type_from_xblock_field(xblock_field: XBlockField) -> Type[Ser
return drf_type
return serializers.JSONField
- def get_fields(self) -> DictType[str, SerializerField]:
+ def get_fields(self) -> DictType[str, SerializerField]: # noqa: UP006
"""
Return the fields for this serializer.
diff --git a/cms/djangoapps/contentstore/rest_api/v0/serializers/tabs.py b/cms/djangoapps/contentstore/rest_api/v0/serializers/tabs.py
index 9f5b6af7321d..ce5eb1589c22 100644
--- a/cms/djangoapps/contentstore/rest_api/v0/serializers/tabs.py
+++ b/cms/djangoapps/contentstore/rest_api/v0/serializers/tabs.py
@@ -1,5 +1,5 @@
""" Serializers for course tabs """
-from typing import Dict
+from typing import Dict # noqa: UP035
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
@@ -41,7 +41,7 @@ class CourseTabSerializer(serializers.Serializer): # pylint: disable=abstract-m
help_text=_("Additional settings specific to the tab"),
)
- def to_representation(self, instance: CourseTab) -> Dict:
+ def to_representation(self, instance: CourseTab) -> Dict: # noqa: UP006
"""
Returns a dict representation of a ``CourseTab`` that contains more data than its ``to_json`` method.
@@ -74,7 +74,7 @@ class TabIDLocatorSerializer(serializers.Serializer): # pylint: disable=abstrac
tab_id = serializers.CharField(required=False, help_text=_("ID of tab to update"))
tab_locator = UsageKeyField(required=False, help_text=_("Location (Usage Key) of tab to update"))
- def validate(self, attrs: Dict) -> Dict:
+ def validate(self, attrs: Dict) -> Dict: # noqa: UP006
"""
Validates that either the ``tab_id`` or ``tab_locator`` are specified, but not both.
diff --git a/cms/djangoapps/contentstore/rest_api/v0/tests/test_advanced_settings.py b/cms/djangoapps/contentstore/rest_api/v0/tests/test_advanced_settings.py
index 30556bc8649b..8c6392109eb2 100644
--- a/cms/djangoapps/contentstore/rest_api/v0/tests/test_advanced_settings.py
+++ b/cms/djangoapps/contentstore/rest_api/v0/tests/test_advanced_settings.py
@@ -156,12 +156,12 @@ def _seed_database_with_policies(cls):
def test_authorized_for_specific_course(self, mock_flag):
"""User authorized for specific course can access."""
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
def test_unauthorized_for_specific_course(self, mock_flag):
"""User without authorization for specific course cannot access."""
response = self.unauthorized_client.get(self.url)
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
def test_unauthorized_for_different_course(self, mock_flag):
"""User authorized for one course cannot access another course."""
@@ -171,12 +171,12 @@ def test_unauthorized_for_different_course(self, mock_flag):
kwargs={"course_id": other_course.id},
)
response = self.authorized_client.get(other_url)
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
def test_staff_authorized_by_default(self, mock_flag):
"""Staff users are authorized by default."""
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
def test_superuser_authorized_by_default(self, mock_flag):
"""Superusers are authorized by default."""
@@ -184,7 +184,7 @@ def test_superuser_authorized_by_default(self, mock_flag):
superuser_client = APIClient()
superuser_client.force_authenticate(user=superuser)
response = superuser_client.get(self.url)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
def test_patch_authorized_for_specific_course(self, mock_flag):
"""User authorized for specific course can PATCH."""
@@ -193,7 +193,7 @@ def test_patch_authorized_for_specific_course(self, mock_flag):
{"display_name": {"value": "Test"}},
content_type="application/json"
)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
def test_patch_unauthorized_for_specific_course(self, mock_flag):
"""User without authorization for specific course cannot PATCH."""
@@ -202,4 +202,4 @@ def test_patch_unauthorized_for_specific_course(self, mock_flag):
{"display_name": {"value": "Test"}},
content_type="application/json"
)
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v0/tests/test_assets.py b/cms/djangoapps/contentstore/rest_api/v0/tests/test_assets.py
index bfd710d499d2..23959f6264b9 100644
--- a/cms/djangoapps/contentstore/rest_api/v0/tests/test_assets.py
+++ b/cms/djangoapps/contentstore/rest_api/v0/tests/test_assets.py
@@ -160,7 +160,7 @@ def assert_assets_handler_called(self, *, mock_handle_assets, response):
mock_handle_assets.assert_called_once()
passed_args = mock_handle_assets.call_args[0][0]
- course_id = self.get_course_key_string()
+ course_id = self.get_course_key_string() # noqa: F841
assert passed_args.data.get("file").name == mock_image.name
assert passed_args.method == "POST"
@@ -203,7 +203,7 @@ def assert_assets_handler_called(self, *, mock_handle_assets, response):
mock_handle_assets.assert_called_once()
passed_args = mock_handle_assets.call_args[0][0]
- course_id = self.get_course_key_string()
+ course_id = self.get_course_key_string() # noqa: F841
assert passed_args.data.get("locked") is True
assert passed_args.method == "PUT"
diff --git a/cms/djangoapps/contentstore/rest_api/v0/tests/test_authoring_grading.py b/cms/djangoapps/contentstore/rest_api/v0/tests/test_authoring_grading.py
index 9c70c7e6fab5..fbca4a6aedf2 100644
--- a/cms/djangoapps/contentstore/rest_api/v0/tests/test_authoring_grading.py
+++ b/cms/djangoapps/contentstore/rest_api/v0/tests/test_authoring_grading.py
@@ -52,7 +52,7 @@ def test_authorized_user_can_access_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_unauthorized_user_cannot_access_post(self):
"""User without role cannot access."""
@@ -61,7 +61,7 @@ def test_unauthorized_user_cannot_access_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_role_scoped_to_course_post(self):
"""Authorization should only apply to the assigned course."""
@@ -72,7 +72,7 @@ def test_role_scoped_to_course_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_staff_user_allowed_via_legacy_post(self):
"""
@@ -85,7 +85,7 @@ def test_staff_user_allowed_via_legacy_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_superuser_allowed_post(self):
"""Superusers should always be allowed."""
@@ -99,7 +99,7 @@ def test_superuser_allowed_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_non_staff_user_cannot_access_post(self):
"""
@@ -116,4 +116,4 @@ def test_non_staff_user_cannot_access_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v0/tests/test_course_optimizer.py b/cms/djangoapps/contentstore/rest_api/v0/tests/test_course_optimizer.py
index 4f0dfe189204..475c60c32403 100644
--- a/cms/djangoapps/contentstore/rest_api/v0/tests/test_course_optimizer.py
+++ b/cms/djangoapps/contentstore/rest_api/v0/tests/test_course_optimizer.py
@@ -30,14 +30,14 @@ def test_produces_4xx_when_invalid_course_id(self):
Test course_id validation
'''
response = self.make_request(course_id='invalid_course_id')
- self.assertIn(response.status_code, range(400, 500))
+ self.assertIn(response.status_code, range(400, 500)) # noqa: PT009
def test_produces_4xx_when_additional_kwargs(self):
'''
Test additional kwargs validation
'''
response = self.make_request(course_id=self.course.id, malicious_kwarg='malicious_kwarg')
- self.assertIn(response.status_code, range(400, 500))
+ self.assertIn(response.status_code, range(400, 500)) # noqa: PT009
class TestPostLinkCheck(AuthorizeStaffTestCase, ModuleStoreTestCase, TestCase):
@@ -62,18 +62,18 @@ def test_produces_4xx_when_invalid_course_id(self):
Test course_id validation
'''
response = self.make_request(course_id='invalid_course_id')
- self.assertIn(response.status_code, range(400, 500))
+ self.assertIn(response.status_code, range(400, 500)) # noqa: PT009
def test_produces_4xx_when_additional_kwargs(self):
'''
Test additional kwargs validation
'''
response = self.make_request(course_id=self.course.id, malicious_kwarg='malicious_kwarg')
- self.assertIn(response.status_code, range(400, 500))
+ self.assertIn(response.status_code, range(400, 500)) # noqa: PT009
def test_produces_4xx_when_unexpected_data(self):
'''
Test validation when request contains unexpected data
'''
response = self.make_request(course_id=self.course.id, data={'unexpected_data': 'unexpected_data'})
- self.assertIn(response.status_code, range(400, 500))
+ self.assertIn(response.status_code, range(400, 500)) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v0/tests/test_course_rerun_link_update.py b/cms/djangoapps/contentstore/rest_api/v0/tests/test_course_rerun_link_update.py
index fa1489545f29..64206571248f 100644
--- a/cms/djangoapps/contentstore/rest_api/v0/tests/test_course_rerun_link_update.py
+++ b/cms/djangoapps/contentstore/rest_api/v0/tests/test_course_rerun_link_update.py
@@ -86,8 +86,8 @@ def test_post_update_all_links_success(self):
data = {"action": "all"}
response = self.make_post_request(data=data)
- self.assertEqual(response.status_code, 200)
- self.assertIn("status", response.json())
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertIn("status", response.json()) # noqa: PT009
mock_task.delay.assert_called_once()
def test_post_update_single_links_success(self):
@@ -113,8 +113,8 @@ def test_post_update_single_links_success(self):
}
response = self.make_post_request(data=data)
- self.assertEqual(response.status_code, 200)
- self.assertIn("status", response.json())
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertIn("status", response.json()) # noqa: PT009
mock_task.delay.assert_called_once()
def test_post_update_missing_action_returns_400(self):
@@ -126,9 +126,9 @@ def test_post_update_missing_action_returns_400(self):
data = {}
response = self.make_post_request(data=data)
- self.assertEqual(response.status_code, 400)
- self.assertIn("error", response.json())
- self.assertIn("action", response.json()["error"])
+ self.assertEqual(response.status_code, 400) # noqa: PT009
+ self.assertIn("error", response.json()) # noqa: PT009
+ self.assertIn("action", response.json()["error"]) # noqa: PT009
def test_error_handling_workflow(self):
"""Test error handling in the complete workflow"""
@@ -142,11 +142,11 @@ def test_error_handling_workflow(self):
data = {"action": "all"}
response = self.make_post_request(data=data)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
# Step 2: Check failed status
with patch(self.task_status_patch) as mock_status:
- with patch(self.user_task_artifact_patch) as mock_artifact:
+ with patch(self.user_task_artifact_patch) as mock_artifact: # noqa: F841
mock_task_status = Mock()
mock_task_status.state = UserTaskStatus.FAILED
mock_status.return_value = mock_task_status
@@ -154,7 +154,7 @@ def test_error_handling_workflow(self):
status_url = self.get_status_url(self.course.id)
status_response = self.client.get(status_url)
- self.assertEqual(status_response.status_code, 200)
+ self.assertEqual(status_response.status_code, 200) # noqa: PT009
status_data = status_response.json()
- self.assertEqual(status_data["status"], "Failed")
- self.assertEqual(status_data["results"], [])
+ self.assertEqual(status_data["status"], "Failed") # noqa: PT009
+ self.assertEqual(status_data["results"], []) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v0/views/__init__.py b/cms/djangoapps/contentstore/rest_api/v0/views/__init__.py
index 5714754b191e..9d9be33f97ff 100644
--- a/cms/djangoapps/contentstore/rest_api/v0/views/__init__.py
+++ b/cms/djangoapps/contentstore/rest_api/v0/views/__init__.py
@@ -1,9 +1,14 @@
"""
Views for v0 contentstore API.
"""
-from .advanced_settings import AdvancedCourseSettingsView
-from .api_heartbeat import APIHeartBeatView
-from .authoring_grading import AuthoringGradingView
-from .course_optimizer import LinkCheckStatusView, LinkCheckView, RerunLinkUpdateStatusView, RerunLinkUpdateView
-from .tabs import CourseTabListView, CourseTabReorderView, CourseTabSettingsView
-from .transcripts import TranscriptView, YoutubeTranscriptCheckView, YoutubeTranscriptUploadView
+from .advanced_settings import AdvancedCourseSettingsView # noqa: F401
+from .api_heartbeat import APIHeartBeatView # noqa: F401
+from .authoring_grading import AuthoringGradingView # noqa: F401
+from .course_optimizer import ( # noqa: F401
+ LinkCheckStatusView,
+ LinkCheckView,
+ RerunLinkUpdateStatusView,
+ RerunLinkUpdateView,
+)
+from .tabs import CourseTabListView, CourseTabReorderView, CourseTabSettingsView # noqa: F401
+from .transcripts import TranscriptView, YoutubeTranscriptCheckView, YoutubeTranscriptUploadView # noqa: F401
diff --git a/cms/djangoapps/contentstore/rest_api/v1/mixins.py b/cms/djangoapps/contentstore/rest_api/v1/mixins.py
index 3ac4795680ff..18f1d66149d5 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/mixins.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/mixins.py
@@ -33,8 +33,8 @@ def test_permissions_unauthenticated(self):
self.client.logout()
response = self.client.get(self.url)
error = self.get_and_check_developer_response(response)
- self.assertEqual(error, "Authentication credentials were not provided.")
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(error, "Authentication credentials were not provided.") # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
@patch.dict("django.conf.settings.FEATURES", {"DISABLE_ADVANCED_SETTINGS": True})
def test_permissions_unauthorized(self):
@@ -44,8 +44,8 @@ def test_permissions_unauthorized(self):
client, _ = self.create_non_staff_authed_user_client()
response = client.get(self.url)
error = self.get_and_check_developer_response(response)
- self.assertEqual(error, "You do not have permission to perform this action.")
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(error, "You do not have permission to perform this action.") # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
class ContainerHandlerMixin:
diff --git a/cms/djangoapps/contentstore/rest_api/v1/serializers/__init__.py b/cms/djangoapps/contentstore/rest_api/v1/serializers/__init__.py
index dab1392d1ef4..26403f734775 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/serializers/__init__.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/serializers/__init__.py
@@ -1,28 +1,28 @@
"""
Serializers for v1 contentstore API.
"""
-from .certificates import CourseCertificatesSerializer
-from .course_details import CourseDetailsSerializer
-from .course_index import CourseIndexSerializer
-from .course_rerun import CourseRerunSerializer
-from .course_team import CourseTeamSerializer
-from .course_waffle_flags import CourseWaffleFlagsSerializer
-from .grading import CourseGradingModelSerializer, CourseGradingSerializer
-from .group_configurations import CourseGroupConfigurationsSerializer
-from .home import CourseHomeTabSerializer, LibraryTabSerializer, StudioHomeSerializer
+from .certificates import CourseCertificatesSerializer # noqa: F401
+from .course_details import CourseDetailsSerializer # noqa: F401
+from .course_index import CourseIndexSerializer # noqa: F401
+from .course_rerun import CourseRerunSerializer # noqa: F401
+from .course_team import CourseTeamSerializer # noqa: F401
+from .course_waffle_flags import CourseWaffleFlagsSerializer # noqa: F401
+from .grading import CourseGradingModelSerializer, CourseGradingSerializer # noqa: F401
+from .group_configurations import CourseGroupConfigurationsSerializer # noqa: F401
+from .home import CourseHomeTabSerializer, LibraryTabSerializer, StudioHomeSerializer # noqa: F401
from .proctoring import (
- LimitedProctoredExamSettingsSerializer,
- ProctoredExamConfigurationSerializer,
- ProctoredExamSettingsSerializer,
- ProctoringErrorsSerializer,
+ LimitedProctoredExamSettingsSerializer, # noqa: F401
+ ProctoredExamConfigurationSerializer, # noqa: F401
+ ProctoredExamSettingsSerializer, # noqa: F401
+ ProctoringErrorsSerializer, # noqa: F401
)
-from .settings import CourseSettingsSerializer
-from .textbooks import CourseTextbooksSerializer
-from .vertical_block import ContainerChildrenSerializer, ContainerHandlerSerializer
+from .settings import CourseSettingsSerializer # noqa: F401
+from .textbooks import CourseTextbooksSerializer # noqa: F401
+from .vertical_block import ContainerChildrenSerializer, ContainerHandlerSerializer # noqa: F401
from .videos import (
- CourseVideosSerializer,
- VideoDownloadSerializer,
- VideoImageSerializer,
- VideoUploadSerializer,
- VideoUsageSerializer,
+ CourseVideosSerializer, # noqa: F401
+ VideoDownloadSerializer, # noqa: F401
+ VideoImageSerializer, # noqa: F401
+ VideoUploadSerializer, # noqa: F401
+ VideoUsageSerializer, # noqa: F401
)
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/__init__.py b/cms/djangoapps/contentstore/rest_api/v1/views/__init__.py
index a7e87082c192..7654c9e0befc 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/__init__.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/__init__.py
@@ -1,18 +1,18 @@
"""
Views for v1 contentstore API.
"""
-from .certificates import CourseCertificatesView
-from .course_details import CourseDetailsView
-from .course_index import ContainerChildrenView, CourseIndexView
-from .course_rerun import CourseRerunView
-from .course_team import CourseTeamView
-from .course_waffle_flags import CourseWaffleFlagsView
-from .grading import CourseGradingView
-from .group_configurations import CourseGroupConfigurationsView
-from .help_urls import HelpUrlsView
-from .home import HomePageCoursesView, HomePageLibrariesView, HomePageView
-from .proctoring import ProctoredExamSettingsView, ProctoringErrorsView
-from .settings import CourseSettingsView
-from .textbooks import CourseTextbooksView
-from .vertical_block import ContainerHandlerView, vertical_container_children_redirect_view
-from .videos import CourseVideosView, VideoDownloadView, VideoUsageView
+from .certificates import CourseCertificatesView # noqa: F401
+from .course_details import CourseDetailsView # noqa: F401
+from .course_index import ContainerChildrenView, CourseIndexView # noqa: F401
+from .course_rerun import CourseRerunView # noqa: F401
+from .course_team import CourseTeamView # noqa: F401
+from .course_waffle_flags import CourseWaffleFlagsView # noqa: F401
+from .grading import CourseGradingView # noqa: F401
+from .group_configurations import CourseGroupConfigurationsView # noqa: F401
+from .help_urls import HelpUrlsView # noqa: F401
+from .home import HomePageCoursesView, HomePageLibrariesView, HomePageView # noqa: F401
+from .proctoring import ProctoredExamSettingsView, ProctoringErrorsView # noqa: F401
+from .settings import CourseSettingsView # noqa: F401
+from .textbooks import CourseTextbooksView # noqa: F401
+from .vertical_block import ContainerHandlerView, vertical_container_children_redirect_view # noqa: F401
+from .videos import CourseVideosView, VideoDownloadView, VideoUsageView # noqa: F401
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_certificates.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_certificates.py
index edf87449ef36..9ae3ba84d8bc 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_certificates.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_certificates.py
@@ -31,13 +31,13 @@ def test_success_response(self):
self._add_course_certificates(count=2, signatory_count=2)
response = self.client.get(self.url)
response_data = response.data
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(len(response_data["certificates"]), 2)
- self.assertEqual(len(response_data["certificates"][0]["signatories"]), 2)
- self.assertEqual(len(response_data["certificates"][1]["signatories"]), 2)
- self.assertEqual(response_data["course_number_override"], self.course.display_coursenumber)
- self.assertEqual(response_data["course_title"], self.course.display_name_with_default)
- self.assertEqual(response_data["course_number"], self.course.number)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(len(response_data["certificates"]), 2) # noqa: PT009
+ self.assertEqual(len(response_data["certificates"][0]["signatories"]), 2) # noqa: PT009
+ self.assertEqual(len(response_data["certificates"][1]["signatories"]), 2) # noqa: PT009
+ self.assertEqual(response_data["course_number_override"], self.course.display_coursenumber) # noqa: PT009
+ self.assertEqual(response_data["course_title"], self.course.display_name_with_default) # noqa: PT009
+ self.assertEqual(response_data["course_number"], self.course.number) # noqa: PT009
class CourseCertificatesAuthzViewTest(
@@ -59,7 +59,7 @@ def test_authorized_user_can_access(self):
self._add_course_certificates(count=2, signatory_count=2)
self.add_user_to_role_in_course(self.authorized_user, COURSE_STAFF.external_key, self.course.id)
resp = self.authorized_client.get(self.url)
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_non_staff_user_cannot_access(self):
"""
@@ -69,4 +69,4 @@ def test_non_staff_user_cannot_access(self):
self._add_course_certificates(count=2, signatory_count=2)
self.add_user_to_role_in_course(self.authorized_user, COURSE_EDITOR.external_key, self.course.id)
resp = self.authorized_client.get(self.url)
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_details.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_details.py
index 40006dee56db..2222dd6af990 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_details.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_details.py
@@ -37,8 +37,8 @@ def test_put_permissions_unauthenticated(self):
self.client.logout()
response = self.client.put(self.url)
error = self.get_and_check_developer_response(response)
- self.assertEqual(error, "Authentication credentials were not provided.")
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(error, "Authentication credentials were not provided.") # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_put_permissions_unauthorized(self):
"""
@@ -53,8 +53,8 @@ def test_put_permissions_unauthorized(self):
content_type="application/json",
)
error = self.get_and_check_developer_response(response)
- self.assertEqual(error, "You do not have permission to perform this action.")
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(error, "You do not have permission to perform this action.") # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
@patch.dict("django.conf.settings.FEATURES", {"ENABLE_PREREQUISITE_COURSES": True})
def test_put_invalid_pre_requisite_course(self):
@@ -65,8 +65,8 @@ def test_put_invalid_pre_requisite_course(self):
data=json.dumps(request_data),
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(response.json()["error"], "Invalid prerequisite course key")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertEqual(response.json()["error"], "Invalid prerequisite course key") # noqa: PT009
def test_put_course_details(self):
request_data = {
@@ -120,7 +120,7 @@ def test_put_course_details(self):
data=json.dumps(request_data),
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
@ddt.ddt
@@ -189,7 +189,7 @@ def test_put_permissions_unauthenticated(self):
client = APIClient() # no auth
response = client.put(self.url)
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_put_permissions_unauthorized(self):
"""
@@ -201,7 +201,7 @@ def test_put_permissions_unauthorized(self):
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_get_course_details_authorized(self):
"""
@@ -214,28 +214,28 @@ def test_get_course_details_authorized(self):
)
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_get_course_details_unauthorized(self):
"""
Unauthorized user should receive 403.
"""
response = self.unauthorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_get_course_details_staff_user(self):
"""
Django staff user should bypass AuthZ and access course details.
"""
response = self.staff_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_get_course_details_super_user(self):
"""
Superuser should bypass AuthZ and access course details.
"""
response = self.super_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
@ddt.data(
# No changes
@@ -269,7 +269,7 @@ def test_get_course_details_super_user(self):
@ddt.unpack
def test_classify_update(self, payload, expected):
result = _classify_update(payload, self.course.id)
- self.assertEqual(result, expected)
+ self.assertEqual(result, expected) # noqa: PT009
def test_classyfy_update_with_get_request(self):
"""
@@ -283,7 +283,7 @@ def test_classyfy_update_with_get_request(self):
self.course.id
)
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
current_course_details = response.json()
# This field is flagged as a details update because of a type mismatch:
# the GET response returns an invalid string, while the stored value has a different type.
@@ -292,7 +292,7 @@ def test_classyfy_update_with_get_request(self):
expected = (False, False)
result = _classify_update(current_course_details, self.course.id)
- self.assertEqual(result, expected)
+ self.assertEqual(result, expected) # noqa: PT009
def test_course_editor_can_edit_course_details(self):
"""
@@ -309,7 +309,7 @@ def test_course_editor_can_edit_course_details(self):
# Get the current status of the course details to use
# as the basis for the update request
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
current_course_details = response.json()
# This field is flagged as a details update because of a type mismatch:
# the GET response returns an invalid string, while the stored value has a different type.
@@ -327,7 +327,7 @@ def test_course_editor_can_edit_course_details(self):
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_course_staff_can_edit_course_schedule(self):
"""
@@ -343,7 +343,7 @@ def test_course_staff_can_edit_course_schedule(self):
# Get the current status of the course details to use
# as the basis for the update request
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
current_course_details = response.json()
# This field is flagged as a details update because of a type mismatch:
# the GET response returns an invalid string, while the stored value has a different type.
@@ -361,7 +361,7 @@ def test_course_staff_can_edit_course_schedule(self):
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_course_editor_cannot_edit_course_schedule(self):
"""
@@ -377,7 +377,7 @@ def test_course_editor_cannot_edit_course_schedule(self):
# Get the current status of the course details to use
# as the basis for the update request
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
current_course_details = response.json()
# This field is flagged as a details update because of a type mismatch:
# the GET response returns an invalid string, while the stored value has a different type.
@@ -395,7 +395,7 @@ def test_course_editor_cannot_edit_course_schedule(self):
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_course_staff_can_edit_course_schedule_and_details(self):
"""
@@ -411,7 +411,7 @@ def test_course_staff_can_edit_course_schedule_and_details(self):
# Get the current status of the course details to use
# as the basis for the update request
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
current_course_details = response.json()
# This field is flagged as a details update because of a type mismatch:
# the GET response returns an invalid string, while the stored value has a different type.
@@ -430,7 +430,7 @@ def test_course_staff_can_edit_course_schedule_and_details(self):
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_course_editor_cannot_edit_course_schedule_and_details(self):
"""
@@ -446,7 +446,7 @@ def test_course_editor_cannot_edit_course_schedule_and_details(self):
# Get the current status of the course details to use
# as the basis for the update request
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
current_course_details = response.json()
# This field is flagged as a details update because of a type mismatch:
# the GET response returns an invalid string, while the stored value has a different type.
@@ -465,7 +465,7 @@ def test_course_editor_cannot_edit_course_schedule_and_details(self):
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_unauthorized_user_cannot_edit_with_any_change_on_the_payload(self):
"""
@@ -481,7 +481,7 @@ def test_unauthorized_user_cannot_edit_with_any_change_on_the_payload(self):
# Get the current status of the course details to use
# as the basis for the update request
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
current_course_details = response.json()
# This field is flagged as a details update because of a type mismatch:
# the GET response returns an invalid string, while the stored value has a different type.
@@ -494,7 +494,7 @@ def test_unauthorized_user_cannot_edit_with_any_change_on_the_payload(self):
data=json.dumps(current_course_details),
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_put_user_without_role_then_added_can_update(self):
"""
@@ -506,7 +506,7 @@ def test_put_user_without_role_then_added_can_update(self):
data=json.dumps(self.request_data),
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
# Assign role dynamically
self.add_user_to_role_in_course(
@@ -520,7 +520,7 @@ def test_put_user_without_role_then_added_can_update(self):
data=json.dumps(self.request_data),
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
@patch.dict("django.conf.settings.FEATURES", {"ENABLE_PREREQUISITE_COURSES": True})
def test_put_invalid_pre_requisite_course_with_authz(self):
@@ -542,8 +542,8 @@ def test_put_invalid_pre_requisite_course_with_authz(self):
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(response.json()["error"], "Invalid prerequisite course key")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertEqual(response.json()["error"], "Invalid prerequisite course key") # noqa: PT009
def test_staff_user_can_update_without_authz_role(self):
"""
@@ -555,7 +555,7 @@ def test_staff_user_can_update_without_authz_role(self):
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_superuser_can_update_without_authz_role(self):
"""
@@ -567,4 +567,4 @@ def test_superuser_can_update_without_authz_role(self):
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_index.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_index.py
index 9ec6434bd96a..42b0d22995ac 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_index.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_index.py
@@ -92,8 +92,8 @@ def test_course_index_response(self):
'created_on': None,
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
@override_waffle_flag(CUSTOM_RELATIVE_DATES, active=False)
def test_course_index_response_with_show_locators(self):
@@ -143,14 +143,14 @@ def test_course_index_response_with_show_locators(self):
'created_on': None,
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
def test_course_index_response_with_invalid_course(self):
"""Check error response for invalid course id"""
response = self.client.get(self.url + "1")
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- self.assertEqual(response.data, {
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
+ self.assertEqual(response.data, { # noqa: PT009
"developer_message": f"Unknown course {self.course.id}1",
"error_code": "course_does_not_exist"
})
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_rerun.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_rerun.py
index 2c97422d9783..f0e970c41c7c 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_rerun.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_rerun.py
@@ -32,5 +32,5 @@ def test_course_rerun_response(self):
"run": self.course.id.run,
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_team.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_team.py
index 967f583f02d1..2fb46dd47ea9 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_team.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_course_team.py
@@ -65,8 +65,8 @@ def test_course_team_response(self):
response = self.client.get(self.url)
expected_response = self.get_expected_course_data()
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
def test_users_response(self):
"""Test the response for users in the course."""
@@ -74,5 +74,5 @@ def test_users_response(self):
response = self.client.get(self.url)
users_response = [dict(item) for item in response.data["users"]]
expected_response = self.get_expected_course_data(instructor, staff)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertListEqual(expected_response["users"], users_response)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertListEqual(expected_response["users"], users_response) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_grading.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_grading.py
index 00e24f9d616c..bc7bd17e1757 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_grading.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_grading.py
@@ -50,8 +50,8 @@ def test_course_grading_response(self):
"default_grade_designations": ['A', 'B', 'C', 'D'],
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
@patch("django.conf.settings.DEFAULT_GRADE_DESIGNATIONS", ['A', 'B'])
def test_default_grade_designations_setting(self):
@@ -60,8 +60,8 @@ def test_default_grade_designations_setting(self):
"""
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(['A', 'B'], response.data["default_grade_designations"])
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(['A', 'B'], response.data["default_grade_designations"]) # noqa: PT009
@patch.dict("django.conf.settings.FEATURES", {"ENABLE_CREDIT_ELIGIBILITY": True})
def test_credit_eligibility_setting(self):
@@ -70,9 +70,9 @@ def test_credit_eligibility_setting(self):
"""
_ = CreditCourseFactory(course_key=self.course.id, enabled=True)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertTrue(response.data["show_credit_eligibility"])
- self.assertTrue(response.data["is_credit_course"])
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertTrue(response.data["show_credit_eligibility"]) # noqa: PT009
+ self.assertTrue(response.data["is_credit_course"]) # noqa: PT009
def test_post_permissions_unauthenticated(self):
"""
@@ -81,8 +81,8 @@ def test_post_permissions_unauthenticated(self):
self.client.logout()
response = self.client.post(self.url)
error = self.get_and_check_developer_response(response)
- self.assertEqual(error, "Authentication credentials were not provided.")
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(error, "Authentication credentials were not provided.") # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_post_permissions_unauthorized(self):
"""
@@ -91,8 +91,8 @@ def test_post_permissions_unauthorized(self):
client, _ = self.create_non_staff_authed_user_client()
response = client.post(self.url)
error = self.get_and_check_developer_response(response)
- self.assertEqual(error, "You do not have permission to perform this action.")
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(error, "You do not have permission to perform this action.") # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
@patch(
"openedx.core.djangoapps.credit.tasks.update_credit_course_requirements.delay"
@@ -120,7 +120,7 @@ def test_post_course_grading(self, mock_update_credit_course_requirements):
data=json.dumps(request_data),
content_type="application/json",
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
mock_update_credit_course_requirements.assert_called_once()
@@ -150,19 +150,19 @@ class CourseGradingViewAuthzTest(CourseAuthzTestMixin, BaseCourseViewTest):
def test_authorized_user_can_access_get(self):
"""User with COURSE_STAFF role can access."""
resp = self.authorized_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_unauthorized_user_cannot_access_get(self):
"""User without role cannot access."""
resp = self.unauthorized_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_role_scoped_to_course_get(self):
"""Authorization should only apply to the assigned course."""
other_course = self.store.create_course("OtherOrg", "OtherCourse", "Run", self.staff.id)
resp = self.authorized_client.get(self.get_url(other_course.id))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_staff_user_allowed_via_legacy_get(self):
"""
@@ -171,7 +171,7 @@ def test_staff_user_allowed_via_legacy_get(self):
self.client.login(username=self.staff.username, password=self.password)
resp = self.client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_superuser_allowed_get(self):
"""Superusers should always be allowed."""
@@ -181,7 +181,7 @@ def test_superuser_allowed_get(self):
client.force_authenticate(user=superuser)
resp = client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_non_staff_user_cannot_access_get(self):
"""
@@ -194,7 +194,7 @@ def test_non_staff_user_cannot_access_get(self):
non_staff_client.force_authenticate(user=non_staff_user)
resp = non_staff_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_authorized_user_can_access_post(self):
"""User with COURSE_STAFF role can access."""
@@ -203,7 +203,7 @@ def test_authorized_user_can_access_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_unauthorized_user_cannot_access_post(self):
"""User without role cannot access."""
@@ -212,7 +212,7 @@ def test_unauthorized_user_cannot_access_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_role_scoped_to_course_post(self):
"""Authorization should only apply to the assigned course."""
@@ -223,7 +223,7 @@ def test_role_scoped_to_course_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_staff_user_allowed_via_legacy_post(self):
"""
@@ -236,7 +236,7 @@ def test_staff_user_allowed_via_legacy_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_superuser_allowed_post(self):
"""Superusers should always be allowed."""
@@ -250,7 +250,7 @@ def test_superuser_allowed_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_non_staff_user_cannot_access_post(self):
"""
@@ -267,4 +267,4 @@ def test_non_staff_user_cannot_access_post(self):
data=self.post_data,
content_type="application/json"
)
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_group_configurations.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_group_configurations.py
index b246e676be5d..496a50437104 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_group_configurations.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_group_configurations.py
@@ -47,12 +47,12 @@ def test_success_response(self):
self.store.update_item(self.course, self.user.id)
response = self.client.get(self.url)
- self.assertEqual(len(response.data["all_group_configurations"]), 1)
- self.assertEqual(len(response.data["experiment_group_configurations"]), 1)
+ self.assertEqual(len(response.data["all_group_configurations"]), 1) # noqa: PT009
+ self.assertEqual(len(response.data["experiment_group_configurations"]), 1) # noqa: PT009
self.assertContains(response, "First name", count=1)
self.assertContains(response, "Group C")
self.assertContains(response, CONTENT_GROUP_CONFIGURATION_NAME)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
class CourseGroupConfigurationsAuthzTest(CourseAuthzTestMixin, BaseCourseViewTest):
"""
@@ -66,19 +66,19 @@ class CourseGroupConfigurationsAuthzTest(CourseAuthzTestMixin, BaseCourseViewTes
def test_authorized_user_can_access(self):
"""User with COURSE_STAFF role can access."""
resp = self.authorized_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_unauthorized_user_cannot_access(self):
"""User without role cannot access."""
resp = self.unauthorized_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_role_scoped_to_course(self):
"""Authorization should only apply to the assigned course."""
other_course = self.store.create_course("OtherOrg", "OtherCourse", "Run", self.staff.id)
resp = self.authorized_client.get(self.get_url(other_course.id))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_staff_user_allowed_via_legacy(self):
"""
@@ -87,7 +87,7 @@ def test_staff_user_allowed_via_legacy(self):
self.client.login(username=self.staff.username, password=self.password)
resp = self.client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_superuser_allowed(self):
"""Superusers should always be allowed."""
@@ -97,7 +97,7 @@ def test_superuser_allowed(self):
client.force_authenticate(user=superuser)
resp = client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_non_staff_user_cannot_access(self):
"""
@@ -110,4 +110,4 @@ def test_non_staff_user_cannot_access(self):
non_staff_client.force_authenticate(user=non_staff_user)
resp = non_staff_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_home.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_home.py
index a155ceb235a4..bebcdfd53dc5 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_home.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_home.py
@@ -66,8 +66,8 @@ def test_home_page_studio_response(self):
"""Check successful response content"""
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(self.expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(self.expected_response, response.data) # noqa: PT009
@override_settings(MEILISEARCH_ENABLED=True)
def test_home_page_studio_with_meilisearch_enabled(self):
@@ -77,8 +77,8 @@ def test_home_page_studio_with_meilisearch_enabled(self):
expected_response = self.expected_response
expected_response["libraries_v2_enabled"] = True
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
@override_settings(ORGANIZATIONS_AUTOCREATE=False)
def test_home_page_studio_with_org_autocreate_disabled(self):
@@ -88,13 +88,13 @@ def test_home_page_studio_with_org_autocreate_disabled(self):
expected_response = self.expected_response
expected_response["allow_to_create_new_org"] = False
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
def test_taxonomy_list_link(self):
response = self.client.get(self.url)
- self.assertTrue(response.data['taxonomies_enabled'])
- self.assertEqual(
+ self.assertTrue(response.data['taxonomies_enabled']) # noqa: PT009
+ self.assertEqual( # noqa: PT009
response.data['taxonomy_list_mfe_url'],
f'{settings.COURSE_AUTHORING_MICROFRONTEND_URL}/taxonomies'
)
@@ -137,8 +137,8 @@ def test_home_page_response(self):
"in_process_course_actions": [],
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
def test_home_page_response_with_api_v2(self):
"""Check successful response content with api v2 modifications.
@@ -166,8 +166,8 @@ def test_home_page_response_with_api_v2(self):
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
@ddt.data(
("active_only", "true", 2, 0),
@@ -207,9 +207,9 @@ def test_filter_and_ordering_courses(
response = self.client.get(self.url, {filter_key: filter_value})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(len(response.data["archived_courses"]), expected_archived_length)
- self.assertEqual(len(response.data["courses"]), expected_active_length)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(len(response.data["archived_courses"]), expected_archived_length) # noqa: PT009
+ self.assertEqual(len(response.data["courses"]), expected_active_length) # noqa: PT009
@ddt.data(
("active_only", "true"),
@@ -224,8 +224,8 @@ def test_filter_and_ordering_no_courses_staff(self, filter_key, filter_value):
response = self.client.get(self.url, {filter_key: filter_value})
- self.assertEqual(len(response.data["courses"]), 0)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.data["courses"]), 0) # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
@ddt.data(
("active_only", "true"),
@@ -240,8 +240,8 @@ def test_home_page_response_no_courses_non_staff(self, filter_key, filter_value)
response = self.non_staff_client.get(self.url, {filter_key: filter_value})
- self.assertEqual(len(response.data["courses"]), 0)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.data["courses"]), 0) # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
@ddt.ddt
@@ -347,8 +347,8 @@ def test_home_page_libraries_response(self):
]
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.json())
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.json()) # noqa: PT009
# Fetch legacy libraries that were migrated to v2
response = self.client.get(self.url + '?is_migrated=true')
@@ -371,8 +371,8 @@ def test_home_page_libraries_response(self):
],
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.json())
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.json()) # noqa: PT009
# Fetch legacy libraries that were not migrated to v2
response = self.client.get(self.url + '?is_migrated=false')
@@ -400,5 +400,5 @@ def test_home_page_libraries_response(self):
],
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.json())
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.json()) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_proctoring.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_proctoring.py
index 527355ddc150..ae94a7ccecf2 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_proctoring.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_proctoring.py
@@ -181,7 +181,7 @@ def test_update_exam_settings_200_escalation_email(self):
# response is correct
assert response.status_code == status.HTTP_200_OK
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response.data,
{
"proctored_exam_settings": {
@@ -218,7 +218,7 @@ def test_update_exam_settings_200_no_escalation_email(self):
# response is correct
assert response.status_code == status.HTTP_200_OK
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response.data,
{
"proctored_exam_settings": {
@@ -249,7 +249,7 @@ def test_update_exam_settings_excluded_field(self):
# response is correct
assert response.status_code == status.HTTP_200_OK
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response.data,
{
"proctored_exam_settings": {
@@ -282,7 +282,7 @@ def test_update_exam_settings_invalid_value(self):
# response is correct
assert response.status_code == status.HTTP_400_BAD_REQUEST
- self.assertIn(
+ self.assertIn( # noqa: PT009
{
"proctoring_provider": (
"The selected proctoring provider, notvalidprovider, is not a valid provider. "
@@ -349,7 +349,7 @@ def test_nonadmin_with_zendesk_ticket(
assert response.status_code == status.HTTP_200_OK
if expect_log:
logger_string = (
- "create_zendesk_tickets set to {ticket_value} but proctoring "
+ "create_zendesk_tickets set to {ticket_value} but proctoring " # noqa: UP032
"provider is {provider} for course {course_id}. create_zendesk_tickets "
"should be updated for this course.".format(
ticket_value=create_zendesk_tickets,
@@ -377,7 +377,7 @@ def test_200_for_lti_provider(self):
# response is correct
assert response.status_code == status.HTTP_200_OK
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response.data,
{
"proctored_exam_settings": {
@@ -409,7 +409,7 @@ def test_400_for_disabled_lti(self):
# response is correct
assert response.status_code == status.HTTP_400_BAD_REQUEST
- self.assertIn(
+ self.assertIn( # noqa: PT009
{
"proctoring_provider": (
"The selected proctoring provider, lti_external, is not a valid provider. "
@@ -449,7 +449,7 @@ def test_disable_advanced_settings_feature(self, disable_advanced_settings):
FEATURES={"DISABLE_ADVANCED_SETTINGS": disable_advanced_settings}
):
response = self.non_staff_client.get(self.url)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
response.status_code, 403 if disable_advanced_settings else 200
)
@@ -459,7 +459,7 @@ def test_authz_user_allowed(self, mock_is_user_allowed, mock_flag):
"""User with authz permission can access proctoring errors."""
mock_is_user_allowed.return_value = True
response = self.non_staff_client.get(self.url)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
mock_is_user_allowed.assert_called_once()
@patch.object(core_toggles.AUTHZ_COURSE_AUTHORING_FLAG, 'is_enabled', return_value=True)
@@ -468,7 +468,7 @@ def test_authz_user_not_allowed(self, mock_is_user_allowed, mock_flag):
"""User without authz permission cannot access proctoring errors."""
mock_is_user_allowed.return_value = False
response = self.non_staff_client.get(self.url)
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
mock_is_user_allowed.assert_called_once()
@patch.object(core_toggles.AUTHZ_COURSE_AUTHORING_FLAG, 'is_enabled', return_value=True)
@@ -477,7 +477,7 @@ def test_authz_with_disable_advanced_settings_staff_allowed(self, mock_is_user_a
"""Staff user can access when DISABLE_ADVANCED_SETTINGS is enabled, bypassing authz."""
with override_settings(FEATURES={"DISABLE_ADVANCED_SETTINGS": True}):
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
mock_is_user_allowed.assert_not_called()
@patch.object(core_toggles.AUTHZ_COURSE_AUTHORING_FLAG, 'is_enabled', return_value=True)
@@ -486,5 +486,5 @@ def test_authz_with_disable_advanced_settings_non_staff_denied(self, mock_is_use
"""Non-staff user is denied when DISABLE_ADVANCED_SETTINGS is enabled, bypassing authz."""
with override_settings(FEATURES={"DISABLE_ADVANCED_SETTINGS": True}):
response = self.non_staff_client.get(self.url)
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
mock_is_user_allowed.assert_not_called()
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_settings.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_settings.py
index 50bceaa16377..83ee03294790 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_settings.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_settings.py
@@ -59,8 +59,8 @@ def test_course_settings_response(self):
"licensing_enabled": False,
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
@patch.dict("django.conf.settings.FEATURES", {"ENABLE_CREDIT_ELIGIBILITY": True})
def test_credit_eligibility_setting(self):
@@ -69,9 +69,9 @@ def test_credit_eligibility_setting(self):
"""
_ = CreditCourseFactory(course_key=self.course.id, enabled=True)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn("credit_requirements", response.data)
- self.assertTrue(response.data["is_credit_course"])
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn("credit_requirements", response.data) # noqa: PT009
+ self.assertTrue(response.data["is_credit_course"]) # noqa: PT009
@patch.dict(
"django.conf.settings.FEATURES",
@@ -85,8 +85,8 @@ def test_prerequisite_courses_enabled_setting(self):
Make sure if the feature flags are enabled we have updated the dict keys in response.
"""
response = self.client.get(self.url)
- self.assertIn("possible_pre_requisite_courses", response.data)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIn("possible_pre_requisite_courses", response.data) # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
@ddt.ddt
@@ -107,14 +107,14 @@ def test_authorized_user_can_access_course_settings(self):
self.add_user_to_role_in_course(self.authorized_user, COURSE_EDITOR.external_key, self.course.id)
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn("course_display_name", response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn("course_display_name", response.data) # noqa: PT009
def test_unauthorized_user_cannot_access_course_settings(self):
"""Unauthorized user should receive 403."""
response = self.unauthorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_user_without_role_then_added_can_access(self):
"""
@@ -122,7 +122,7 @@ def test_user_without_role_then_added_can_access(self):
"""
# Initially unauthorized
response = self.unauthorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
# Assign role dynamically
self.add_user_to_role_in_course(
@@ -132,7 +132,7 @@ def test_user_without_role_then_added_can_access(self):
)
response = self.unauthorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
@patch.dict("django.conf.settings.FEATURES", {"ENABLE_CREDIT_ELIGIBILITY": True})
def test_credit_eligibility_setting_with_authz(self):
@@ -144,21 +144,21 @@ def test_credit_eligibility_setting_with_authz(self):
self.add_user_to_role_in_course(self.authorized_user, COURSE_EDITOR.external_key, self.course.id)
response = self.authorized_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn("credit_requirements", response.data)
- self.assertTrue(response.data["is_credit_course"])
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn("credit_requirements", response.data) # noqa: PT009
+ self.assertTrue(response.data["is_credit_course"]) # noqa: PT009
def test_staff_user_can_access_without_authz_role(self):
"""Django staff user should access course settings without AuthZ role."""
response = self.staff_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn("course_display_name", response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn("course_display_name", response.data) # noqa: PT009
def test_superuser_can_access_without_authz_role(self):
"""Superuser should access course settings without AuthZ role."""
response = self.super_client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn("course_display_name", response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn("course_display_name", response.data) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_textbooks.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_textbooks.py
index f4dcef0cd131..26ec42f839a3 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_textbooks.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_textbooks.py
@@ -42,8 +42,8 @@ def test_success_response(self):
self.save_course()
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.data["textbooks"], expected_textbook)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(response.data["textbooks"], expected_textbook) # noqa: PT009
class CourseTextbooksAuthzTest(CourseAuthoringAuthzTestMixin, CourseTestCase):
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_vertical_block.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_vertical_block.py
index f9955b7f06af..260ed4732320 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_vertical_block.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_vertical_block.py
@@ -138,7 +138,7 @@ def test_success_response(self):
"""
url = self.get_reverse_url(self.vertical.location)
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_ancestor_xblocks_response(self):
"""
@@ -184,7 +184,7 @@ def test_ancestor_xblocks_response(self):
def sort_key(block):
return block.get("title", "")
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
sorted(response_ancestor_xblocks, key=sort_key),
sorted(expected_ancestor_xblocks, key=sort_key)
)
@@ -198,7 +198,7 @@ def test_not_valid_usage_key_string(self):
)
url = self.get_reverse_url(usage_key_string)
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
class ContainerVerticalViewTest(BaseXBlockContainer):
@@ -214,13 +214,13 @@ def test_success_response(self):
"""
url = self.get_reverse_url(self.vertical.location)
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(len(data["children"]), 2)
- self.assertFalse(data["is_published"])
- self.assertTrue(data["can_paste_component"])
- self.assertEqual(data["display_name"], "Unit")
- self.assertEqual(data["upstream_ready_to_sync_children_info"], [])
+ self.assertEqual(len(data["children"]), 2) # noqa: PT009
+ self.assertFalse(data["is_published"]) # noqa: PT009
+ self.assertTrue(data["can_paste_component"]) # noqa: PT009
+ self.assertEqual(data["display_name"], "Unit") # noqa: PT009
+ self.assertEqual(data["upstream_ready_to_sync_children_info"], []) # noqa: PT009
def test_success_response_with_upstream_info(self):
"""
@@ -228,13 +228,13 @@ def test_success_response_with_upstream_info(self):
"""
url = self.get_reverse_url(self.vertical.location)
response = self.client.get(f"{url}?get_upstream_info=true")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(len(data["children"]), 2)
- self.assertFalse(data["is_published"])
- self.assertTrue(data["can_paste_component"])
- self.assertEqual(data["display_name"], "Unit")
- self.assertEqual(data["upstream_ready_to_sync_children_info"], [{
+ self.assertEqual(len(data["children"]), 2) # noqa: PT009
+ self.assertFalse(data["is_published"]) # noqa: PT009
+ self.assertTrue(data["can_paste_component"]) # noqa: PT009
+ self.assertEqual(data["display_name"], "Unit") # noqa: PT009
+ self.assertEqual(data["upstream_ready_to_sync_children_info"], [{ # noqa: PT009
"id": str(self.html_unit_second.usage_key),
"upstream": self.html_block["id"],
"block_type": "html",
@@ -249,7 +249,7 @@ def test_xblock_is_published(self):
self.publish_item(self.store, self.vertical.location)
url = self.get_reverse_url(self.vertical.location)
response = self.client.get(url)
- self.assertTrue(response.data["is_published"])
+ self.assertTrue(response.data["is_published"]) # noqa: PT009
def test_children_content(self):
"""
@@ -324,7 +324,7 @@ def test_children_content(self):
]
self.maxDiff = None
# Using json() shows meaningful diff in case of error
- self.assertEqual(response.json()["children"], expected_response)
+ self.assertEqual(response.json()["children"], expected_response) # noqa: PT009
def test_not_valid_usage_key_string(self):
"""
@@ -335,7 +335,7 @@ def test_not_valid_usage_key_string(self):
)
url = self.get_reverse_url(usage_key_string)
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
@override_waffle_flag(DISABLE_TAGGING_FEATURE, True)
def test_actions_with_turned_off_taxonomy_flag(self):
@@ -345,7 +345,7 @@ def test_actions_with_turned_off_taxonomy_flag(self):
url = self.get_reverse_url(self.vertical.location)
response = self.client.get(url)
for children in response.data["children"]:
- self.assertFalse(children["actions"]["can_manage_tags"])
+ self.assertFalse(children["actions"]["can_manage_tags"]) # noqa: PT009
def test_validation_errors(self):
"""
@@ -381,7 +381,7 @@ def test_validation_errors(self):
children_response = response.data["children"]
# Verify that html_unit_first access settings contradict its parent's access settings.
- self.assertEqual(children_response[0]["validation_messages"][0]["type"], ValidationMessage.ERROR)
+ self.assertEqual(children_response[0]["validation_messages"][0]["type"], ValidationMessage.ERROR) # noqa: PT009
# Verify that html_unit_second has no validation messages.
- self.assertFalse(children_response[1]["validation_messages"])
+ self.assertFalse(children_response[1]["validation_messages"]) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_videos.py b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_videos.py
index 91fe2ab0d7d1..9da850244ccc 100644
--- a/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_videos.py
+++ b/cms/djangoapps/contentstore/rest_api/v1/views/tests/test_videos.py
@@ -73,8 +73,8 @@ def test_course_videos_response(self):
"pagination_context": {}
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
@override_waffle_switch(WaffleSwitch( # lint-amnesty, pylint: disable=toggle-missing-annotation
'videos.video_image_upload_enabled', __name__
@@ -84,12 +84,12 @@ def test_video_image_upload_enabled(self):
Make sure if the feature flag is enabled we have updated the dict keys in response.
"""
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn("video_image_settings", response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn("video_image_settings", response.data) # noqa: PT009
imageSettings = response.data["video_image_settings"]
- self.assertIn("video_image_upload_enabled", imageSettings)
- self.assertTrue(imageSettings["video_image_upload_enabled"])
+ self.assertIn("video_image_upload_enabled", imageSettings) # noqa: PT009
+ self.assertTrue(imageSettings["video_image_upload_enabled"]) # noqa: PT009
def test_VideoTranscriptEnabledFlag_enabled(self):
"""
@@ -98,40 +98,40 @@ def test_VideoTranscriptEnabledFlag_enabled(self):
with patch('openedx.core.djangoapps.video_config.models.VideoTranscriptEnabledFlag.feature_enabled') as feature:
feature.return_value = True
response = self.client.get(self.url)
- self.assertIn("is_video_transcript_enabled", response.data)
- self.assertTrue(response.data["is_video_transcript_enabled"])
+ self.assertIn("is_video_transcript_enabled", response.data) # noqa: PT009
+ self.assertTrue(response.data["is_video_transcript_enabled"]) # noqa: PT009
expect_active_preferences = get_transcript_preferences(str(self.course.id))
- self.assertIn("active_transcript_preferences", response.data)
- self.assertEqual(expect_active_preferences, response.data["active_transcript_preferences"])
+ self.assertIn("active_transcript_preferences", response.data) # noqa: PT009
+ self.assertEqual(expect_active_preferences, response.data["active_transcript_preferences"]) # noqa: PT009
expected_credentials = get_transcript_credentials_state_for_org(self.course.id.org)
- self.assertIn("transcript_credentials", response.data)
- self.assertDictEqual(expected_credentials, response.data["transcript_credentials"])
+ self.assertIn("transcript_credentials", response.data) # noqa: PT009
+ self.assertDictEqual(expected_credentials, response.data["transcript_credentials"]) # noqa: PT009
transcript_settings = response.data["video_transcript_settings"]
expected_plans = get_3rd_party_transcription_plans()
- self.assertIn("transcription_plans", transcript_settings)
- self.assertDictEqual(expected_plans, transcript_settings["transcription_plans"])
+ self.assertIn("transcription_plans", transcript_settings) # noqa: PT009
+ self.assertDictEqual(expected_plans, transcript_settings["transcription_plans"]) # noqa: PT009
expected_preference_handler = reverse_course_url(
'transcript_preferences_handler',
str(self.course.id)
)
- self.assertIn("transcript_preferences_handler_url", transcript_settings)
- self.assertEqual(expected_preference_handler, transcript_settings["transcript_preferences_handler_url"])
+ self.assertIn("transcript_preferences_handler_url", transcript_settings) # noqa: PT009
+ self.assertEqual(expected_preference_handler, transcript_settings["transcript_preferences_handler_url"]) # noqa: PT009 # pylint: disable=line-too-long
expected_credentials_handler = reverse_course_url(
'transcript_credentials_handler',
str(self.course.id)
)
- self.assertIn("transcript_credentials_handler_url", transcript_settings)
- self.assertEqual(expected_credentials_handler, transcript_settings["transcript_credentials_handler_url"])
+ self.assertIn("transcript_credentials_handler_url", transcript_settings) # noqa: PT009
+ self.assertEqual(expected_credentials_handler, transcript_settings["transcript_credentials_handler_url"]) # noqa: PT009 # pylint: disable=line-too-long
with patch(
'openedx.core.djangoapps.video_config.toggles.XPERT_TRANSLATIONS_UI.is_enabled'
) as xpertTranslationfeature:
xpertTranslationfeature.return_value = True
response = self.client.get(self.url)
- self.assertIn("is_ai_translations_enabled", response.data)
- self.assertTrue(response.data["is_ai_translations_enabled"])
+ self.assertIn("is_ai_translations_enabled", response.data) # noqa: PT009
+ self.assertTrue(response.data["is_ai_translations_enabled"]) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py b/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py
index 822fc513ee2b..ffa8b0fa7089 100644
--- a/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py
+++ b/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py
@@ -26,7 +26,7 @@ class CourseToLibraryTestCase(ContentLibrariesRestApiTest, ImmediateOnCommitMixi
def setUp(self):
super().setUp()
- self.now = datetime.now(timezone.utc)
+ self.now = datetime.now(timezone.utc) # noqa: UP017
freezer = freeze_time(self.now)
self.addCleanup(freezer.stop)
freezer.start()
@@ -160,7 +160,7 @@ def _get_downstream_links(
def assertXmlEqual(self, xml_str_a: str, xml_str_b: str) -> None:
""" Assert that the given XML strings are equal, ignoring attribute order and some whitespace variations. """
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
ElementTree.canonicalize(xml_str_a, strip_text=True),
ElementTree.canonicalize(xml_str_b, strip_text=True),
)
@@ -441,8 +441,8 @@ def test_unit_sync(self):
}
]
data = downstreams.json()
- self.assertEqual(data["count"], 4)
- self.assertListEqual(data["results"], expected_downstreams)
+ self.assertEqual(data["count"], 4) # noqa: PT009
+ self.assertListEqual(data["results"], expected_downstreams) # noqa: PT009
# 2️⃣ Now, lets modify the upstream problem 1:
self._set_library_block_olx(
@@ -594,8 +594,8 @@ def test_unit_sync(self):
}
]
data = downstreams.json()
- self.assertEqual(data["count"], 4)
- self.assertListEqual(data["results"], expected_downstreams)
+ self.assertEqual(data["count"], 4) # noqa: PT009
+ self.assertListEqual(data["results"], expected_downstreams) # noqa: PT009
# 3️⃣ Now, add and delete a component
upstream_problem3 = self._add_block_to_library(
@@ -746,8 +746,8 @@ def test_unit_sync(self):
}
]
data = downstreams.json()
- self.assertEqual(data["count"], 4)
- self.assertListEqual(data["results"], expected_downstreams)
+ self.assertEqual(data["count"], 4) # noqa: PT009
+ self.assertListEqual(data["results"], expected_downstreams) # noqa: PT009
# 4️⃣ Now, reorder components
self._patch_container_children(self.upstream_unit["id"], [
@@ -879,8 +879,8 @@ def test_unit_sync(self):
}
]
data = downstreams.json()
- self.assertEqual(data["count"], 4)
- self.assertListEqual(data["results"], expected_downstreams)
+ self.assertEqual(data["count"], 4) # noqa: PT009
+ self.assertListEqual(data["results"], expected_downstreams) # noqa: PT009
def test_unit_sync_with_modified_downstream(self):
"""
@@ -1120,8 +1120,8 @@ def test_modified_html_copy_paste(self):
},
]
data = downstreams.json()
- self.assertEqual(data["count"], 1)
- self.assertListEqual(data["results"], expected_downstreams)
+ self.assertEqual(data["count"], 1) # noqa: PT009
+ self.assertListEqual(data["results"], expected_downstreams) # noqa: PT009
# 2️⃣ Now, lets modify the upstream html AND the downstream display_name:
self._update_course_block_fields(downstream_html1["locator"], {
@@ -1182,8 +1182,8 @@ def test_modified_html_copy_paste(self):
},
]
data = downstreams.json()
- self.assertEqual(data["count"], 1)
- self.assertListEqual(data["results"], expected_downstreams)
+ self.assertEqual(data["count"], 1) # noqa: PT009
+ self.assertListEqual(data["results"], expected_downstreams) # noqa: PT009
# 3️⃣ Now, sync and check the resulting OLX of the downstream
diff --git a/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstreams.py b/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstreams.py
index f82859f74bd3..96ad82451f1f 100644
--- a/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstreams.py
+++ b/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstreams.py
@@ -70,7 +70,7 @@ def setUp(self):
"""
# pylint: disable=too-many-statements
super().setUp()
- self.now = datetime.now(timezone.utc)
+ self.now = datetime.now(timezone.utc) # noqa: UP017
freezer = freeze_time(self.now)
self.addCleanup(freezer.stop)
freezer.start()
@@ -653,7 +653,7 @@ def test_200_single_upstream_container(self):
assert data['ready_to_sync'] is True
assert len(data['ready_to_sync_children']) == 1
html_block = modulestore().get_item(self.top_level_downstream_html_key)
- self.assertDictEqual(data['ready_to_sync_children'][0], {
+ self.assertDictEqual(data['ready_to_sync_children'][0], { # noqa: PT009
'name': html_block.display_name,
'upstream': str(self.html_lib_id_2),
'block_type': 'html',
@@ -870,8 +870,8 @@ def test_200_all_downstreams_for_a_course(self):
'downstream_customized': [],
},
]
- self.assertListEqual(data["results"], expected)
- self.assertEqual(data["count"], 11)
+ self.assertListEqual(data["results"], expected) # noqa: PT009
+ self.assertEqual(data["count"], 11) # noqa: PT009
def test_permission_denied_with_course_filter(self):
self.client.login(username="simple_user", password="password")
@@ -964,8 +964,8 @@ def test_200_component_downstreams_for_a_course(self):
'downstream_customized': [],
},
]
- self.assertListEqual(data["results"], expected)
- self.assertEqual(data["count"], 4)
+ self.assertListEqual(data["results"], expected) # noqa: PT009
+ self.assertEqual(data["count"], 4) # noqa: PT009
def test_200_container_downstreams_for_a_course(self):
"""
@@ -1107,8 +1107,8 @@ def test_200_container_downstreams_for_a_course(self):
'downstream_customized': [],
},
]
- self.assertListEqual(data["results"], expected)
- self.assertEqual(data["count"], 7)
+ self.assertListEqual(data["results"], expected) # noqa: PT009
+ self.assertEqual(data["count"], 7) # noqa: PT009
@ddt.data(
('all', 2),
@@ -1127,8 +1127,8 @@ def test_200_downstreams_ready_to_sync(self, item_type, expected_count):
)
assert response.status_code == 200
data = response.json()
- self.assertTrue(all(o["ready_to_sync"] for o in data["results"]))
- self.assertEqual(data["count"], expected_count)
+ self.assertTrue(all(o["ready_to_sync"] for o in data["results"])) # noqa: PT009
+ self.assertEqual(data["count"], expected_count) # noqa: PT009
def test_permission_denied_without_filter(self):
self.client.login(username="simple_user", password="password")
@@ -1145,8 +1145,8 @@ def test_200_component_downstream_context_list(self):
data = response.json()
expected = [str(self.downstream_video_key)] + [str(key) for key in self.another_video_keys]
got = [str(o["downstream_usage_key"]) for o in data["results"]]
- self.assertListEqual(got, expected)
- self.assertEqual(data["count"], 4)
+ self.assertListEqual(got, expected) # noqa: PT009
+ self.assertEqual(data["count"], 4) # noqa: PT009
def test_200_container_downstream_context_list(self):
"""
@@ -1158,8 +1158,8 @@ def test_200_container_downstream_context_list(self):
data = response.json()
expected = [str(self.downstream_unit_key)]
got = [str(o["downstream_usage_key"]) for o in data["results"]]
- self.assertListEqual(got, expected)
- self.assertEqual(data["count"], 1)
+ self.assertListEqual(got, expected) # noqa: PT009
+ self.assertEqual(data["count"], 1) # noqa: PT009
def test_200_get_ready_to_sync_top_level_parents_with_components(self):
"""
@@ -1180,7 +1180,7 @@ def test_200_get_ready_to_sync_top_level_parents_with_components(self):
)
assert response.status_code == 200
data = response.json()
- self.assertEqual(data["count"], 4)
+ self.assertEqual(data["count"], 4) # noqa: PT009
date_format = self.now.isoformat().split("+")[0] + 'Z'
# The expected results are
@@ -1261,7 +1261,7 @@ def test_200_get_ready_to_sync_top_level_parents_with_components(self):
'downstream_customized': [],
},
]
- self.assertListEqual(data["results"], expected)
+ self.assertListEqual(data["results"], expected) # noqa: PT009
def test_200_get_ready_to_sync_top_level_parents_with_containers(self):
"""
@@ -1280,7 +1280,7 @@ def test_200_get_ready_to_sync_top_level_parents_with_containers(self):
)
assert response.status_code == 200
data = response.json()
- self.assertEqual(data["count"], 3)
+ self.assertEqual(data["count"], 3) # noqa: PT009
date_format = self.now.isoformat().split("+")[0] + 'Z'
# The expected results are
@@ -1342,7 +1342,7 @@ def test_200_get_ready_to_sync_top_level_parents_with_containers(self):
'downstream_customized': [],
},
]
- self.assertListEqual(data["results"], expected)
+ self.assertListEqual(data["results"], expected) # noqa: PT009
def test_200_get_ready_to_sync_duplicated_top_level_parents(self):
"""
@@ -1370,7 +1370,7 @@ def test_200_get_ready_to_sync_duplicated_top_level_parents(self):
)
assert response.status_code == 200
data = response.json()
- self.assertEqual(data["count"], 3)
+ self.assertEqual(data["count"], 3) # noqa: PT009
date_format = self.now.isoformat().split("+")[0] + 'Z'
# The expected results are
@@ -1432,7 +1432,7 @@ def test_200_get_ready_to_sync_duplicated_top_level_parents(self):
'downstream_customized': [],
},
]
- self.assertListEqual(data["results"], expected)
+ self.assertListEqual(data["results"], expected) # noqa: PT009
class GetDownstreamSummaryViewTest(
@@ -1462,7 +1462,7 @@ def test_200_summary(self):
'total_count': 3,
'last_published_at': self.now.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
}]
- self.assertListEqual(data, expected)
+ self.assertListEqual(data, expected) # noqa: PT009
response = self.call_api(str(self.course.id))
assert response.status_code == 200
data = response.json()
@@ -1482,7 +1482,7 @@ def test_200_summary(self):
'total_count': 7,
'last_published_at': self.now.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
}]
- self.assertListEqual(data, expected)
+ self.assertListEqual(data, expected) # noqa: PT009
# Publish Subsection
self._update_container(self.top_level_subsection_id, display_name="Subsection 3")
@@ -1498,7 +1498,7 @@ def test_200_summary(self):
'total_count': 7,
'last_published_at': self.now.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
}]
- self.assertListEqual(data, expected)
+ self.assertListEqual(data, expected) # noqa: PT009
# Publish Section
self._update_container(self.top_level_section_id, display_name="Section 3")
@@ -1514,7 +1514,7 @@ def test_200_summary(self):
'total_count': 7,
'last_published_at': self.now.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
}]
- self.assertListEqual(data, expected)
+ self.assertListEqual(data, expected) # noqa: PT009
class GetDownstreamDeletedUpstream(
@@ -1620,4 +1620,4 @@ def test_delete_component_should_be_ready_to_sync(self):
'version_synced': 2,
}
- self.assertDictEqual(data[0], expected_results)
+ self.assertDictEqual(data[0], expected_results) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_home.py b/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_home.py
index 93a9941f4f1a..eb2d8adb1d51 100644
--- a/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_home.py
+++ b/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_home.py
@@ -35,7 +35,7 @@ def setUp(self):
display_name="Demo Course (Sample)",
id=archived_course_key,
org=archived_course_key.org,
- end=(datetime.now() - timedelta(days=365)).replace(tzinfo=timezone.utc),
+ end=(datetime.now() - timedelta(days=365)).replace(tzinfo=timezone.utc), # noqa: UP017
)
self.non_staff_client, _ = self.create_non_staff_authed_user_client()
@@ -93,8 +93,8 @@ def test_home_page_response(self):
('results', expected_data),
])
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_response, response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_response, response.data) # noqa: PT009
def test_active_only_query_if_passed(self):
"""Get list of active courses only.
@@ -104,8 +104,8 @@ def test_active_only_query_if_passed(self):
"""
response = self.client.get(self.api_v2_url, {"active_only": "true"})
- self.assertEqual(len(response.data["results"]["courses"]), 1)
- self.assertEqual(response.data["results"]["courses"], [OrderedDict([
+ self.assertEqual(len(response.data["results"]["courses"]), 1) # noqa: PT009
+ self.assertEqual(response.data["results"]["courses"], [OrderedDict([ # noqa: PT009
("course_key", str(self.course.id)),
("display_name", self.course.display_name),
("lms_link", f'{settings.LMS_ROOT_URL}/courses/{str(self.course.id)}/jump_to/{self.course.location}'),
@@ -117,7 +117,7 @@ def test_active_only_query_if_passed(self):
("url", f'/course/{str(self.course.id)}'),
("is_active", True),
])])
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_archived_only_query_if_passed(self):
"""Get list of archived courses only.
@@ -127,13 +127,13 @@ def test_archived_only_query_if_passed(self):
"""
response = self.client.get(self.api_v2_url, {"archived_only": "true"})
- self.assertEqual(len(response.data["results"]["courses"]), 1)
- self.assertEqual(response.data["results"]["courses"], [OrderedDict([
+ self.assertEqual(len(response.data["results"]["courses"]), 1) # noqa: PT009
+ self.assertEqual(response.data["results"]["courses"], [OrderedDict([ # noqa: PT009
("course_key", str(self.archived_course.id)),
("display_name", self.archived_course.display_name),
(
"lms_link",
- '{url_root}/courses/{course_id}/jump_to/{location}'.format(
+ '{url_root}/courses/{course_id}/jump_to/{location}'.format( # noqa: UP032
url_root=settings.LMS_ROOT_URL,
course_id=str(self.archived_course.id),
location=self.archived_course.location
@@ -147,7 +147,7 @@ def test_archived_only_query_if_passed(self):
("url", f'/course/{str(self.archived_course.id)}'),
("is_active", False),
])])
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_search_query_if_passed(self):
"""Get list of courses when search filter passed as a query param.
@@ -157,13 +157,13 @@ def test_search_query_if_passed(self):
"""
response = self.client.get(self.api_v2_url, {"search": "sample"})
- self.assertEqual(len(response.data["results"]["courses"]), 1)
- self.assertEqual(response.data["results"]["courses"], [OrderedDict([
+ self.assertEqual(len(response.data["results"]["courses"]), 1) # noqa: PT009
+ self.assertEqual(response.data["results"]["courses"], [OrderedDict([ # noqa: PT009
("course_key", str(self.archived_course.id)),
("display_name", self.archived_course.display_name),
(
"lms_link",
- '{url_root}/courses/{course_id}/jump_to/{location}'.format(
+ '{url_root}/courses/{course_id}/jump_to/{location}'.format( # noqa: UP032
url_root=settings.LMS_ROOT_URL,
course_id=str(self.archived_course.id),
location=self.archived_course.location
@@ -177,7 +177,7 @@ def test_search_query_if_passed(self):
("url", f'/course/{str(self.archived_course.id)}'),
("is_active", False),
])])
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_order_query_if_passed(self):
"""Get list of courses when order filter passed as a query param.
@@ -187,9 +187,9 @@ def test_order_query_if_passed(self):
"""
response = self.client.get(self.api_v2_url, {"order": "org"})
- self.assertEqual(len(response.data["results"]["courses"]), 2)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data["results"]["courses"][0]["org"], "demo-org")
+ self.assertEqual(len(response.data["results"]["courses"]), 2) # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data["results"]["courses"][0]["org"], "demo-org") # noqa: PT009
def test_page_query_if_passed(self):
"""Get list of courses when page filter passed as a query param.
@@ -199,8 +199,8 @@ def test_page_query_if_passed(self):
"""
response = self.client.get(self.api_v2_url, {"page": 1})
- self.assertEqual(response.data["count"], 2)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.data["count"], 2) # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
@ddt.data(
("active_only", "true"),
@@ -221,8 +221,8 @@ def test_if_empty_list_of_courses(self, query_param, value):
response = self.client.get(self.api_v2_url, {query_param: value})
- self.assertEqual(len(response.data['results']['courses']), 0)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.data['results']['courses']), 0) # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
@ddt.data(
("active_only", "true", 2, 0),
@@ -255,7 +255,7 @@ def test_filter_and_ordering_courses(
display_name="Course (Demo)",
id=archived_course_key,
org=archived_course_key.org,
- end=(datetime.now() - timedelta(days=365)).replace(tzinfo=timezone.utc),
+ end=(datetime.now() - timedelta(days=365)).replace(tzinfo=timezone.utc), # noqa: UP017
)
active_course_key = self.store.make_course_key("foo-org", "foo-number", "foo-run")
CourseOverviewFactory.create(
@@ -266,12 +266,12 @@ def test_filter_and_ordering_courses(
response = self.client.get(self.api_v2_url, {filter_key: filter_value})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual( # noqa: PT009
len([course for course in response.data["results"]["courses"] if course["is_active"]]),
expected_active_length
)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
len([course for course in response.data["results"]["courses"] if not course["is_active"]]),
expected_archived_length
)
@@ -295,5 +295,5 @@ def test_if_empty_list_of_courses_non_staff(self, query_param, value):
response = self.non_staff_client.get(self.api_v2_url, {query_param: value})
- self.assertEqual(len(response.data["results"]["courses"]), 0)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.data["results"]["courses"]), 0) # noqa: PT009
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/signals/handlers.py b/cms/djangoapps/contentstore/signals/handlers.py
index 64cf1d733bb7..53476d0eb43a 100644
--- a/cms/djangoapps/contentstore/signals/handlers.py
+++ b/cms/djangoapps/contentstore/signals/handlers.py
@@ -75,7 +75,7 @@ def wrapper(*args, **kwargs):
return task_decorator
-def _create_catalog_data_for_signal(course_key: CourseKey) -> (Optional[datetime], Optional[CourseCatalogData]):
+def _create_catalog_data_for_signal(course_key: CourseKey) -> (Optional[datetime], Optional[CourseCatalogData]): # noqa: UP045 # pylint: disable=line-too-long
"""
Creates data for catalog-info-changed signal when course is published.
@@ -94,7 +94,7 @@ def _create_catalog_data_for_signal(course_key: CourseKey) -> (Optional[datetime
store = modulestore()
with store.branch_setting(ModuleStoreEnum.Branch.published_only, course_key):
course = store.get_course(course_key)
- timestamp = course.subtree_edited_on.replace(tzinfo=timezone.utc)
+ timestamp = course.subtree_edited_on.replace(tzinfo=timezone.utc) # noqa: UP017
return timestamp, CourseCatalogData(
course_key=course_key.for_branch(None), # Shouldn't be necessary, but just in case...
name=course.display_name,
@@ -238,7 +238,7 @@ def handle_grading_policy_changed(sender, **kwargs):
'event_transaction_type': str(get_event_transaction_type()),
}
result = task_compute_all_grades_for_course.apply_async(kwargs=kwargs, countdown=GRADING_POLICY_COUNTDOWN_SECONDS)
- log.info("Grades: Created {task_name}[{task_id}] with arguments {kwargs}".format(
+ log.info("Grades: Created {task_name}[{task_id}] with arguments {kwargs}".format( # noqa: UP032
task_name=task_compute_all_grades_for_course.name,
task_id=result.task_id,
kwargs=kwargs,
diff --git a/cms/djangoapps/contentstore/signals/tests/test_handlers.py b/cms/djangoapps/contentstore/signals/tests/test_handlers.py
index 87e57e311dae..f70a8a11fabb 100644
--- a/cms/djangoapps/contentstore/signals/tests/test_handlers.py
+++ b/cms/djangoapps/contentstore/signals/tests/test_handlers.py
@@ -48,7 +48,7 @@ def setUp(self):
autospec=True, side_effect=lambda func: func(), # run right away
)
@patch('cms.djangoapps.contentstore.signals.handlers.emit_catalog_info_changed_signal', autospec=True)
- def test_signal_chain(self, mock_emit, _mock_on_commit):
+ def test_signal_chain(self, mock_emit, _mock_on_commit): # noqa: PT019
"""
Test that the course_published signal handler invokes the catalog info signal emitter.
@@ -66,7 +66,7 @@ def test_emit_regular_course(self, mock_signal):
with patch.object(EditInfoMixin, 'subtree_edited_on', now):
sh.emit_catalog_info_changed_signal(self.course_key)
mock_signal.send_event.assert_called_once_with(
- time=now.replace(tzinfo=timezone.utc),
+ time=now.replace(tzinfo=timezone.utc), # noqa: UP017
catalog_info=self.expected_data)
@patch('cms.djangoapps.contentstore.signals.handlers.COURSE_CATALOG_INFO_CHANGED', autospec=True)
diff --git a/cms/djangoapps/contentstore/tasks.py b/cms/djangoapps/contentstore/tasks.py
index c3211d75ade0..b73800053288 100644
--- a/cms/djangoapps/contentstore/tasks.py
+++ b/cms/djangoapps/contentstore/tasks.py
@@ -194,7 +194,7 @@ def rerun_course(source_course_key_string, destination_course_key_string, user_i
CourseRerunState.objects.succeeded(course_key=destination_course_key)
COURSE_RERUN_COMPLETED.send_event(
- time=datetime.now(timezone.utc),
+ time=datetime.now(timezone.utc), # noqa: UP017
course=CourseData(
course_key=destination_course_key
)
@@ -525,7 +525,7 @@ def sync_discussion_settings(course_key, user):
fields = ["enable_graded_units", "unit_level_visibility", "enable_in_context", "posting_restrictions"]
# Plugin configuration is stored in the course settings under the provider name.
- field_mappings = dict(zip(fields, fields)) | {"plugin_configuration": discussion_config.provider_type}
+ field_mappings = dict(zip(fields, fields)) | {"plugin_configuration": discussion_config.provider_type} # noqa: B905 # pylint: disable=line-too-long
for attr_name, settings_key in field_mappings.items():
if settings_key in discussion_settings:
@@ -1171,7 +1171,7 @@ def _check_broken_links(task_instance, user_id, course_key_string, language):
Checks for broken links in a course and stores the results in a file.
Also checks for previous run links if the feature is enabled.
"""
- user = _validate_user(task_instance, user_id, language)
+ user = _validate_user(task_instance, user_id, language) # noqa: F841
task_instance.status.set_state(UserTaskStatus.IN_PROGRESS)
course_key = CourseKey.from_string(course_key_string)
@@ -1226,7 +1226,7 @@ def _validate_user(task, user_id, language):
"""Validate if the user exists. Otherwise log an unknown user id error."""
try:
return User.objects.get(pk=user_id)
- except User.DoesNotExist as exc:
+ except User.DoesNotExist as exc: # noqa: F841
with translation_language(language):
task.status.fail(UserErrors.UNKNOWN_USER_ID.format(user_id))
return
@@ -1688,7 +1688,7 @@ def create_or_update_upstream_links(
ensure_cms("create_or_update_upstream_links may only be executed in a CMS context")
if not created:
- created = datetime.now(timezone.utc)
+ created = datetime.now(timezone.utc) # noqa: UP017
course_status = LearningContextLinksStatus.get_or_create(course_key_str, created)
if course_status.status in [
LearningContextLinksStatusChoices.COMPLETED,
@@ -2167,7 +2167,7 @@ def _update_broken_links_file_with_updated_links(course_key, updated_links):
try:
with latest_artifact.file.open("r") as file:
existing_broken_links = json.load(file)
- except (json.JSONDecodeError, IOError) as e:
+ except (json.JSONDecodeError, IOError) as e: # noqa: UP024
LOGGER.error(
f"Failed to read broken links file for course {course_key}: {e}"
)
diff --git a/cms/djangoapps/contentstore/tests/test_bulk_enabledisable_discussions.py b/cms/djangoapps/contentstore/tests/test_bulk_enabledisable_discussions.py
index 0d394e203460..69a6d1a39beb 100644
--- a/cms/djangoapps/contentstore/tests/test_bulk_enabledisable_discussions.py
+++ b/cms/djangoapps/contentstore/tests/test_bulk_enabledisable_discussions.py
@@ -49,13 +49,13 @@ def setUp(self):
category='sequential',
display_name="Generated Sequence",
)
- unit1 = BlockFactory.create(
+ unit1 = BlockFactory.create( # noqa: F841
parent=sequence,
category='vertical',
display_name="Unit in Section1",
discussion_enabled=True,
)
- unit2 = BlockFactory.create(
+ unit2 = BlockFactory.create( # noqa: F841
parent=sequence,
category='vertical',
display_name="Unit in Section2",
@@ -82,16 +82,16 @@ def enable_disable_discussions_for_all_units(self, is_enabled):
"discussion_enabled": is_enabled
}
response = self.client.put(self.url, data=json.dumps(data), content_type='application/json')
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
response_data = response.json()
print(response_data)
- self.assertEqual(response_data['units_updated_and_republished'], 0 if is_enabled else 2)
+ self.assertEqual(response_data['units_updated_and_republished'], 0 if is_enabled else 2) # noqa: PT009
# Check that all verticals now have discussion_enabled set to the expected value
with self.store.bulk_operations(self.course_key):
verticals = self.store.get_items(self.course_key, qualifiers={'block_type': 'vertical'})
for vertical in verticals:
- self.assertEqual(vertical.discussion_enabled, is_enabled)
+ self.assertEqual(vertical.discussion_enabled, is_enabled) # noqa: PT009
def test_permission_denied_for_non_staff(self):
"""
@@ -107,11 +107,11 @@ def test_permission_denied_for_non_staff(self):
non_staff_client.login(username=non_staff_user.username, password=self.user_password)
response = non_staff_client.put(self.url, content_type='application/json')
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
def test_badrequest_for_empty_request_body(self):
"""
Test that the API returns a 400 for an empty request body.
"""
response = self.client.put(self.url, data=json.dumps({}), content_type='application/json')
- self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.status_code, 400) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_clone_course.py b/cms/djangoapps/contentstore/tests/test_clone_course.py
index 6d45ae5469e1..2449c9269288 100644
--- a/cms/djangoapps/contentstore/tests/test_clone_course.py
+++ b/cms/djangoapps/contentstore/tests/test_clone_course.py
@@ -69,8 +69,8 @@ def test_space_in_asset_name_for_rerun_course(self):
# Get & verify all assets of the course
assets, count = contentstore().get_all_content_for_course(course.id)
- self.assertEqual(count, 1)
- self.assertEqual({asset['asset_key'].block_id for asset in assets}, course_assets) # lint-amnesty, pylint: disable=consider-using-set-comprehension
+ self.assertEqual(count, 1) # noqa: PT009
+ self.assertEqual({asset['asset_key'].block_id for asset in assets}, course_assets) # lint-amnesty, pylint: disable=consider-using-set-comprehension # noqa: PT009
# rerun from split into split
split_rerun_id = CourseLocator(org=org, course=course_number, run="2012_Q2")
@@ -83,9 +83,9 @@ def test_space_in_asset_name_for_rerun_course(self):
)
# Check if re-run was successful
- self.assertEqual(result.get(), "succeeded")
+ self.assertEqual(result.get(), "succeeded") # noqa: PT009
rerun_state = CourseRerunState.objects.find_first(course_key=split_rerun_id)
- self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.SUCCEEDED)
+ self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.SUCCEEDED) # noqa: PT009
def test_rerun_course(self):
"""
@@ -114,14 +114,14 @@ def test_rerun_course(self):
CourseRerunState.objects.initiated(split_course.id, split_course3_id, self.user, fields['display_name'])
result = rerun_course.delay(str(split_course.id), str(split_course3_id), self.user.id,
json.dumps(fields, cls=EdxJSONEncoder))
- self.assertEqual(result.get(), "succeeded")
- self.assertTrue(has_course_author_access(self.user, split_course3_id), "Didn't grant access")
+ self.assertEqual(result.get(), "succeeded") # noqa: PT009
+ self.assertTrue(has_course_author_access(self.user, split_course3_id), "Didn't grant access") # noqa: PT009
rerun_state = CourseRerunState.objects.find_first(course_key=split_course3_id)
- self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.SUCCEEDED)
+ self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.SUCCEEDED) # noqa: PT009
# try creating rerunning again to same name and ensure it generates error
result = rerun_course.delay(str(split_course.id), str(split_course3_id), self.user.id)
- self.assertEqual(result.get(), "duplicate course")
+ self.assertEqual(result.get(), "duplicate course") # noqa: PT009
# the below will raise an exception if the record doesn't exist
CourseRerunState.objects.find_first(
course_key=split_course3_id,
@@ -135,8 +135,8 @@ def test_rerun_course(self):
CourseRerunState.objects.initiated(split_course3_id, split_course4_id, self.user, fields['display_name'])
result = rerun_course.delay(str(split_course3_id), str(split_course4_id), self.user.id,
json.dumps(fields, cls=EdxJSONEncoder))
- self.assertIn("exception: ", result.get())
- self.assertIsNone(self.store.get_course(split_course4_id), "Didn't delete course after error")
+ self.assertIn("exception: ", result.get()) # noqa: PT009
+ self.assertIsNone(self.store.get_course(split_course4_id), "Didn't delete course after error") # noqa: PT009 # pylint: disable=line-too-long
CourseRerunState.objects.find_first(
course_key=split_course4_id,
state=CourseRerunUIStateManager.State.FAILED
diff --git a/cms/djangoapps/contentstore/tests/test_contentstore.py b/cms/djangoapps/contentstore/tests/test_contentstore.py
index da48930bc49a..5c33e156721b 100644
--- a/cms/djangoapps/contentstore/tests/test_contentstore.py
+++ b/cms/djangoapps/contentstore/tests/test_contentstore.py
@@ -61,7 +61,7 @@
from xmodule.video_block import VideoBlock
TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
-TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex
+TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex # noqa: UP031
TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT
@@ -79,7 +79,7 @@ def decorated_func(*args, **kwargs):
try:
from PIL import Image
except ImportError:
- raise SkipTest("Pillow is not installed (or not found)") # lint-amnesty, pylint: disable=raise-missing-from
+ raise SkipTest("Pillow is not installed (or not found)") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not getattr(Image.core, "jpeg_decoder", False):
raise SkipTest("Pillow cannot open JPEG files")
return func(*args, **kwargs)
@@ -107,15 +107,15 @@ def test_no_static_link_rewrites_on_import(self):
handouts_usage_key = course.id.make_usage_key('course_info', 'handouts')
handouts = self.store.get_item(handouts_usage_key)
- self.assertIn('/static/', handouts.data)
+ self.assertIn('/static/', handouts.data) # noqa: PT009
handouts_usage_key = course.id.make_usage_key('html', 'toyhtml')
handouts = self.store.get_item(handouts_usage_key)
- self.assertIn('/static/', handouts.data)
+ self.assertIn('/static/', handouts.data) # noqa: PT009
def test_xlint_fails(self):
err_cnt = perform_xlint(TEST_DATA_DIR, ['toy'])
- self.assertGreater(err_cnt, 0)
+ self.assertGreater(err_cnt, 0) # noqa: PT009
def test_invalid_asset_overwrite(self):
"""
@@ -146,7 +146,7 @@ def test_invalid_asset_overwrite(self):
'import_draft_order',
'import_draft_order'
))
- self.assertIsNotNone(course)
+ self.assertIsNotNone(course) # noqa: PT009
# Add a new asset in the course, and make sure to name it such that it overwrite the one existing
# asset in the course. (i.e. _invalid_displayname_subs-esLhHcdKGWvKs.srt)
@@ -158,11 +158,11 @@ def test_invalid_asset_overwrite(self):
# Get & verify that course actually has two assets
assets, count = content_store.get_all_content_for_course(course.id)
- self.assertEqual(count, 2)
+ self.assertEqual(count, 2) # noqa: PT009
# Verify both assets have similar `displayname` after saving.
for asset in assets:
- self.assertEqual(asset['displayname'], expected_displayname)
+ self.assertEqual(asset['displayname'], expected_displayname) # noqa: PT009
# Test course export does not fail
root_dir = path(mkdtemp_clean())
@@ -173,9 +173,9 @@ def test_invalid_asset_overwrite(self):
exported_static_files = filesystem.listdir('/')
# Verify that asset have been overwritten during export.
- self.assertEqual(len(exported_static_files), 1)
- self.assertTrue(filesystem.exists(expected_displayname))
- self.assertEqual(exported_static_files[0], expected_displayname)
+ self.assertEqual(len(exported_static_files), 1) # noqa: PT009
+ self.assertTrue(filesystem.exists(expected_displayname)) # noqa: PT009
+ self.assertEqual(exported_static_files[0], expected_displayname) # noqa: PT009
# Remove exported course
shutil.rmtree(root_dir)
@@ -191,11 +191,11 @@ def test_about_overrides(self):
)
course_key = course_items[0].id
effort = self.store.get_item(course_key.make_usage_key('about', 'effort'))
- self.assertEqual(effort.data, '6 hours')
+ self.assertEqual(effort.data, '6 hours') # noqa: PT009
# this one should be in a non-override folder
effort = self.store.get_item(course_key.make_usage_key('about', 'end_date'))
- self.assertEqual(effort.data, 'TBD')
+ self.assertEqual(effort.data, 'TBD') # noqa: PT009
@requires_pillow_jpeg
def test_asset_import(self):
@@ -211,23 +211,23 @@ def test_asset_import(self):
course = self.store.get_course(self.store.make_course_key('edX', 'toy', '2012_Fall'))
- self.assertIsNotNone(course)
+ self.assertIsNotNone(course) # noqa: PT009
# make sure we have some assets in our contentstore
all_assets, __ = content_store.get_all_content_for_course(course.id)
- self.assertGreater(len(all_assets), 0)
+ self.assertGreater(len(all_assets), 0) # noqa: PT009
# make sure we have some thumbnails in our contentstore
all_thumbnails = content_store.get_all_content_thumbnails_for_course(course.id)
- self.assertGreater(len(all_thumbnails), 0)
+ self.assertGreater(len(all_thumbnails), 0) # noqa: PT009
location = AssetKey.from_string('asset-v1:edX+toy+2012_Fall+type@asset+block@just_a_test.jpg')
content = content_store.find(location)
- self.assertIsNotNone(content)
+ self.assertIsNotNone(content) # noqa: PT009
- self.assertIsNotNone(content.thumbnail_location)
+ self.assertIsNotNone(content.thumbnail_location) # noqa: PT009
thumbnail = content_store.find(content.thumbnail_location)
- self.assertIsNotNone(thumbnail)
+ self.assertIsNotNone(thumbnail) # noqa: PT009
def test_course_info_updates_import_export(self):
"""
@@ -241,26 +241,26 @@ def test_course_info_updates_import_export(self):
)
course = courses[0]
- self.assertIsNotNone(course)
+ self.assertIsNotNone(course) # noqa: PT009
course_updates = self.store.get_item(course.id.make_usage_key('course_info', 'updates'))
- self.assertIsNotNone(course_updates)
+ self.assertIsNotNone(course_updates) # noqa: PT009
# check that course which is imported has files 'updates.html' and 'updates.items.json'
filesystem = OSFS(str(data_dir + '/course_info_updates/info'))
- self.assertTrue(filesystem.exists('updates.html'))
- self.assertTrue(filesystem.exists('updates.items.json'))
+ self.assertTrue(filesystem.exists('updates.html')) # noqa: PT009
+ self.assertTrue(filesystem.exists('updates.items.json')) # noqa: PT009
# verify that course info update module has same data content as in data file from which it is imported
# check 'data' field content
with filesystem.open('updates.html', 'r') as course_policy:
on_disk = course_policy.read()
- self.assertEqual(course_updates.data, on_disk)
+ self.assertEqual(course_updates.data, on_disk) # noqa: PT009
# check 'items' field content
with filesystem.open('updates.items.json', 'r') as course_policy:
on_disk = loads(course_policy.read())
- self.assertEqual(course_updates.items, on_disk)
+ self.assertEqual(course_updates.items, on_disk) # noqa: PT009
# now export the course to a tempdir and test that it contains files 'updates.html' and 'updates.items.json'
# with same content as in course 'info' directory
@@ -270,17 +270,17 @@ def test_course_info_updates_import_export(self):
# check that exported course has files 'updates.html' and 'updates.items.json'
filesystem = OSFS(str(root_dir / 'test_export/info'))
- self.assertTrue(filesystem.exists('updates.html'))
- self.assertTrue(filesystem.exists('updates.items.json'))
+ self.assertTrue(filesystem.exists('updates.html')) # noqa: PT009
+ self.assertTrue(filesystem.exists('updates.items.json')) # noqa: PT009
# verify that exported course has same data content as in course_info_update module
with filesystem.open('updates.html', 'r') as grading_policy:
on_disk = grading_policy.read()
- self.assertEqual(on_disk, course_updates.data)
+ self.assertEqual(on_disk, course_updates.data) # noqa: PT009
with filesystem.open('updates.items.json', 'r') as grading_policy:
on_disk = loads(grading_policy.read())
- self.assertEqual(on_disk, course_updates.items)
+ self.assertEqual(on_disk, course_updates.items) # noqa: PT009
def test_rewrite_nonportable_links_on_import(self):
content_store = contentstore()
@@ -294,22 +294,22 @@ def test_rewrite_nonportable_links_on_import(self):
course_key = self.store.make_course_key('edX', 'toy', '2012_Fall')
html_block_location = course_key.make_usage_key('html', 'nonportable')
html_block = self.store.get_item(html_block_location)
- self.assertIn('/static/foo.jpg', html_block.data)
+ self.assertIn('/static/foo.jpg', html_block.data) # noqa: PT009
# then check a intra courseware link
html_block_location = course_key.make_usage_key('html', 'nonportable_link')
html_block = self.store.get_item(html_block_location)
- self.assertIn('/jump_to_id/nonportable_link', html_block.data)
+ self.assertIn('/jump_to_id/nonportable_link', html_block.data) # noqa: PT009
def verify_content_existence(self, store, root_dir, course_id, dirname, category_name, filename_suffix=''): # lint-amnesty, pylint: disable=missing-function-docstring
filesystem = OSFS(root_dir / 'test_export')
- self.assertTrue(filesystem.exists(dirname))
+ self.assertTrue(filesystem.exists(dirname)) # noqa: PT009
items = store.get_items(course_id, qualifiers={'category': category_name})
for item in items:
filesystem = OSFS(root_dir / ('test_export/' + dirname))
- self.assertTrue(filesystem.exists(item.location.block_id + filename_suffix))
+ self.assertTrue(filesystem.exists(item.location.block_id + filename_suffix)) # noqa: PT009
def test_export_course_with_metadata_only_video(self):
content_store = contentstore()
@@ -322,7 +322,7 @@ def test_export_course_with_metadata_only_video(self):
# anything in 'data' field, the export was blowing up
verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'})
- self.assertGreater(len(verticals), 0)
+ self.assertGreater(len(verticals), 0) # noqa: PT009
parent = verticals[0]
@@ -348,7 +348,7 @@ def test_export_course_with_metadata_only_word_cloud(self):
verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'})
- self.assertGreater(len(verticals), 0)
+ self.assertGreater(len(verticals), 0) # noqa: PT009
parent = verticals[0]
@@ -380,14 +380,14 @@ def test_import_after_renaming_xml_data(self):
)
all_items = split_store.get_items(course_after_rename[0].id, qualifiers={'category': 'chapter'})
renamed_chapter = [item for item in all_items if item.location.block_id == 'renamed_chapter'][0]
- self.assertIsNotNone(renamed_chapter.published_on)
- self.assertIsNotNone(renamed_chapter.parent)
- self.assertIn(renamed_chapter.location, course_after_rename[0].children)
+ self.assertIsNotNone(renamed_chapter.published_on) # noqa: PT009
+ self.assertIsNotNone(renamed_chapter.parent) # noqa: PT009
+ self.assertIn(renamed_chapter.location, course_after_rename[0].children) # noqa: PT009
original_chapter = [item for item in all_items
if item.location.block_id == 'b9870b9af59841a49e6e02765d0e3bbf'][0]
- self.assertIsNone(original_chapter.published_on)
- self.assertIsNone(original_chapter.parent)
- self.assertNotIn(original_chapter.location, course_after_rename[0].children)
+ self.assertIsNone(original_chapter.published_on) # noqa: PT009
+ self.assertIsNone(original_chapter.parent) # noqa: PT009
+ self.assertNotIn(original_chapter.location, course_after_rename[0].children) # noqa: PT009
def test_empty_data_roundtrip(self):
"""
@@ -401,7 +401,7 @@ def test_empty_data_roundtrip(self):
verticals = self.store.get_items(course_id, qualifiers={'category': 'vertical'})
- self.assertGreater(len(verticals), 0)
+ self.assertGreater(len(verticals), 0) # noqa: PT009
parent = verticals[0]
@@ -409,7 +409,7 @@ def test_empty_data_roundtrip(self):
word_cloud = BlockFactory.create(
parent_location=parent.location, category="word_cloud", display_name="untitled")
del word_cloud.data
- self.assertEqual(word_cloud.data, '')
+ self.assertEqual(word_cloud.data, '') # noqa: PT009
# Export the course
root_dir = path(mkdtemp_clean())
@@ -420,7 +420,7 @@ def test_empty_data_roundtrip(self):
imported_word_cloud = self.store.get_item(course_id.make_usage_key('word_cloud', 'untitled'))
# It should now contain empty data
- self.assertEqual(imported_word_cloud.data, '')
+ self.assertEqual(imported_word_cloud.data, '') # noqa: PT009
def test_html_export_roundtrip(self):
"""
@@ -441,11 +441,11 @@ def test_html_export_roundtrip(self):
# get the sample HTML with styling information
html_block = self.store.get_item(course_id.make_usage_key('html', 'with_styling'))
- self.assertIn('', html_block.data)
+ self.assertIn('
', html_block.data) # noqa: PT009 # pylint: disable=line-too-long
# get the sample HTML with just a simple
tag information
html_block = self.store.get_item(course_id.make_usage_key('html', 'just_img'))
- self.assertIn('
', html_block.data)
+ self.assertIn('
', html_block.data) # noqa: PT009
def test_export_course_without_content_store(self):
# Create toy course
@@ -479,7 +479,7 @@ def test_export_course_without_content_store(self):
'name': 'vertical_sequential',
}
)
- self.assertEqual(len(items), 1)
+ self.assertEqual(len(items), 1) # noqa: PT009
def test_export_course_no_xml_attributes(self):
"""
@@ -504,7 +504,7 @@ def test_export_course_no_xml_attributes(self):
)
# note that it has no `xml_attributes` attribute
- self.assertFalse(hasattr(draft_open_assessment, "xml_attributes"))
+ self.assertFalse(hasattr(draft_open_assessment, "xml_attributes")) # noqa: PT009
# export should still complete successfully
root_dir = path(mkdtemp_clean())
@@ -622,9 +622,9 @@ def test_export_on_invalid_displayname(self, invalid_displayname):
# Verify that the course has only one asset and it has been added with an invalid asset name.
assets, count = content_store.get_all_content_for_course(self.course.id)
- self.assertEqual(count, 1)
+ self.assertEqual(count, 1) # noqa: PT009
display_name = assets[0]['displayname']
- self.assertEqual(display_name, invalid_displayname)
+ self.assertEqual(display_name, invalid_displayname) # noqa: PT009
# Now export the course to a tempdir and test that it contains assets. The export should pass
root_dir = path(mkdtemp_clean())
@@ -635,8 +635,8 @@ def test_export_on_invalid_displayname(self, invalid_displayname):
exported_static_files = filesystem.listdir('/')
# Verify that only single asset has been exported with the expected asset name.
- self.assertTrue(filesystem.exists(exported_asset_name))
- self.assertEqual(len(exported_static_files), 1)
+ self.assertTrue(filesystem.exists(exported_asset_name)) # noqa: PT009
+ self.assertEqual(len(exported_static_files), 1) # noqa: PT009
# Remove tempdir
shutil.rmtree(root_dir)
@@ -659,7 +659,7 @@ def test_export_with_orphan_vertical(self):
# mocking get_item to for drafts. Expect no draft is exported.
# Specifically get_item is used in `xmodule.modulestore.xml_exporter._export_drafts`
export_draft_dir = OSFS(root_dir / 'test_export/drafts')
- self.assertEqual(len(export_draft_dir.listdir('/')), 0)
+ self.assertEqual(len(export_draft_dir.listdir('/')), 0) # noqa: PT009
# Remove tempdir
shutil.rmtree(root_dir)
@@ -680,11 +680,11 @@ def test_assets_overwrite(self):
# Fetch & verify course assets to be equal to 2.
assets, count = content_store.get_all_content_for_course(self.course.id)
- self.assertEqual(count, 2)
+ self.assertEqual(count, 2) # noqa: PT009
# Verify both assets have similar 'displayname' after saving.
for asset in assets:
- self.assertEqual(asset['displayname'], asset_displayname)
+ self.assertEqual(asset['displayname'], asset_displayname) # noqa: PT009
# Now export the course to a tempdir and test that it contains assets.
root_dir = path(mkdtemp_clean())
@@ -694,8 +694,8 @@ def test_assets_overwrite(self):
# Verify that asset have been overwritten during export.
filesystem = OSFS(root_dir / 'test_export/static')
exported_static_files = filesystem.listdir('/')
- self.assertTrue(filesystem.exists(asset_displayname))
- self.assertEqual(len(exported_static_files), 1)
+ self.assertTrue(filesystem.exists(asset_displayname)) # noqa: PT009
+ self.assertEqual(len(exported_static_files), 1) # noqa: PT009
# Remove tempdir
shutil.rmtree(root_dir)
@@ -729,14 +729,14 @@ def test_get_items(self):
self.course.id, revision=ModuleStoreEnum.RevisionOption.published_only
)
items_from_direct_store = [item for item in direct_store_items if item.location == self.problem.location]
- self.assertEqual(len(items_from_direct_store), 0)
+ self.assertEqual(len(items_from_direct_store), 0) # noqa: PT009
# Fetch from the draft store.
draft_store_items = self.store.get_items(
self.course.id, revision=ModuleStoreEnum.RevisionOption.draft_only
)
items_from_draft_store = [item for item in draft_store_items if item.location == self.problem.location]
- self.assertEqual(len(items_from_draft_store), 1)
+ self.assertEqual(len(items_from_draft_store), 1) # noqa: PT009
def test_draft_metadata(self):
"""
@@ -750,16 +750,16 @@ def test_draft_metadata(self):
course = self.store.update_item(course, self.user.id)
problem = self.store.get_item(self.problem.location)
- self.assertEqual(problem.graceperiod, course.graceperiod)
- self.assertNotIn('graceperiod', own_metadata(problem))
+ self.assertEqual(problem.graceperiod, course.graceperiod) # noqa: PT009
+ self.assertNotIn('graceperiod', own_metadata(problem)) # noqa: PT009
self.store.convert_to_draft(problem.location, self.user.id)
# refetch to check metadata
problem = self.store.get_item(problem.location)
- self.assertEqual(problem.graceperiod, course.graceperiod)
- self.assertNotIn('graceperiod', own_metadata(problem))
+ self.assertEqual(problem.graceperiod, course.graceperiod) # noqa: PT009
+ self.assertNotIn('graceperiod', own_metadata(problem)) # noqa: PT009
# publish block
self.store.publish(problem.location, self.user.id)
@@ -767,8 +767,8 @@ def test_draft_metadata(self):
# refetch to check metadata
problem = self.store.get_item(problem.location)
- self.assertEqual(problem.graceperiod, course.graceperiod)
- self.assertNotIn('graceperiod', own_metadata(problem))
+ self.assertEqual(problem.graceperiod, course.graceperiod) # noqa: PT009
+ self.assertNotIn('graceperiod', own_metadata(problem)) # noqa: PT009
# put back in draft and change metadata and see if it's now marked as 'own_metadata'
self.store.convert_to_draft(problem.location, self.user.id)
@@ -776,21 +776,21 @@ def test_draft_metadata(self):
new_graceperiod = timedelta(hours=1)
- self.assertNotIn('graceperiod', own_metadata(problem))
+ self.assertNotIn('graceperiod', own_metadata(problem)) # noqa: PT009
problem.graceperiod = new_graceperiod
# Save the data that we've just changed to the underlying
# MongoKeyValueStore before we update the mongo datastore.
problem.save()
- self.assertIn('graceperiod', own_metadata(problem))
- self.assertEqual(problem.graceperiod, new_graceperiod)
+ self.assertIn('graceperiod', own_metadata(problem)) # noqa: PT009
+ self.assertEqual(problem.graceperiod, new_graceperiod) # noqa: PT009
self.store.update_item(problem, self.user.id)
# read back to make sure it reads as 'own-metadata'
problem = self.store.get_item(problem.location)
- self.assertIn('graceperiod', own_metadata(problem))
- self.assertEqual(problem.graceperiod, new_graceperiod)
+ self.assertIn('graceperiod', own_metadata(problem)) # noqa: PT009
+ self.assertEqual(problem.graceperiod, new_graceperiod) # noqa: PT009
# republish
self.store.publish(problem.location, self.user.id)
@@ -799,27 +799,27 @@ def test_draft_metadata(self):
self.store.convert_to_draft(problem.location, self.user.id)
problem = self.store.get_item(problem.location)
- self.assertIn('graceperiod', own_metadata(problem))
- self.assertEqual(problem.graceperiod, new_graceperiod)
+ self.assertIn('graceperiod', own_metadata(problem)) # noqa: PT009
+ self.assertEqual(problem.graceperiod, new_graceperiod) # noqa: PT009
def test_get_depth_with_drafts(self):
# make sure no draft items have been returned
num_drafts = self._get_draft_counts(self.course)
- self.assertEqual(num_drafts, 0)
+ self.assertEqual(num_drafts, 0) # noqa: PT009
# put into draft
self.problem = self.store.unpublish(self.problem.location, self.user.id)
# make sure we can query that item and verify that it is a draft
draft_problem = self.store.get_item(self.problem.location)
- self.assertEqual(self.store.has_published_version(draft_problem), False)
+ self.assertEqual(self.store.has_published_version(draft_problem), False) # noqa: PT009
# now requery with depth
course = self.store.get_course(self.course.id, depth=None)
# make sure just one draft item have been returned
num_drafts = self._get_draft_counts(course)
- self.assertEqual(num_drafts, 1)
+ self.assertEqual(num_drafts, 1) # noqa: PT009
@mock.patch('xmodule.course_block.requests.get')
def test_import_textbook_as_content_element(self, mock_get):
@@ -830,13 +830,13 @@ def test_import_textbook_as_content_element(self, mock_get):
""").strip()
self.course.textbooks = [Textbook("Textbook", "https://s3.amazonaws.com/edx-textbooks/guttag_computation_v3/")]
course = self.store.update_item(self.course, self.user.id)
- self.assertGreater(len(course.textbooks), 0)
+ self.assertGreater(len(course.textbooks), 0) # noqa: PT009
def test_import_polls(self):
items = self.store.get_items(self.course.id, qualifiers={'category': 'poll_question'})
- self.assertGreater(len(items), 0)
+ self.assertGreater(len(items), 0) # noqa: PT009
# check that there's actually content in the 'question' field
- self.assertGreater(len(items[0].question), 0)
+ self.assertGreater(len(items[0].question), 0) # noqa: PT009
def test_module_preview_in_whitelist(self):
"""
@@ -847,7 +847,7 @@ def test_module_preview_in_whitelist(self):
resp = self.client.get_json(
get_url('xblock_view_handler', self.vert_loc, kwargs={'view_name': 'container_preview'})
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
vertical = self.store.get_item(self.vert_loc)
for child in vertical.children:
@@ -857,17 +857,17 @@ def test_delete(self):
# make sure the parent points to the child object which is to be deleted
# need to refetch chapter b/c at the time it was assigned it had no children
chapter = self.store.get_item(self.chapter_loc)
- self.assertIn(self.seq_loc, chapter.children)
+ self.assertIn(self.seq_loc, chapter.children) # noqa: PT009
self.client.delete(get_url('xblock_handler', self.seq_loc))
- with self.assertRaises(ItemNotFoundError):
+ with self.assertRaises(ItemNotFoundError): # noqa: PT027
self.store.get_item(self.seq_loc)
chapter = self.store.get_item(self.chapter_loc)
# make sure the parent no longer points to the child object which was deleted
- self.assertNotIn(self.seq_loc, chapter.children)
+ self.assertNotIn(self.seq_loc, chapter.children) # noqa: PT009
def test_asset_delete_and_restore(self):
"""
@@ -877,18 +877,18 @@ def test_asset_delete_and_restore(self):
# now try to find it in store, but they should not be there any longer
content = contentstore().find(asset_key, throw_on_not_found=False)
- self.assertIsNone(content)
+ self.assertIsNone(content) # noqa: PT009
# now try to find it and the thumbnail in trashcan - should be in there
content = contentstore('trashcan').find(asset_key, throw_on_not_found=False)
- self.assertIsNotNone(content)
+ self.assertIsNotNone(content) # noqa: PT009
# let's restore the asset
restore_asset_from_trashcan(str(asset_key))
# now try to find it in courseware store, and they should be back after restore
content = contentstore('trashcan').find(asset_key, throw_on_not_found=False)
- self.assertIsNotNone(content)
+ self.assertIsNotNone(content) # noqa: PT009
def _delete_asset_in_course(self):
"""
@@ -911,7 +911,7 @@ def _delete_asset_in_course(self):
kwargs={'asset_key_string': str(asset_key)}
)
resp = self.client.delete(url)
- self.assertEqual(resp.status_code, 204)
+ self.assertEqual(resp.status_code, 204) # noqa: PT009
return asset_key
@@ -923,22 +923,22 @@ def test_empty_trashcan(self):
# make sure there's something in the trashcan
all_assets, __ = contentstore('trashcan').get_all_content_for_course(self.course.id)
- self.assertGreater(len(all_assets), 0)
+ self.assertGreater(len(all_assets), 0) # noqa: PT009
# empty the trashcan
empty_asset_trashcan([self.course.id])
# make sure trashcan is empty
all_assets, count = contentstore('trashcan').get_all_content_for_course(self.course.id)
- self.assertEqual(len(all_assets), 0)
- self.assertEqual(count, 0)
+ self.assertEqual(len(all_assets), 0) # noqa: PT009
+ self.assertEqual(count, 0) # noqa: PT009
def test_illegal_draft_crud_ops(self):
chapter = self.store.get_item(self.chapter_loc)
chapter.data = 'chapter data'
self.store.update_item(chapter, self.user.id)
- with self.assertRaises(InvalidVersionError):
+ with self.assertRaises(InvalidVersionError): # noqa: PT027
self.store.unpublish(self.chapter_loc, self.user.id)
def test_bad_contentstore_request(self):
@@ -947,10 +947,10 @@ def test_bad_contentstore_request(self):
asset/course key
"""
resp = self.client.get_html('asset-v1:CDX+123123+2012_Fall+type@asset+block@&invalid.png')
- self.assertEqual(resp.status_code, 404)
+ self.assertEqual(resp.status_code, 404) # noqa: PT009
resp = self.client.get_html('asset-v1:CDX+123123+2012_Fall+type@asset+block@invalid.png')
- self.assertEqual(resp.status_code, 404)
+ self.assertEqual(resp.status_code, 404) # noqa: PT009
@override_waffle_switch(waffle.ENABLE_ACCESSIBILITY_POLICY_PAGE, active=False)
def test_disabled_accessibility_page(self):
@@ -958,7 +958,7 @@ def test_disabled_accessibility_page(self):
Test that accessibility page returns 404 when waffle switch is disabled
"""
resp = self.client.get_html('/accessibility')
- self.assertEqual(resp.status_code, 404)
+ self.assertEqual(resp.status_code, 404) # noqa: PT009
def test_delete_course(self):
"""
@@ -972,8 +972,8 @@ def test_delete_course(self):
)
contentstore().save(content)
assets, count = contentstore().get_all_content_for_course(self.course.id)
- self.assertGreater(len(assets), 0)
- self.assertGreater(count, 0)
+ self.assertGreater(len(assets), 0) # noqa: PT009
+ self.assertGreater(count, 0) # noqa: PT009
self.store.unpublish(self.vert_loc, self.user.id)
@@ -982,14 +982,14 @@ def test_delete_course(self):
# assert that there's absolutely no non-draft blocks in the course
# this should also include all draft items
- with self.assertRaises(ItemNotFoundError):
+ with self.assertRaises(ItemNotFoundError): # noqa: PT027
self.store.get_items(self.course.id)
# assert that all content in the asset library is keeped
# in case the course is later restored.
assets, count = contentstore().get_all_content_for_course(self.course.id)
- self.assertGreater(len(assets), 0)
- self.assertGreater(count, 0)
+ self.assertGreater(len(assets), 0) # noqa: PT009
+ self.assertGreater(count, 0) # noqa: PT009
def test_course_handouts_rewrites(self):
"""
@@ -1005,7 +1005,7 @@ def test_course_handouts_rewrites(self):
resp = self.client.get(get_url('xblock_handler', handouts.location))
# make sure we got a successful response
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# check that /static/ has been converted to the full path
# note, we know the link it should be because that's what in the 'toy' course in the test data
asset_key = self.course.id.make_asset_key('asset', 'handouts_sample_handout.txt')
@@ -1024,10 +1024,10 @@ def test_prefetch_children(self):
course = self.store.get_course(self.course.id, depth=2, lazy=False)
# make sure we pre-fetched a known sequential which should be at depth=2
- self.assertIn(BlockKey.from_usage_key(self.seq_loc), course.runtime.module_data)
+ self.assertIn(BlockKey.from_usage_key(self.seq_loc), course.runtime.module_data) # noqa: PT009
# make sure we don't have a specific vertical which should be at depth=3
- self.assertNotIn(BlockKey.from_usage_key(self.vert_loc), course.runtime.module_data)
+ self.assertNotIn(BlockKey.from_usage_key(self.vert_loc), course.runtime.module_data) # noqa: PT009
# Now, test with the branch set to draft. No extra round trips b/c it doesn't go deep enough to get
# beyond direct only categories
@@ -1038,10 +1038,10 @@ def test_prefetch_children(self):
def _check_verticals(self, locations):
""" Test getting the editing HTML for each vertical. """
# Assert is here to make sure that the course being tested actually has verticals (units) to check.
- self.assertGreater(len(locations), 0)
+ self.assertGreater(len(locations), 0) # noqa: PT009
for loc in locations:
resp = self.client.get_html(get_url('container_handler', loc))
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
@ddt.ddt
@@ -1073,7 +1073,7 @@ def assert_created_course(self, number_suffix=None):
course_key = _get_course_id(self.store, test_course_data)
_create_course(self, course_key, test_course_data)
# Verify that the creator is now registered in the course.
- self.assertTrue(CourseEnrollment.is_enrolled(self.user, course_key))
+ self.assertTrue(CourseEnrollment.is_enrolled(self.user, course_key)) # noqa: PT009
return test_course_data
def assert_create_course_failed(self, error_message):
@@ -1081,9 +1081,9 @@ def assert_create_course_failed(self, error_message):
Checks that the course not created.
"""
resp = self.client.ajax_post('/course/', self.course_data)
- self.assertEqual(resp.status_code, 400)
+ self.assertEqual(resp.status_code, 400) # noqa: PT009
data = parse_json(resp)
- self.assertEqual(data['error'], error_message)
+ self.assertEqual(data['error'], error_message) # noqa: PT009
def test_create_course(self):
"""Test new course creation - happy path"""
@@ -1117,7 +1117,7 @@ def test_create_course__default_enable_flexible_peer_openassessments(
new_course = self.store.get_course(new_course_key)
# ... and our setting got toggled appropriately on the course
- self.assertEqual(new_course.force_on_flexible_peer_openassessments, mock_toggle_state)
+ self.assertEqual(new_course.force_on_flexible_peer_openassessments, mock_toggle_state) # noqa: PT009
@override_settings(DEFAULT_COURSE_LANGUAGE='hr')
def test_create_course_default_language(self):
@@ -1125,7 +1125,7 @@ def test_create_course_default_language(self):
test_course_data = self.assert_created_course()
course_id = _get_course_id(self.store, test_course_data)
course_block = self.store.get_course(course_id)
- self.assertEqual(course_block.language, 'hr')
+ self.assertEqual(course_block.language, 'hr') # noqa: PT009
def test_create_course_with_dots(self):
"""Test new course creation with dots in the name"""
@@ -1151,16 +1151,16 @@ def test_course_with_different_cases(self):
def test_create_course_check_forum_seeding(self):
"""Test new course creation and verify forum seeding """
test_course_data = self.assert_created_course(number_suffix=uuid4().hex)
- self.assertTrue(are_permissions_roles_seeded(_get_course_id(self.store, test_course_data)))
+ self.assertTrue(are_permissions_roles_seeded(_get_course_id(self.store, test_course_data))) # noqa: PT009
def test_forum_unseeding_on_delete(self):
"""Test new course creation and verify forum unseeding """
test_course_data = self.assert_created_course(number_suffix=uuid4().hex)
course_id = _get_course_id(self.store, test_course_data)
- self.assertTrue(are_permissions_roles_seeded(course_id))
+ self.assertTrue(are_permissions_roles_seeded(course_id)) # noqa: PT009
delete_course(course_id, self.user.id)
# should raise an exception for checking permissions on deleted course
- with self.assertRaises(ItemNotFoundError):
+ with self.assertRaises(ItemNotFoundError): # noqa: PT027
are_permissions_roles_seeded(course_id)
def test_forum_unseeding_with_multiple_courses(self):
@@ -1172,12 +1172,12 @@ def test_forum_unseeding_with_multiple_courses(self):
course_id = _get_course_id(self.store, test_course_data)
delete_course(course_id, self.user.id)
# should raise an exception for checking permissions on deleted course
- with self.assertRaises(ItemNotFoundError):
+ with self.assertRaises(ItemNotFoundError): # noqa: PT027
are_permissions_roles_seeded(course_id)
second_course_id = _get_course_id(self.store, second_course_data)
# permissions should still be there for the other course
- self.assertTrue(are_permissions_roles_seeded(second_course_id))
+ self.assertTrue(are_permissions_roles_seeded(second_course_id)) # noqa: PT009
def test_course_enrollments_and_roles_on_delete(self):
"""
@@ -1187,14 +1187,14 @@ def test_course_enrollments_and_roles_on_delete(self):
course_id = _get_course_id(self.store, test_course_data)
# test that a user gets his enrollment and its 'student' role as default on creating a course
- self.assertTrue(CourseEnrollment.is_enrolled(self.user, course_id))
- self.assertTrue(self.user.roles.filter(name="Student", course_id=course_id))
+ self.assertTrue(CourseEnrollment.is_enrolled(self.user, course_id)) # noqa: PT009
+ self.assertTrue(self.user.roles.filter(name="Student", course_id=course_id)) # noqa: PT009
delete_course(course_id, self.user.id)
# check that user's enrollment for this course is not deleted
- self.assertTrue(CourseEnrollment.is_enrolled(self.user, course_id))
+ self.assertTrue(CourseEnrollment.is_enrolled(self.user, course_id)) # noqa: PT009
# check that user has form role "Student" for this course even after deleting it
- self.assertTrue(self.user.roles.filter(name="Student", course_id=course_id))
+ self.assertTrue(self.user.roles.filter(name="Student", course_id=course_id)) # noqa: PT009
def test_course_access_groups_on_delete(self):
"""
@@ -1209,7 +1209,7 @@ def test_course_access_groups_on_delete(self):
auth.add_users(self.user, instructor_role, self.user)
- self.assertGreater(len(instructor_role.users_with_role()), 0)
+ self.assertGreater(len(instructor_role.users_with_role()), 0) # noqa: PT009
# Now delete course and check that user not in instructor groups of this course
delete_course(course_id, self.user.id)
@@ -1217,8 +1217,8 @@ def test_course_access_groups_on_delete(self):
# Update our cached user since its roles have changed
self.user = User.objects.get_by_natural_key(self.user.natural_key()[0])
- self.assertFalse(instructor_role.has_user(self.user))
- self.assertEqual(len(instructor_role.users_with_role()), 0)
+ self.assertFalse(instructor_role.has_user(self.user)) # noqa: PT009
+ self.assertEqual(len(instructor_role.users_with_role()), 0) # noqa: PT009
def test_delete_course_with_keep_instructors(self):
"""
@@ -1231,14 +1231,14 @@ def test_delete_course_with_keep_instructors(self):
# Add and verify instructor role for the course
instructor_role = CourseInstructorRole(course_id)
instructor_role.add_users(self.user)
- self.assertTrue(instructor_role.has_user(self.user))
+ self.assertTrue(instructor_role.has_user(self.user)) # noqa: PT009
delete_course(course_id, self.user.id, keep_instructors=True)
# Update our cached user so if any change in roles can be captured
self.user = User.objects.get_by_natural_key(self.user.natural_key()[0])
- self.assertTrue(instructor_role.has_user(self.user))
+ self.assertTrue(instructor_role.has_user(self.user)) # noqa: PT009
def test_create_course_after_delete(self):
"""
@@ -1269,14 +1269,14 @@ def assert_course_creation_failed(self, error_message):
# b/c the intent of the test with bad chars isn't to test auth but to test the handler, ignore
pass
resp = self.client.ajax_post('/course/', self.course_data)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
data = parse_json(resp)
assert 'ErrMsg' in data, "Expected the course creation to fail"
- self.assertRegex(data['ErrMsg'], error_message)
+ self.assertRegex(data['ErrMsg'], error_message) # noqa: PT009
if test_enrollment:
# One test case involves trying to create the same course twice. Hence for that course,
# the user will be enrolled. In the other cases, initially_enrolled will be False.
- self.assertEqual(initially_enrolled, CourseEnrollment.is_enrolled(self.user, course_id))
+ self.assertEqual(initially_enrolled, CourseEnrollment.is_enrolled(self.user, course_id)) # noqa: PT009
def test_create_course_duplicate_number(self):
"""Test new course creation - error path"""
@@ -1322,11 +1322,11 @@ def test_course_substring(self):
cache_current = self.course_data['number']
self.course_data['number'] = '{}a'.format(self.course_data['number'])
resp = self.client.ajax_post('/course/', self.course_data)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
self.course_data['number'] = cache_current
self.course_data['org'] = 'a{}'.format(self.course_data['org'])
resp = self.client.ajax_post('/course/', self.course_data)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def test_create_course_with_bad_organization(self):
"""Test new course creation - error path for bad organization name"""
@@ -1383,18 +1383,18 @@ def assert_course_permission_denied(self):
Checks that the course did not get created due to a PermissionError.
"""
resp = self.client.ajax_post('/course/', self.course_data)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
def test_course_factory(self):
"""Test that the course factory works correctly."""
course = CourseFactory.create()
- self.assertIsInstance(course, CourseBlock)
+ self.assertIsInstance(course, CourseBlock) # noqa: PT009
def test_item_factory(self):
"""Test that the item factory works correctly."""
course = CourseFactory.create()
item = BlockFactory.create(parent_location=course.location)
- self.assertIsInstance(item, SequenceBlock)
+ self.assertIsInstance(item, SequenceBlock) # noqa: PT009
def test_create_block(self):
"""Test creating a new xblock instance."""
@@ -1408,12 +1408,12 @@ def test_create_block(self):
resp = self.client.ajax_post(reverse_url('xblock_handler'), section_data)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
data = parse_json(resp)
retarget = re.escape(
str(course.id.make_usage_key('chapter', 'REPLACE'))
).replace('REPLACE', r'([0-9]|[a-f]){3,}')
- self.assertRegex(data['locator'], retarget)
+ self.assertRegex(data['locator'], retarget) # noqa: PT009
@ddt.data(True, False)
def test_hide_xblock_from_toc_via_handler(self, hide_from_toc):
@@ -1429,8 +1429,8 @@ def test_hide_xblock_from_toc_via_handler(self, hide_from_toc):
response = self.client.ajax_post(get_url("xblock_handler", sequential.location), data)
sequential = self.store.get_item(sequential.location)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(hide_from_toc, sequential.hide_from_toc)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(hide_from_toc, sequential.hide_from_toc) # noqa: PT009
def test_capa_block(self):
"""Test that a problem treats markdown specially."""
@@ -1442,12 +1442,12 @@ def test_capa_block(self):
}
resp = self.client.ajax_post(reverse_url('xblock_handler'), problem_data)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
payload = parse_json(resp)
problem_loc = UsageKey.from_string(payload['locator'])
problem = self.store.get_item(problem_loc)
- self.assertIsInstance(problem, ProblemBlock, "New problem is not a ProblemBlock")
- self.assertNotIn('markdown', problem.editable_metadata_fields, "Markdown slipped into the editable metadata fields") # lint-amnesty, pylint: disable=line-too-long
+ self.assertIsInstance(problem, ProblemBlock, "New problem is not a ProblemBlock") # noqa: PT009
+ self.assertNotIn('markdown', problem.editable_metadata_fields, "Markdown slipped into the editable metadata fields") # lint-amnesty, pylint: disable=line-too-long # noqa: PT009
def test_cms_imported_course_walkthrough(self):
"""
@@ -1460,7 +1460,7 @@ def test_get_html(handler):
resp = self.client.get_html(
get_url(handler, course_key, 'course_key_string')
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def test_get_json(handler):
# Helper function for getting HTML for a page in Studio and
@@ -1469,7 +1469,7 @@ def test_get_json(handler):
get_url(handler, course_key, 'course_key_string'),
HTTP_ACCEPT="application/json",
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
course_items = import_course_from_xml(
self.store, self.user.id, TEST_DATA_DIR, ['simple'], create_if_not_present=True
@@ -1480,10 +1480,10 @@ def test_get_json(handler):
# course_handler raise 404 for old mongo course
if course_key.deprecated:
- self.assertEqual(resp.status_code, 404)
+ self.assertEqual(resp.status_code, 404) # noqa: PT009
return
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
self.assertContains(resp, 'Chapter 2')
# go to various pages
@@ -1514,19 +1514,19 @@ def test_get_json(handler):
resp = self.client.get(
get_url('cms.djangoapps.contentstore:v0:course_tab_list', course_key, 'course_id')
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# go look at the Edit page
unit_key = course_key.make_usage_key('vertical', 'test_vertical')
with override_waffle_flag(toggles.LEGACY_STUDIO_UNIT_EDITOR, True):
resp = self.client.get_html(get_url('container_handler', unit_key))
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def delete_item(category, name):
""" Helper method for testing the deletion of an xblock item. """
item_key = course_key.make_usage_key(category, name)
resp = self.client.delete(get_url('xblock_handler', item_key))
- self.assertEqual(resp.status_code, 204)
+ self.assertEqual(resp.status_code, 204) # noqa: PT009
# delete a component
delete_item(category='html', name='test_html')
@@ -1550,7 +1550,7 @@ def test_import_into_new_course_id(self):
# we should have a number of blocks in there
# we can't specify an exact number since it'll always be changing
- self.assertGreater(len(blocks), 10)
+ self.assertGreater(len(blocks), 10) # noqa: PT009
#
# test various re-namespacing elements
@@ -1559,10 +1559,10 @@ def test_import_into_new_course_id(self):
# first check PDF textbooks, to make sure the url paths got updated
course_block = self.store.get_course(target_id)
- self.assertEqual(len(course_block.pdf_textbooks), 1)
- self.assertEqual(len(course_block.pdf_textbooks[0]["chapters"]), 2)
- self.assertEqual(course_block.pdf_textbooks[0]["chapters"][0]["url"], '/static/Chapter1.pdf')
- self.assertEqual(course_block.pdf_textbooks[0]["chapters"][1]["url"], '/static/Chapter2.pdf')
+ self.assertEqual(len(course_block.pdf_textbooks), 1) # noqa: PT009
+ self.assertEqual(len(course_block.pdf_textbooks[0]["chapters"]), 2) # noqa: PT009
+ self.assertEqual(course_block.pdf_textbooks[0]["chapters"][0]["url"], '/static/Chapter1.pdf') # noqa: PT009
+ self.assertEqual(course_block.pdf_textbooks[0]["chapters"][1]["url"], '/static/Chapter2.pdf') # noqa: PT009
def test_import_into_new_course_id_wiki_slug_renamespacing(self):
# If reimporting into the same course change the wiki_slug.
@@ -1581,7 +1581,7 @@ def test_import_into_new_course_id_wiki_slug_renamespacing(self):
# Import a course with wiki_slug == location.course
import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], target_id=target_id)
course_block = self.store.get_course(target_id)
- self.assertEqual(course_block.wiki_slug, 'edX.toy.2012_Fall')
+ self.assertEqual(course_block.wiki_slug, 'edX.toy.2012_Fall') # noqa: PT009
# But change the wiki_slug if it is a different course.
target_id = self.store.make_course_key('MITx', '111', '2013_Spring')
@@ -1596,12 +1596,12 @@ def test_import_into_new_course_id_wiki_slug_renamespacing(self):
# Import a course with wiki_slug == location.course
import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['toy'], target_id=target_id)
course_block = self.store.get_course(target_id)
- self.assertEqual(course_block.wiki_slug, 'MITx.111.2013_Spring')
+ self.assertEqual(course_block.wiki_slug, 'MITx.111.2013_Spring') # noqa: PT009
# Now try importing a course with wiki_slug == '{0}.{1}.{2}'.format(location.org, location.course, location.run)
import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['two_toys'], target_id=target_id)
course_block = self.store.get_course(target_id)
- self.assertEqual(course_block.wiki_slug, 'MITx.111.2013_Spring')
+ self.assertEqual(course_block.wiki_slug, 'MITx.111.2013_Spring') # noqa: PT009
def test_import_metadata_with_attempts_empty_string(self):
import_course_from_xml(self.store, self.user.id, TEST_DATA_DIR, ['simple'], create_if_not_present=True)
@@ -1615,7 +1615,7 @@ def test_import_metadata_with_attempts_empty_string(self):
pass
# make sure we found the item (e.g. it didn't error while loading)
- self.assertTrue(did_load_item)
+ self.assertTrue(did_load_item) # noqa: PT009
def test_forum_id_generation(self):
"""
@@ -1634,11 +1634,11 @@ def test_forum_id_generation(self):
refetched = self.store.get_item(discussion_item.location)
# and make sure the same discussion items have the same discussion ids
- self.assertEqual(fetched.discussion_id, discussion_item.discussion_id)
- self.assertEqual(fetched.discussion_id, refetched.discussion_id)
+ self.assertEqual(fetched.discussion_id, discussion_item.discussion_id) # noqa: PT009
+ self.assertEqual(fetched.discussion_id, refetched.discussion_id) # noqa: PT009
# and make sure that the id isn't the old "$$GUID$$"
- self.assertNotEqual(discussion_item.discussion_id, '$$GUID$$')
+ self.assertNotEqual(discussion_item.discussion_id, '$$GUID$$') # noqa: PT009
def test_metadata_inheritance(self):
course_items = import_course_from_xml(
@@ -1650,10 +1650,10 @@ def test_metadata_inheritance(self):
# let's assert on the metadata_inheritance on an existing vertical
for vertical in verticals:
- self.assertEqual(course.xqa_key, vertical.xqa_key)
- self.assertEqual(course.start, vertical.start)
+ self.assertEqual(course.xqa_key, vertical.xqa_key) # noqa: PT009
+ self.assertEqual(course.start, vertical.start) # noqa: PT009
- self.assertGreater(len(verticals), 0)
+ self.assertGreater(len(verticals), 0) # noqa: PT009
# crate a new block and add it as a child to a vertical
parent = verticals[0]
@@ -1665,11 +1665,11 @@ def test_metadata_inheritance(self):
new_block = self.store.get_item(new_block.location)
# check for grace period definition which should be defined at the course level
- self.assertEqual(parent.graceperiod, new_block.graceperiod)
- self.assertEqual(parent.start, new_block.start)
- self.assertEqual(course.start, new_block.start)
+ self.assertEqual(parent.graceperiod, new_block.graceperiod) # noqa: PT009
+ self.assertEqual(parent.start, new_block.start) # noqa: PT009
+ self.assertEqual(course.start, new_block.start) # noqa: PT009
- self.assertEqual(course.xqa_key, new_block.xqa_key)
+ self.assertEqual(course.xqa_key, new_block.xqa_key) # noqa: PT009
#
# now let's define an override at the leaf node level
@@ -1680,26 +1680,26 @@ def test_metadata_inheritance(self):
# flush the cache and refetch
new_block = self.store.get_item(new_block.location)
- self.assertEqual(timedelta(1), new_block.graceperiod)
+ self.assertEqual(timedelta(1), new_block.graceperiod) # noqa: PT009
def test_default_metadata_inheritance(self):
course = CourseFactory.create()
vertical = BlockFactory.create(parent_location=course.location)
course.children.append(vertical)
# in memory
- self.assertIsNotNone(course.start)
- self.assertEqual(course.start, vertical.start)
- self.assertEqual(course.textbooks, [])
- self.assertIn('GRADER', course.grading_policy)
- self.assertIn('GRADE_CUTOFFS', course.grading_policy)
+ self.assertIsNotNone(course.start) # noqa: PT009
+ self.assertEqual(course.start, vertical.start) # noqa: PT009
+ self.assertEqual(course.textbooks, []) # noqa: PT009
+ self.assertIn('GRADER', course.grading_policy) # noqa: PT009
+ self.assertIn('GRADE_CUTOFFS', course.grading_policy) # noqa: PT009
# by fetching
fetched_course = self.store.get_item(course.location)
fetched_item = self.store.get_item(vertical.location)
- self.assertIsNotNone(fetched_course.start)
- self.assertEqual(course.start, fetched_course.start)
- self.assertEqual(fetched_course.start, fetched_item.start)
- self.assertEqual(course.textbooks, fetched_course.textbooks)
+ self.assertIsNotNone(fetched_course.start) # noqa: PT009
+ self.assertEqual(course.start, fetched_course.start) # noqa: PT009
+ self.assertEqual(fetched_course.start, fetched_item.start) # noqa: PT009
+ self.assertEqual(course.textbooks, fetched_course.textbooks) # noqa: PT009
def test_image_import(self):
"""Test backwards compatibilty of course image."""
@@ -1718,7 +1718,7 @@ def test_image_import(self):
course = courses[0]
# Make sure the course image is set to the right place
- self.assertEqual(course.course_image, 'images_course_image.jpg')
+ self.assertEqual(course.course_image, 'images_course_image.jpg') # noqa: PT009
# Ensure that the imported course image is present -- this shouldn't raise an exception
asset_key = course.id.make_asset_key('asset', course.course_image)
@@ -1738,13 +1738,13 @@ def test_wiki_slug(self):
course_key = _get_course_id(self.store, self.course_data)
_create_course(self, course_key, self.course_data)
course_block = self.store.get_course(course_key)
- self.assertEqual(course_block.wiki_slug, 'MITx.111.2013_Spring')
+ self.assertEqual(course_block.wiki_slug, 'MITx.111.2013_Spring') # noqa: PT009
def test_course_handler_with_invalid_course_key_string(self):
"""Test viewing the course overview page with invalid course id"""
response = self.client.get_html('/course/edX/test')
- self.assertEqual(response.status_code, 404)
+ self.assertEqual(response.status_code, 404) # noqa: PT009
class MetadataSaveTestCase(ContentStoreTestCase):
@@ -1777,7 +1777,7 @@ def test_metadata_not_persistence(self):
Test that blocks which set metadata fields in their
constructor are correctly deleted.
"""
- self.assertIn('html5_sources', own_metadata(self.video_block))
+ self.assertIn('html5_sources', own_metadata(self.video_block)) # noqa: PT009
attrs_to_strip = {
'show_captions',
'youtube_id_1_0',
@@ -1795,11 +1795,11 @@ def test_metadata_not_persistence(self):
for field_name in attrs_to_strip:
delattr(self.video_block, field_name)
- self.assertNotIn('html5_sources', own_metadata(self.video_block))
+ self.assertNotIn('html5_sources', own_metadata(self.video_block)) # noqa: PT009
self.store.update_item(self.video_block, self.user.id)
block = self.store.get_item(location)
- self.assertNotIn('html5_sources', own_metadata(block))
+ self.assertNotIn('html5_sources', own_metadata(block)) # noqa: PT009
def test_metadata_persistence(self):
# TODO: create the same test as `test_metadata_not_persistence`,
@@ -1838,10 +1838,10 @@ def post_rerun_request(
response = self.client.ajax_post(course_url, rerun_course_data)
# verify response
- self.assertEqual(response.status_code, response_code)
+ self.assertEqual(response.status_code, response_code) # noqa: PT009
if not expect_error:
json_resp = parse_json(response)
- self.assertNotIn('ErrMsg', json_resp)
+ self.assertNotIn('ErrMsg', json_resp) # noqa: PT009
destination_course_key = CourseKey.from_string(json_resp['destination_course_key'])
return destination_course_key
@@ -1883,10 +1883,10 @@ def verify_rerun_course(self, source_course_key, destination_course_key, destina
'should_display': True,
}
for field_name, expected_value in expected_states.items():
- self.assertEqual(getattr(rerun_state, field_name), expected_value)
+ self.assertEqual(getattr(rerun_state, field_name), expected_value) # noqa: PT009
# Verify that the creator is now enrolled in the course.
- self.assertTrue(CourseEnrollment.is_enrolled(self.user, destination_course_key))
+ self.assertTrue(CourseEnrollment.is_enrolled(self.user, destination_course_key)) # noqa: PT009
# Verify both courses are in the course listing section
self.assertInCourseListing(source_course_key)
@@ -1901,7 +1901,7 @@ def test_rerun_course_no_videos_in_val(self):
self.verify_rerun_course(source_course.id, destination_course_key, self.destination_course_data['display_name'])
videos, __ = get_videos_for_course(str(destination_course_key))
videos = list(videos)
- self.assertEqual(0, len(videos))
+ self.assertEqual(0, len(videos)) # noqa: PT009
self.assertInCourseListing(destination_course_key)
def test_rerun_course_video_upload_token(self):
@@ -1921,8 +1921,8 @@ def test_rerun_course_video_upload_token(self):
# Verify video upload pipeline is empty.
source_course = self.store.get_course(source_course.id)
new_course = self.store.get_course(destination_course_key)
- self.assertDictEqual(source_course.video_upload_pipeline, {"course_video_upload_token": 'test-token'})
- self.assertEqual(new_course.video_upload_pipeline, {})
+ self.assertDictEqual(source_course.video_upload_pipeline, {"course_video_upload_token": 'test-token'}) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(new_course.video_upload_pipeline, {}) # noqa: PT009
def test_rerun_course_success(self):
source_course = CourseFactory.create(default_store=ModuleStoreEnum.Type.split)
@@ -1943,12 +1943,12 @@ def test_rerun_course_success(self):
source_videos = list(videos)
videos, __ = get_videos_for_course(str(destination_course_key))
target_videos = list(videos)
- self.assertEqual(1, len(source_videos))
- self.assertEqual(source_videos, target_videos)
+ self.assertEqual(1, len(source_videos)) # noqa: PT009
+ self.assertEqual(source_videos, target_videos) # noqa: PT009
# Verify that video upload token is empty for rerun.
new_course = self.store.get_course(destination_course_key)
- self.assertEqual(new_course.video_upload_pipeline, {})
+ self.assertEqual(new_course.video_upload_pipeline, {}) # noqa: PT009
def test_rerun_course_resets_advertised_date(self):
source_course = CourseFactory.create(
@@ -1958,7 +1958,7 @@ def test_rerun_course_resets_advertised_date(self):
destination_course_key = self.post_rerun_request(source_course.id)
destination_course = self.store.get_course(destination_course_key)
- self.assertEqual(None, destination_course.advertised_start)
+ self.assertEqual(None, destination_course.advertised_start) # noqa: PT009
def test_rerun_of_rerun(self):
source_course = CourseFactory.create(default_store=ModuleStoreEnum.Type.split)
@@ -1979,11 +1979,11 @@ def test_rerun_course_fail_no_source_course(self):
# Verify that the course rerun action is marked failed
rerun_state = CourseRerunState.objects.find_first(course_key=destination_course_key)
- self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.FAILED)
- self.assertIn("Cannot find a course at", rerun_state.message)
+ self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.FAILED) # noqa: PT009
+ self.assertIn("Cannot find a course at", rerun_state.message) # noqa: PT009
# Verify that the creator is not enrolled in the course.
- self.assertFalse(CourseEnrollment.is_enrolled(self.user, non_existent_course_key))
+ self.assertFalse(CourseEnrollment.is_enrolled(self.user, non_existent_course_key)) # noqa: PT009
# Verify that the existing course continues to be in the course listings
self.assertInCourseListing(existent_course_key)
@@ -2004,7 +2004,7 @@ def test_rerun_course_fail_duplicate_course(self):
)
# Verify that the course rerun action doesn't exist
- with self.assertRaises(CourseActionStateItemNotFoundError):
+ with self.assertRaises(CourseActionStateItemNotFoundError): # noqa: PT027
CourseRerunState.objects.find_first(course_key=destination_course_key)
# Verify that the existing course continues to be in the course listing
@@ -2027,8 +2027,8 @@ def test_rerun_error(self):
source_course = CourseFactory.create()
destination_course_key = self.post_rerun_request(source_course.id)
rerun_state = CourseRerunState.objects.find_first(course_key=destination_course_key)
- self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.FAILED)
- self.assertIn(error_message, rerun_state.message)
+ self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.FAILED) # noqa: PT009
+ self.assertIn(error_message, rerun_state.message) # noqa: PT009
def test_rerun_error_trunc_message(self):
"""
@@ -2046,9 +2046,9 @@ def test_rerun_error_trunc_message(self):
with mock.patch('traceback.format_exc', return_value=message_too_long):
destination_course_key = self.post_rerun_request(source_course.id)
rerun_state = CourseRerunState.objects.find_first(course_key=destination_course_key)
- self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.FAILED)
- self.assertTrue(rerun_state.message.endswith("traceback"))
- self.assertEqual(len(rerun_state.message), CourseRerunState.MAX_MESSAGE_LENGTH)
+ self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.FAILED) # noqa: PT009
+ self.assertTrue(rerun_state.message.endswith("traceback")) # noqa: PT009
+ self.assertEqual(len(rerun_state.message), CourseRerunState.MAX_MESSAGE_LENGTH) # noqa: PT009
def test_rerun_course_wiki_slug(self):
"""
@@ -2069,7 +2069,7 @@ def test_rerun_course_wiki_slug(self):
source_course = self.store.get_course(source_course_key)
# Verify created course's wiki_slug.
- self.assertEqual(source_course.wiki_slug, source_wiki_slug)
+ self.assertEqual(source_course.wiki_slug, source_wiki_slug) # noqa: PT009
destination_course_data = course_data
destination_course_data['run'] = '2013_Rerun'
@@ -2080,12 +2080,12 @@ def test_rerun_course_wiki_slug(self):
self.verify_rerun_course(source_course.id, destination_course_key, destination_course_data['display_name'])
destination_course = self.store.get_course(destination_course_key)
- destination_wiki_slug = '{}.{}.{}'.format(
+ destination_wiki_slug = '{}.{}.{}'.format( # noqa: UP032
destination_course.id.org, destination_course.id.course, destination_course.id.run
)
# Verify rerun course's wiki_slug.
- self.assertEqual(destination_course.wiki_slug, destination_wiki_slug)
+ self.assertEqual(destination_course.wiki_slug, destination_wiki_slug) # noqa: PT009
class ContentLicenseTest(ContentStoreTestCase):
@@ -2103,7 +2103,7 @@ def test_course_license_export(self):
run_file_path = root_dir / "test_license" / "course" / fname
with run_file_path.open() as f:
run_xml = etree.parse(f)
- self.assertEqual(run_xml.getroot().get("license"), "creative-commons: BY SA")
+ self.assertEqual(run_xml.getroot().get("license"), "creative-commons: BY SA") # noqa: PT009
def test_video_license_export(self):
content_store = contentstore()
@@ -2117,16 +2117,16 @@ def test_video_license_export(self):
video_file_path = root_dir / "test_license" / "video" / fname
with video_file_path.open() as f:
video_xml = etree.parse(f)
- self.assertEqual(video_xml.getroot().get("license"), "all-rights-reserved")
+ self.assertEqual(video_xml.getroot().get("license"), "all-rights-reserved") # noqa: PT009
def test_license_import(self):
course_items = import_course_from_xml(
self.store, self.user.id, TEST_DATA_DIR, ['toy'], create_if_not_present=True
)
course = course_items[0]
- self.assertEqual(course.license, "creative-commons: BY")
+ self.assertEqual(course.license, "creative-commons: BY") # noqa: PT009
videos = self.store.get_items(course.id, qualifiers={'category': 'video'})
- self.assertEqual(videos[0].license, "all-rights-reserved")
+ self.assertEqual(videos[0].license, "all-rights-reserved") # noqa: PT009
class EntryPageTestCase(TestCase):
@@ -2140,7 +2140,7 @@ def setUp(self):
def _test_page(self, page, status_code=200):
resp = self.client.get_html(page)
- self.assertEqual(resp.status_code, status_code)
+ self.assertEqual(resp.status_code, status_code) # noqa: PT009
@override_waffle_flag(toggles.LEGACY_STUDIO_LOGGED_OUT_HOME, True)
def test_how_it_works_legacy(self):
@@ -2174,10 +2174,10 @@ def _create_course(test, course_key, course_data):
"""
course_url = get_url('course_handler', course_key, 'course_key_string')
response = test.client.ajax_post(course_url, course_data)
- test.assertEqual(response.status_code, 200)
+ test.assertEqual(response.status_code, 200) # noqa: PT009
data = parse_json(response)
- test.assertNotIn('ErrMsg', data)
- test.assertEqual(data['url'], course_url)
+ test.assertNotIn('ErrMsg', data) # noqa: PT009
+ test.assertEqual(data['url'], course_url) # noqa: PT009
return data
diff --git a/cms/djangoapps/contentstore/tests/test_core_caching.py b/cms/djangoapps/contentstore/tests/test_core_caching.py
index e6b23c2deeed..956397214a64 100644
--- a/cms/djangoapps/contentstore/tests/test_core_caching.py
+++ b/cms/djangoapps/contentstore/tests/test_core_caching.py
@@ -32,15 +32,15 @@ class CachingTestCase(TestCase):
def test_put_and_get(self):
set_cached_content(self.mockAsset)
- self.assertEqual(self.mockAsset.content, get_cached_content(self.unicodeLocation).content,
+ self.assertEqual(self.mockAsset.content, get_cached_content(self.unicodeLocation).content, # noqa: PT009
'should be stored in cache with unicodeLocation')
- self.assertEqual(self.mockAsset.content, get_cached_content(self.nonUnicodeLocation).content,
+ self.assertEqual(self.mockAsset.content, get_cached_content(self.nonUnicodeLocation).content, # noqa: PT009
'should be stored in cache with nonUnicodeLocation')
def test_delete(self):
set_cached_content(self.mockAsset)
del_cached_content(self.nonUnicodeLocation)
- self.assertEqual(None, get_cached_content(self.unicodeLocation),
+ self.assertEqual(None, get_cached_content(self.unicodeLocation), # noqa: PT009
'should not be stored in cache with unicodeLocation')
- self.assertEqual(None, get_cached_content(self.nonUnicodeLocation),
+ self.assertEqual(None, get_cached_content(self.nonUnicodeLocation), # noqa: PT009
'should not be stored in cache with nonUnicodeLocation')
diff --git a/cms/djangoapps/contentstore/tests/test_course_create_rerun.py b/cms/djangoapps/contentstore/tests/test_course_create_rerun.py
index b1c484b7f262..21c1ecc19f21 100644
--- a/cms/djangoapps/contentstore/tests/test_course_create_rerun.py
+++ b/cms/djangoapps/contentstore/tests/test_course_create_rerun.py
@@ -99,19 +99,19 @@ def test_rerun(self):
'org': self.source_course_key.org, 'course': self.source_course_key.course, 'run': 'copy',
'display_name': 'not the same old name',
})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
data = parse_json(response)
dest_course_key = CourseKey.from_string(data['destination_course_key'])
- self.assertEqual(dest_course_key.run, 'copy')
+ self.assertEqual(dest_course_key.run, 'copy') # noqa: PT009
dest_course = self.store.get_course(dest_course_key)
- self.assertEqual(dest_course.start, CourseFields.start.default)
- self.assertEqual(dest_course.end, None)
- self.assertEqual(dest_course.enrollment_start, None)
- self.assertEqual(dest_course.enrollment_end, None)
+ self.assertEqual(dest_course.start, CourseFields.start.default) # noqa: PT009
+ self.assertEqual(dest_course.end, None) # noqa: PT009
+ self.assertEqual(dest_course.enrollment_start, None) # noqa: PT009
+ self.assertEqual(dest_course.enrollment_end, None) # noqa: PT009
course_orgs = get_course_organizations(dest_course_key)
- self.assertEqual(len(course_orgs), 1)
- self.assertEqual(course_orgs[0]['short_name'], self.source_course_key.org)
+ self.assertEqual(len(course_orgs), 1) # noqa: PT009
+ self.assertEqual(course_orgs[0]['short_name'], self.source_course_key.org) # noqa: PT009
def test_newly_created_course_has_web_certs_enabled(self):
"""
@@ -123,11 +123,11 @@ def test_newly_created_course_has_web_certs_enabled(self):
'display_name': 'Course with web certs enabled',
'run': '2015_T2'
})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
data = parse_json(response)
new_course_key = CourseKey.from_string(data['course_key'])
course = self.store.get_course(new_course_key)
- self.assertTrue(course.cert_html_view_enabled)
+ self.assertTrue(course.cert_html_view_enabled) # noqa: PT009
def test_course_creation_for_unknown_organization_relaxed(self):
"""
@@ -135,7 +135,7 @@ def test_course_creation_for_unknown_organization_relaxed(self):
creating a course-run with an unknown org slug will create an organization
and organization-course linkage in the system.
"""
- with self.assertRaises(InvalidOrganizationException):
+ with self.assertRaises(InvalidOrganizationException): # noqa: PT027
get_organization_by_short_name("orgX")
response = self.client.ajax_post(self.course_create_rerun_url, {
'org': 'orgX',
@@ -143,13 +143,13 @@ def test_course_creation_for_unknown_organization_relaxed(self):
'display_name': 'Course with web certs enabled',
'run': '2015_T2'
})
- self.assertEqual(response.status_code, 200)
- self.assertIsNotNone(get_organization_by_short_name("orgX"))
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertIsNotNone(get_organization_by_short_name("orgX")) # noqa: PT009
data = parse_json(response)
new_course_key = CourseKey.from_string(data['course_key'])
course_orgs = get_course_organizations(new_course_key)
- self.assertEqual(len(course_orgs), 1)
- self.assertEqual(course_orgs[0]['short_name'], 'orgX')
+ self.assertEqual(len(course_orgs), 1) # noqa: PT009
+ self.assertEqual(course_orgs[0]['short_name'], 'orgX') # noqa: PT009
@override_settings(ORGANIZATIONS_AUTOCREATE=False)
def test_course_creation_for_unknown_organization_strict(self):
@@ -163,11 +163,11 @@ def test_course_creation_for_unknown_organization_strict(self):
'display_name': 'Course with web certs enabled',
'run': '2015_T2'
})
- self.assertEqual(response.status_code, 400)
- with self.assertRaises(InvalidOrganizationException):
+ self.assertEqual(response.status_code, 400) # noqa: PT009
+ with self.assertRaises(InvalidOrganizationException): # noqa: PT027
get_organization_by_short_name("orgX")
data = parse_json(response)
- self.assertIn('Organization you selected does not exist in the system', data['error'])
+ self.assertIn('Organization you selected does not exist in the system', data['error']) # noqa: PT009
@ddt.data(True, False)
def test_course_creation_for_known_organization(self, organizations_autocreate):
@@ -186,12 +186,12 @@ def test_course_creation_for_known_organization(self, organizations_autocreate):
'display_name': 'Course with web certs enabled',
'run': '2015_T2'
})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
data = parse_json(response)
new_course_key = CourseKey.from_string(data['course_key'])
course_orgs = get_course_organizations(new_course_key)
- self.assertEqual(len(course_orgs), 1)
- self.assertEqual(course_orgs[0]['short_name'], 'orgX')
+ self.assertEqual(len(course_orgs), 1) # noqa: PT009
+ self.assertEqual(course_orgs[0]['short_name'], 'orgX') # noqa: PT009
@override_settings(FEATURES={'ENABLE_CREATOR_GROUP': True})
def test_course_creation_when_user_not_in_org(self):
@@ -204,7 +204,7 @@ def test_course_creation_when_user_not_in_org(self):
'display_name': 'Course with web certs enabled',
'run': '2021_T1'
})
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
@override_settings(FEATURES={'ENABLE_CREATOR_GROUP': True})
@mock.patch(
@@ -224,14 +224,14 @@ def test_course_creation_when_user_in_org_with_creator_role(self):
self.course_creator_entry.all_organizations = True
self.course_creator_entry.state = CourseCreator.GRANTED
self.creator_admin.save_model(self.request, self.course_creator_entry, None, True)
- self.assertIn(self.source_course_key.org, get_allowed_organizations(self.user))
+ self.assertIn(self.source_course_key.org, get_allowed_organizations(self.user)) # noqa: PT009
response = self.client.ajax_post(self.course_create_rerun_url, {
'org': self.source_course_key.org,
'number': 'CS101',
'display_name': 'Course with web certs enabled',
'run': '2021_T1'
})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
@override_settings(FEATURES={'ENABLE_CREATOR_GROUP': True})
@mock.patch(
@@ -250,15 +250,15 @@ def test_course_creation_with_all_org_checked(self):
self.course_creator_entry.all_organizations = True
self.course_creator_entry.state = CourseCreator.GRANTED
self.creator_admin.save_model(self.request, self.course_creator_entry, None, True)
- self.assertIn(self.source_course_key.org, get_allowed_organizations(self.user))
- self.assertFalse(user_can_create_organizations(self.user))
+ self.assertIn(self.source_course_key.org, get_allowed_organizations(self.user)) # noqa: PT009
+ self.assertFalse(user_can_create_organizations(self.user)) # noqa: PT009
response = self.client.ajax_post(self.course_create_rerun_url, {
'org': self.source_course_key.org,
'number': 'CS101',
'display_name': 'Course with web certs enabled',
'run': '2021_T1'
})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
@override_settings(FEATURES={'ENABLE_CREATOR_GROUP': True})
@mock.patch(
@@ -279,15 +279,15 @@ def test_course_creation_with_permission_for_specific_organization(self):
self.creator_admin.save_model(self.request, self.course_creator_entry, None, True)
dc_org_object = Organization.objects.get(name='Test Organization')
self.course_creator_entry.organizations.add(dc_org_object)
- self.assertIn(self.source_course_key.org, get_allowed_organizations(self.user))
- self.assertFalse(user_can_create_organizations(self.user))
+ self.assertIn(self.source_course_key.org, get_allowed_organizations(self.user)) # noqa: PT009
+ self.assertFalse(user_can_create_organizations(self.user)) # noqa: PT009
response = self.client.ajax_post(self.course_create_rerun_url, {
'org': self.source_course_key.org,
'number': 'CS101',
'display_name': 'Course with web certs enabled',
'run': '2021_T1'
})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
@override_settings(FEATURES={'ENABLE_CREATOR_GROUP': True})
@mock.patch(
@@ -315,15 +315,15 @@ def test_course_creation_without_permission_for_specific_organization(self):
# When the user tries to create course under `Test Organization` it throws a 403.
dc_org_object = Organization.objects.get(name='DC')
self.course_creator_entry.organizations.add(dc_org_object)
- self.assertNotIn(self.source_course_key.org, get_allowed_organizations(self.user))
- self.assertFalse(user_can_create_organizations(self.user))
+ self.assertNotIn(self.source_course_key.org, get_allowed_organizations(self.user)) # noqa: PT009
+ self.assertFalse(user_can_create_organizations(self.user)) # noqa: PT009
response = self.client.ajax_post(self.course_create_rerun_url, {
'org': self.source_course_key.org,
'number': 'CS101',
'display_name': 'Course with web certs enabled',
'run': '2021_T1'
})
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
@ddt.data(*product([True, False], [True, False]))
@ddt.unpack
@@ -360,7 +360,7 @@ def test_default_enable_flexible_peer_openassessments_on_rerun(
})
# Then the process completes successfully
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
data = parse_json(response)
dest_course_key = CourseKey.from_string(data['destination_course_key'])
@@ -368,10 +368,10 @@ def test_default_enable_flexible_peer_openassessments_on_rerun(
# ... and our setting got enabled appropriately on our new course
if mock_toggle_state:
- self.assertTrue(dest_course.force_on_flexible_peer_openassessments)
+ self.assertTrue(dest_course.force_on_flexible_peer_openassessments) # noqa: PT009
# ... or preserved if the default enable setting is not on
else:
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
source_course.force_on_flexible_peer_openassessments,
dest_course.force_on_flexible_peer_openassessments
)
diff --git a/cms/djangoapps/contentstore/tests/test_course_listing.py b/cms/djangoapps/contentstore/tests/test_course_listing.py
index 9ce181c531ef..f3f812800d15 100644
--- a/cms/djangoapps/contentstore/tests/test_course_listing.py
+++ b/cms/djangoapps/contentstore/tests/test_course_listing.py
@@ -107,20 +107,20 @@ def test_get_course_list(self):
# get courses through iterating all courses
courses_iter, __ = _accessible_courses_iter_for_tests(self.request)
courses_list = list(courses_iter)
- self.assertEqual(len(courses_list), 1)
+ self.assertEqual(len(courses_list), 1) # noqa: PT009
courses_summary_list, __ = _accessible_courses_summary_iter(self.request)
- self.assertEqual(len(list(courses_summary_list)), 1)
+ self.assertEqual(len(list(courses_summary_list)), 1) # noqa: PT009
# get courses by reversing group name formats
courses_list_by_groups, __ = _accessible_courses_list_from_groups(self.request)
- self.assertEqual(len(courses_list_by_groups), 1)
+ self.assertEqual(len(courses_list_by_groups), 1) # noqa: PT009
# check both course lists have same courses
course_keys_in_course_list = [course.id for course in courses_list]
course_keys_in_courses_list_by_groups = [course.id for course in courses_list_by_groups]
- self.assertEqual(course_keys_in_course_list, course_keys_in_courses_list_by_groups)
+ self.assertEqual(course_keys_in_course_list, course_keys_in_courses_list_by_groups) # noqa: PT009
def test_courses_list_with_ccx_courses(self):
"""
@@ -136,8 +136,8 @@ def test_courses_list_with_ccx_courses(self):
# Test that CCX courses are filtered out.
courses_list, __ = _accessible_courses_list_from_groups(self.request)
- self.assertEqual(len(courses_list), 1)
- self.assertNotIn(
+ self.assertEqual(len(courses_list), 1) # noqa: PT009
+ self.assertNotIn( # noqa: PT009
ccx_course_key,
[course.id for course in courses_list]
)
@@ -148,7 +148,7 @@ def test_courses_list_with_ccx_courses(self):
all_courses = (instructor_courses | staff_courses)
# Verify that CCX course exists in access but filtered by `_accessible_courses_list_from_groups`.
- self.assertIn(
+ self.assertIn( # noqa: PT009
ccx_course_key,
[access.course_id for access in all_courses]
)
@@ -160,7 +160,7 @@ def test_courses_list_with_ccx_courses(self):
return_value=[mocked_ccx_course],
):
courses_iter, __ = _accessible_courses_iter_for_tests(self.request)
- self.assertEqual(len(list(courses_iter)), 0)
+ self.assertEqual(len(list(courses_iter)), 0) # noqa: PT009
def test_staff_course_listing(self):
"""
@@ -170,7 +170,7 @@ def test_staff_course_listing(self):
# Assign & verify staff role to the user
GlobalStaff().add_users(self.user)
- self.assertTrue(GlobalStaff().has_user(self.user))
+ self.assertTrue(GlobalStaff().has_user(self.user)) # noqa: PT009
# Create few courses
for num in range(TOTAL_COURSES_COUNT):
@@ -180,8 +180,8 @@ def test_staff_course_listing(self):
# Fetch accessible courses list & verify their count
courses_list_by_staff, __ = get_courses_accessible_to_user(self.request)
- self.assertEqual(len(list(courses_list_by_staff)), TOTAL_COURSES_COUNT)
- self.assertTrue(all(isinstance(course, CourseOverview) for course in courses_list_by_staff))
+ self.assertEqual(len(list(courses_list_by_staff)), TOTAL_COURSES_COUNT) # noqa: PT009
+ self.assertTrue(all(isinstance(course, CourseOverview) for course in courses_list_by_staff)) # noqa: PT009
# Now count the db queries for staff
with self.assertNumQueries(2):
@@ -199,7 +199,7 @@ def test_course_limited_staff_course_listing(self):
# Add the user as a course_limited_staff on the course
CourseLimitedStaffRole(course.id).add_users(self.user)
- self.assertTrue(CourseLimitedStaffRole(course.id).has_user(self.user))
+ self.assertTrue(CourseLimitedStaffRole(course.id).has_user(self.user)) # noqa: PT009
# Fetch accessible courses list & verify their count
courses_list_by_staff, __ = get_courses_accessible_to_user(self.request)
@@ -216,7 +216,7 @@ def test_org_limited_staff_course_listing(self):
number=course_location.course,
run=course_location.run
)
- course = CourseOverviewFactory.create(id=course_location, org=course_location.org)
+ course = CourseOverviewFactory.create(id=course_location, org=course_location.org) # noqa: F841
# Add a user as course_limited_staff on the org
# This is not possible using the course roles classes but is possible via Django admin so we
@@ -240,21 +240,21 @@ def test_get_course_list_with_invalid_course_location(self):
# get courses through iterating all courses
courses_iter, __ = _accessible_courses_iter_for_tests(self.request)
courses_list = list(courses_iter)
- self.assertEqual(len(courses_list), 1)
+ self.assertEqual(len(courses_list), 1) # noqa: PT009
courses_summary_iter, __ = _accessible_courses_summary_iter(self.request)
courses_summary_list = list(courses_summary_iter)
- self.assertTrue(all(isinstance(course, CourseOverview) for course in courses_summary_list))
- self.assertEqual(len(courses_summary_list), 1)
+ self.assertTrue(all(isinstance(course, CourseOverview) for course in courses_summary_list)) # noqa: PT009
+ self.assertEqual(len(courses_summary_list), 1) # noqa: PT009
# get courses by reversing group name formats
courses_list_by_groups, __ = _accessible_courses_list_from_groups(self.request)
- self.assertEqual(len(courses_list_by_groups), 1)
+ self.assertEqual(len(courses_list_by_groups), 1) # noqa: PT009
course_keys_in_course_list = [course.id for course in courses_list]
course_keys_in_courses_list_by_groups = [course.id for course in courses_list_by_groups]
# check course lists have same courses
- self.assertEqual(course_keys_in_course_list, course_keys_in_courses_list_by_groups)
+ self.assertEqual(course_keys_in_course_list, course_keys_in_courses_list_by_groups) # noqa: PT009
# now delete this course and re-add user to instructor group of this course
delete_course(course_key, self.user.id)
course.delete()
@@ -271,7 +271,7 @@ def test_get_course_list_with_invalid_course_location(self):
courses_list_by_groups, __ = _accessible_courses_list_from_groups(self.request)
# Test that course list returns no course
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
[len(list(courses_iter)), len(courses_list_by_groups), len(list(courses_summary_iter))],
[0, 0, 0]
)
@@ -298,19 +298,19 @@ def test_course_listing_performance(self):
# get courses by iterating through all courses
courses_iter, __ = _accessible_courses_iter_for_tests(self.request)
- self.assertEqual(len(list(courses_iter)), USER_COURSES_COUNT)
+ self.assertEqual(len(list(courses_iter)), USER_COURSES_COUNT) # noqa: PT009
# again get courses by iterating through all courses
courses_iter, __ = _accessible_courses_iter_for_tests(self.request)
- self.assertEqual(len(list(courses_iter)), USER_COURSES_COUNT)
+ self.assertEqual(len(list(courses_iter)), USER_COURSES_COUNT) # noqa: PT009
# get courses by reversing django groups
courses_list, __ = _accessible_courses_list_from_groups(self.request)
- self.assertEqual(len(courses_list), USER_COURSES_COUNT)
+ self.assertEqual(len(courses_list), USER_COURSES_COUNT) # noqa: PT009
# again get courses by reversing django groups
courses_list, __ = _accessible_courses_list_from_groups(self.request)
- self.assertEqual(len(courses_list), USER_COURSES_COUNT)
+ self.assertEqual(len(courses_list), USER_COURSES_COUNT) # noqa: PT009
with self.assertNumQueries(2, table_ignorelist=QUERY_COUNT_TABLE_IGNORELIST):
_accessible_courses_list_from_groups(self.request)
@@ -331,7 +331,7 @@ def test_course_listing_errored_deleted_courses(self):
course.delete()
courses_list, __ = _accessible_courses_list_from_groups(self.request)
- self.assertEqual(len(courses_list), 1, courses_list)
+ self.assertEqual(len(courses_list), 1, courses_list) # noqa: PT009
@ddt.data(OrgStaffRole('AwesomeOrg'), OrgInstructorRole('AwesomeOrg'))
def test_course_listing_org_permissions(self, role):
@@ -362,8 +362,8 @@ def test_course_listing_org_permissions(self, role):
# Verify fetched accessible courses list is a list of CourseSummery instances and test expacted
# course count is returned
- self.assertEqual(len(list(courses_list)), 2)
- self.assertTrue(all(isinstance(course, CourseOverview) for course in courses_list))
+ self.assertEqual(len(list(courses_list)), 2) # noqa: PT009
+ self.assertTrue(all(isinstance(course, CourseOverview) for course in courses_list)) # noqa: PT009
@ddt.data(OrgStaffRole(), OrgInstructorRole())
def test_course_listing_org_permissions_exception(self, role):
@@ -373,7 +373,7 @@ def test_course_listing_org_permissions_exception(self, role):
"""
role.add_users(self.user)
- with self.assertRaises(AccessListFallback):
+ with self.assertRaises(AccessListFallback): # noqa: PT027
_accessible_courses_list_from_groups(self.request)
def test_course_listing_with_actions_in_progress(self):
@@ -407,8 +407,8 @@ def _set_of_course_keys(course_list, key_attribute_name='id'):
return {getattr(c, key_attribute_name) for c in course_list}
found_courses, unsucceeded_course_actions = _accessible_courses_iter_for_tests(self.request)
- self.assertSetEqual(_set_of_course_keys(courses + courses_in_progress), _set_of_course_keys(found_courses))
- self.assertSetEqual(
+ self.assertSetEqual(_set_of_course_keys(courses + courses_in_progress), _set_of_course_keys(found_courses)) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertSetEqual( # noqa: PT009
_set_of_course_keys(courses_in_progress), _set_of_course_keys(unsucceeded_course_actions, 'course_key')
)
@@ -472,7 +472,7 @@ def test_course_listing_with_course_staff_authz_permission(self):
course1 = self._create_course(course_key_1)
course_key_2 = CourseLocator("Org1", "Course2", "Run1")
- course2 = self._create_course(course_key_2)
+ course2 = self._create_course(course_key_2) # noqa: F841
assign_role_to_user_in_scope(
self.authorized_user.username,
@@ -487,9 +487,9 @@ def test_course_listing_with_course_staff_authz_permission(self):
courses = list(courses_list)
- self.assertEqual(len(courses), 1)
- self.assertEqual(courses[0].id, course1.id)
- self.assertNotIn(course_key_2, {c.id for c in courses})
+ self.assertEqual(len(courses), 1) # noqa: PT009
+ self.assertEqual(courses[0].id, course1.id) # noqa: PT009
+ self.assertNotIn(course_key_2, {c.id for c in courses}) # noqa: PT009
def test_course_listing_with_course_editor_authz_permission(self):
"""
@@ -501,7 +501,7 @@ def test_course_listing_with_course_editor_authz_permission(self):
course1 = self._create_course(course_key_1)
course_key_2 = CourseLocator("Org1", "Course2", "Run1")
- course2 = self._create_course(course_key_2)
+ course2 = self._create_course(course_key_2) # noqa: F841
assign_role_to_user_in_scope(
self.authorized_user.username,
@@ -516,9 +516,9 @@ def test_course_listing_with_course_editor_authz_permission(self):
courses = list(courses_list)
- self.assertEqual(len(courses), 1)
- self.assertEqual(courses[0].id, course1.id)
- self.assertNotIn(course_key_2, {c.id for c in courses})
+ self.assertEqual(len(courses), 1) # noqa: PT009
+ self.assertEqual(courses[0].id, course1.id) # noqa: PT009
+ self.assertNotIn(course_key_2, {c.id for c in courses}) # noqa: PT009
def test_course_listing_without_permissions(self):
"""
@@ -534,7 +534,7 @@ def test_course_listing_without_permissions(self):
courses_list, _ = get_courses_accessible_to_user(request)
- self.assertEqual(len(list(courses_list)), 0)
+ self.assertEqual(len(list(courses_list)), 0) # noqa: PT009
def test_non_staff_user_cannot_access(self):
"""
@@ -551,7 +551,7 @@ def test_non_staff_user_cannot_access(self):
courses_list, _ = get_courses_accessible_to_user(request)
- self.assertEqual(len(list(courses_list)), 0)
+ self.assertEqual(len(list(courses_list)), 0) # noqa: PT009
def test_authz_and_legacy_basic(self):
"""
@@ -593,7 +593,7 @@ def test_authz_and_legacy_basic(self):
legacy_courses[0].id,
}
- self.assertEqual(result_ids, expected_ids)
+ self.assertEqual(result_ids, expected_ids) # noqa: PT009
def test_authz_role_ignored_when_toggle_off(self):
"""
@@ -621,7 +621,7 @@ def test_authz_role_ignored_when_toggle_off(self):
result_ids = {c.id for c in courses}
expected_ids = set() # no access since toggle is off
- self.assertEqual(result_ids, expected_ids)
+ self.assertEqual(result_ids, expected_ids) # noqa: PT009
def test_multiple_roles_mixed_authz_and_legacy(self):
"""
@@ -665,7 +665,7 @@ def test_multiple_roles_mixed_authz_and_legacy(self):
legacy_courses[2].id,
}
- self.assertEqual(result_ids, expected_ids)
+ self.assertEqual(result_ids, expected_ids) # noqa: PT009
def test_staff_gets_all_courses(self):
"""
@@ -690,7 +690,7 @@ def test_staff_gets_all_courses(self):
*(c.id for c in legacy_courses),
}
- self.assertEqual(result_ids, expected_ids)
+ self.assertEqual(result_ids, expected_ids) # noqa: PT009
def test_superuser_gets_all_courses(self):
"""
@@ -714,4 +714,4 @@ def test_superuser_gets_all_courses(self):
*(c.id for c in legacy_courses),
}
- self.assertEqual(result_ids, expected_ids)
+ self.assertEqual(result_ids, expected_ids) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_course_settings.py b/cms/djangoapps/contentstore/tests/test_course_settings.py
index 770a44c01a75..5d726627f27e 100644
--- a/cms/djangoapps/contentstore/tests/test_course_settings.py
+++ b/cms/djangoapps/contentstore/tests/test_course_settings.py
@@ -69,14 +69,14 @@ def test_encoder(self):
details = CourseDetails.fetch(self.course.id)
jsondetails = json.dumps(details, cls=CourseSettingsEncoder)
jsondetails = json.loads(jsondetails)
- self.assertEqual(jsondetails['course_image_name'], self.course.course_image)
- self.assertIsNone(jsondetails['end_date'], "end date somehow initialized ")
- self.assertIsNone(jsondetails['enrollment_start'], "enrollment_start date somehow initialized ")
- self.assertIsNone(jsondetails['enrollment_end'], "enrollment_end date somehow initialized ")
- self.assertIsNone(jsondetails['syllabus'], "syllabus somehow initialized")
- self.assertIsNone(jsondetails['intro_video'], "intro_video somehow initialized")
- self.assertIsNone(jsondetails['effort'], "effort somehow initialized")
- self.assertIsNone(jsondetails['language'], "language somehow initialized")
+ self.assertEqual(jsondetails['course_image_name'], self.course.course_image) # noqa: PT009
+ self.assertIsNone(jsondetails['end_date'], "end date somehow initialized ") # noqa: PT009
+ self.assertIsNone(jsondetails['enrollment_start'], "enrollment_start date somehow initialized ") # noqa: PT009
+ self.assertIsNone(jsondetails['enrollment_end'], "enrollment_end date somehow initialized ") # noqa: PT009
+ self.assertIsNone(jsondetails['syllabus'], "syllabus somehow initialized") # noqa: PT009
+ self.assertIsNone(jsondetails['intro_video'], "intro_video somehow initialized") # noqa: PT009
+ self.assertIsNone(jsondetails['effort'], "effort somehow initialized") # noqa: PT009
+ self.assertIsNone(jsondetails['language'], "language somehow initialized") # noqa: PT009
def test_pre_1900_date(self):
"""
@@ -88,7 +88,7 @@ def test_pre_1900_date(self):
details.enrollment_start = pre_1900
dumped_jsondetails = json.dumps(details, cls=CourseSettingsEncoder)
loaded_jsondetails = json.loads(dumped_jsondetails)
- self.assertEqual(loaded_jsondetails['enrollment_start'], pre_1900.isoformat())
+ self.assertEqual(loaded_jsondetails['enrollment_start'], pre_1900.isoformat()) # noqa: PT009
def test_ooc_encoder(self):
"""
@@ -102,8 +102,8 @@ def test_ooc_encoder(self):
jsondetails = json.dumps(details, cls=CourseSettingsEncoder)
jsondetails = json.loads(jsondetails)
- self.assertEqual(1, jsondetails['number'])
- self.assertEqual(jsondetails['string'], 'string')
+ self.assertEqual(1, jsondetails['number']) # noqa: PT009
+ self.assertEqual(jsondetails['string'], 'string') # noqa: PT009
@ddt.ddt
@@ -137,8 +137,8 @@ def test_mobile_field_available(self):
end = response.content.decode('utf-8').find("}", start)
settings_fields = json.loads(response.content.decode('utf-8')[start + len("mobile_available: "):end + 1])
- self.assertEqual(settings_fields["display_name"], "Mobile Course Available")
- self.assertEqual(settings_fields["deprecated"], True)
+ self.assertEqual(settings_fields["display_name"], "Mobile Course Available") # noqa: PT009
+ self.assertEqual(settings_fields["deprecated"], True) # noqa: PT009
@ddt.data(
(False, False, True),
@@ -157,10 +157,10 @@ def test_discussion_fields_available(self, is_pages_and_resources_enabled,
with override_waffle_flag(ENABLE_PAGES_AND_RESOURCES_MICROFRONTEND, is_pages_and_resources_enabled):
with override_waffle_flag(OVERRIDE_DISCUSSION_LEGACY_SETTINGS_FLAG, is_legacy_discussion_setting_enabled):
response = self.client.get_html(self.course_setting_url).content.decode('utf-8')
- self.assertEqual('allow_anonymous' in response, fields_visible)
- self.assertEqual('allow_anonymous_to_peers' in response, fields_visible)
- self.assertEqual('discussion_blackouts' in response, fields_visible)
- self.assertEqual('discussion_topics' in response, fields_visible)
+ self.assertEqual('allow_anonymous' in response, fields_visible) # noqa: PT009
+ self.assertEqual('allow_anonymous_to_peers' in response, fields_visible) # noqa: PT009
+ self.assertEqual('discussion_blackouts' in response, fields_visible) # noqa: PT009
+ self.assertEqual('discussion_topics' in response, fields_visible) # noqa: PT009
@ddt.data(False, True)
@override_waffle_flag(toggles.LEGACY_STUDIO_ADVANCED_SETTINGS, True)
@@ -174,7 +174,7 @@ def test_disable_advanced_settings_feature(self, disable_advanced_settings):
If this feature is enabled, only Django Staff/Superuser should be able to access the "Advanced Settings" page.
For non-staff users the "Advanced Settings" tab link should not be visible.
"""
- advanced_settings_link_html = f"Advanced Settings".encode('utf-8')
+ advanced_settings_link_html = f"Advanced Settings".encode('utf-8') # noqa: UP012 # pylint: disable=line-too-long
with override_settings(FEATURES={
'DISABLE_ADVANCED_SETTINGS': disable_advanced_settings,
@@ -190,26 +190,26 @@ def test_disable_advanced_settings_feature(self, disable_advanced_settings):
response = self.non_staff_client.get_html(
get_url(self.course.id, handler)
)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
if disable_advanced_settings:
- self.assertNotIn(advanced_settings_link_html, response.content)
+ self.assertNotIn(advanced_settings_link_html, response.content) # noqa: PT009
else:
- self.assertIn(advanced_settings_link_html, response.content)
+ self.assertIn(advanced_settings_link_html, response.content) # noqa: PT009
# Test that staff users see the "Advanced Settings" tab link.
response = self.client.get_html(
get_url(self.course.id, handler)
)
- self.assertEqual(response.status_code, 200)
- self.assertIn(advanced_settings_link_html, response.content)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertIn(advanced_settings_link_html, response.content) # noqa: PT009
# Test that non-staff users can't access the "Advanced Settings" page.
response = self.non_staff_client.get_html(self.course_setting_url)
- self.assertEqual(response.status_code, 403 if disable_advanced_settings else 200)
+ self.assertEqual(response.status_code, 403 if disable_advanced_settings else 200) # noqa: PT009
# Test that staff users can access the "Advanced Settings" page.
response = self.client.get_html(self.course_setting_url)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
@ddt.ddt
@@ -273,17 +273,17 @@ def compare_details_with_encoding(self, encoded, details, context):
self.compare_date_fields(details, encoded, context, 'end_date')
self.compare_date_fields(details, encoded, context, 'enrollment_start')
self.compare_date_fields(details, encoded, context, 'enrollment_end')
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
details['short_description'], encoded['short_description'], context + " short_description not =="
)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
details['about_sidebar_html'], encoded['about_sidebar_html'], context + " about_sidebar_html not =="
)
- self.assertEqual(details['overview'], encoded['overview'], context + " overviews not ==")
- self.assertEqual(details['intro_video'], encoded.get('intro_video', None), context + " intro_video not ==")
- self.assertEqual(details['effort'], encoded['effort'], context + " efforts not ==")
- self.assertEqual(details['course_image_name'], encoded['course_image_name'], context + " images not ==")
- self.assertEqual(details['language'], encoded['language'], context + " languages not ==")
+ self.assertEqual(details['overview'], encoded['overview'], context + " overviews not ==") # noqa: PT009
+ self.assertEqual(details['intro_video'], encoded.get('intro_video', None), context + " intro_video not ==") # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(details['effort'], encoded['effort'], context + " efforts not ==") # noqa: PT009
+ self.assertEqual(details['course_image_name'], encoded['course_image_name'], context + " images not ==") # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(details['language'], encoded['language'], context + " languages not ==") # noqa: PT009
def compare_date_fields(self, details, encoded, context, field):
"""
@@ -295,7 +295,7 @@ def compare_date_fields(self, details, encoded, context, field):
dt1 = date.from_json(encoded[field])
dt2 = details[field]
- self.assertEqual(dt1, dt2, msg=f"{dt1} != {dt2} at {context}")
+ self.assertEqual(dt1, dt2, msg=f"{dt1} != {dt2} at {context}") # noqa: PT009
else:
self.fail(field + " missing from encoded but in details at " + context)
elif field in encoded and encoded[field] is not None:
@@ -323,7 +323,7 @@ def test_upgrade_deadline(self, has_verified_mode, has_expiration_date):
settings_details_url = get_url(self.course.id)
response = self.client.get_html(settings_details_url)
- self.assertEqual(b"Upgrade Deadline Date" in response.content, has_expiration_date and has_verified_mode)
+ self.assertEqual(b"Upgrade Deadline Date" in response.content, has_expiration_date and has_verified_mode) # noqa: PT009 # pylint: disable=line-too-long
@mock.patch.dict("django.conf.settings.FEATURES", {'ENABLE_PREREQUISITE_COURSES': True})
@override_waffle_flag(toggles.LEGACY_STUDIO_SCHEDULE_DETAILS, True)
@@ -334,14 +334,14 @@ def test_pre_requisite_course_list_present(self):
@mock.patch.dict("django.conf.settings.FEATURES", {'ENABLE_PREREQUISITE_COURSES': True})
def test_pre_requisite_course_update_and_fetch(self):
- self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
+ self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id), # noqa: PT009
msg='The initial empty state should be: no prerequisite courses')
url = get_url(self.course.id)
resp = self.client.get_json(url)
course_detail_json = json.loads(resp.content.decode('utf-8'))
# assert pre_requisite_courses is initialized
- self.assertEqual([], course_detail_json['pre_requisite_courses'])
+ self.assertEqual([], course_detail_json['pre_requisite_courses']) # noqa: PT009
# update pre requisite courses with a new course keys
pre_requisite_course = CourseFactory.create(org='edX', course='900', run='test_run')
@@ -353,9 +353,9 @@ def test_pre_requisite_course_update_and_fetch(self):
# fetch updated course to assert pre_requisite_courses has new values
resp = self.client.get_json(url)
course_detail_json = json.loads(resp.content.decode('utf-8'))
- self.assertEqual(pre_requisite_course_keys, course_detail_json['pre_requisite_courses'])
+ self.assertEqual(pre_requisite_course_keys, course_detail_json['pre_requisite_courses']) # noqa: PT009
- self.assertTrue(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
+ self.assertTrue(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id), # noqa: PT009
msg='Should have prerequisite courses')
# remove pre requisite course
@@ -363,9 +363,9 @@ def test_pre_requisite_course_update_and_fetch(self):
self.client.ajax_post(url, course_detail_json)
resp = self.client.get_json(url)
course_detail_json = json.loads(resp.content.decode('utf-8'))
- self.assertEqual([], course_detail_json['pre_requisite_courses'])
+ self.assertEqual([], course_detail_json['pre_requisite_courses']) # noqa: PT009
- self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
+ self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id), # noqa: PT009
msg='Should not have prerequisite courses anymore')
@mock.patch.dict("django.conf.settings.FEATURES", {'ENABLE_PREREQUISITE_COURSES': True})
@@ -379,7 +379,7 @@ def test_invalid_pre_requisite_course(self):
pre_requisite_course_keys = [str(pre_requisite_course.id), 'invalid_key']
course_detail_json['pre_requisite_courses'] = pre_requisite_course_keys
response = self.client.ajax_post(url, course_detail_json)
- self.assertEqual(400, response.status_code)
+ self.assertEqual(400, response.status_code) # noqa: PT009
@ddt.data(
(False, False, False),
@@ -399,7 +399,7 @@ def test_visibility_of_entrance_exam_section(self, feature_flags):
}), override_settings(ENTRANCE_EXAMS=feature_flags[0]):
course_details_url = get_url(self.course.id)
resp = self.client.get_html(course_details_url)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
feature_flags[2],
b'
' in resp.content
)
@@ -444,7 +444,7 @@ def test_entrance_exam_created_updated_and_deleted_successfully(self):
Splitting the test requires significant refactoring `settings_handler()` view.
"""
- self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
+ self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id), # noqa: PT009
msg='The initial empty state should be: no entrance exam')
settings_details_url = get_url(self.course.id)
@@ -461,10 +461,10 @@ def test_entrance_exam_created_updated_and_deleted_successfully(self):
}
response = self.client.post(settings_details_url, data=json.dumps(data), content_type='application/json',
HTTP_ACCEPT='application/json')
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
course = modulestore().get_course(self.course.id)
- self.assertTrue(course.entrance_exam_enabled)
- self.assertEqual(course.entrance_exam_minimum_score_pct, .60)
+ self.assertTrue(course.entrance_exam_enabled) # noqa: PT009
+ self.assertEqual(course.entrance_exam_minimum_score_pct, .60) # noqa: PT009
# Update the entrance exam
data['entrance_exam_enabled'] = "true"
@@ -475,12 +475,12 @@ def test_entrance_exam_created_updated_and_deleted_successfully(self):
content_type='application/json',
HTTP_ACCEPT='application/json'
)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
course = modulestore().get_course(self.course.id)
- self.assertTrue(course.entrance_exam_enabled)
- self.assertEqual(course.entrance_exam_minimum_score_pct, .80)
+ self.assertTrue(course.entrance_exam_enabled) # noqa: PT009
+ self.assertEqual(course.entrance_exam_minimum_score_pct, .80) # noqa: PT009
- self.assertTrue(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
+ self.assertTrue(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id), # noqa: PT009
msg='The entrance exam should be required.')
# Delete the entrance exam
@@ -492,15 +492,15 @@ def test_entrance_exam_created_updated_and_deleted_successfully(self):
HTTP_ACCEPT='application/json'
)
course = modulestore().get_course(self.course.id)
- self.assertEqual(response.status_code, 200)
- self.assertFalse(course.entrance_exam_enabled)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertFalse(course.entrance_exam_enabled) # noqa: PT009
entrance_exam_minimum_score_pct = float(settings.ENTRANCE_EXAM_MIN_SCORE_PCT)
if entrance_exam_minimum_score_pct.is_integer():
entrance_exam_minimum_score_pct = entrance_exam_minimum_score_pct / 100
- self.assertEqual(course.entrance_exam_minimum_score_pct, entrance_exam_minimum_score_pct)
+ self.assertEqual(course.entrance_exam_minimum_score_pct, entrance_exam_minimum_score_pct) # noqa: PT009
- self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id),
+ self.assertFalse(milestones_helpers.any_unfulfilled_milestones(self.course.id, self.user.id), # noqa: PT009
msg='The entrance exam should not be required anymore')
@unittest.skipUnless(settings.FEATURES.get('ENTRANCE_EXAMS', False), True)
@@ -526,12 +526,12 @@ def test_entrance_exam_store_default_min_score(self):
content_type='application/json',
HTTP_ACCEPT='application/json'
)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
course = modulestore().get_course(self.course.id)
- self.assertTrue(course.entrance_exam_enabled)
+ self.assertTrue(course.entrance_exam_enabled) # noqa: PT009
# entrance_exam_minimum_score_pct is not present in the request so default value should be saved.
- self.assertEqual(course.entrance_exam_minimum_score_pct, .5)
+ self.assertEqual(course.entrance_exam_minimum_score_pct, .5) # noqa: PT009
#add entrance_exam_minimum_score_pct with empty value in json request.
test_data_2 = {
@@ -552,10 +552,10 @@ def test_entrance_exam_store_default_min_score(self):
content_type='application/json',
HTTP_ACCEPT='application/json'
)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
course = modulestore().get_course(self.course.id)
- self.assertTrue(course.entrance_exam_enabled)
- self.assertEqual(course.entrance_exam_minimum_score_pct, .5)
+ self.assertTrue(course.entrance_exam_enabled) # noqa: PT009
+ self.assertEqual(course.entrance_exam_minimum_score_pct, .5) # noqa: PT009
@unittest.skipUnless(settings.FEATURES.get('ENTRANCE_EXAMS', False), True)
@mock.patch.dict("django.conf.settings.FEATURES", {'ENABLE_PREREQUISITE_COURSES': True})
@@ -605,7 +605,7 @@ def test_entrance_after_changing_other_setting(self):
# Call the settings handler again then ensure it didn't delete the settings of the entrance exam
data.update({
'start_date': '2018-01-01',
- 'end_date': '{year}-12-31'.format(year=datetime.datetime.now().year + 4),
+ 'end_date': '{year}-12-31'.format(year=datetime.datetime.now().year + 4), # noqa: UP032
})
response = self.client.post(
settings_details_url,
@@ -653,8 +653,8 @@ def test_empty_course_overview_keep_default_value(self):
)
course_details = CourseDetails.fetch(self.course.id)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(course_details.overview, '
')
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(course_details.overview, '
') # noqa: PT009
@override_waffle_flag(toggles.LEGACY_STUDIO_SCHEDULE_DETAILS, True)
def test_regular_site_fetch(self):
@@ -695,17 +695,17 @@ class CourseGradingTest(CourseTestCase):
def test_initial_grader(self):
test_grader = CourseGradingModel(self.course)
- self.assertIsNotNone(test_grader.graders)
- self.assertIsNotNone(test_grader.grade_cutoffs)
+ self.assertIsNotNone(test_grader.graders) # noqa: PT009
+ self.assertIsNotNone(test_grader.grade_cutoffs) # noqa: PT009
def test_fetch_grader(self):
test_grader = CourseGradingModel.fetch(self.course.id)
- self.assertIsNotNone(test_grader.graders, "No graders")
- self.assertIsNotNone(test_grader.grade_cutoffs, "No cutoffs")
+ self.assertIsNotNone(test_grader.graders, "No graders") # noqa: PT009
+ self.assertIsNotNone(test_grader.grade_cutoffs, "No cutoffs") # noqa: PT009
for i, grader in enumerate(test_grader.graders):
subgrader = CourseGradingModel.fetch_grader(self.course.id, i)
- self.assertDictEqual(grader, subgrader, str(i) + "th graders not equal")
+ self.assertDictEqual(grader, subgrader, str(i) + "th graders not equal") # noqa: PT009
@mock.patch('common.djangoapps.track.event_transaction_utils.uuid4')
@mock.patch('cms.djangoapps.models.settings.course_grading.tracker')
@@ -716,10 +716,10 @@ def test_update_from_json(self, send_signal, tracker, uuid):
test_grader = CourseGradingModel.fetch(self.course.id)
# there should be no event raised after this call, since nothing got modified
altered_grader = CourseGradingModel.update_from_json(self.course.id, test_grader.__dict__, self.user)
- self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "Noop update")
+ self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "Noop update") # noqa: PT009
test_grader.graders[0]['weight'] = test_grader.graders[0].get('weight') * 2
altered_grader = CourseGradingModel.update_from_json(self.course.id, test_grader.__dict__, self.user)
- self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "Weight[0] * 2")
+ self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "Weight[0] * 2") # noqa: PT009
grading_policy_2 = self._grading_policy_hash_for_course()
# test for bug LMS-11485
with modulestore().bulk_operations(self.course.id):
@@ -731,15 +731,15 @@ def test_update_from_json(self, send_signal, tracker, uuid):
# don't use altered cached def, get a fresh one
CourseGradingModel.update_from_json(self.course.id, test_grader.__dict__, self.user)
altered_grader = CourseGradingModel.fetch(self.course.id)
- self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__)
+ self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__) # noqa: PT009
grading_policy_3 = self._grading_policy_hash_for_course()
test_grader.grade_cutoffs['D'] = 0.3
altered_grader = CourseGradingModel.update_from_json(self.course.id, test_grader.__dict__, self.user)
- self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "cutoff add D")
+ self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "cutoff add D") # noqa: PT009
grading_policy_4 = self._grading_policy_hash_for_course()
test_grader.grace_period = {'hours': 4, 'minutes': 5, 'seconds': 0}
altered_grader = CourseGradingModel.update_from_json(self.course.id, test_grader.__dict__, self.user)
- self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "4 hour grace period")
+ self.assertDictEqual(test_grader.__dict__, altered_grader.__dict__, "4 hour grace period") # noqa: PT009
# one for each of the calls to update_from_json()
send_signal.assert_has_calls([
@@ -789,7 +789,7 @@ def test_must_fire_grading_event_and_signal_multiple_type(self):
modulestore().get_course(self.course.id),
course_grading_model.__dict__
)
- self.assertTrue(result)
+ self.assertTrue(result) # noqa: PT009
@override_waffle_flag(MATERIAL_RECOMPUTE_ONLY_FLAG, True)
def test_must_fire_grading_event_and_signal_multiple_type_waffle_on(self):
@@ -814,7 +814,7 @@ def test_must_fire_grading_event_and_signal_multiple_type_waffle_on(self):
modulestore().get_course(self.course.id),
course_grading_model.__dict__
)
- self.assertFalse(result)
+ self.assertFalse(result) # noqa: PT009
def test_must_fire_grading_event_and_signal_return_true(self):
"""
@@ -838,7 +838,7 @@ def test_must_fire_grading_event_and_signal_return_true(self):
modulestore().get_course(self.course.id),
course_grading_model.__dict__
)
- self.assertTrue(result)
+ self.assertTrue(result) # noqa: PT009
@mock.patch('common.djangoapps.track.event_transaction_utils.uuid4')
@mock.patch('cms.djangoapps.models.settings.course_grading.tracker')
@@ -849,18 +849,18 @@ def test_update_grader_from_json(self, send_signal, tracker, uuid):
altered_grader = CourseGradingModel.update_grader_from_json(
self.course.id, test_grader.graders[1], self.user
)
- self.assertDictEqual(test_grader.graders[1], altered_grader, "Noop update")
+ self.assertDictEqual(test_grader.graders[1], altered_grader, "Noop update") # noqa: PT009
test_grader.graders[1]['min_count'] = test_grader.graders[1].get('min_count') + 2
altered_grader = CourseGradingModel.update_grader_from_json(
self.course.id, test_grader.graders[1], self.user)
- self.assertDictEqual(test_grader.graders[1], altered_grader, "min_count[1] + 2")
+ self.assertDictEqual(test_grader.graders[1], altered_grader, "min_count[1] + 2") # noqa: PT009
grading_policy_2 = self._grading_policy_hash_for_course()
test_grader.graders[1]['drop_count'] = test_grader.graders[1].get('drop_count') + 1
altered_grader = CourseGradingModel.update_grader_from_json(
self.course.id, test_grader.graders[1], self.user)
- self.assertDictEqual(test_grader.graders[1], altered_grader, "drop_count[1] + 2")
+ self.assertDictEqual(test_grader.graders[1], altered_grader, "drop_count[1] + 2") # noqa: PT009
grading_policy_3 = self._grading_policy_hash_for_course()
# one for each of the calls to update_grader_from_json()
@@ -894,19 +894,19 @@ def test_update_cutoffs_from_json(self, tracker, uuid):
# Unlike other tests, need to actually perform a db fetch for this test since update_cutoffs_from_json
# simply returns the cutoffs you send into it, rather than returning the db contents.
altered_grader = CourseGradingModel.fetch(self.course.id)
- self.assertDictEqual(test_grader.grade_cutoffs, altered_grader.grade_cutoffs, "Noop update")
+ self.assertDictEqual(test_grader.grade_cutoffs, altered_grader.grade_cutoffs, "Noop update") # noqa: PT009
grading_policy_1 = self._grading_policy_hash_for_course()
test_grader.grade_cutoffs['D'] = 0.3
CourseGradingModel.update_cutoffs_from_json(self.course.id, test_grader.grade_cutoffs, self.user)
altered_grader = CourseGradingModel.fetch(self.course.id)
- self.assertDictEqual(test_grader.grade_cutoffs, altered_grader.grade_cutoffs, "cutoff add D")
+ self.assertDictEqual(test_grader.grade_cutoffs, altered_grader.grade_cutoffs, "cutoff add D") # noqa: PT009
grading_policy_2 = self._grading_policy_hash_for_course()
test_grader.grade_cutoffs['Pass'] = 0.75
CourseGradingModel.update_cutoffs_from_json(self.course.id, test_grader.grade_cutoffs, self.user)
altered_grader = CourseGradingModel.fetch(self.course.id)
- self.assertDictEqual(test_grader.grade_cutoffs, altered_grader.grade_cutoffs, "cutoff change 'Pass'")
+ self.assertDictEqual(test_grader.grade_cutoffs, altered_grader.grade_cutoffs, "cutoff change 'Pass'") # noqa: PT009 # pylint: disable=line-too-long
grading_policy_3 = self._grading_policy_hash_for_course()
# one for each of the calls to update_cutoffs_from_json()
@@ -930,13 +930,13 @@ def test_delete_grace_period(self):
)
# update_grace_period_from_json doesn't return anything, so query the db for its contents.
altered_grader = CourseGradingModel.fetch(self.course.id)
- self.assertEqual(test_grader.grace_period, altered_grader.grace_period, "Noop update")
+ self.assertEqual(test_grader.grace_period, altered_grader.grace_period, "Noop update") # noqa: PT009
test_grader.grace_period = {'hours': 15, 'minutes': 5, 'seconds': 30}
CourseGradingModel.update_grace_period_from_json(
self.course.id, test_grader.grace_period, self.user)
altered_grader = CourseGradingModel.fetch(self.course.id)
- self.assertDictEqual(test_grader.grace_period, altered_grader.grace_period, "Adding in a grace period")
+ self.assertDictEqual(test_grader.grace_period, altered_grader.grace_period, "Adding in a grace period") # noqa: PT009 # pylint: disable=line-too-long
test_grader.grace_period = {'hours': 1, 'minutes': 10, 'seconds': 0}
# Now delete the grace period
@@ -944,7 +944,7 @@ def test_delete_grace_period(self):
# update_grace_period_from_json doesn't return anything, so query the db for its contents.
altered_grader = CourseGradingModel.fetch(self.course.id)
# Once deleted, the grace period should simply be None
- self.assertEqual(None, altered_grader.grace_period, "Delete grace period")
+ self.assertEqual(None, altered_grader.grace_period, "Delete grace period") # noqa: PT009
@mock.patch('common.djangoapps.track.event_transaction_utils.uuid4')
@mock.patch('cms.djangoapps.models.settings.course_grading.tracker')
@@ -955,9 +955,9 @@ def test_update_section_grader_type(self, send_signal, tracker, uuid):
block = modulestore().get_item(self.course.location)
section_grader_type = CourseGradingModel.get_section_grader_type(self.course.location)
- self.assertEqual('notgraded', section_grader_type['graderType'])
- self.assertEqual(None, block.format)
- self.assertEqual(False, block.graded)
+ self.assertEqual('notgraded', section_grader_type['graderType']) # noqa: PT009
+ self.assertEqual(None, block.format) # noqa: PT009
+ self.assertEqual(False, block.graded) # noqa: PT009
# Change the default grader type to Homework, which should also mark the section as graded
CourseGradingModel.update_section_grader_type(self.course, 'Homework', self.user)
@@ -965,9 +965,9 @@ def test_update_section_grader_type(self, send_signal, tracker, uuid):
section_grader_type = CourseGradingModel.get_section_grader_type(self.course.location)
grading_policy_1 = self._grading_policy_hash_for_course()
- self.assertEqual('Homework', section_grader_type['graderType'])
- self.assertEqual('Homework', block.format)
- self.assertEqual(True, block.graded)
+ self.assertEqual('Homework', section_grader_type['graderType']) # noqa: PT009
+ self.assertEqual('Homework', block.format) # noqa: PT009
+ self.assertEqual(True, block.graded) # noqa: PT009
# Change the grader type back to notgraded, which should also unmark the section as graded
CourseGradingModel.update_section_grader_type(self.course, 'notgraded', self.user)
@@ -975,9 +975,9 @@ def test_update_section_grader_type(self, send_signal, tracker, uuid):
section_grader_type = CourseGradingModel.get_section_grader_type(self.course.location)
grading_policy_2 = self._grading_policy_hash_for_course()
- self.assertEqual('notgraded', section_grader_type['graderType'])
- self.assertEqual(None, block.format)
- self.assertEqual(False, block.graded)
+ self.assertEqual('notgraded', section_grader_type['graderType']) # noqa: PT009
+ self.assertEqual(None, block.format) # noqa: PT009
+ self.assertEqual(False, block.graded) # noqa: PT009
# one for each call to update_section_grader_type()
send_signal.assert_has_calls([
@@ -1011,21 +1011,21 @@ def test_get_set_grader_types_ajax(self):
grader_type_url_base = get_url(self.course.id, 'grading_handler')
whole_model = self._model_from_url(grader_type_url_base)
- self.assertIn('graders', whole_model)
- self.assertIn('grade_cutoffs', whole_model)
- self.assertIn('grace_period', whole_model)
+ self.assertIn('graders', whole_model) # noqa: PT009
+ self.assertIn('grade_cutoffs', whole_model) # noqa: PT009
+ self.assertIn('grace_period', whole_model) # noqa: PT009
# test post/update whole
whole_model['grace_period'] = {'hours': 1, 'minutes': 30, 'seconds': 0}
response = self.client.ajax_post(grader_type_url_base, whole_model)
- self.assertEqual(200, response.status_code)
+ self.assertEqual(200, response.status_code) # noqa: PT009
whole_model = self._model_from_url(grader_type_url_base)
- self.assertEqual(whole_model['grace_period'], {'hours': 1, 'minutes': 30, 'seconds': 0})
+ self.assertEqual(whole_model['grace_period'], {'hours': 1, 'minutes': 30, 'seconds': 0}) # noqa: PT009
# test get one grader
- self.assertGreater(len(whole_model['graders']), 1) # ensure test will make sense
+ self.assertGreater(len(whole_model['graders']), 1) # ensure test will make sense # noqa: PT009
grader_sample = self._model_from_url(grader_type_url_base + '/1')
- self.assertEqual(grader_sample, whole_model['graders'][1])
+ self.assertEqual(grader_sample, whole_model['graders'][1]) # noqa: PT009
@mock.patch('cms.djangoapps.contentstore.signals.signals.GRADING_POLICY_CHANGED.send')
def test_add_delete_grader(self, send_signal):
@@ -1046,19 +1046,19 @@ def test_add_delete_grader(self, send_signal):
new_grader
)
grading_policy_hash1 = self._grading_policy_hash_for_course()
- self.assertEqual(200, response.status_code)
+ self.assertEqual(200, response.status_code) # noqa: PT009
grader_sample = json.loads(response.content.decode('utf-8'))
new_grader['id'] = len(original_model['graders'])
- self.assertEqual(new_grader, grader_sample)
+ self.assertEqual(new_grader, grader_sample) # noqa: PT009
# test deleting the original grader
response = self.client.delete(grader_type_url_base + '/1', HTTP_ACCEPT="application/json")
grading_policy_hash2 = self._grading_policy_hash_for_course()
- self.assertEqual(204, response.status_code)
+ self.assertEqual(204, response.status_code) # noqa: PT009
updated_model = self._model_from_url(grader_type_url_base)
new_grader['id'] -= 1 # one fewer and the id mutates
- self.assertIn(new_grader, updated_model['graders'])
- self.assertNotIn(original_model['graders'][1], updated_model['graders'])
+ self.assertIn(new_grader, updated_model['graders']) # noqa: PT009
+ self.assertNotIn(original_model['graders'][1], updated_model['graders']) # noqa: PT009
send_signal.assert_has_calls([
# once for the POST
# pylint: disable=line-too-long
@@ -1075,7 +1075,7 @@ def setup_test_set_get_section_grader_ajax(self):
self.populate_course()
sections = modulestore().get_items(self.course.id, qualifiers={'category': "sequential"})
# see if test makes sense
- self.assertGreater(len(sections), 0, "No sections found")
+ self.assertGreater(len(sections), 0, "No sections found") # noqa: PT009
section = sections[0] # just take the first one
return reverse_usage_url('xblock_handler', section.location)
@@ -1085,14 +1085,14 @@ def test_set_get_section_grader_ajax(self):
"""
grade_type_url = self.setup_test_set_get_section_grader_ajax()
response = self.client.ajax_post(grade_type_url, {'graderType': 'Homework'})
- self.assertEqual(200, response.status_code)
+ self.assertEqual(200, response.status_code) # noqa: PT009
response = self.client.get_json(grade_type_url + '?fields=graderType')
- self.assertEqual(json.loads(response.content.decode('utf-8')).get('graderType'), 'Homework')
+ self.assertEqual(json.loads(response.content.decode('utf-8')).get('graderType'), 'Homework') # noqa: PT009
# and unset
response = self.client.ajax_post(grade_type_url, {'graderType': 'notgraded'})
- self.assertEqual(200, response.status_code)
+ self.assertEqual(200, response.status_code) # noqa: PT009
response = self.client.get_json(grade_type_url + '?fields=graderType')
- self.assertEqual(json.loads(response.content.decode('utf-8')).get('graderType'), 'notgraded')
+ self.assertEqual(json.loads(response.content.decode('utf-8')).get('graderType'), 'notgraded') # noqa: PT009
def _grading_policy_hash_for_course(self):
return hash_grading_policy(modulestore().get_course(self.course.id).grading_policy)
@@ -1118,16 +1118,16 @@ def setUp(self):
def test_fetch_initial_fields(self):
test_model = CourseMetadata.fetch(self.course)
- self.assertIn('display_name', test_model, 'Missing editable metadata field')
- self.assertEqual(test_model['display_name']['value'], self.course.display_name)
+ self.assertIn('display_name', test_model, 'Missing editable metadata field') # noqa: PT009
+ self.assertEqual(test_model['display_name']['value'], self.course.display_name) # noqa: PT009
test_model = CourseMetadata.fetch(self.fullcourse)
- self.assertNotIn('graceperiod', test_model, 'blacklisted field leaked in')
- self.assertIn('display_name', test_model, 'full missing editable metadata field')
- self.assertEqual(test_model['display_name']['value'], self.fullcourse.display_name)
- self.assertIn('rerandomize', test_model, 'Missing rerandomize metadata field')
- self.assertIn('showanswer', test_model, 'showanswer field ')
- self.assertIn('xqa_key', test_model, 'xqa_key field ')
+ self.assertNotIn('graceperiod', test_model, 'blacklisted field leaked in') # noqa: PT009
+ self.assertIn('display_name', test_model, 'full missing editable metadata field') # noqa: PT009
+ self.assertEqual(test_model['display_name']['value'], self.fullcourse.display_name) # noqa: PT009
+ self.assertIn('rerandomize', test_model, 'Missing rerandomize metadata field') # noqa: PT009
+ self.assertIn('showanswer', test_model, 'showanswer field ') # noqa: PT009
+ self.assertIn('xqa_key', test_model, 'xqa_key field ') # noqa: PT009
@override_settings(ENABLE_EXPORT_GIT=True)
def test_fetch_giturl_present(self):
@@ -1135,7 +1135,7 @@ def test_fetch_giturl_present(self):
If feature flag ENABLE_EXPORT_GIT is on, show the setting as a non-deprecated Advanced Setting.
"""
test_model = CourseMetadata.fetch(self.fullcourse)
- self.assertIn('giturl', test_model)
+ self.assertIn('giturl', test_model) # noqa: PT009
@override_settings(ENABLE_EXPORT_GIT=False)
def test_fetch_giturl_not_present(self):
@@ -1143,7 +1143,7 @@ def test_fetch_giturl_not_present(self):
If feature flag ENABLE_EXPORT_GIT is off, don't show the setting at all on the Advanced Settings page.
"""
test_model = CourseMetadata.fetch(self.fullcourse)
- self.assertNotIn('giturl', test_model)
+ self.assertNotIn('giturl', test_model) # noqa: PT009
@override_settings(
PROCTORING_BACKENDS={
@@ -1157,7 +1157,7 @@ def test_fetch_proctoring_escalation_email_present(self):
show the escalation email setting
"""
test_model = CourseMetadata.fetch(self.fullcourse)
- self.assertIn('proctoring_escalation_email', test_model)
+ self.assertIn('proctoring_escalation_email', test_model) # noqa: PT009
@override_settings(
PROCTORING_BACKENDS={
@@ -1171,7 +1171,7 @@ def test_fetch_proctoring_escalation_email_not_present(self):
don't show the escalation email setting
"""
test_model = CourseMetadata.fetch(self.fullcourse)
- self.assertNotIn('proctoring_escalation_email', test_model)
+ self.assertNotIn('proctoring_escalation_email', test_model) # noqa: PT009
@override_settings(ENABLE_EXPORT_GIT=False)
def test_validate_update_filtered_off(self):
@@ -1186,7 +1186,7 @@ def test_validate_update_filtered_off(self):
},
user=self.user
)
- self.assertNotIn('giturl', test_model)
+ self.assertNotIn('giturl', test_model) # noqa: PT009
@override_settings(ENABLE_EXPORT_GIT=True)
def test_validate_update_filtered_on(self):
@@ -1201,7 +1201,7 @@ def test_validate_update_filtered_on(self):
},
user=self.user
)
- self.assertIn('giturl', test_model)
+ self.assertIn('giturl', test_model) # noqa: PT009
@override_settings(ENABLE_EXPORT_GIT=True)
def test_update_from_json_filtered_on(self):
@@ -1215,7 +1215,7 @@ def test_update_from_json_filtered_on(self):
},
user=self.user
)
- self.assertIn('giturl', test_model)
+ self.assertIn('giturl', test_model) # noqa: PT009
@override_settings(ENABLE_EXPORT_GIT=False)
def test_update_from_json_filtered_off(self):
@@ -1229,7 +1229,7 @@ def test_update_from_json_filtered_off(self):
},
user=self.user
)
- self.assertNotIn('giturl', test_model)
+ self.assertNotIn('giturl', test_model) # noqa: PT009
@patch.dict(settings.FEATURES, {'ENABLE_EDXNOTES': True})
def test_edxnotes_present(self):
@@ -1237,7 +1237,7 @@ def test_edxnotes_present(self):
If feature flag ENABLE_EDXNOTES is on, show the setting as a non-deprecated Advanced Setting.
"""
test_model = CourseMetadata.fetch(self.fullcourse)
- self.assertIn('edxnotes', test_model)
+ self.assertIn('edxnotes', test_model) # noqa: PT009
@patch.dict(settings.FEATURES, {'ENABLE_EDXNOTES': False})
def test_edxnotes_not_present(self):
@@ -1245,7 +1245,7 @@ def test_edxnotes_not_present(self):
If feature flag ENABLE_EDXNOTES is off, don't show the setting at all on the Advanced Settings page.
"""
test_model = CourseMetadata.fetch(self.fullcourse)
- self.assertNotIn('edxnotes', test_model)
+ self.assertNotIn('edxnotes', test_model) # noqa: PT009
@patch.dict(settings.FEATURES, {'ENABLE_EDXNOTES': False})
def test_validate_update_filtered_edxnotes_off(self):
@@ -1260,7 +1260,7 @@ def test_validate_update_filtered_edxnotes_off(self):
},
user=self.user
)
- self.assertNotIn('edxnotes', test_model)
+ self.assertNotIn('edxnotes', test_model) # noqa: PT009
@patch.dict(settings.FEATURES, {'ENABLE_EDXNOTES': True})
def test_validate_update_filtered_edxnotes_on(self):
@@ -1275,7 +1275,7 @@ def test_validate_update_filtered_edxnotes_on(self):
},
user=self.user
)
- self.assertIn('edxnotes', test_model)
+ self.assertIn('edxnotes', test_model) # noqa: PT009
@patch.dict(settings.FEATURES, {'ENABLE_EDXNOTES': True})
def test_update_from_json_filtered_edxnotes_on(self):
@@ -1289,7 +1289,7 @@ def test_update_from_json_filtered_edxnotes_on(self):
},
user=self.user
)
- self.assertIn('edxnotes', test_model)
+ self.assertIn('edxnotes', test_model) # noqa: PT009
@patch.dict(settings.FEATURES, {'ENABLE_EDXNOTES': False})
def test_update_from_json_filtered_edxnotes_off(self):
@@ -1303,7 +1303,7 @@ def test_update_from_json_filtered_edxnotes_off(self):
},
user=self.user
)
- self.assertNotIn('edxnotes', test_model)
+ self.assertNotIn('edxnotes', test_model) # noqa: PT009
@patch.dict(settings.FEATURES, {'ENABLE_OTHER_COURSE_SETTINGS': True})
def test_othercoursesettings_present(self):
@@ -1311,7 +1311,7 @@ def test_othercoursesettings_present(self):
If feature flag ENABLE_OTHER_COURSE_SETTINGS is on, show the setting in Advanced Settings.
"""
test_model = CourseMetadata.fetch(self.fullcourse)
- self.assertIn('other_course_settings', test_model)
+ self.assertIn('other_course_settings', test_model) # noqa: PT009
@patch.dict(settings.FEATURES, {'ENABLE_OTHER_COURSE_SETTINGS': False})
def test_othercoursesettings_not_present(self):
@@ -1319,16 +1319,16 @@ def test_othercoursesettings_not_present(self):
If feature flag ENABLE_OTHER_COURSE_SETTINGS is off, don't show the setting at all in Advanced Settings.
"""
test_model = CourseMetadata.fetch(self.fullcourse)
- self.assertNotIn('other_course_settings', test_model)
+ self.assertNotIn('other_course_settings', test_model) # noqa: PT009
def test_allow_unsupported_xblocks(self):
"""
allow_unsupported_xblocks is only shown in Advanced Settings if
XBlockStudioConfigurationFlag is enabled.
"""
- self.assertNotIn('allow_unsupported_xblocks', CourseMetadata.fetch(self.fullcourse))
+ self.assertNotIn('allow_unsupported_xblocks', CourseMetadata.fetch(self.fullcourse)) # noqa: PT009
XBlockStudioConfigurationFlag(enabled=True).save()
- self.assertIn('allow_unsupported_xblocks', CourseMetadata.fetch(self.fullcourse))
+ self.assertIn('allow_unsupported_xblocks', CourseMetadata.fetch(self.fullcourse)) # noqa: PT009
def test_validate_from_json_correct_inputs(self):
is_valid, errors, test_model = CourseMetadata.validate_and_update_from_json(
@@ -1340,13 +1340,13 @@ def test_validate_from_json_correct_inputs(self):
},
user=self.user
)
- self.assertTrue(is_valid)
- self.assertEqual(len(errors), 0)
+ self.assertTrue(is_valid) # noqa: PT009
+ self.assertEqual(len(errors), 0) # noqa: PT009
self.update_check(test_model)
# Tab gets tested in test_advanced_settings_munge_tabs
- self.assertIn('advanced_modules', test_model, 'Missing advanced_modules')
- self.assertEqual(test_model['advanced_modules']['value'], ['notes'], 'advanced_module is not updated')
+ self.assertIn('advanced_modules', test_model, 'Missing advanced_modules') # noqa: PT009
+ self.assertEqual(test_model['advanced_modules']['value'], ['notes'], 'advanced_module is not updated') # noqa: PT009 # pylint: disable=line-too-long
def test_validate_from_json_wrong_inputs(self):
# input incorrectly formatted data
@@ -1362,21 +1362,21 @@ def test_validate_from_json_wrong_inputs(self):
)
# Check valid results from validate_and_update_from_json
- self.assertFalse(is_valid)
- self.assertEqual(len(errors), 3)
- self.assertFalse(test_model)
+ self.assertFalse(is_valid) # noqa: PT009
+ self.assertEqual(len(errors), 3) # noqa: PT009
+ self.assertFalse(test_model) # noqa: PT009
error_keys = {error_obj['model']['display_name'] for error_obj in errors}
test_keys = {'Advanced Module List', 'Course Advertised Start Date', 'Days Early for Beta Users'}
- self.assertEqual(error_keys, test_keys)
+ self.assertEqual(error_keys, test_keys) # noqa: PT009
# try fresh fetch to ensure no update happened
fresh = modulestore().get_course(self.course.id)
test_model = CourseMetadata.fetch(fresh)
- self.assertNotEqual(test_model['advertised_start']['value'], 1,
+ self.assertNotEqual(test_model['advertised_start']['value'], 1, # noqa: PT009
'advertised_start should not be updated to a wrong value')
- self.assertNotEqual(test_model['days_early_for_beta']['value'], "supposed to be an integer",
+ self.assertNotEqual(test_model['days_early_for_beta']['value'], "supposed to be an integer", # noqa: PT009
'days_early_for beta should not be updated to a wrong value')
def test_correct_http_status(self):
@@ -1389,7 +1389,7 @@ def test_correct_http_status(self):
"advanced_modules": {"value": 1, "display_name": "Advanced Module List", },
})
response = self.client.ajax_post(self.course_setting_url, json_data)
- self.assertEqual(400, response.status_code)
+ self.assertEqual(400, response.status_code) # noqa: PT009
def test_update_from_json(self):
test_model = CourseMetadata.update_from_json(
@@ -1414,36 +1414,36 @@ def test_update_from_json(self):
},
user=self.user
)
- self.assertIn('display_name', test_model, 'Missing editable metadata field')
- self.assertEqual(test_model['display_name']['value'], 'jolly roger', "not expected value")
- self.assertIn('advertised_start', test_model, 'Missing revised advertised_start metadata field')
- self.assertEqual(test_model['advertised_start']['value'], 'start B', "advertised_start not expected value")
+ self.assertIn('display_name', test_model, 'Missing editable metadata field') # noqa: PT009
+ self.assertEqual(test_model['display_name']['value'], 'jolly roger', "not expected value") # noqa: PT009
+ self.assertIn('advertised_start', test_model, 'Missing revised advertised_start metadata field') # noqa: PT009
+ self.assertEqual(test_model['advertised_start']['value'], 'start B', "advertised_start not expected value") # noqa: PT009 # pylint: disable=line-too-long
def update_check(self, test_model):
"""
checks that updates were made
"""
- self.assertIn('display_name', test_model, 'Missing editable metadata field')
- self.assertEqual(test_model['display_name']['value'], self.course.display_name)
- self.assertIn('advertised_start', test_model, 'Missing new advertised_start metadata field')
- self.assertEqual(test_model['advertised_start']['value'], 'start A', "advertised_start not expected value")
- self.assertIn('days_early_for_beta', test_model, 'Missing days_early_for_beta metadata field')
- self.assertEqual(test_model['days_early_for_beta']['value'], 2, "days_early_for_beta not expected value")
+ self.assertIn('display_name', test_model, 'Missing editable metadata field') # noqa: PT009
+ self.assertEqual(test_model['display_name']['value'], self.course.display_name) # noqa: PT009
+ self.assertIn('advertised_start', test_model, 'Missing new advertised_start metadata field') # noqa: PT009
+ self.assertEqual(test_model['advertised_start']['value'], 'start A', "advertised_start not expected value") # noqa: PT009 # pylint: disable=line-too-long
+ self.assertIn('days_early_for_beta', test_model, 'Missing days_early_for_beta metadata field') # noqa: PT009
+ self.assertEqual(test_model['days_early_for_beta']['value'], 2, "days_early_for_beta not expected value") # noqa: PT009 # pylint: disable=line-too-long
def test_http_fetch_initial_fields(self):
response = self.client.get_json(self.course_setting_url)
test_model = json.loads(response.content.decode('utf-8'))
- self.assertIn('display_name', test_model, 'Missing editable metadata field')
- self.assertEqual(test_model['display_name']['value'], self.course.display_name)
+ self.assertIn('display_name', test_model, 'Missing editable metadata field') # noqa: PT009
+ self.assertEqual(test_model['display_name']['value'], self.course.display_name) # noqa: PT009
response = self.client.get_json(self.fullcourse_setting_url)
test_model = json.loads(response.content.decode('utf-8'))
- self.assertNotIn('graceperiod', test_model, 'blacklisted field leaked in')
- self.assertIn('display_name', test_model, 'full missing editable metadata field')
- self.assertEqual(test_model['display_name']['value'], self.fullcourse.display_name)
- self.assertIn('rerandomize', test_model, 'Missing rerandomize metadata field')
- self.assertIn('showanswer', test_model, 'showanswer field ')
- self.assertIn('xqa_key', test_model, 'xqa_key field ')
+ self.assertNotIn('graceperiod', test_model, 'blacklisted field leaked in') # noqa: PT009
+ self.assertIn('display_name', test_model, 'full missing editable metadata field') # noqa: PT009
+ self.assertEqual(test_model['display_name']['value'], self.fullcourse.display_name) # noqa: PT009
+ self.assertIn('rerandomize', test_model, 'Missing rerandomize metadata field') # noqa: PT009
+ self.assertIn('showanswer', test_model, 'showanswer field ') # noqa: PT009
+ self.assertIn('xqa_key', test_model, 'xqa_key field ') # noqa: PT009
def test_http_update_from_json(self):
response = self.client.ajax_post(self.course_setting_url, {
@@ -1462,10 +1462,10 @@ def test_http_update_from_json(self):
"display_name": {"value": "jolly roger"}
})
test_model = json.loads(response.content.decode('utf-8'))
- self.assertIn('display_name', test_model, 'Missing editable metadata field')
- self.assertEqual(test_model['display_name']['value'], 'jolly roger', "not expected value")
- self.assertIn('advertised_start', test_model, 'Missing revised advertised_start metadata field')
- self.assertEqual(test_model['advertised_start']['value'], 'start B', "advertised_start not expected value")
+ self.assertIn('display_name', test_model, 'Missing editable metadata field') # noqa: PT009
+ self.assertEqual(test_model['display_name']['value'], 'jolly roger', "not expected value") # noqa: PT009
+ self.assertIn('advertised_start', test_model, 'Missing revised advertised_start metadata field') # noqa: PT009
+ self.assertEqual(test_model['advertised_start']['value'], 'start B', "advertised_start not expected value") # noqa: PT009 # pylint: disable=line-too-long
@patch.dict(settings.FEATURES, {'ENABLE_EDXNOTES': True})
@patch('xmodule.util.xmodule_django.get_current_request')
@@ -1482,7 +1482,7 @@ def test_post_settings_with_staff_not_enrolled(self, mock_request):
response = self.client.ajax_post(self.course_setting_url, {
'advanced_modules': {"value": [""]}
})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
@ddt.data(True, False)
@override_settings(
@@ -1510,20 +1510,20 @@ def test_validate_update_does_not_allow_proctoring_provider_changes_after_course
)
if staff_user:
- self.assertTrue(did_validate)
- self.assertEqual(len(errors), 0)
- self.assertIn(field_name, test_model)
+ self.assertTrue(did_validate) # noqa: PT009
+ self.assertEqual(len(errors), 0) # noqa: PT009
+ self.assertIn(field_name, test_model) # noqa: PT009
else:
- self.assertFalse(did_validate)
- self.assertEqual(len(errors), 1)
- self.assertEqual(
+ self.assertFalse(did_validate) # noqa: PT009
+ self.assertEqual(len(errors), 1) # noqa: PT009
+ self.assertEqual( # noqa: PT009
errors[0].get('message'),
(
'The proctoring provider cannot be modified after a course has started.'
' Contact support@foobar.com for assistance'
)
)
- self.assertIsNone(test_model)
+ self.assertIsNone(test_model) # noqa: PT009
@ddt.data(True, False)
@override_settings(
@@ -1546,10 +1546,10 @@ def test_validate_update_requires_escalation_email_if_relevant_flag_is_set(self,
json_data,
user=self.user
)
- self.assertFalse(did_validate)
- self.assertEqual(len(errors), 1)
- self.assertIsNone(test_model)
- self.assertEqual(
+ self.assertFalse(did_validate) # noqa: PT009
+ self.assertEqual(len(errors), 1) # noqa: PT009
+ self.assertIsNone(test_model) # noqa: PT009
+ self.assertEqual( # noqa: PT009
errors[0].get('message'),
'Provider \'test_proctoring_provider\' requires an exam escalation contact.'
)
@@ -1568,9 +1568,9 @@ def test_validate_update_does_not_require_escalation_email_by_default(self):
},
user=self.user
)
- self.assertTrue(did_validate)
- self.assertEqual(len(errors), 0)
- self.assertIn('proctoring_provider', test_model)
+ self.assertTrue(did_validate) # noqa: PT009
+ self.assertEqual(len(errors), 0) # noqa: PT009
+ self.assertIn('proctoring_provider', test_model) # noqa: PT009
@override_settings(
PROCTORING_BACKENDS={
@@ -1592,10 +1592,10 @@ def test_validate_update_cannot_unset_escalation_email_when_requires_escalation_
},
user=self.user
)
- self.assertFalse(did_validate)
- self.assertEqual(len(errors), 1)
- self.assertIsNone(test_model)
- self.assertEqual(
+ self.assertFalse(did_validate) # noqa: PT009
+ self.assertEqual(len(errors), 1) # noqa: PT009
+ self.assertIsNone(test_model) # noqa: PT009
+ self.assertEqual( # noqa: PT009
errors[0].get('message'),
'Provider \'test_proctoring_provider\' requires an exam escalation contact.'
)
@@ -1615,10 +1615,10 @@ def test_validate_update_set_proctoring_provider_with_valid_escalation_email(sel
},
user=self.user
)
- self.assertTrue(did_validate)
- self.assertEqual(len(errors), 0)
- self.assertIn('proctoring_provider', test_model)
- self.assertIn('proctoring_escalation_email', test_model)
+ self.assertTrue(did_validate) # noqa: PT009
+ self.assertEqual(len(errors), 0) # noqa: PT009
+ self.assertIn('proctoring_provider', test_model) # noqa: PT009
+ self.assertIn('proctoring_escalation_email', test_model) # noqa: PT009
@override_settings(
PROCTORING_BACKENDS={
@@ -1644,9 +1644,9 @@ def test_validate_update_disable_proctoring_with_no_escalation_email(self):
},
user=self.user
)
- self.assertTrue(did_validate)
- self.assertEqual(len(errors), 0)
- self.assertIn('enable_proctored_exams', test_model)
+ self.assertTrue(did_validate) # noqa: PT009
+ self.assertEqual(len(errors), 0) # noqa: PT009
+ self.assertIn('enable_proctored_exams', test_model) # noqa: PT009
@override_settings(
PROCTORING_BACKENDS={
@@ -1664,11 +1664,11 @@ def test_validate_update_disable_proctoring_and_change_escalation_email(self):
},
user=self.user
)
- self.assertTrue(did_validate)
- self.assertEqual(len(errors), 0)
- self.assertIn('proctoring_provider', test_model)
- self.assertIn('proctoring_escalation_email', test_model)
- self.assertIn('enable_proctored_exams', test_model)
+ self.assertTrue(did_validate) # noqa: PT009
+ self.assertEqual(len(errors), 0) # noqa: PT009
+ self.assertIn('proctoring_provider', test_model) # noqa: PT009
+ self.assertIn('proctoring_escalation_email', test_model) # noqa: PT009
+ self.assertIn('enable_proctored_exams', test_model) # noqa: PT009
@override_settings(
PROCTORING_BACKENDS={
@@ -1690,11 +1690,11 @@ def test_validate_update_disabled_proctoring_and_unset_escalation_email(self):
},
user=self.user
)
- self.assertTrue(did_validate)
- self.assertEqual(len(errors), 0)
- self.assertIn('proctoring_provider', test_model)
- self.assertIn('proctoring_escalation_email', test_model)
- self.assertIn('enable_proctored_exams', test_model)
+ self.assertTrue(did_validate) # noqa: PT009
+ self.assertEqual(len(errors), 0) # noqa: PT009
+ self.assertIn('proctoring_provider', test_model) # noqa: PT009
+ self.assertIn('proctoring_escalation_email', test_model) # noqa: PT009
+ self.assertIn('enable_proctored_exams', test_model) # noqa: PT009
def test_create_zendesk_tickets_present_for_edx_staff(self):
"""
@@ -1703,7 +1703,7 @@ def test_create_zendesk_tickets_present_for_edx_staff(self):
self._set_request_user_to_staff()
test_model = CourseMetadata.fetch(self.fullcourse)
- self.assertIn('create_zendesk_tickets', test_model)
+ self.assertIn('create_zendesk_tickets', test_model) # noqa: PT009
def test_validate_update_does_not_filter_out_create_zendesk_tickets_for_edx_staff(self):
"""
@@ -1721,7 +1721,7 @@ def test_validate_update_does_not_filter_out_create_zendesk_tickets_for_edx_staf
},
user=self.user
)
- self.assertIn(field_name, test_model)
+ self.assertIn(field_name, test_model) # noqa: PT009
def test_update_from_json_does_not_filter_out_create_zendesk_tickets_for_edx_staff(self):
"""
@@ -1739,7 +1739,7 @@ def test_update_from_json_does_not_filter_out_create_zendesk_tickets_for_edx_sta
},
user=self.user
)
- self.assertIn(field_name, test_model)
+ self.assertIn(field_name, test_model) # noqa: PT009
def test_validate_update_does_not_filter_out_create_zendesk_tickets_for_course_staff(self):
"""
@@ -1755,7 +1755,7 @@ def test_validate_update_does_not_filter_out_create_zendesk_tickets_for_course_s
},
user=self.user
)
- self.assertIn(field_name, test_model)
+ self.assertIn(field_name, test_model) # noqa: PT009
def test_update_from_json_does_not_filter_out_create_zendesk_tickets_for_course_staff(self):
"""
@@ -1771,7 +1771,7 @@ def test_update_from_json_does_not_filter_out_create_zendesk_tickets_for_course_
},
user=self.user
)
- self.assertIn(field_name, test_model)
+ self.assertIn(field_name, test_model) # noqa: PT009
def _set_request_user_to_staff(self):
"""
@@ -1816,9 +1816,9 @@ def test_team_content_groups_off(self):
user=self.user
)
- self.assertEqual(len(errors), 0)
+ self.assertEqual(len(errors), 0) # noqa: PT009
for team_set in updated_data["teams_configuration"]["value"]["team_sets"]:
- self.assertNotIn("user_partition_id", team_set)
+ self.assertNotIn("user_partition_id", team_set) # noqa: PT009
@patch("cms.djangoapps.models.settings.course_metadata.CONTENT_GROUPS_FOR_TEAMS.is_enabled", lambda _: True)
def test_team_content_groups_on(self):
@@ -1856,9 +1856,9 @@ def test_team_content_groups_on(self):
user=self.user
)
- self.assertEqual(len(errors), 0)
+ self.assertEqual(len(errors), 0) # noqa: PT009
for team_set in updated_data["teams_configuration"]["value"]["team_sets"]:
- self.assertIn("user_partition_id", team_set)
+ self.assertIn("user_partition_id", team_set) # noqa: PT009
class CourseGraderUpdatesTest(CourseTestCase):
@@ -1875,17 +1875,17 @@ def setUp(self):
def test_get(self):
"""Test getting a specific grading type record."""
resp = self.client.get_json(self.url + '/0')
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
obj = json.loads(resp.content.decode('utf-8'))
- self.assertEqual(self.starting_graders[0], obj)
+ self.assertEqual(self.starting_graders[0], obj) # noqa: PT009
def test_delete(self):
"""Test deleting a specific grading type record."""
resp = self.client.delete(self.url + '/0', HTTP_ACCEPT="application/json")
- self.assertEqual(resp.status_code, 204)
+ self.assertEqual(resp.status_code, 204) # noqa: PT009
current_graders = CourseGradingModel.fetch(self.course.id).graders
- self.assertNotIn(self.starting_graders[0], current_graders)
- self.assertEqual(len(self.starting_graders) - 1, len(current_graders))
+ self.assertNotIn(self.starting_graders[0], current_graders) # noqa: PT009
+ self.assertEqual(len(self.starting_graders) - 1, len(current_graders)) # noqa: PT009
def test_update(self):
"""Test updating a specific grading type record."""
@@ -1898,11 +1898,11 @@ def test_update(self):
"weight": 17.3,
}
resp = self.client.ajax_post(self.url + '/0', grader)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
obj = json.loads(resp.content.decode('utf-8'))
- self.assertEqual(obj, grader)
+ self.assertEqual(obj, grader) # noqa: PT009
current_graders = CourseGradingModel.fetch(self.course.id).graders
- self.assertEqual(len(self.starting_graders), len(current_graders))
+ self.assertEqual(len(self.starting_graders), len(current_graders)) # noqa: PT009
def test_add(self):
"""Test adding a grading type record."""
@@ -1917,13 +1917,13 @@ def test_add(self):
"weight": 17.3,
}
resp = self.client.ajax_post(f'{self.url}/{len(self.starting_graders) + 1}', grader)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
obj = json.loads(resp.content.decode('utf-8'))
- self.assertEqual(obj['id'], len(self.starting_graders))
+ self.assertEqual(obj['id'], len(self.starting_graders)) # noqa: PT009
del obj['id']
- self.assertEqual(obj, grader)
+ self.assertEqual(obj, grader) # noqa: PT009
current_graders = CourseGradingModel.fetch(self.course.id).graders
- self.assertEqual(len(self.starting_graders) + 1, len(current_graders))
+ self.assertEqual(len(self.starting_graders) + 1, len(current_graders)) # noqa: PT009
class CourseEnrollmentEndFieldTest(CourseTestCase):
@@ -1988,7 +1988,7 @@ def _verify_editable(self, response):
Assert that all editable field content exists and no
uneditable field content exists for enrollment end fields.
"""
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
for element in self.NOT_EDITABLE_ELEMENTS:
self.assertNotContains(response, element)
@@ -2002,7 +2002,7 @@ def _verify_not_editable(self, response):
Assert that all uneditable field content exists and no
editable field content exists for enrollment end fields.
"""
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
for element in self.NOT_EDITABLE_ELEMENTS:
self.assertContains(response, element)
diff --git a/cms/djangoapps/contentstore/tests/test_courseware_index.py b/cms/djangoapps/contentstore/tests/test_courseware_index.py
index ee7bc4e49afb..f298b570b2b5 100644
--- a/cms/djangoapps/contentstore/tests/test_courseware_index.py
+++ b/cms/djangoapps/contentstore/tests/test_courseware_index.py
@@ -212,15 +212,15 @@ def _test_indexing_course(self, store):
""" indexing course tests """
# Only published blocks should be in the index
added_to_index = self.reindex_course(store) # This reindex may not be necessary (it may already be indexed)
- self.assertEqual(added_to_index, 3)
+ self.assertEqual(added_to_index, 3) # noqa: PT009
response = self.search()
- self.assertEqual(response["total"], 3)
+ self.assertEqual(response["total"], 3) # noqa: PT009
# Publish the vertical as is, and any unpublished children should now be available
self.publish_item(store, self.vertical.location)
self.reindex_course(store)
response = self.search()
- self.assertEqual(response["total"], 4)
+ self.assertEqual(response["total"], 4) # noqa: PT009
def _test_not_indexing_unpublished_content(self, store):
""" add a new one, only appers in index once added """
@@ -228,7 +228,7 @@ def _test_not_indexing_unpublished_content(self, store):
self.publish_item(store, self.vertical.location)
self.reindex_course(store)
response = self.search()
- self.assertEqual(response["total"], 4)
+ self.assertEqual(response["total"], 4) # noqa: PT009
# Now add a new unit to the existing vertical
BlockFactory.create(
@@ -240,14 +240,14 @@ def _test_not_indexing_unpublished_content(self, store):
)
self.reindex_course(store)
response = self.search()
- self.assertEqual(response["total"], 4)
+ self.assertEqual(response["total"], 4) # noqa: PT009
# Now publish it and we should find it
# Publish the vertical as is, and everything should be available
self.publish_item(store, self.vertical.location)
self.reindex_course(store)
response = self.search()
- self.assertEqual(response["total"], 5)
+ self.assertEqual(response["total"], 5) # noqa: PT009
def _test_delete_course_from_search_index_after_course_deletion(self, store): # pylint: disable=invalid-name
"""
@@ -257,14 +257,14 @@ def _test_delete_course_from_search_index_after_course_deletion(self, store): #
# index the course in search_index (it may already be indexed)
self.reindex_course(store)
response = self.search()
- self.assertEqual(response["total"], 1)
+ self.assertEqual(response["total"], 1) # noqa: PT009
# delete the course and look course in search_index
store.delete_course(self.course.id, ModuleStoreEnum.UserID.test)
- self.assertIsNone(store.get_course(self.course.id))
+ self.assertIsNone(store.get_course(self.course.id)) # noqa: PT009
# Now, because of contentstore.signals.handlers.listen_for_course_delete, the index should already be updated:
response = self.search()
- self.assertEqual(response["total"], 0)
+ self.assertEqual(response["total"], 0) # noqa: PT009
def _test_deleting_item(self, store):
""" test deleting an item """
@@ -272,19 +272,19 @@ def _test_deleting_item(self, store):
self.publish_item(store, self.vertical.location)
self.reindex_course(store)
response = self.search()
- self.assertEqual(response["total"], 4)
+ self.assertEqual(response["total"], 4) # noqa: PT009
# just a delete should not change anything
self.delete_item(store, self.html_unit.location)
self.reindex_course(store)
response = self.search()
- self.assertEqual(response["total"], 4)
+ self.assertEqual(response["total"], 4) # noqa: PT009
# but after publishing, we should no longer find the html_unit
self.publish_item(store, self.vertical.location)
self.reindex_course(store)
response = self.search()
- self.assertEqual(response["total"], 3)
+ self.assertEqual(response["total"], 3) # noqa: PT009
def _test_start_date_propagation(self, store):
""" make sure that the start date is applied at the right level """
@@ -295,7 +295,7 @@ def _test_start_date_propagation(self, store):
self.publish_item(store, self.vertical.location)
self.reindex_course(store)
response = self.search()
- self.assertEqual(response["total"], 4)
+ self.assertEqual(response["total"], 4) # noqa: PT009
results = response["results"]
date_map = {
@@ -305,19 +305,19 @@ def _test_start_date_propagation(self, store):
str(self.html_unit.location): later_date,
}
for result in results:
- self.assertEqual(result["data"]["start_date"], date_map[result["data"]["id"]])
+ self.assertEqual(result["data"]["start_date"], date_map[result["data"]["id"]]) # noqa: PT009
@patch('django.conf.settings.SEARCH_ENGINE', None)
def _test_search_disabled(self, store):
""" if search setting has it as off, confirm that nothing is indexed """
indexed_count = self.reindex_course(store)
- self.assertFalse(indexed_count)
+ self.assertFalse(indexed_count) # noqa: PT009
def _test_time_based_index(self, store):
""" Make sure that a time based request to index does not index anything too old """
self.publish_item(store, self.vertical.location)
indexed_count = self.reindex_course(store)
- self.assertEqual(indexed_count, 4)
+ self.assertEqual(indexed_count, 4) # noqa: PT009
# Add a new sequential
sequential2 = BlockFactory.create(
@@ -351,11 +351,11 @@ def _test_time_based_index(self, store):
# because it is in a common subtree but not of the original vertical
# because the original sequential's subtree is too old
new_indexed_count = self.index_recent_changes(store, before_time)
- self.assertEqual(new_indexed_count, 5)
+ self.assertEqual(new_indexed_count, 5) # noqa: PT009
# full index again
indexed_count = self.reindex_course(store)
- self.assertEqual(indexed_count, 7)
+ self.assertEqual(indexed_count, 7) # noqa: PT009
def _test_course_about_property_index(self, store):
"""
@@ -369,8 +369,8 @@ def _test_course_about_property_index(self, store):
response = self.searcher.search(
field_dictionary={"course": str(self.course.id)}
)
- self.assertEqual(response["total"], 1)
- self.assertEqual(response["results"][0]["data"]["content"]["display_name"], display_name)
+ self.assertEqual(response["total"], 1) # noqa: PT009
+ self.assertEqual(response["results"][0]["data"]["content"]["display_name"], display_name) # noqa: PT009
def _test_course_about_store_index(self, store):
"""
@@ -386,8 +386,8 @@ def _test_course_about_store_index(self, store):
response = self.searcher.search(
field_dictionary={"course": str(self.course.id)}
)
- self.assertEqual(response["total"], 1)
- self.assertEqual(response["results"][0]["data"]["content"]["short_description"], short_description)
+ self.assertEqual(response["total"], 1) # noqa: PT009
+ self.assertEqual(response["results"][0]["data"]["content"]["short_description"], short_description) # noqa: PT009 # pylint: disable=line-too-long
def _test_course_about_mode_index(self, store):
"""
@@ -413,20 +413,20 @@ def _test_course_about_mode_index(self, store):
response = self.searcher.search(
field_dictionary={"course": str(self.course.id)}
)
- self.assertEqual(response["total"], 1)
- self.assertIn(CourseMode.HONOR, response["results"][0]["data"]["modes"])
- self.assertIn(CourseMode.VERIFIED, response["results"][0]["data"]["modes"])
+ self.assertEqual(response["total"], 1) # noqa: PT009
+ self.assertIn(CourseMode.HONOR, response["results"][0]["data"]["modes"]) # noqa: PT009
+ self.assertIn(CourseMode.VERIFIED, response["results"][0]["data"]["modes"]) # noqa: PT009
def _test_course_location_info(self, store):
""" Test that course location information is added to index """
self.publish_item(store, self.vertical.location)
self.reindex_course(store)
response = self.search(query_string="Html Content")
- self.assertEqual(response["total"], 1)
+ self.assertEqual(response["total"], 1) # noqa: PT009
result = response["results"][0]["data"]
- self.assertEqual(result["course_name"], "Search Index Test Course")
- self.assertEqual(result["location"], ["Week 1", "Lesson 1", "Subsection 1"])
+ self.assertEqual(result["course_name"], "Search Index Test Course") # noqa: PT009
+ self.assertEqual(result["location"], ["Week 1", "Lesson 1", "Subsection 1"]) # noqa: PT009
def _test_course_location_null(self, store):
""" Test that course location information is added to index """
@@ -455,17 +455,17 @@ def _test_course_location_null(self, store):
)
self.reindex_course(store)
response = self.search(query_string="Find Me")
- self.assertEqual(response["total"], 1)
+ self.assertEqual(response["total"], 1) # noqa: PT009
result = response["results"][0]["data"]
- self.assertEqual(result["course_name"], "Search Index Test Course")
- self.assertEqual(result["location"], ["Week 1", CoursewareSearchIndexer.UNNAMED_MODULE_NAME, "Subsection 2"])
+ self.assertEqual(result["course_name"], "Search Index Test Course") # noqa: PT009
+ self.assertEqual(result["location"], ["Week 1", CoursewareSearchIndexer.UNNAMED_MODULE_NAME, "Subsection 2"]) # noqa: PT009 # pylint: disable=line-too-long
@patch('django.conf.settings.SEARCH_ENGINE', 'search.tests.utils.ErroringIndexEngine')
def _test_exception(self, store):
""" Test that exception within indexing yields a SearchIndexingError """
self.publish_item(store, self.vertical.location)
- with self.assertRaises(SearchIndexingError):
+ with self.assertRaises(SearchIndexingError): # noqa: PT027
self.reindex_course(store)
def test_indexing_course(self):
@@ -545,7 +545,7 @@ def assert_search_count(self, expected_count):
""" Check that the search within this course will yield the expected number of results """
response = self.searcher.search(field_dictionary={"course": self.course_id})
- self.assertEqual(response["total"], expected_count)
+ self.assertEqual(response["total"], expected_count) # noqa: PT009
def _do_test_large_course_deletion(self, store, load_factor):
""" Test that deleting items from a course works even when present within a very large course """
@@ -671,7 +671,7 @@ def test_task_indexing_course(self):
response = searcher.search(
field_dictionary={"course": str(self.course.id)}
)
- self.assertEqual(response["total"], 0)
+ self.assertEqual(response["total"], 0) # noqa: PT009
listen_for_course_publish(self, self.course.id)
@@ -679,20 +679,20 @@ def test_task_indexing_course(self):
response = searcher.search(
field_dictionary={"course": str(self.course.id)}
)
- self.assertEqual(response["total"], 3)
+ self.assertEqual(response["total"], 3) # noqa: PT009
def test_task_library_update(self):
""" Making sure that the receiver correctly fires off the task when invoked by signal """
searcher = SearchEngine.get_search_engine(LibrarySearchIndexer.INDEX_NAME)
library_search_key = str(normalize_key_for_search(self.library.location.library_key))
response = searcher.search(field_dictionary={"library": library_search_key})
- self.assertEqual(response["total"], 0)
+ self.assertEqual(response["total"], 0) # noqa: PT009
listen_for_library_update(self, self.library.location.library_key)
# Note that this test will only succeed if celery is working in inline mode
response = searcher.search(field_dictionary={"library": library_search_key})
- self.assertEqual(response["total"], 2)
+ self.assertEqual(response["total"], 2) # noqa: PT009
def test_ignore_ccx(self):
"""Test that we ignore CCX courses (it's too slow now)."""
@@ -701,12 +701,12 @@ def test_ignore_ccx(self):
# fall through to the normal indexing and raise an exception because
# there is no data or backing course behind the course key.
with patch('cms.djangoapps.contentstore.courseware_index.CoursewareSearchIndexer.index') as mock_index:
- self.assertIsNone(
+ self.assertIsNone( # noqa: PT009
update_search_index(
"ccx-v1:OpenEdX+FAKECOURSE+FAKERUN+ccx@1", "2020-09-28T16:41:57.150796"
)
)
- self.assertFalse(mock_index.called)
+ self.assertFalse(mock_index.called) # noqa: PT009
@pytest.mark.django_db
@@ -764,18 +764,18 @@ def _test_indexing_library(self, store):
""" indexing course tests """
self.reindex_library(store)
response = self.search()
- self.assertEqual(response["total"], 2)
+ self.assertEqual(response["total"], 2) # noqa: PT009
added_to_index = self.reindex_library(store)
- self.assertEqual(added_to_index, 2)
+ self.assertEqual(added_to_index, 2) # noqa: PT009
response = self.search()
- self.assertEqual(response["total"], 2)
+ self.assertEqual(response["total"], 2) # noqa: PT009
def _test_creating_item(self, store):
""" test updating an item """
self.reindex_library(store)
response = self.search()
- self.assertEqual(response["total"], 2)
+ self.assertEqual(response["total"], 2) # noqa: PT009
# updating a library item causes immediate reindexing
data = "Some data"
@@ -790,15 +790,15 @@ def _test_creating_item(self, store):
self.reindex_library(store)
response = self.search()
- self.assertEqual(response["total"], 3)
+ self.assertEqual(response["total"], 3) # noqa: PT009
html_contents = [cont['html_content'] for cont in self._get_contents(response)]
- self.assertIn(data, html_contents)
+ self.assertIn(data, html_contents) # noqa: PT009
def _test_updating_item(self, store):
""" test updating an item """
self.reindex_library(store)
response = self.search()
- self.assertEqual(response["total"], 2)
+ self.assertEqual(response["total"], 2) # noqa: PT009
# updating a library item causes immediate reindexing
new_data = "I'm new data"
@@ -806,32 +806,32 @@ def _test_updating_item(self, store):
self.update_item(store, self.html_unit1)
self.reindex_library(store)
response = self.search()
- self.assertEqual(response["total"], 2)
+ self.assertEqual(response["total"], 2) # noqa: PT009
html_contents = [cont['html_content'] for cont in self._get_contents(response)]
- self.assertIn(new_data, html_contents)
+ self.assertIn(new_data, html_contents) # noqa: PT009
def _test_deleting_item(self, store):
""" test deleting an item """
self.reindex_library(store)
response = self.search()
- self.assertEqual(response["total"], 2)
+ self.assertEqual(response["total"], 2) # noqa: PT009
# deleting a library item causes immediate reindexing
self.delete_item(store, self.html_unit1.location)
self.reindex_library(store)
response = self.search()
- self.assertEqual(response["total"], 1)
+ self.assertEqual(response["total"], 1) # noqa: PT009
@patch('django.conf.settings.SEARCH_ENGINE', None)
def _test_search_disabled(self, store):
""" if search setting has it as off, confirm that nothing is indexed """
indexed_count = self.reindex_library(store)
- self.assertFalse(indexed_count)
+ self.assertFalse(indexed_count) # noqa: PT009
@patch('django.conf.settings.SEARCH_ENGINE', 'search.tests.utils.ErroringIndexEngine')
def _test_exception(self, store):
""" Test that exception within indexing yields a SearchIndexingError """
- with self.assertRaises(SearchIndexingError):
+ with self.assertRaises(SearchIndexingError): # noqa: PT027
self.reindex_library(store)
@ddt.data(*WORKS_WITH_STORES)
@@ -1177,9 +1177,9 @@ def test_content_group_gets_indexed(self):
# Only published blocks should be in the index
added_to_index = self.reindex_course(self.store)
- self.assertEqual(added_to_index, 16)
+ self.assertEqual(added_to_index, 16) # noqa: PT009
response = self.searcher.search(field_dictionary={"course": str(self.course.id)})
- self.assertEqual(response["total"], 16)
+ self.assertEqual(response["total"], 16) # noqa: PT009
group_access_content = {'group_access': {666: [1]}}
@@ -1193,46 +1193,46 @@ def test_content_group_gets_indexed(self):
with patch(settings.SEARCH_ENGINE + '.index') as mock_index:
self.reindex_course(self.store)
- self.assertTrue(mock_index.called)
+ self.assertTrue(mock_index.called) # noqa: PT009
indexed_content = self._get_index_values_from_call_args(mock_index)
- self.assertIn(self._html_group_result(self.html_unit1, [1]), indexed_content)
- self.assertIn(self._html_experiment_group_result(self.html_unit4, [str(2)]), indexed_content)
- self.assertIn(self._html_experiment_group_result(self.html_unit5, [str(3)]), indexed_content)
- self.assertIn(self._html_experiment_group_result(self.html_unit6, [str(4)]), indexed_content)
- self.assertNotIn(self._html_experiment_group_result(self.html_unit6, [str(5)]), indexed_content)
- self.assertIn(
+ self.assertIn(self._html_group_result(self.html_unit1, [1]), indexed_content) # noqa: PT009
+ self.assertIn(self._html_experiment_group_result(self.html_unit4, [str(2)]), indexed_content) # noqa: PT009
+ self.assertIn(self._html_experiment_group_result(self.html_unit5, [str(3)]), indexed_content) # noqa: PT009
+ self.assertIn(self._html_experiment_group_result(self.html_unit6, [str(4)]), indexed_content) # noqa: PT009
+ self.assertNotIn(self._html_experiment_group_result(self.html_unit6, [str(5)]), indexed_content) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertIn( # noqa: PT009
self._vertical_experiment_group_result(self.condition_0_vertical, [str(2)]),
indexed_content
)
- self.assertNotIn(
+ self.assertNotIn( # noqa: PT009
self._vertical_experiment_group_result(self.condition_1_vertical, [str(2)]),
indexed_content
)
- self.assertNotIn(
+ self.assertNotIn( # noqa: PT009
self._vertical_experiment_group_result(self.condition_2_vertical, [str(2)]),
indexed_content
)
- self.assertNotIn(
+ self.assertNotIn( # noqa: PT009
self._vertical_experiment_group_result(self.condition_0_vertical, [str(3)]),
indexed_content
)
- self.assertIn(
+ self.assertIn( # noqa: PT009
self._vertical_experiment_group_result(self.condition_1_vertical, [str(3)]),
indexed_content
)
- self.assertNotIn(
+ self.assertNotIn( # noqa: PT009
self._vertical_experiment_group_result(self.condition_2_vertical, [str(3)]),
indexed_content
)
- self.assertNotIn(
+ self.assertNotIn( # noqa: PT009
self._vertical_experiment_group_result(self.condition_0_vertical, [str(4)]),
indexed_content
)
- self.assertNotIn(
+ self.assertNotIn( # noqa: PT009
self._vertical_experiment_group_result(self.condition_1_vertical, [str(4)]),
indexed_content
)
- self.assertIn(
+ self.assertIn( # noqa: PT009
self._vertical_experiment_group_result(self.condition_2_vertical, [str(4)]),
indexed_content
)
@@ -1243,9 +1243,9 @@ def test_content_group_not_assigned(self):
with patch(settings.SEARCH_ENGINE + '.index') as mock_index:
self.reindex_course(self.store)
- self.assertTrue(mock_index.called)
+ self.assertTrue(mock_index.called) # noqa: PT009
indexed_content = self._get_index_values_from_call_args(mock_index)
- self.assertIn(self._html_nogroup_result(self.html_unit1), indexed_content)
+ self.assertIn(self._html_nogroup_result(self.html_unit1), indexed_content) # noqa: PT009
mock_index.reset_mock()
def test_content_group_not_indexed_on_delete(self):
@@ -1263,9 +1263,9 @@ def test_content_group_not_indexed_on_delete(self):
# Checking group indexed correctly
with patch(settings.SEARCH_ENGINE + '.index') as mock_index:
self.reindex_course(self.store)
- self.assertTrue(mock_index.called)
+ self.assertTrue(mock_index.called) # noqa: PT009
indexed_content = self._get_index_values_from_call_args(mock_index)
- self.assertIn(self._html_group_result(self.html_unit1, [1]), indexed_content)
+ self.assertIn(self._html_group_result(self.html_unit1, [1]), indexed_content) # noqa: PT009
mock_index.reset_mock()
empty_group_access = {'group_access': {}}
@@ -1280,9 +1280,9 @@ def test_content_group_not_indexed_on_delete(self):
# Checking group removed and not indexed any more
with patch(settings.SEARCH_ENGINE + '.index') as mock_index:
self.reindex_course(self.store)
- self.assertTrue(mock_index.called)
+ self.assertTrue(mock_index.called) # noqa: PT009
indexed_content = self._get_index_values_from_call_args(mock_index)
- self.assertIn(self._html_nogroup_result(self.html_unit1), indexed_content)
+ self.assertIn(self._html_nogroup_result(self.html_unit1), indexed_content) # noqa: PT009
mock_index.reset_mock()
def test_group_indexed_only_on_assigned_html_block(self):
@@ -1297,10 +1297,10 @@ def test_group_indexed_only_on_assigned_html_block(self):
with patch(settings.SEARCH_ENGINE + '.index') as mock_index:
self.reindex_course(self.store)
- self.assertTrue(mock_index.called)
+ self.assertTrue(mock_index.called) # noqa: PT009
indexed_content = self._get_index_values_from_call_args(mock_index)
- self.assertIn(self._html_group_result(self.html_unit1, [1]), indexed_content)
- self.assertIn(self._html_nogroup_result(self.html_unit2), indexed_content)
+ self.assertIn(self._html_group_result(self.html_unit1, [1]), indexed_content) # noqa: PT009
+ self.assertIn(self._html_nogroup_result(self.html_unit2), indexed_content) # noqa: PT009
mock_index.reset_mock()
def test_different_groups_indexed_on_assigned_html_blocks(self):
@@ -1322,10 +1322,10 @@ def test_different_groups_indexed_on_assigned_html_blocks(self):
with patch(settings.SEARCH_ENGINE + '.index') as mock_index:
self.reindex_course(self.store)
- self.assertTrue(mock_index.called)
+ self.assertTrue(mock_index.called) # noqa: PT009
indexed_content = self._get_index_values_from_call_args(mock_index)
- self.assertIn(self._html_group_result(self.html_unit1, [1]), indexed_content)
- self.assertIn(self._html_group_result(self.html_unit2, [0]), indexed_content)
+ self.assertIn(self._html_group_result(self.html_unit1, [1]), indexed_content) # noqa: PT009
+ self.assertIn(self._html_group_result(self.html_unit2, [0]), indexed_content) # noqa: PT009
mock_index.reset_mock()
def test_different_groups_indexed_on_same_vertical_html_blocks(self):
@@ -1351,8 +1351,8 @@ def test_different_groups_indexed_on_same_vertical_html_blocks(self):
with patch(settings.SEARCH_ENGINE + '.index') as mock_index:
self.reindex_course(self.store)
- self.assertTrue(mock_index.called)
+ self.assertTrue(mock_index.called) # noqa: PT009
indexed_content = self._get_index_values_from_call_args(mock_index)
- self.assertIn(self._html_group_result(self.html_unit2, [1]), indexed_content)
- self.assertIn(self._html_group_result(self.html_unit3, [0]), indexed_content)
+ self.assertIn(self._html_group_result(self.html_unit2, [1]), indexed_content) # noqa: PT009
+ self.assertIn(self._html_group_result(self.html_unit3, [0]), indexed_content) # noqa: PT009
mock_index.reset_mock()
diff --git a/cms/djangoapps/contentstore/tests/test_crud.py b/cms/djangoapps/contentstore/tests/test_crud.py
index 792d0386ac48..dc151254dc6a 100644
--- a/cms/djangoapps/contentstore/tests/test_crud.py
+++ b/cms/djangoapps/contentstore/tests/test_crud.py
@@ -17,22 +17,22 @@ class TemplateTests(ModuleStoreTestCase):
"""
def test_get_templates(self):
found = templates.all_templates()
- self.assertIsNotNone(found.get('course'))
- self.assertIsNotNone(found.get('about'))
- self.assertIsNotNone(found.get('html'))
- self.assertEqual(len(found.get('course')), 0)
- self.assertEqual(len(found.get('about')), 1)
- self.assertGreaterEqual(len(found.get('html')), 2)
+ self.assertIsNotNone(found.get('course')) # noqa: PT009
+ self.assertIsNotNone(found.get('about')) # noqa: PT009
+ self.assertIsNotNone(found.get('html')) # noqa: PT009
+ self.assertEqual(len(found.get('course')), 0) # noqa: PT009
+ self.assertEqual(len(found.get('about')), 1) # noqa: PT009
+ self.assertGreaterEqual(len(found.get('html')), 2) # noqa: PT009
def test_get_some_templates(self):
course = CourseFactory.create()
htmlblock = BlockFactory.create(category="html", parent_location=course.location)
- self.assertEqual(len(SequenceBlock.templates()), 0)
- self.assertGreater(len(htmlblock.templates()), 0)
- self.assertIsNone(SequenceBlock.get_template('doesntexist.yaml'))
- self.assertIsNone(htmlblock.get_template('doesntexist.yaml'))
- self.assertIsNotNone(htmlblock.get_template('announcement.yaml'))
+ self.assertEqual(len(SequenceBlock.templates()), 0) # noqa: PT009
+ self.assertGreater(len(htmlblock.templates()), 0) # noqa: PT009
+ self.assertIsNone(SequenceBlock.get_template('doesntexist.yaml')) # noqa: PT009
+ self.assertIsNone(htmlblock.get_template('doesntexist.yaml')) # noqa: PT009
+ self.assertIsNotNone(htmlblock.get_template('announcement.yaml')) # noqa: PT009
def test_factories(self):
test_course = CourseFactory.create(
@@ -42,24 +42,24 @@ def test_factories(self):
display_name='fun test course',
user_id=ModuleStoreEnum.UserID.test,
)
- self.assertIsInstance(test_course, CourseBlock)
- self.assertEqual(test_course.display_name, 'fun test course')
+ self.assertIsInstance(test_course, CourseBlock) # noqa: PT009
+ self.assertEqual(test_course.display_name, 'fun test course') # noqa: PT009
course_from_store = self.store.get_course(test_course.id)
- self.assertEqual(course_from_store.id.org, 'testx')
- self.assertEqual(course_from_store.id.course, 'course')
- self.assertEqual(course_from_store.id.run, '2014')
+ self.assertEqual(course_from_store.id.org, 'testx') # noqa: PT009
+ self.assertEqual(course_from_store.id.course, 'course') # noqa: PT009
+ self.assertEqual(course_from_store.id.run, '2014') # noqa: PT009
test_chapter = BlockFactory.create(
parent_location=test_course.location,
category='chapter',
display_name='chapter 1'
)
- self.assertIsInstance(test_chapter, SequenceBlock)
+ self.assertIsInstance(test_chapter, SequenceBlock) # noqa: PT009
# refetch parent which should now point to child
test_course = self.store.get_course(test_course.id.version_agnostic())
- self.assertIn(test_chapter.location, test_course.children)
+ self.assertIn(test_chapter.location, test_course.children) # noqa: PT009
- with self.assertRaises(DuplicateCourseError):
+ with self.assertRaises(DuplicateCourseError): # noqa: PT027
CourseFactory.create(
org='testx',
course='course',
@@ -81,9 +81,9 @@ def test_temporary_xblocks(self):
test_course.runtime, test_course.id, 'chapter', fields={'display_name': 'chapter n'},
parent_xblock=test_course
)
- self.assertIsInstance(test_chapter, SequenceBlock)
- self.assertEqual(test_chapter.display_name, 'chapter n')
- self.assertIn(test_chapter, test_course.get_children())
+ self.assertIsInstance(test_chapter, SequenceBlock) # noqa: PT009
+ self.assertEqual(test_chapter.display_name, 'chapter n') # noqa: PT009
+ self.assertIn(test_chapter, test_course.get_children()) # noqa: PT009
# test w/ a definition (e.g., a problem)
test_def_content = 'boo'
@@ -91,11 +91,11 @@ def test_temporary_xblocks(self):
test_course.runtime, test_course.id, 'problem', fields={'data': test_def_content},
parent_xblock=test_chapter
)
- self.assertIsInstance(test_problem, ProblemBlock)
- self.assertEqual(test_problem.data, test_def_content)
- self.assertIn(test_problem, test_chapter.get_children())
+ self.assertIsInstance(test_problem, ProblemBlock) # noqa: PT009
+ self.assertEqual(test_problem.data, test_def_content) # noqa: PT009
+ self.assertIn(test_problem, test_chapter.get_children()) # noqa: PT009
test_problem.display_name = 'test problem'
- self.assertEqual(test_problem.display_name, 'test problem')
+ self.assertEqual(test_problem.display_name, 'test problem') # noqa: PT009
def test_delete_course(self):
test_course = CourseFactory.create(
@@ -113,13 +113,13 @@ def test_delete_course(self):
id_locator = test_course.id.for_branch(ModuleStoreEnum.BranchName.draft)
# verify it can be retrieved by id
- self.assertIsInstance(self.store.get_course(id_locator), CourseBlock)
+ self.assertIsInstance(self.store.get_course(id_locator), CourseBlock) # noqa: PT009
# TODO reenable when split_draft supports getting specific versions
# guid_locator = test_course.location.course_agnostic()
# Verify it can be retrieved by guid
# self.assertIsInstance(self.store.get_item(guid_locator), CourseBlock)
self.store.delete_course(id_locator, ModuleStoreEnum.UserID.test)
# Test can no longer retrieve by id.
- self.assertIsNone(self.store.get_course(id_locator))
+ self.assertIsNone(self.store.get_course(id_locator)) # noqa: PT009
# But can retrieve by guid -- same TODO as above
# self.assertIsInstance(self.store.get_item(guid_locator), CourseBlock)
diff --git a/cms/djangoapps/contentstore/tests/test_exams.py b/cms/djangoapps/contentstore/tests/test_exams.py
index 1e3ad0657d78..6974c234c019 100644
--- a/cms/djangoapps/contentstore/tests/test_exams.py
+++ b/cms/djangoapps/contentstore/tests/test_exams.py
@@ -182,7 +182,7 @@ def test_feature_flag_off(self, mock_patch_course_exams):
@ddt.data(
*itertools.product(
(True, False),
- (datetime(2035, 1, 1, 0, 0, tzinfo=timezone.utc), None),
+ (datetime(2035, 1, 1, 0, 0, tzinfo=timezone.utc), None), # noqa: UP017
('null', 'lti_external'),
)
)
@@ -236,7 +236,7 @@ def test_subsection_due_date_prioritized_instructor_paced(
Test that exam due date is computed correctly.
"""
self.course.self_paced = is_self_paced
- self.course.end = datetime(2035, 1, 1, 0, 0, tzinfo=timezone.utc)
+ self.course.end = datetime(2035, 1, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.course.proctoring_provider = proctoring_provider
self.course = self.update_course(self.course, 1)
diff --git a/cms/djangoapps/contentstore/tests/test_export_git.py b/cms/djangoapps/contentstore/tests/test_export_git.py
index e65c441d0e90..a59dbe422b9b 100644
--- a/cms/djangoapps/contentstore/tests/test_export_git.py
+++ b/cms/djangoapps/contentstore/tests/test_export_git.py
@@ -19,7 +19,7 @@
from .utils import CourseTestCase
TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
-TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex
+TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex # noqa: UP031
@override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE)
@@ -46,7 +46,7 @@ def make_bare_repo_with_course(self, repo_name):
os.mkdir(repo_dir)
self.addCleanup(shutil.rmtree, repo_dir)
- bare_repo_dir = '{}/{}.git'.format(
+ bare_repo_dir = '{}/{}.git'.format( # noqa: UP032
os.path.abspath(git_export_utils.GIT_REPO_EXPORT_DIR),
repo_name
)
@@ -136,7 +136,7 @@ def test_dirty_repo(self):
)
test_file = os.path.join(repo_dir, 'test.txt')
open(test_file, 'a').close()
- self.assertTrue(os.path.isfile(test_file))
+ self.assertTrue(os.path.isfile(test_file)) # noqa: PT009
git_export_utils.export_to_git(self.course.id,
self.course_block.giturl, self.user)
- self.assertFalse(os.path.isfile(test_file))
+ self.assertFalse(os.path.isfile(test_file)) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_filters.py b/cms/djangoapps/contentstore/tests/test_filters.py
index b6deb542f814..2f9dfce50813 100644
--- a/cms/djangoapps/contentstore/tests/test_filters.py
+++ b/cms/djangoapps/contentstore/tests/test_filters.py
@@ -74,7 +74,7 @@ def test_lms_url_requested_filter_executed(self):
self.course_key
)
- self.assertEqual(output.get('external_url'), urljoin('https://lms-url-creation', self.asset_url))
+ self.assertEqual(output.get('external_url'), urljoin('https://lms-url-creation', self.asset_url)) # noqa: PT009
@override_settings(OPEN_EDX_FILTERS_CONFIG={}, LMS_ROOT_URL="https://lms-base")
def test_lms_url_requested_without_filter_configuration(self):
@@ -95,4 +95,4 @@ def test_lms_url_requested_without_filter_configuration(self):
self.course_key
)
- self.assertEqual(output.get('external_url'), urljoin('https://lms-base', self.asset_url))
+ self.assertEqual(output.get('external_url'), urljoin('https://lms-base', self.asset_url)) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_i18n.py b/cms/djangoapps/contentstore/tests/test_i18n.py
index 0db5a03aa9a7..1aaab8b52e36 100644
--- a/cms/djangoapps/contentstore/tests/test_i18n.py
+++ b/cms/djangoapps/contentstore/tests/test_i18n.py
@@ -72,8 +72,8 @@ def get_block_i18n_service(self, block):
return the block i18n service.
"""
i18n_service = self.block.runtime.service(block, 'i18n')
- self.assertIsNotNone(i18n_service)
- self.assertIsInstance(i18n_service, XBlockI18nService)
+ self.assertIsNotNone(i18n_service) # noqa: PT009
+ self.assertIsInstance(i18n_service, XBlockI18nService) # noqa: PT009
return i18n_service
def test_django_service_translation_works(self):
@@ -111,10 +111,10 @@ def __exit__(self, _type, _value, _traceback):
# wrap the ugettext functions so that 'XYZ ' will prefix each translation
with wrap_ugettext_with_xyz(french_translation):
- self.assertEqual(i18n_service.ugettext(self.test_language), 'XYZ dummy language')
+ self.assertEqual(i18n_service.ugettext(self.test_language), 'XYZ dummy language') # noqa: PT009
# Check that the old ugettext has been put back into place
- self.assertEqual(i18n_service.ugettext(self.test_language), 'dummy language')
+ self.assertEqual(i18n_service.ugettext(self.test_language), 'dummy language') # noqa: PT009
@mock.patch('django.utils.translation.gettext', mock.Mock(return_value='XYZ-TEST-LANGUAGE'))
def test_django_translator_in_use_with_empty_block(self):
@@ -122,7 +122,7 @@ def test_django_translator_in_use_with_empty_block(self):
Test: Django default translator should in use if we have an empty block
"""
i18n_service = XBlockI18nService(None)
- self.assertEqual(i18n_service.ugettext(self.test_language), 'XYZ-TEST-LANGUAGE')
+ self.assertEqual(i18n_service.ugettext(self.test_language), 'XYZ-TEST-LANGUAGE') # noqa: PT009
@mock.patch('django.utils.translation.gettext', mock.Mock(return_value='XYZ-TEST-LANGUAGE'))
def test_message_catalog_translations(self):
@@ -140,24 +140,24 @@ def test_message_catalog_translations(self):
with mock.patch('gettext.translation', return_value=_translator(domain='text', localedir=localedir,
languages=[get_language()])):
i18n_service = self.get_block_i18n_service(self.block)
- self.assertEqual(i18n_service.ugettext('Hello'), 'es-hello-world')
+ self.assertEqual(i18n_service.ugettext('Hello'), 'es-hello-world') # noqa: PT009
translation.activate("ar")
with mock.patch('gettext.translation', return_value=_translator(domain='text', localedir=localedir,
languages=[get_language()])):
i18n_service = self.get_block_i18n_service(self.block)
- self.assertEqual(i18n_service.gettext('Hello'), 'Hello')
- self.assertNotEqual(i18n_service.gettext('Hello'), 'fr-hello-world')
- self.assertNotEqual(i18n_service.gettext('Hello'), 'es-hello-world')
+ self.assertEqual(i18n_service.gettext('Hello'), 'Hello') # noqa: PT009
+ self.assertNotEqual(i18n_service.gettext('Hello'), 'fr-hello-world') # noqa: PT009
+ self.assertNotEqual(i18n_service.gettext('Hello'), 'es-hello-world') # noqa: PT009
translation.activate("fr")
with mock.patch('gettext.translation', return_value=_translator(domain='text', localedir=localedir,
languages=[get_language()])):
i18n_service = self.get_block_i18n_service(self.block)
- self.assertEqual(i18n_service.ugettext('Hello'), 'fr-hello-world')
+ self.assertEqual(i18n_service.ugettext('Hello'), 'fr-hello-world') # noqa: PT009
def test_i18n_service_callable(self):
"""
Test: i18n service should be callable in studio.
"""
- self.assertTrue(callable(self.block.runtime._services.get('i18n'))) # pylint: disable=protected-access
+ self.assertTrue(callable(self.block.runtime._services.get('i18n'))) # pylint: disable=protected-access # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_import.py b/cms/djangoapps/contentstore/tests/test_import.py
index ff5f4f39603a..d7e8d7905842 100644
--- a/cms/djangoapps/contentstore/tests/test_import.py
+++ b/cms/djangoapps/contentstore/tests/test_import.py
@@ -25,7 +25,7 @@
from xmodule.modulestore.xml_importer import import_course_from_xml
TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
-TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex
+TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex # noqa: UP031
TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT
@@ -72,7 +72,7 @@ def load_test_import_course(self, target_id=None, create_if_not_present=True, mo
)
course_id = module_store.make_course_key('edX', 'test_import_course', '2012_Fall')
course = module_store.get_course(course_id)
- self.assertIsNotNone(course)
+ self.assertIsNotNone(course) # noqa: PT009
return module_store, content_store, course
@@ -89,7 +89,7 @@ def test_import_course_into_similar_namespace(self):
target_id=course.id,
verbose=True,
)
- self.assertEqual(len(course_items), 1)
+ self.assertEqual(len(course_items), 1) # noqa: PT009
def test_unicode_chars_in_course_name_import(self):
"""
@@ -109,10 +109,10 @@ def test_unicode_chars_in_course_name_import(self):
)
course = module_store.get_course(course_id)
- self.assertIsNotNone(course)
+ self.assertIsNotNone(course) # noqa: PT009
# test that course 'display_name' same as imported course 'display_name'
- self.assertEqual(course.display_name, "Φυσικά το όνομα Unicode")
+ self.assertEqual(course.display_name, "Φυσικά το όνομα Unicode") # noqa: PT009
def test_static_import(self):
'''
@@ -122,9 +122,9 @@ def test_static_import(self):
# make sure we have ONE asset in our contentstore ("should_be_imported.html")
all_assets, count = content_store.get_all_content_for_course(course.id)
- print("len(all_assets)=%d" % len(all_assets))
- self.assertEqual(len(all_assets), 1)
- self.assertEqual(count, 1)
+ print("len(all_assets)=%d" % len(all_assets)) # noqa: UP031
+ self.assertEqual(len(all_assets), 1) # noqa: PT009
+ self.assertEqual(count, 1) # noqa: PT009
content = None
try:
@@ -133,11 +133,11 @@ def test_static_import(self):
except NotFoundError:
pass
- self.assertIsNotNone(content)
+ self.assertIsNotNone(content) # noqa: PT009
# make sure course.static_asset_path is correct
print(f"static_asset_path = {course.static_asset_path}")
- self.assertEqual(course.static_asset_path, 'test_import_course')
+ self.assertEqual(course.static_asset_path, 'test_import_course') # noqa: PT009
def test_asset_import_nostatic(self):
'''
@@ -157,8 +157,8 @@ def test_asset_import_nostatic(self):
# make sure we have NO assets in our contentstore
all_assets, count = content_store.get_all_content_for_course(course.id)
- self.assertEqual(all_assets, [])
- self.assertEqual(count, 0)
+ self.assertEqual(all_assets, []) # noqa: PT009
+ self.assertEqual(count, 0) # noqa: PT009
def test_no_static_link_rewrites_on_import(self):
module_store = modulestore()
@@ -169,15 +169,15 @@ def test_no_static_link_rewrites_on_import(self):
course_key = courses[0].id
handouts = module_store.get_item(course_key.make_usage_key('course_info', 'handouts'))
- self.assertIn('/static/', handouts.data)
+ self.assertIn('/static/', handouts.data) # noqa: PT009
handouts = module_store.get_item(course_key.make_usage_key('html', 'toyhtml'))
- self.assertIn('/static/', handouts.data)
+ self.assertIn('/static/', handouts.data) # noqa: PT009
def test_tab_name_imports_correctly(self):
_module_store, _content_store, course = self.load_test_import_course()
print(f"course tabs = {course.tabs}")
- self.assertEqual(course.tabs[1]['name'], 'Syllabus')
+ self.assertEqual(course.tabs[1]['name'], 'Syllabus') # noqa: PT009
def test_reimport(self):
__, __, course = self.load_test_import_course(create_if_not_present=True)
@@ -200,16 +200,16 @@ def test_rewrite_reference_list(self):
conditional_block = module_store.get_item(
target_id.make_usage_key('conditional', 'condone')
)
- self.assertIsNotNone(conditional_block)
+ self.assertIsNotNone(conditional_block) # noqa: PT009
different_course_id = module_store.make_course_key('edX', 'different_course', 'course_run')
- self.assertListEqual(
+ self.assertListEqual( # noqa: PT009
[
target_id.make_usage_key('problem', 'choiceprob'),
different_course_id.make_usage_key('html', 'for_testing_import_rewrites')
],
conditional_block.sources_list
)
- self.assertListEqual(
+ self.assertListEqual( # noqa: PT009
[
target_id.make_usage_key('html', 'congrats'),
target_id.make_usage_key('html', 'secret_page')
@@ -253,13 +253,13 @@ def _verify_split_test_import(self, target_course_name, source_course_name, spli
split_test_block = module_store.get_item(
target_id.make_usage_key('split_test', split_test_name)
)
- self.assertIsNotNone(split_test_block)
+ self.assertIsNotNone(split_test_block) # noqa: PT009
remapped_verticals = {
key: target_id.make_usage_key('vertical', value) for key, value in groups_to_verticals.items()
}
- self.assertEqual(remapped_verticals, split_test_block.group_id_to_child)
+ self.assertEqual(remapped_verticals, split_test_block.group_id_to_child) # noqa: PT009
def test_video_components_present_while_import(self):
"""
@@ -277,7 +277,7 @@ def test_video_components_present_while_import(self):
vertical = module_store.get_item(re_course.id.make_usage_key('vertical', 'vertical_test'))
video = module_store.get_item(vertical.children[1])
- self.assertEqual(video.display_name, 'default')
+ self.assertEqual(video.display_name, 'default') # noqa: PT009
@override_settings(
COURSE_IMPORT_EXPORT_STORAGE="cms.djangoapps.contentstore.storage.ImportExportS3Storage",
@@ -290,7 +290,7 @@ def test_video_components_present_while_import(self):
def test_default_storage(self):
""" Ensure the default storage is invoked, even if course export storage is configured """
storage = storages["default"]
- self.assertEqual(storage.__class__.__name__, "FileSystemStorage")
+ self.assertEqual(storage.__class__.__name__, "FileSystemStorage") # noqa: PT009
@override_settings(
COURSE_IMPORT_EXPORT_STORAGE="cms.djangoapps.contentstore.storage.ImportExportS3Storage",
@@ -307,8 +307,8 @@ def test_resolve_happy_path_storage(self):
storage_key="course_import_export",
legacy_setting_key="COURSE_IMPORT_EXPORT_STORAGE"
)
- self.assertEqual(storage.__class__.__name__, "ImportExportS3Storage")
- self.assertEqual(storage.bucket_name, "bucket_name_test")
+ self.assertEqual(storage.__class__.__name__, "ImportExportS3Storage") # noqa: PT009
+ self.assertEqual(storage.bucket_name, "bucket_name_test") # noqa: PT009
@override_settings()
def test_resolve_storage_with_no_config(self):
@@ -319,7 +319,7 @@ def test_resolve_storage_with_no_config(self):
storage_key="course_import_export",
legacy_setting_key="COURSE_IMPORT_EXPORT_STORAGE"
)
- self.assertEqual(storage.__class__.__name__, "FileSystemStorage")
+ self.assertEqual(storage.__class__.__name__, "FileSystemStorage") # noqa: PT009
@override_settings(
COURSE_IMPORT_EXPORT_STORAGE=None,
@@ -337,8 +337,8 @@ def test_resolve_storage_using_django5_settings(self):
storage_key="course_import_export",
legacy_setting_key="COURSE_IMPORT_EXPORT_STORAGE"
)
- self.assertEqual(storage.__class__.__name__, "ImportExportS3Storage")
- self.assertEqual(storage.bucket_name, "bucket_name_test")
+ self.assertEqual(storage.__class__.__name__, "ImportExportS3Storage") # noqa: PT009
+ self.assertEqual(storage.bucket_name, "bucket_name_test") # noqa: PT009
@override_settings(
STORAGES={
@@ -358,5 +358,5 @@ def test_resolve_storage_using_django5_settings_with_options(self):
storage_key="course_import_export",
legacy_setting_key="COURSE_IMPORT_EXPORT_STORAGE"
)
- self.assertEqual(storage.__class__.__name__, S3Boto3Storage.__name__)
- self.assertEqual(storage.bucket_name, "bucket_name_test")
+ self.assertEqual(storage.__class__.__name__, S3Boto3Storage.__name__) # noqa: PT009
+ self.assertEqual(storage.bucket_name, "bucket_name_test") # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_import_draft_order.py b/cms/djangoapps/contentstore/tests/test_import_draft_order.py
index f87efc043fbc..16ba4872655f 100644
--- a/cms/djangoapps/contentstore/tests/test_import_draft_order.py
+++ b/cms/djangoapps/contentstore/tests/test_import_draft_order.py
@@ -36,21 +36,21 @@ def test_order(self):
# 2 , 4 , 6 , 5 , and 0 respectively.
#
# '5a05be9d59fc4bb79282c94c9e6b88c7' and 'second' are public verticals.
- self.assertEqual(7, len(verticals))
- self.assertEqual(course_key.make_usage_key('vertical', 'z'), verticals[0])
- self.assertEqual(course_key.make_usage_key('vertical', '5a05be9d59fc4bb79282c94c9e6b88c7'), verticals[1])
- self.assertEqual(course_key.make_usage_key('vertical', 'a'), verticals[2])
- self.assertEqual(course_key.make_usage_key('vertical', 'second'), verticals[3])
- self.assertEqual(course_key.make_usage_key('vertical', 'b'), verticals[4])
- self.assertEqual(course_key.make_usage_key('vertical', 'd'), verticals[5])
- self.assertEqual(course_key.make_usage_key('vertical', 'c'), verticals[6])
+ self.assertEqual(7, len(verticals)) # noqa: PT009
+ self.assertEqual(course_key.make_usage_key('vertical', 'z'), verticals[0]) # noqa: PT009
+ self.assertEqual(course_key.make_usage_key('vertical', '5a05be9d59fc4bb79282c94c9e6b88c7'), verticals[1]) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(course_key.make_usage_key('vertical', 'a'), verticals[2]) # noqa: PT009
+ self.assertEqual(course_key.make_usage_key('vertical', 'second'), verticals[3]) # noqa: PT009
+ self.assertEqual(course_key.make_usage_key('vertical', 'b'), verticals[4]) # noqa: PT009
+ self.assertEqual(course_key.make_usage_key('vertical', 'd'), verticals[5]) # noqa: PT009
+ self.assertEqual(course_key.make_usage_key('vertical', 'c'), verticals[6]) # noqa: PT009
# Now also test that the verticals in a second sequential are correct.
sequential = store.get_item(course_key.make_usage_key('sequential', 'secondseq'))
verticals = sequential.children
# 'asecond' and 'zsecond' are drafts with 'index_in_children_list' 0 and 2, respectively.
# 'secondsubsection' is a public vertical.
- self.assertEqual(3, len(verticals))
- self.assertEqual(course_key.make_usage_key('vertical', 'asecond'), verticals[0])
- self.assertEqual(course_key.make_usage_key('vertical', 'secondsubsection'), verticals[1])
- self.assertEqual(course_key.make_usage_key('vertical', 'zsecond'), verticals[2])
+ self.assertEqual(3, len(verticals)) # noqa: PT009
+ self.assertEqual(course_key.make_usage_key('vertical', 'asecond'), verticals[0]) # noqa: PT009
+ self.assertEqual(course_key.make_usage_key('vertical', 'secondsubsection'), verticals[1]) # noqa: PT009
+ self.assertEqual(course_key.make_usage_key('vertical', 'zsecond'), verticals[2]) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_import_pure_xblock.py b/cms/djangoapps/contentstore/tests/test_import_pure_xblock.py
index 0a0e8663bae3..8b998ff852ff 100644
--- a/cms/djangoapps/contentstore/tests/test_import_pure_xblock.py
+++ b/cms/djangoapps/contentstore/tests/test_import_pure_xblock.py
@@ -62,5 +62,5 @@ def _assert_import(self, course_dir, expected_field_val, has_draft=False):
xblock_location = courses[0].id.make_usage_key('stubxblock', 'xblock_test')
xblock = self.store.get_item(xblock_location)
- self.assertTrue(isinstance(xblock, StubXBlock))
- self.assertEqual(xblock.test_field, expected_field_val)
+ self.assertTrue(isinstance(xblock, StubXBlock)) # noqa: PT009
+ self.assertEqual(xblock.test_field, expected_field_val) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_libraries.py b/cms/djangoapps/contentstore/tests/test_libraries.py
index 5b20b2c254c9..29a194fd017e 100644
--- a/cms/djangoapps/contentstore/tests/test_libraries.py
+++ b/cms/djangoapps/contentstore/tests/test_libraries.py
@@ -66,10 +66,10 @@ def _create_library(self, org="org", library="lib", display_name="Test Library")
'library': library,
'display_name': display_name,
})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
lib_info = parse_json(response)
lib_key = CourseKey.from_string(lib_info['library_key'])
- self.assertIsInstance(lib_key, LibraryLocator)
+ self.assertIsInstance(lib_key, LibraryLocator) # noqa: PT009
return lib_key
def _add_library_content_block(self, course, library_key, publish_item=False, other_settings=None):
@@ -110,7 +110,7 @@ def _upgrade_and_sync(self, lib_content_block, status_code_expected=200):
kwargs={'handler': 'upgrade_and_sync'}
)
response = self.client.ajax_post(handler_url)
- self.assertEqual(response.status_code, status_code_expected)
+ self.assertEqual(response.status_code, status_code_expected) # noqa: PT009
return modulestore().get_item(lib_content_block.location)
def _bind_block(self, block, user=None):
@@ -142,7 +142,7 @@ def _list_libraries(self):
Use the REST API to get a list of libraries visible to the current user.
"""
response = self.client.get_json(LIBRARY_REST_URL)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
return parse_json(response)
@@ -169,7 +169,7 @@ def test_max_items(self, num_to_create, num_to_select, num_expected):
course = CourseFactory.create()
lc_block = self._add_library_content_block(course, self.lib_key, other_settings={'max_count': num_to_select})
- self.assertEqual(len(lc_block.children), 0)
+ self.assertEqual(len(lc_block.children), 0) # noqa: PT009
lc_block = self._upgrade_and_sync(lc_block)
# Now, we want to make sure that .children has the total # of potential
@@ -178,8 +178,8 @@ def test_max_items(self, num_to_create, num_to_select, num_expected):
# In order to be able to call get_child_blocks(), we must first
# call bind_for_student:
self._bind_block(lc_block)
- self.assertEqual(len(lc_block.children), num_to_create)
- self.assertEqual(len(lc_block.get_child_blocks()), num_expected)
+ self.assertEqual(len(lc_block.children), num_to_create) # noqa: PT009
+ self.assertEqual(len(lc_block.get_child_blocks()), num_expected) # noqa: PT009
def test_consistent_children(self):
"""
@@ -204,7 +204,7 @@ def get_child_of_lc_block(block):
Fetch the child shown to the current user.
"""
children = block.get_child_blocks()
- self.assertEqual(len(children), 1)
+ self.assertEqual(len(children), 1) # noqa: PT009
return children[0]
# Check which child a student will see:
@@ -224,9 +224,9 @@ def check():
lc_block = modulestore().get_item(lc_block_key) # Reload block from the database
self._bind_block(lc_block)
current_child = get_child_of_lc_block(lc_block)
- self.assertEqual(current_child.location, chosen_child.location)
- self.assertEqual(current_child.data, chosen_child.data)
- self.assertEqual(current_child.definition_locator.definition_id, chosen_child_defn_id)
+ self.assertEqual(current_child.location, chosen_child.location) # noqa: PT009
+ self.assertEqual(current_child.data, chosen_child.data) # noqa: PT009
+ self.assertEqual(current_child.definition_locator.definition_id, chosen_child_defn_id) # noqa: PT009
check()
# Refresh the children:
@@ -242,7 +242,7 @@ def test_definition_shared_with_library(self):
def_id1 = block1.definition_locator.definition_id
block2 = self._add_simple_content_block()
def_id2 = block2.definition_locator.definition_id
- self.assertNotEqual(def_id1, def_id2)
+ self.assertNotEqual(def_id1, def_id2) # noqa: PT009
# Next, create a course:
with modulestore().default_store(ModuleStoreEnum.Type.split):
@@ -254,7 +254,7 @@ def test_definition_shared_with_library(self):
for child_key in lc_block.children:
child = modulestore().get_item(child_key)
def_id = child.definition_locator.definition_id
- self.assertIn(def_id, (def_id1, def_id2))
+ self.assertIn(def_id, (def_id1, def_id2)) # noqa: PT009
def test_fields(self):
"""
@@ -271,8 +271,8 @@ def test_fields(self):
display_name=name_value,
data=data_value,
)
- self.assertEqual(lib_block.data, data_value)
- self.assertEqual(lib_block.display_name, name_value)
+ self.assertEqual(lib_block.data, data_value) # noqa: PT009
+ self.assertEqual(lib_block.display_name, name_value) # noqa: PT009
# Next, create a course:
with modulestore().default_store(ModuleStoreEnum.Type.split):
@@ -283,8 +283,8 @@ def test_fields(self):
lc_block = self._upgrade_and_sync(lc_block)
course_block = modulestore().get_item(lc_block.children[0])
- self.assertEqual(course_block.data, data_value)
- self.assertEqual(course_block.display_name, name_value)
+ self.assertEqual(course_block.data, data_value) # noqa: PT009
+ self.assertEqual(course_block.display_name, name_value) # noqa: PT009
def test_block_with_children(self):
"""
@@ -307,8 +307,8 @@ def test_block_with_children(self):
display_name=name_value,
data=data_value,
)
- self.assertEqual(child_block.data, data_value)
- self.assertEqual(child_block.display_name, name_value)
+ self.assertEqual(child_block.data, data_value) # noqa: PT009
+ self.assertEqual(child_block.display_name, name_value) # noqa: PT009
# Next, create a course:
with modulestore().default_store(ModuleStoreEnum.Type.split):
@@ -317,13 +317,13 @@ def test_block_with_children(self):
# Add a LibraryContent block to the course:
lc_block = self._add_library_content_block(course, self.lib_key)
lc_block = self._upgrade_and_sync(lc_block)
- self.assertEqual(len(lc_block.children), 1)
+ self.assertEqual(len(lc_block.children), 1) # noqa: PT009
course_vert_block = modulestore().get_item(lc_block.children[0])
- self.assertEqual(len(course_vert_block.children), 1)
+ self.assertEqual(len(course_vert_block.children), 1) # noqa: PT009
course_child_block = modulestore().get_item(course_vert_block.children[0])
- self.assertEqual(course_child_block.data, data_value)
- self.assertEqual(course_child_block.display_name, name_value)
+ self.assertEqual(course_child_block.data, data_value) # noqa: PT009
+ self.assertEqual(course_child_block.display_name, name_value) # noqa: PT009
def test_switch_to_unknown_source_library_preserves_settings(self):
"""
@@ -353,8 +353,8 @@ def test_switch_to_unknown_source_library_preserves_settings(self):
good_library_version = lc_block.source_library_version
assert good_library_id
assert good_library_version
- self.assertEqual(len(lc_block.children), 1)
- self.assertEqual(modulestore().get_item(lc_block.children[0]).data, data_value)
+ self.assertEqual(len(lc_block.children), 1) # noqa: PT009
+ self.assertEqual(modulestore().get_item(lc_block.children[0]).data, data_value) # noqa: PT009
# Now, change the block settings to have an invalid library key:
bad_library_id = "library-v1:NOT+FOUND"
@@ -362,7 +362,7 @@ def test_switch_to_unknown_source_library_preserves_settings(self):
lc_block.location,
{"source_library_id": bad_library_id},
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
lc_block = modulestore().get_item(lc_block.location)
# Source library id should be set to the new bad one...
@@ -370,8 +370,8 @@ def test_switch_to_unknown_source_library_preserves_settings(self):
# ...but old source library version should be preserved...
assert lc_block.source_library_version == good_library_version
# ...and children should not be deleted due to a bad setting.
- self.assertEqual(len(lc_block.children), 1)
- self.assertEqual(modulestore().get_item(lc_block.children[0]).data, data_value)
+ self.assertEqual(len(lc_block.children), 1) # noqa: PT009
+ self.assertEqual(modulestore().get_item(lc_block.children[0]).data, data_value) # noqa: PT009
# Attempting to force an upgrade (the user would have to do this through the API, as
# the UI wouldn't give them the option) returns a 400 and preserves the LC block's state.
@@ -384,8 +384,8 @@ def test_switch_to_unknown_source_library_preserves_settings(self):
# ...but old source library version should be preserved...
assert lc_block.source_library_version == good_library_version
# ...and children should not be deleted due to a bad setting.
- self.assertEqual(len(lc_block.children), 1)
- self.assertEqual(modulestore().get_item(lc_block.children[0]).data, data_value)
+ self.assertEqual(len(lc_block.children), 1) # noqa: PT009
+ self.assertEqual(modulestore().get_item(lc_block.children[0]).data, data_value) # noqa: PT009
def test_sync_if_source_library_changed(self):
"""
@@ -421,9 +421,9 @@ def test_sync_if_source_library_changed(self):
lc_block = self._upgrade_and_sync(lc_block)
# Sanity check the initial condition.
- self.assertEqual(len(lc_block.children), 1)
+ self.assertEqual(len(lc_block.children), 1) # noqa: PT009
html_block_1 = modulestore().get_item(lc_block.children[0])
- self.assertEqual(html_block_1.data, data1)
+ self.assertEqual(html_block_1.data, data1) # noqa: PT009
# Now, switch over to new library. Don't call upgrade_and_sync, because we are
# testing that it happens automatically.
@@ -431,13 +431,13 @@ def test_sync_if_source_library_changed(self):
lc_block.location,
{"source_library_id": str(library2key)},
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# Check that the course now has the new lib's new block.
lc_block = modulestore().get_item(lc_block.location)
- self.assertEqual(len(lc_block.children), 1)
+ self.assertEqual(len(lc_block.children), 1) # noqa: PT009
html_block_2 = modulestore().get_item(lc_block.children[0])
- self.assertEqual(html_block_2.data, data2)
+ self.assertEqual(html_block_2.data, data2) # noqa: PT009
def test_sync_if_capa_type_changed(self):
""" Tests that children are automatically refreshed if capa type field changes """
@@ -466,29 +466,29 @@ def test_sync_if_capa_type_changed(self):
# Add a LibraryContent block to the course:
lc_block = self._add_library_content_block(course, self.lib_key)
lc_block = self._upgrade_and_sync(lc_block)
- self.assertEqual(len(lc_block.children), 2)
+ self.assertEqual(len(lc_block.children), 2) # noqa: PT009
resp = self._update_block(
lc_block.location,
{"capa_type": 'optionresponse'},
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
lc_block = modulestore().get_item(lc_block.location)
- self.assertEqual(len(lc_block.children), 1)
+ self.assertEqual(len(lc_block.children), 1) # noqa: PT009
html_block = modulestore().get_item(lc_block.children[0])
- self.assertEqual(html_block.display_name, name1)
+ self.assertEqual(html_block.display_name, name1) # noqa: PT009
resp = self._update_block(
lc_block.location,
{"capa_type": 'multiplechoiceresponse'},
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
lc_block = modulestore().get_item(lc_block.location)
- self.assertEqual(len(lc_block.children), 1)
+ self.assertEqual(len(lc_block.children), 1) # noqa: PT009
html_block = modulestore().get_item(lc_block.children[0])
- self.assertEqual(html_block.display_name, name2)
+ self.assertEqual(html_block.display_name, name2) # noqa: PT009
def test_library_filters(self):
"""
@@ -499,12 +499,12 @@ def test_library_filters(self):
self._create_library(library="l3", display_name="Library-Title-3", org='org-test1')
self._create_library(library="l4", display_name="Library-Title-4", org='org-test2')
- self.assertEqual(len(self.client.get_json(LIBRARY_REST_URL).json()), 5) # 1 more from self.setUp()
- self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?org=org-test1').json()), 2)
- self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=test-lib').json()), 2)
- self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=library-title').json()), 3)
- self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=library-').json()), 3)
- self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=org-test').json()), 3)
+ self.assertEqual(len(self.client.get_json(LIBRARY_REST_URL).json()), 5) # 1 more from self.setUp() # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?org=org-test1').json()), 2) # noqa: PT009
+ self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=test-lib').json()), 2) # noqa: PT009
+ self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=library-title').json()), 3) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=library-').json()), 3) # noqa: PT009
+ self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=org-test').json()), 3) # noqa: PT009
@ddt.ddt
@@ -528,14 +528,14 @@ def _login_as_non_staff_user(self, logout_first=True):
def _assert_cannot_create_library(self, org="org", library="libfail", expected_code=403):
""" Ensure the current user is not able to create a library. """
- self.assertGreaterEqual(expected_code, 300)
+ self.assertGreaterEqual(expected_code, 300) # noqa: PT009
response = self.client.ajax_post(
LIBRARY_REST_URL,
{'org': org, 'library': library, 'display_name': "Irrelevant"}
)
- self.assertEqual(response.status_code, expected_code)
+ self.assertEqual(response.status_code, expected_code) # noqa: PT009
key = LibraryLocator(org=org, library=library)
- self.assertEqual(modulestore().get_library(key), None)
+ self.assertEqual(modulestore().get_library(key), None) # noqa: PT009
def _can_access_library(self, library):
"""
@@ -548,7 +548,7 @@ def _can_access_library(self, library):
else:
lib_key = library.location.library_key
response = self.client.get(reverse_library_url('library_handler', str(lib_key)))
- self.assertIn(response.status_code, (200, 302, 403))
+ self.assertIn(response.status_code, (200, 302, 403)) # noqa: PT009
return response.status_code == 200
def tearDown(self):
@@ -563,10 +563,10 @@ def test_creation(self):
The user that creates a library should have instructor (admin) and staff permissions
"""
# self.library has been auto-created by the staff user.
- self.assertTrue(has_studio_write_access(self.user, self.lib_key))
- self.assertTrue(has_studio_read_access(self.user, self.lib_key))
+ self.assertTrue(has_studio_write_access(self.user, self.lib_key)) # noqa: PT009
+ self.assertTrue(has_studio_read_access(self.user, self.lib_key)) # noqa: PT009
# Make sure the user was actually assigned the instructor role and not just using is_staff superpowers:
- self.assertTrue(CourseInstructorRole(self.lib_key).has_user(self.user))
+ self.assertTrue(CourseInstructorRole(self.lib_key).has_user(self.user)) # noqa: PT009
# Now log out and ensure we are forbidden from creating a library:
self.client.logout()
@@ -582,7 +582,7 @@ def test_creation(self):
with patch.dict('django.conf.settings.FEATURES', {'ENABLE_CREATOR_GROUP': True}):
lib_key2 = self._create_library(library="lib2", display_name="Test Library 2")
library2 = modulestore().get_library(lib_key2)
- self.assertIsNotNone(library2)
+ self.assertIsNotNone(library2) # noqa: PT009
@ddt.data(
CourseInstructorRole,
@@ -601,19 +601,19 @@ def test_acccess(self, access_role):
# non_staff_user shouldn't be able to access any libraries:
lib_list = self._list_libraries()
- self.assertEqual(len(lib_list), 0)
- self.assertFalse(self._can_access_library(self.library))
- self.assertFalse(self._can_access_library(library2_key))
+ self.assertEqual(len(lib_list), 0) # noqa: PT009
+ self.assertFalse(self._can_access_library(self.library)) # noqa: PT009
+ self.assertFalse(self._can_access_library(library2_key)) # noqa: PT009
# Now manually intervene to give non_staff_user access to library2_key:
access_role(library2_key).add_users(self.non_staff_user)
# Now non_staff_user should be able to access library2_key only:
lib_list = self._list_libraries()
- self.assertEqual(len(lib_list), 1)
- self.assertEqual(lib_list[0]["library_key"], str(library2_key))
- self.assertTrue(self._can_access_library(library2_key))
- self.assertFalse(self._can_access_library(self.library))
+ self.assertEqual(len(lib_list), 1) # noqa: PT009
+ self.assertEqual(lib_list[0]["library_key"], str(library2_key)) # noqa: PT009
+ self.assertTrue(self._can_access_library(library2_key)) # noqa: PT009
+ self.assertFalse(self._can_access_library(self.library)) # noqa: PT009
@ddt.data(
OrgStaffRole,
@@ -637,11 +637,11 @@ def test_org_based_access(self, org_access_role):
# Now non_staff_user should be able to access lib_key_pacific only:
lib_list = self._list_libraries()
- self.assertEqual(len(lib_list), 1)
- self.assertEqual(lib_list[0]["library_key"], str(lib_key_pacific))
- self.assertTrue(self._can_access_library(lib_key_pacific))
- self.assertFalse(self._can_access_library(lib_key_atlantic))
- self.assertFalse(self._can_access_library(self.lib_key))
+ self.assertEqual(len(lib_list), 1) # noqa: PT009
+ self.assertEqual(lib_list[0]["library_key"], str(lib_key_pacific)) # noqa: PT009
+ self.assertTrue(self._can_access_library(lib_key_pacific)) # noqa: PT009
+ self.assertFalse(self._can_access_library(lib_key_atlantic)) # noqa: PT009
+ self.assertFalse(self._can_access_library(self.lib_key)) # noqa: PT009
@ddt.data(True, False)
def test_read_only_role(self, use_org_level_role):
@@ -653,26 +653,26 @@ def test_read_only_role(self, use_org_level_role):
# Login as a non_staff_user:
self._login_as_non_staff_user()
- self.assertFalse(self._can_access_library(self.library))
+ self.assertFalse(self._can_access_library(self.library)) # noqa: PT009
block_url = reverse_usage_url('xblock_handler', block.location)
def can_read_block():
""" Check if studio lets us view the XBlock in the library """
response = self.client.get_json(block_url)
- self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous
+ self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous # noqa: PT009
return response.status_code == 200
def can_edit_block():
""" Check if studio lets us edit the XBlock in the library """
response = self.client.ajax_post(block_url)
- self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous
+ self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous # noqa: PT009
return response.status_code == 200
def can_delete_block():
""" Check if studio lets us delete the XBlock in the library """
response = self.client.delete(block_url)
- self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous
+ self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous # noqa: PT009
return response.status_code == 200
def can_copy_block():
@@ -681,7 +681,7 @@ def can_copy_block():
'parent_locator': str(self.library.location),
'duplicate_source_locator': str(block.location),
})
- self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous
+ self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous # noqa: PT009
return response.status_code == 200
def can_create_block():
@@ -689,15 +689,15 @@ def can_create_block():
response = self.client.ajax_post(reverse_url('xblock_handler'), {
'parent_locator': str(self.library.location), 'category': 'html',
})
- self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous
+ self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous # noqa: PT009
return response.status_code == 200
# Check that we do not have read or write access to block:
- self.assertFalse(can_read_block())
- self.assertFalse(can_edit_block())
- self.assertFalse(can_delete_block())
- self.assertFalse(can_copy_block())
- self.assertFalse(can_create_block())
+ self.assertFalse(can_read_block()) # noqa: PT009
+ self.assertFalse(can_edit_block()) # noqa: PT009
+ self.assertFalse(can_delete_block()) # noqa: PT009
+ self.assertFalse(can_copy_block()) # noqa: PT009
+ self.assertFalse(can_create_block()) # noqa: PT009
# Give non_staff_user read-only permission:
if use_org_level_role:
@@ -705,12 +705,12 @@ def can_create_block():
else:
LibraryUserRole(self.lib_key).add_users(self.non_staff_user)
- self.assertTrue(self._can_access_library(self.library))
- self.assertTrue(can_read_block())
- self.assertFalse(can_edit_block())
- self.assertFalse(can_delete_block())
- self.assertFalse(can_copy_block())
- self.assertFalse(can_create_block())
+ self.assertTrue(self._can_access_library(self.library)) # noqa: PT009
+ self.assertTrue(can_read_block()) # noqa: PT009
+ self.assertFalse(can_edit_block()) # noqa: PT009
+ self.assertFalse(can_delete_block()) # noqa: PT009
+ self.assertFalse(can_copy_block()) # noqa: PT009
+ self.assertFalse(can_create_block()) # noqa: PT009
@ddt.data(
(LibraryUserRole, CourseStaffRole, True),
@@ -743,9 +743,9 @@ def test_duplicate_across_courses(self, library_role, course_role, expected_resu
'parent_locator': str(course.location),
'duplicate_source_locator': str(block.location),
})
- self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous
+ self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous # noqa: PT009
duplicate_action_allowed = (response.status_code == 200)
- self.assertEqual(duplicate_action_allowed, expected_result)
+ self.assertEqual(duplicate_action_allowed, expected_result) # noqa: PT009
@ddt.data(
(LibraryUserRole, CourseStaffRole, True),
@@ -780,7 +780,7 @@ def test_upgrade_and_sync_handler_content_permissions(self, library_role, course
# We must use the CMS's module system in order to get permissions checks.
self._bind_block(lc_block, user=self.non_staff_user)
lc_block = self._upgrade_and_sync(lc_block, status_code_expected=200 if expected_result else 403)
- self.assertEqual(len(lc_block.children), 1 if expected_result else 0)
+ self.assertEqual(len(lc_block.children), 1 if expected_result else 0) # noqa: PT009
def test_studio_user_permissions(self):
"""
@@ -818,27 +818,27 @@ def _get_settings_html():
edit_view_url = reverse_usage_url("xblock_view_handler", lib_block.location, {"view_name": STUDIO_VIEW})
resp = self.client.get_json(edit_view_url)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
return parse_json(resp)['html']
self._login_as_staff_user()
staff_settings_html = _get_settings_html()
- self.assertIn('staff_lib_1', staff_settings_html)
- self.assertIn('staff_lib_2', staff_settings_html)
- self.assertIn('admin_lib_1', staff_settings_html)
- self.assertIn('admin_lib_2', staff_settings_html)
+ self.assertIn('staff_lib_1', staff_settings_html) # noqa: PT009
+ self.assertIn('staff_lib_2', staff_settings_html) # noqa: PT009
+ self.assertIn('admin_lib_1', staff_settings_html) # noqa: PT009
+ self.assertIn('admin_lib_2', staff_settings_html) # noqa: PT009
self._login_as_non_staff_user()
response = self.client.get_json(LIBRARY_REST_URL)
staff_libs = parse_json(response)
- self.assertEqual(2, len(staff_libs))
+ self.assertEqual(2, len(staff_libs)) # noqa: PT009
non_staff_settings_html = _get_settings_html()
- self.assertIn('staff_lib_1', non_staff_settings_html)
- self.assertIn('staff_lib_2', non_staff_settings_html)
- self.assertNotIn('admin_lib_1', non_staff_settings_html)
- self.assertNotIn('admin_lib_2', non_staff_settings_html)
+ self.assertIn('staff_lib_1', non_staff_settings_html) # noqa: PT009
+ self.assertIn('staff_lib_2', non_staff_settings_html) # noqa: PT009
+ self.assertNotIn('admin_lib_1', non_staff_settings_html) # noqa: PT009
+ self.assertNotIn('admin_lib_2', non_staff_settings_html) # noqa: PT009
@ddt.ddt
@@ -892,11 +892,11 @@ def test_overrides(self):
self.problem_in_course = modulestore().get_item(self.lc_block.children[0])
problem2_in_course = modulestore().get_item(lc_block2.children[0])
- self.assertEqual(self.problem_in_course.display_name, new_display_name)
- self.assertEqual(self.problem_in_course.weight, new_weight)
+ self.assertEqual(self.problem_in_course.display_name, new_display_name) # noqa: PT009
+ self.assertEqual(self.problem_in_course.weight, new_weight) # noqa: PT009
- self.assertEqual(problem2_in_course.display_name, self.original_display_name)
- self.assertEqual(problem2_in_course.weight, self.original_weight)
+ self.assertEqual(problem2_in_course.display_name, self.original_display_name) # noqa: PT009
+ self.assertEqual(problem2_in_course.weight, self.original_weight) # noqa: PT009
def test_reset_override(self):
"""
@@ -909,8 +909,8 @@ def test_reset_override(self):
modulestore().update_item(self.problem_in_course, self.user.id)
self.problem_in_course = modulestore().get_item(self.problem_in_course.location)
- self.assertEqual(self.problem_in_course.display_name, new_display_name)
- self.assertEqual(self.problem_in_course.weight, new_weight)
+ self.assertEqual(self.problem_in_course.display_name, new_display_name) # noqa: PT009
+ self.assertEqual(self.problem_in_course.weight, new_weight) # noqa: PT009
# Reset:
for field_name in ["display_name", "weight"]:
@@ -920,8 +920,8 @@ def test_reset_override(self):
modulestore().update_item(self.problem_in_course, self.user.id)
self.problem_in_course = modulestore().get_item(self.problem_in_course.location)
- self.assertEqual(self.problem_in_course.display_name, self.original_display_name)
- self.assertEqual(self.problem_in_course.weight, self.original_weight)
+ self.assertEqual(self.problem_in_course.display_name, self.original_display_name) # noqa: PT009
+ self.assertEqual(self.problem_in_course.weight, self.original_weight) # noqa: PT009
def test_consistent_definitions(self):
"""
@@ -931,7 +931,7 @@ def test_consistent_definitions(self):
This test is specific to split mongo.
"""
definition_id = self.problem.definition_locator.definition_id
- self.assertEqual(self.problem_in_course.definition_locator.definition_id, definition_id)
+ self.assertEqual(self.problem_in_course.definition_locator.definition_id, definition_id) # noqa: PT009
# Now even if we change some Scope.settings fields and refresh, the definition should be unchanged
self.problem.weight = 20
@@ -940,8 +940,8 @@ def test_consistent_definitions(self):
self.lc_block = self._upgrade_and_sync(self.lc_block)
self.problem_in_course = modulestore().get_item(self.problem_in_course.location)
- self.assertEqual(self.problem.definition_locator.definition_id, definition_id)
- self.assertEqual(self.problem_in_course.definition_locator.definition_id, definition_id)
+ self.assertEqual(self.problem.definition_locator.definition_id, definition_id) # noqa: PT009
+ self.assertEqual(self.problem_in_course.definition_locator.definition_id, definition_id) # noqa: PT009
@ddt.data(False, True)
def test_persistent_overrides(self, duplicate):
@@ -964,8 +964,8 @@ def test_persistent_overrides(self, duplicate):
self.problem_in_course = modulestore().get_item(self.lc_block.children[0])
else:
self.problem_in_course = modulestore().get_item(self.problem_in_course.location)
- self.assertEqual(self.problem_in_course.display_name, new_display_name)
- self.assertEqual(self.problem_in_course.weight, new_weight)
+ self.assertEqual(self.problem_in_course.display_name, new_display_name) # noqa: PT009
+ self.assertEqual(self.problem_in_course.weight, new_weight) # noqa: PT009
# Change the settings in the library version:
self.problem.display_name = "X"
@@ -977,9 +977,9 @@ def test_persistent_overrides(self, duplicate):
self.lc_block = self._upgrade_and_sync(self.lc_block)
self.problem_in_course = modulestore().get_item(self.problem_in_course.location)
- self.assertEqual(self.problem_in_course.display_name, new_display_name)
- self.assertEqual(self.problem_in_course.weight, new_weight)
- self.assertEqual(self.problem_in_course.data, new_data_value)
+ self.assertEqual(self.problem_in_course.display_name, new_display_name) # noqa: PT009
+ self.assertEqual(self.problem_in_course.weight, new_weight) # noqa: PT009
+ self.assertEqual(self.problem_in_course.data, new_data_value) # noqa: PT009
def test_duplicated_version(self):
"""
@@ -987,8 +987,8 @@ def test_duplicated_version(self):
the new block will use the old library version and not the new one.
"""
store = modulestore()
- self.assertEqual(len(self.library.children), 1)
- self.assertEqual(len(self.lc_block.children), 1)
+ self.assertEqual(len(self.library.children), 1) # noqa: PT009
+ self.assertEqual(len(self.lc_block.children), 1) # noqa: PT009
# Edit the only problem in the library:
self.problem.display_name = "--changed in library--"
@@ -1005,28 +1005,28 @@ def test_duplicated_version(self):
self.library = store.get_library(self.lib_key)
# The library has changed...
- self.assertEqual(len(self.library.children), 2)
+ self.assertEqual(len(self.library.children), 2) # noqa: PT009
# But the block hasn't.
self.lc_block = store.get_item(self.lc_block.location)
- self.assertEqual(len(self.lc_block.children), 1)
- self.assertEqual(self.problem_in_course.location, self.lc_block.children[0])
- self.assertEqual(self.problem_in_course.display_name, self.original_display_name)
+ self.assertEqual(len(self.lc_block.children), 1) # noqa: PT009
+ self.assertEqual(self.problem_in_course.location, self.lc_block.children[0]) # noqa: PT009
+ self.assertEqual(self.problem_in_course.display_name, self.original_display_name) # noqa: PT009
# Duplicate self.lc_block:
duplicate = store.get_item(
duplicate_block(self.course.location, self.lc_block.location, self.user)
)
# The duplicate should have identical children to the original:
- self.assertTrue(self.lc_block.source_library_version)
- self.assertEqual(self.lc_block.source_library_version, duplicate.source_library_version)
- self.assertEqual(len(duplicate.children), 1)
+ self.assertTrue(self.lc_block.source_library_version) # noqa: PT009
+ self.assertEqual(self.lc_block.source_library_version, duplicate.source_library_version) # noqa: PT009
+ self.assertEqual(len(duplicate.children), 1) # noqa: PT009
problem2_in_course = store.get_item(duplicate.children[0])
- self.assertEqual(problem2_in_course.display_name, self.original_display_name)
+ self.assertEqual(problem2_in_course.display_name, self.original_display_name) # noqa: PT009
# Refresh our reference to the block
self.lc_block = self._upgrade_and_sync(self.lc_block)
self.problem_in_course = store.get_item(self.problem_in_course.location)
# and the block has changed too.
- self.assertEqual(len(self.lc_block.children), 2)
+ self.assertEqual(len(self.lc_block.children), 2) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_orphan.py b/cms/djangoapps/contentstore/tests/test_orphan.py
index 63bf0e012997..312089a437ed 100644
--- a/cms/djangoapps/contentstore/tests/test_orphan.py
+++ b/cms/djangoapps/contentstore/tests/test_orphan.py
@@ -73,7 +73,7 @@ def assertOrphanCount(self, course_key, number):
Asserts that we have the expected count of orphans
for a given course_key
"""
- self.assertEqual(len(self.store.get_orphans(course_key)), number)
+ self.assertEqual(len(self.store.get_orphans(course_key)), number) # noqa: PT009
class TestOrphan(TestOrphanBase):
@@ -94,13 +94,13 @@ def test_get_orphans(self):
HTTP_ACCEPT='application/json'
).content.decode('utf-8')
)
- self.assertEqual(len(orphans), 3, f"Wrong # {orphans}")
+ self.assertEqual(len(orphans), 3, f"Wrong # {orphans}") # noqa: PT009
location = course.location.replace(category='chapter', name='OrphanChapter')
- self.assertIn(str(location), orphans)
+ self.assertIn(str(location), orphans) # noqa: PT009
location = course.location.replace(category='vertical', name='OrphanVert')
- self.assertIn(str(location), orphans)
+ self.assertIn(str(location), orphans) # noqa: PT009
location = course.location.replace(category='html', name='OrphanHtml')
- self.assertIn(str(location), orphans)
+ self.assertIn(str(location), orphans) # noqa: PT009
def test_delete_orphans(self):
"""
@@ -115,11 +115,11 @@ def test_delete_orphans(self):
orphans = json.loads(
self.client.get(orphan_url, HTTP_ACCEPT='application/json').content.decode('utf-8')
)
- self.assertEqual(len(orphans), 0, f"Orphans not deleted {orphans}")
+ self.assertEqual(len(orphans), 0, f"Orphans not deleted {orphans}") # noqa: PT009
# make sure that any children with one orphan parent and one non-orphan
# parent are not deleted
- self.assertTrue(self.store.has_item(course.id.make_usage_key('html', "multi_parent_html")))
+ self.assertTrue(self.store.has_item(course.id.make_usage_key('html', "multi_parent_html"))) # noqa: PT009
def test_not_permitted(self):
"""
@@ -131,9 +131,9 @@ def test_not_permitted(self):
test_user_client, test_user = self.create_non_staff_authed_user_client()
CourseEnrollment.enroll(test_user, course.id)
response = test_user_client.get(orphan_url)
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
response = test_user_client.delete(orphan_url)
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
def test_path_to_location_for_orphan_vertical(self):
r"""
@@ -158,16 +158,16 @@ def test_path_to_location_for_orphan_vertical(self):
multi_parent_html = self.store.get_item(BlockUsageLocator(course.id, 'html', 'multi_parent_html'))
# Verify `OrphanVert` is an orphan
- self.assertIn(orphan_vertical.location, self.store.get_orphans(course.id))
+ self.assertIn(orphan_vertical.location, self.store.get_orphans(course.id)) # noqa: PT009
# Verify `multi_parent_html` is child of both `Vertical1` and `OrphanVert`
- self.assertIn(multi_parent_html.location, orphan_vertical.children)
- self.assertIn(multi_parent_html.location, vertical1.children)
+ self.assertIn(multi_parent_html.location, orphan_vertical.children) # noqa: PT009
+ self.assertIn(multi_parent_html.location, vertical1.children) # noqa: PT009
# HTML component has `vertical1` as its parent.
html_parent = self.store.get_parent_location(multi_parent_html.location)
- self.assertNotEqual(str(html_parent), str(orphan_vertical.location))
- self.assertEqual(str(html_parent), str(vertical1.location))
+ self.assertNotEqual(str(html_parent), str(orphan_vertical.location)) # noqa: PT009
+ self.assertEqual(str(html_parent), str(vertical1.location)) # noqa: PT009
# Get path of the `multi_parent_html` & verify path_to_location returns a expected path
path = path_to_location(self.store, multi_parent_html.location)
@@ -179,9 +179,9 @@ def test_path_to_location_for_orphan_vertical(self):
"",
path[-1]
)
- self.assertIsNotNone(path)
- self.assertEqual(len(path), 6)
- self.assertEqual(path, expected_path)
+ self.assertIsNotNone(path) # noqa: PT009
+ self.assertEqual(len(path), 6) # noqa: PT009
+ self.assertEqual(path, expected_path) # noqa: PT009
def test_path_to_location_for_orphan_chapter(self):
r"""
@@ -204,7 +204,7 @@ def test_path_to_location_for_orphan_chapter(self):
vertical1 = self.store.get_item(BlockUsageLocator(course.id, 'vertical', 'Vertical1'))
# Verify `OrhanChapter` is an orphan
- self.assertIn(orphan_chapter.location, self.store.get_orphans(course.id))
+ self.assertIn(orphan_chapter.location, self.store.get_orphans(course.id)) # noqa: PT009
# Create a vertical (`Vertical0`) in orphan chapter (`OrphanChapter`).
# OrphanChapter -> Vertical0
@@ -218,7 +218,7 @@ def test_path_to_location_for_orphan_chapter(self):
# Verify chapter1 is parent of vertical1.
vertical1_parent = self.store.get_parent_location(vertical1.location)
- self.assertEqual(str(vertical1_parent), str(chapter1.location))
+ self.assertEqual(str(vertical1_parent), str(chapter1.location)) # noqa: PT009
# Make `Vertical1` the parent of `HTML0`. So `HTML0` will have to parents (`Vertical0` & `Vertical1`)
vertical1.children.append(html.location)
@@ -227,7 +227,7 @@ def test_path_to_location_for_orphan_chapter(self):
# Get parent location & verify its either of the two verticals. As both parents are non-orphan,
# alphabetically least is returned
html_parent = self.store.get_parent_location(html.location)
- self.assertEqual(str(html_parent), str(vertical1.location))
+ self.assertEqual(str(html_parent), str(vertical1.location)) # noqa: PT009
# verify path_to_location returns a expected path
path = path_to_location(self.store, html.location)
@@ -239,6 +239,6 @@ def test_path_to_location_for_orphan_chapter(self):
"",
path[-1]
)
- self.assertIsNotNone(path)
- self.assertEqual(len(path), 6)
- self.assertEqual(path, expected_path)
+ self.assertIsNotNone(path) # noqa: PT009
+ self.assertEqual(len(path), 6) # noqa: PT009
+ self.assertEqual(path, expected_path) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_outlines.py b/cms/djangoapps/contentstore/tests/test_outlines.py
index 6586c9b84eee..3c0ceddfdfee 100644
--- a/cms/djangoapps/contentstore/tests/test_outlines.py
+++ b/cms/djangoapps/contentstore/tests/test_outlines.py
@@ -71,7 +71,7 @@ def test_empty_course_metadata(self):
# published_at
assert isinstance(outline.published_at, datetime)
assert outline.published_at == published_course.subtree_edited_on
- assert outline.published_at.tzinfo == timezone.utc
+ assert outline.published_at.tzinfo == timezone.utc # noqa: UP017
# published_version
assert isinstance(outline.published_version, str)
@@ -522,7 +522,7 @@ class OutlineFromModuleStoreTaskTestCase(ModuleStoreTestCase):
def test_task_invocation(self):
"""Test outline auto-creation after course publish"""
course_key = CourseKey.from_string("course-v1:TNL+7733+2021-01-21")
- with self.assertRaises(CourseOutlineData.DoesNotExist):
+ with self.assertRaises(CourseOutlineData.DoesNotExist): # noqa: PT027
get_course_outline(course_key)
course = CourseFactory.create(
diff --git a/cms/djangoapps/contentstore/tests/test_permissions.py b/cms/djangoapps/contentstore/tests/test_permissions.py
index a811dc31e995..86e77118426d 100644
--- a/cms/djangoapps/contentstore/tests/test_permissions.py
+++ b/cms/djangoapps/contentstore/tests/test_permissions.py
@@ -80,7 +80,7 @@ def test_get_all_users(self):
"""
# first check the course creator.has explicit access (don't use has_access as is_staff
# will trump the actual test)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
CourseInstructorRole(self.course_key).has_user(self.user),
"Didn't add creator as instructor."
)
@@ -101,7 +101,7 @@ def test_get_all_users(self):
user = users.pop()
group.add_users(user)
user_by_role[role].append(user)
- self.assertTrue(auth.has_course_author_access(user, self.course_key), f"{user} does not have access") # lint-amnesty, pylint: disable=line-too-long
+ self.assertTrue(auth.has_course_author_access(user, self.course_key), f"{user} does not have access") # lint-amnesty, pylint: disable=line-too-long # noqa: PT009
course_team_url = reverse_course_url('course_team_handler', self.course_key)
response = self.client.get_html(course_team_url)
@@ -134,9 +134,9 @@ def test_get_all_users(self):
if hasattr(user, '_roles'):
del user._roles
- self.assertTrue(auth.has_course_author_access(user, copy_course_key), f"{user} no copy access")
+ self.assertTrue(auth.has_course_author_access(user, copy_course_key), f"{user} no copy access") # noqa: PT009 # pylint: disable=line-too-long
if (role is OrgStaffRole) or (role is OrgInstructorRole):
auth.remove_users(self.user, role(self.course_key.org), user)
else:
auth.remove_users(self.user, role(self.course_key), user)
- self.assertFalse(auth.has_course_author_access(user, self.course_key), f"{user} remove didn't work") # lint-amnesty, pylint: disable=line-too-long
+ self.assertFalse(auth.has_course_author_access(user, self.course_key), f"{user} remove didn't work") # lint-amnesty, pylint: disable=line-too-long # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_proctoring.py b/cms/djangoapps/contentstore/tests/test_proctoring.py
index aa3d46bfd553..83b46ca2a063 100644
--- a/cms/djangoapps/contentstore/tests/test_proctoring.py
+++ b/cms/djangoapps/contentstore/tests/test_proctoring.py
@@ -52,27 +52,27 @@ def _verify_exam_data(self, sequence, expected_active):
"""
exams = get_all_exams_for_course(str(self.course.id))
- self.assertEqual(len(exams), 1)
+ self.assertEqual(len(exams), 1) # noqa: PT009
exam = exams[0]
if exam['is_proctored'] and not exam['is_practice_exam']:
# get the review policy object
exam_review_policy = get_review_policy_by_exam_id(exam['id'])
- self.assertEqual(exam_review_policy['review_policy'], sequence.exam_review_rules)
+ self.assertEqual(exam_review_policy['review_policy'], sequence.exam_review_rules) # noqa: PT009
if not exam['is_proctored'] and not exam['is_practice_exam']:
# the hide after due value only applies to timed exams
- self.assertEqual(exam['hide_after_due'], sequence.hide_after_due)
+ self.assertEqual(exam['hide_after_due'], sequence.hide_after_due) # noqa: PT009
- self.assertEqual(exam['course_id'], str(self.course.id))
- self.assertEqual(exam['content_id'], str(sequence.location))
- self.assertEqual(exam['exam_name'], sequence.display_name)
- self.assertEqual(exam['time_limit_mins'], sequence.default_time_limit_minutes)
- self.assertEqual(exam['is_proctored'], sequence.is_proctored_exam)
- self.assertEqual(exam['is_practice_exam'], sequence.is_practice_exam or sequence.is_onboarding_exam)
- self.assertEqual(exam['is_active'], expected_active)
- self.assertEqual(exam['backend'], self.course.proctoring_provider)
+ self.assertEqual(exam['course_id'], str(self.course.id)) # noqa: PT009
+ self.assertEqual(exam['content_id'], str(sequence.location)) # noqa: PT009
+ self.assertEqual(exam['exam_name'], sequence.display_name) # noqa: PT009
+ self.assertEqual(exam['time_limit_mins'], sequence.default_time_limit_minutes) # noqa: PT009
+ self.assertEqual(exam['is_proctored'], sequence.is_proctored_exam) # noqa: PT009
+ self.assertEqual(exam['is_practice_exam'], sequence.is_practice_exam or sequence.is_onboarding_exam) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(exam['is_active'], expected_active) # noqa: PT009
+ self.assertEqual(exam['backend'], self.course.proctoring_provider) # noqa: PT009
@ddt.data(
(False, True),
@@ -174,7 +174,7 @@ def test_unpublishing_proctored_exam(self):
listen_for_course_publish(self, self.course.id)
exams = get_all_exams_for_course(str(self.course.id))
- self.assertEqual(len(exams), 1)
+ self.assertEqual(len(exams), 1) # noqa: PT009
sequence.is_time_limited = False
sequence.is_proctored_exam = False
@@ -205,7 +205,7 @@ def test_dangling_exam(self):
listen_for_course_publish(self, self.course.id)
exams = get_all_exams_for_course(str(self.course.id))
- self.assertEqual(len(exams), 1)
+ self.assertEqual(len(exams), 1) # noqa: PT009
self.store.delete_item(chapter.location, self.user.id)
@@ -215,10 +215,10 @@ def test_dangling_exam(self):
# look through exam table, the dangling exam
# should be disabled
exams = get_all_exams_for_course(str(self.course.id))
- self.assertEqual(len(exams), 1)
+ self.assertEqual(len(exams), 1) # noqa: PT009
exam = exams[0]
- self.assertEqual(exam['is_active'], False)
+ self.assertEqual(exam['is_active'], False) # noqa: PT009
@patch.dict('django.conf.settings.FEATURES', {'ENABLE_SPECIAL_EXAMS': False})
def test_feature_flag_off(self):
@@ -240,7 +240,7 @@ def test_feature_flag_off(self):
listen_for_course_publish(self, self.course.id)
exams = get_all_exams_for_course(str(self.course.id))
- self.assertEqual(len(exams), 0)
+ self.assertEqual(len(exams), 0) # noqa: PT009
@ddt.data(
(True, False, 1),
@@ -279,7 +279,7 @@ def test_advanced_settings(self, enable_timed_exams, enable_proctored_exams, exp
# there shouldn't be any exams because we haven't enabled that
# advanced setting flag
exams = get_all_exams_for_course(str(self.course.id))
- self.assertEqual(len(exams), expected_count)
+ self.assertEqual(len(exams), expected_count) # noqa: PT009
def test_self_paced_no_due_dates(self):
self.course = CourseFactory.create(
@@ -336,7 +336,7 @@ def test_async_waffle_flag_publishes(self):
listen_for_course_publish(self, self.course.id)
exams = get_all_exams_for_course(str(self.course.id))
- self.assertEqual(len(exams), 1)
+ self.assertEqual(len(exams), 1) # noqa: PT009
self._verify_exam_data(sequence, True)
def test_async_waffle_flag_task(self):
diff --git a/cms/djangoapps/contentstore/tests/test_request_event.py b/cms/djangoapps/contentstore/tests/test_request_event.py
index c4d21f72497a..ee99dc12c934 100644
--- a/cms/djangoapps/contentstore/tests/test_request_event.py
+++ b/cms/djangoapps/contentstore/tests/test_request_event.py
@@ -23,7 +23,7 @@ def test_post_answers_to_log(self):
]
for request_params in requests:
response = self.client.post(reverse(cms_user_track), request_params)
- self.assertEqual(response.status_code, 204)
+ self.assertEqual(response.status_code, 204) # noqa: PT009
def test_get_answers_to_log(self):
"""
@@ -36,4 +36,4 @@ def test_get_answers_to_log(self):
]
for request_params in requests:
response = self.client.get(reverse(cms_user_track), request_params)
- self.assertEqual(response.status_code, 204)
+ self.assertEqual(response.status_code, 204) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/test_signals.py b/cms/djangoapps/contentstore/tests/test_signals.py
index 8e9a0a915ed2..8cfb01730664 100644
--- a/cms/djangoapps/contentstore/tests/test_signals.py
+++ b/cms/djangoapps/contentstore/tests/test_signals.py
@@ -38,6 +38,6 @@ def test_locked(self, lock_available, compute_grades_async_mock, add_mock):
handle_grading_policy_changed(sender, course_key=str(self.course.id))
cache_key = f'handle_grading_policy_changed-{str(self.course.id)}'
- self.assertEqual(lock_available, compute_grades_async_mock.called)
+ self.assertEqual(lock_available, compute_grades_async_mock.called) # noqa: PT009
if lock_available:
add_mock.assert_called_once_with(cache_key, "true", GRADING_POLICY_COUNTDOWN_SECONDS)
diff --git a/cms/djangoapps/contentstore/tests/test_tasks.py b/cms/djangoapps/contentstore/tests/test_tasks.py
index 28e2f9f4f1f5..e1dd0b68d273 100644
--- a/cms/djangoapps/contentstore/tests/test_tasks.py
+++ b/cms/djangoapps/contentstore/tests/test_tasks.py
@@ -56,7 +56,7 @@
logging = logging.getLogger(__name__)
TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
-TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex
+TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex # noqa: UP031
def side_effect_exception(*args, **kwargs):
@@ -79,11 +79,11 @@ def test_success(self):
key = str(self.course.location.course_key)
result = export_olx.delay(self.user.id, key, 'en')
status = UserTaskStatus.objects.get(task_id=result.id)
- self.assertEqual(status.state, UserTaskStatus.SUCCEEDED)
+ self.assertEqual(status.state, UserTaskStatus.SUCCEEDED) # noqa: PT009
artifacts = UserTaskArtifact.objects.filter(status=status)
- self.assertEqual(len(artifacts), 1)
+ self.assertEqual(len(artifacts), 1) # noqa: PT009
output = artifacts[0]
- self.assertEqual(output.name, 'Output')
+ self.assertEqual(output.name, 'Output') # noqa: PT009
@mock.patch('cms.djangoapps.contentstore.tasks.export_course_to_xml', side_effect=side_effect_exception)
def test_exception(self, mock_export): # pylint: disable=unused-argument
@@ -118,12 +118,12 @@ def _assert_failed(self, task_result, error_message):
Verify that a task failed with the specified error message
"""
status = UserTaskStatus.objects.get(task_id=task_result.id)
- self.assertEqual(status.state, UserTaskStatus.FAILED)
+ self.assertEqual(status.state, UserTaskStatus.FAILED) # noqa: PT009
artifacts = UserTaskArtifact.objects.filter(status=status)
- self.assertEqual(len(artifacts), 1)
+ self.assertEqual(len(artifacts), 1) # noqa: PT009
error = artifacts[0]
- self.assertEqual(error.name, 'Error')
- self.assertEqual(error.text, error_message)
+ self.assertEqual(error.name, 'Error') # noqa: PT009
+ self.assertEqual(error.text, error_message) # noqa: PT009
@override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE)
@@ -139,11 +139,11 @@ def test_success(self):
key = str(self.lib_key)
result = export_olx.delay(self.user.id, key, 'en')
status = UserTaskStatus.objects.get(task_id=result.id)
- self.assertEqual(status.state, UserTaskStatus.SUCCEEDED)
+ self.assertEqual(status.state, UserTaskStatus.SUCCEEDED) # noqa: PT009
artifacts = UserTaskArtifact.objects.filter(status=status)
- self.assertEqual(len(artifacts), 1)
+ self.assertEqual(len(artifacts), 1) # noqa: PT009
output = artifacts[0]
- self.assertEqual(output.name, 'Output')
+ self.assertEqual(output.name, 'Output') # noqa: PT009
@override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE)
@@ -180,18 +180,18 @@ def test_success(self):
# Verify the new course run exists
course = modulestore().get_course(new_course_key)
- self.assertIsNotNone(course)
+ self.assertIsNotNone(course) # noqa: PT009
# Verify the OrganizationCourse is cloned
- self.assertEqual(OrganizationCourse.objects.count(), 2)
+ self.assertEqual(OrganizationCourse.objects.count(), 2) # noqa: PT009
# This will raise an error if the OrganizationCourse object was not cloned
OrganizationCourse.objects.get(course_id=new_course_id, organization=organization)
# Verify the RestrictedCourse and related objects are cloned
- self.assertEqual(RestrictedCourse.objects.count(), 2)
+ self.assertEqual(RestrictedCourse.objects.count(), 2) # noqa: PT009
restricted_course = RestrictedCourse.objects.get(course_key=new_course_key)
- self.assertEqual(CountryAccessRule.objects.count(), 2)
+ self.assertEqual(CountryAccessRule.objects.count(), 2) # noqa: PT009
CountryAccessRule.objects.get(
rule_type=CountryAccessRule.BLACKLIST_RULE,
restricted_course=restricted_course,
@@ -215,7 +215,7 @@ def test_success_different_org(self):
self._rerun_course(old_course_key, new_course_key)
# Verify the OrganizationCourse is cloned with a different org
- self.assertEqual(OrganizationCourse.objects.count(), 2)
+ self.assertEqual(OrganizationCourse.objects.count(), 2) # noqa: PT009
OrganizationCourse.objects.get(course_id=new_course_id, organization__short_name='neworg')
@@ -224,7 +224,7 @@ class RegisterExamsTaskTestCase(CourseTestCase): # pylint: disable=missing-clas
@mock.patch('cms.djangoapps.contentstore.exams.register_exams')
@mock.patch('cms.djangoapps.contentstore.proctoring.register_special_exams')
- def test_exam_service_not_enabled_success(self, _mock_register_exams_proctoring, _mock_register_exams_service):
+ def test_exam_service_not_enabled_success(self, _mock_register_exams_proctoring, _mock_register_exams_service): # noqa: PT019 # pylint: disable=line-too-long
""" edx-proctoring interface is called if exam service is not enabled """
update_special_exams_and_publish(str(self.course.id))
_mock_register_exams_proctoring.assert_called_once_with(self.course.id)
@@ -233,7 +233,7 @@ def test_exam_service_not_enabled_success(self, _mock_register_exams_proctoring,
@mock.patch('cms.djangoapps.contentstore.exams.register_exams')
@mock.patch('cms.djangoapps.contentstore.proctoring.register_special_exams')
@override_waffle_flag(EXAMS_IDA, active=True)
- def test_exam_service_enabled_success(self, _mock_register_exams_proctoring, _mock_register_exams_service):
+ def test_exam_service_enabled_success(self, _mock_register_exams_proctoring, _mock_register_exams_service): # noqa: PT019 # pylint: disable=line-too-long
""" exams service interface is called if exam service is enabled """
update_special_exams_and_publish(str(self.course.id))
_mock_register_exams_proctoring.assert_not_called()
@@ -241,7 +241,7 @@ def test_exam_service_enabled_success(self, _mock_register_exams_proctoring, _mo
@mock.patch('cms.djangoapps.contentstore.exams.register_exams')
@mock.patch('cms.djangoapps.contentstore.proctoring.register_special_exams')
- def test_register_exams_failure(self, _mock_register_exams_proctoring, _mock_register_exams_service):
+ def test_register_exams_failure(self, _mock_register_exams_proctoring, _mock_register_exams_service): # noqa: PT019
""" credit requirements update signal fires even if exam registration fails """
with mock.patch('openedx.core.djangoapps.credit.signals.handlers.on_course_publish') as course_publish:
_mock_register_exams_proctoring.side_effect = Exception('boom!')
@@ -363,22 +363,22 @@ def test_hash_tags_stripped_from_url_lists(self):
f'Processed URL list lines = {processed_lines}; expected {original_lines - 2}'
def test_http_url_not_recognized_as_studio_url_scheme(self):
- self.assertFalse(_is_studio_url('http://www.google.com'))
+ self.assertFalse(_is_studio_url('http://www.google.com')) # noqa: PT009
def test_https_url_not_recognized_as_studio_url_scheme(self):
- self.assertFalse(_is_studio_url('https://www.google.com'))
+ self.assertFalse(_is_studio_url('https://www.google.com')) # noqa: PT009
def test_http_with_studio_base_url_recognized_as_studio_url_scheme(self):
- self.assertTrue(_is_studio_url(f'http://{settings.CMS_BASE}/testurl'))
+ self.assertTrue(_is_studio_url(f'http://{settings.CMS_BASE}/testurl')) # noqa: PT009
def test_https_with_studio_base_url_recognized_as_studio_url_scheme(self):
- self.assertTrue(_is_studio_url(f'https://{settings.CMS_BASE}/testurl'))
+ self.assertTrue(_is_studio_url(f'https://{settings.CMS_BASE}/testurl')) # noqa: PT009
def test_container_url_without_url_base_is_recognized_as_studio_url_scheme(self):
- self.assertTrue(_is_studio_url('container/test'))
+ self.assertTrue(_is_studio_url('container/test')) # noqa: PT009
def test_slash_url_without_url_base_is_recognized_as_studio_url_scheme(self):
- self.assertTrue(_is_studio_url('/static/test'))
+ self.assertTrue(_is_studio_url('/static/test')) # noqa: PT009
@mock.patch('cms.djangoapps.contentstore.tasks.ModuleStoreEnum', autospec=True)
@mock.patch('cms.djangoapps.contentstore.tasks.modulestore', autospec=True)
@@ -407,7 +407,7 @@ def test_number_of_scanned_blocks_equals_blocks_in_course(self, mockextract_cont
expected_blocks = self.store.get_items(self.test_course.id)
_scan_course_for_links(self.test_course.id)
- self.assertEqual(len(expected_blocks), mockextract_content_URLs_from_course.call_count)
+ self.assertEqual(len(expected_blocks), mockextract_content_URLs_from_course.call_count) # noqa: PT009
@mock.patch('cms.djangoapps.contentstore.tasks.get_block_info', autospec=True)
@mock.patch('cms.djangoapps.contentstore.tasks.modulestore', autospec=True)
@@ -443,11 +443,11 @@ def get_block_side_effect(block):
urls = _scan_course_for_links(self.test_course.id)
# The drag-and-drop block should not appear in the results
- self.assertFalse(
+ self.assertFalse( # noqa: PT009
any(block_id == str(drag_and_drop_block.usage_key) for block_id, _ in urls),
"Drag and Drop blocks should be excluded"
)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
any(block_id == str(text_block.usage_key) for block_id, _ in urls),
"Text block should be included"
)
@@ -545,8 +545,8 @@ def test_filter_by_status(self):
filtered_results, retry_list = _filter_by_status(results)
- self.assertEqual(filtered_results, expected_filtered_results)
- self.assertEqual(retry_list, expected_retry_list)
+ self.assertEqual(filtered_results, expected_filtered_results) # noqa: PT009
+ self.assertEqual(retry_list, expected_retry_list) # noqa: PT009
@patch("cms.djangoapps.contentstore.tasks._validate_user", return_value=MagicMock())
@patch("cms.djangoapps.contentstore.tasks._scan_course_for_links", return_value=["url1", "url2"])
@@ -615,7 +615,7 @@ def __init__(self):
logging.exception("Error checking links for course %s", course_key_string, exc_info=True)
if mock_self.status.state != "FAILED":
mock_self.status.fail({"raw_error_msg": str(e)})
- assert False, "Exception should not occur"
+ assert False, "Exception should not occur" # noqa: B011, PT015
# Assertions to confirm patched calls were invoked
mock_validate_user.assert_called_once_with(mock_self, user_id, language)
@@ -647,7 +647,7 @@ def test_convert_to_standard_url(self):
]
for url, expected in test_cases:
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
_convert_to_standard_url(url, course_key),
expected,
f"Failed for URL: {url}",
@@ -676,7 +676,7 @@ def test_extract_content_URLs_from_course(self):
"https://validsite.com",
"https://another-valid.com"
]
- self.assertEqual(extract_content_URLs_from_course(content), set(expected))
+ self.assertEqual(extract_content_URLs_from_course(content), set(expected)) # noqa: PT009
@ddt.ddt
diff --git a/cms/djangoapps/contentstore/tests/test_transcripts_utils.py b/cms/djangoapps/contentstore/tests/test_transcripts_utils.py
index 16587ac798bd..721bc59eb2d2 100644
--- a/cms/djangoapps/contentstore/tests/test_transcripts_utils.py
+++ b/cms/djangoapps/contentstore/tests/test_transcripts_utils.py
@@ -32,7 +32,7 @@
)
TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
-TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex
+TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex # noqa: UP031
class TestGenerateSubs(unittest.TestCase):
@@ -54,7 +54,7 @@ def setUp(self):
def test_generate_subs_increase_speed(self):
subs = transcripts_utils.generate_subs(2, 1, self.source_subs)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
subs,
{
'start': [200, 400, 480, 780, 2000],
@@ -65,7 +65,7 @@ def test_generate_subs_increase_speed(self):
def test_generate_subs_decrease_speed_1(self):
subs = transcripts_utils.generate_subs(0.5, 1, self.source_subs)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
subs,
{
'start': [50, 100, 120, 195, 500],
@@ -77,7 +77,7 @@ def test_generate_subs_decrease_speed_1(self):
def test_generate_subs_decrease_speed_2(self):
"""Test for correct devision during `generate_subs` process."""
subs = transcripts_utils.generate_subs(1, 2, self.source_subs)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
subs,
{
'start': [50, 100, 120, 195, 500],
@@ -148,7 +148,7 @@ def setUp(self):
self.clear_subs_content()
def test_save_subs_to_store(self):
- with self.assertRaises(NotFoundError):
+ with self.assertRaises(NotFoundError): # noqa: PT027
contentstore().find(self.content_location)
result_location = transcripts_utils.save_subs_to_store(
@@ -156,23 +156,23 @@ def test_save_subs_to_store(self):
self.subs_id,
self.course)
- self.assertTrue(contentstore().find(self.content_location))
- self.assertEqual(result_location, self.content_location)
+ self.assertTrue(contentstore().find(self.content_location)) # noqa: PT009
+ self.assertEqual(result_location, self.content_location) # noqa: PT009
def test_save_unjsonable_subs_to_store(self):
"""
Ensures that subs, that can't be dumped, can't be found later.
"""
- with self.assertRaises(NotFoundError):
+ with self.assertRaises(NotFoundError): # noqa: PT027
contentstore().find(self.content_location_unjsonable)
- with self.assertRaises(TypeError):
+ with self.assertRaises(TypeError): # noqa: PT027
transcripts_utils.save_subs_to_store(
self.unjsonable_subs,
self.unjsonable_subs_id,
self.course)
- with self.assertRaises(NotFoundError):
+ with self.assertRaises(NotFoundError): # noqa: PT027
contentstore().find(self.content_location_unjsonable)
@@ -238,11 +238,11 @@ def test_success_downloading_subs(self):
setup_caption_responses(mock_get, language_code, caption_response_string)
transcripts_utils.download_youtube_subs(good_youtube_sub, self.course, settings)
- self.assertEqual(2, len(mock_get.mock_calls))
+ self.assertEqual(2, len(mock_get.mock_calls)) # noqa: PT009
args, kwargs = mock_get.call_args_list[0]
- self.assertEqual(args[0], 'https://www.youtube.com/watch?v=good_id_2')
+ self.assertEqual(args[0], 'https://www.youtube.com/watch?v=good_id_2') # noqa: PT009
args, kwargs = mock_get.call_args_list[1]
- self.assertTrue(re.match(r"^https://www\.youtube\.com/api/timedtext.*", args[0]))
+ self.assertTrue(re.match(r"^https://www\.youtube\.com/api/timedtext.*", args[0])) # noqa: PT009
def test_subs_for_html5_vid_with_periods(self):
"""
@@ -251,11 +251,11 @@ def test_subs_for_html5_vid_with_periods(self):
incorrect subs name parsing
"""
html5_ids = transcripts_utils.get_html5_ids(['foo.mp4', 'foo.1.bar.mp4', 'foo/bar/baz.1.4.mp4', 'foo'])
- self.assertEqual(4, len(html5_ids))
- self.assertEqual(html5_ids[0], 'foo')
- self.assertEqual(html5_ids[1], 'foo.1.bar')
- self.assertEqual(html5_ids[2], 'baz.1.4')
- self.assertEqual(html5_ids[3], 'foo')
+ self.assertEqual(4, len(html5_ids)) # noqa: PT009
+ self.assertEqual(html5_ids[0], 'foo') # noqa: PT009
+ self.assertEqual(html5_ids[1], 'foo.1.bar') # noqa: PT009
+ self.assertEqual(html5_ids[2], 'baz.1.4') # noqa: PT009
+ self.assertEqual(html5_ids[3], 'foo') # noqa: PT009
@patch('openedx.core.djangoapps.video_config.transcripts_utils.requests.get')
def test_fail_downloading_subs(self, mock_get):
@@ -266,7 +266,7 @@ def test_fail_downloading_subs(self, mock_get):
bad_youtube_sub = 'BAD_YOUTUBE_ID2'
self.clear_sub_content(bad_youtube_sub)
- with self.assertRaises(transcripts_utils.GetTranscriptsFromYouTubeException):
+ with self.assertRaises(transcripts_utils.GetTranscriptsFromYouTubeException): # noqa: PT027
transcripts_utils.download_youtube_subs(bad_youtube_sub, self.course, settings)
def test_success_downloading_chinese_transcripts(self):
@@ -283,12 +283,12 @@ def test_success_downloading_chinese_transcripts(self):
transcripts_utils.download_youtube_subs(good_youtube_sub, self.course, settings)
# Check assets status after importing subtitles.
- for subs_id in good_youtube_subs.values(): # lint-amnesty, pylint: disable=undefined-variable
+ for subs_id in good_youtube_subs.values(): # lint-amnesty, pylint: disable=undefined-variable # noqa: F821
filename = f'subs_{subs_id}.srt.sjson'
content_location = StaticContent.compute_location(
self.course.id, filename
)
- self.assertTrue(contentstore().find(content_location))
+ self.assertTrue(contentstore().find(content_location)) # noqa: PT009
self.clear_sub_content(good_youtube_sub)
@@ -323,7 +323,7 @@ def test_success_generating_subs(self):
content_location = StaticContent.compute_location(
self.course.id, filename
)
- self.assertTrue(contentstore().find(content_location))
+ self.assertTrue(contentstore().find(content_location)) # noqa: PT009
self.clear_subs_content(youtube_subs)
@@ -344,10 +344,10 @@ def test_fail_bad_subs_type(self):
At the left we can see...
""")
- with self.assertRaises(TranscriptsGenerationException) as cm:
+ with self.assertRaises(TranscriptsGenerationException) as cm: # noqa: PT027
transcripts_utils.generate_subs_from_source(youtube_subs, 'BAD_FORMAT', srt_filedata, self.course)
exception_message = str(cm.exception)
- self.assertEqual(exception_message, "We support only SubRip (*.srt) transcripts format.")
+ self.assertEqual(exception_message, "We support only SubRip (*.srt) transcripts format.") # noqa: PT009
def test_fail_bad_subs_filedata(self):
youtube_subs = {
@@ -358,10 +358,10 @@ def test_fail_bad_subs_filedata(self):
srt_filedata = """BAD_DATA"""
- with self.assertRaises(TranscriptsGenerationException) as cm:
+ with self.assertRaises(TranscriptsGenerationException) as cm: # noqa: PT027
transcripts_utils.generate_subs_from_source(youtube_subs, 'srt', srt_filedata, self.course)
exception_message = str(cm.exception)
- self.assertEqual(exception_message, "Something wrong with SubRip transcripts file during parsing.")
+ self.assertEqual(exception_message, "Something wrong with SubRip transcripts file during parsing.") # noqa: PT009 # pylint: disable=line-too-long
class TestGenerateSrtFromSjson(TestDownloadYoutubeSubs): # lint-amnesty, pylint: disable=test-inherits-tests
@@ -380,7 +380,7 @@ def test_success_generating_subs(self):
]
}
srt_subs = transcripts_utils.generate_srt_from_sjson(sjson_subs, 1)
- self.assertTrue(srt_subs)
+ self.assertTrue(srt_subs) # noqa: PT009
expected_subs = [
'00:00:00,100 --> 00:00:00,200\nsubs #1',
'00:00:00,200 --> 00:00:00,240\nsubs #2',
@@ -390,7 +390,7 @@ def test_success_generating_subs(self):
]
for sub in expected_subs:
- self.assertIn(sub, srt_subs)
+ self.assertIn(sub, srt_subs) # noqa: PT009
def test_success_generating_subs_speed_up(self):
sjson_subs = {
@@ -405,7 +405,7 @@ def test_success_generating_subs_speed_up(self):
]
}
srt_subs = transcripts_utils.generate_srt_from_sjson(sjson_subs, 0.5)
- self.assertTrue(srt_subs)
+ self.assertTrue(srt_subs) # noqa: PT009
expected_subs = [
'00:00:00,050 --> 00:00:00,100\nsubs #1',
'00:00:00,100 --> 00:00:00,120\nsubs #2',
@@ -414,7 +414,7 @@ def test_success_generating_subs_speed_up(self):
'00:00:27,000 --> 00:00:39,200\nsubs #5',
]
for sub in expected_subs:
- self.assertIn(sub, srt_subs)
+ self.assertIn(sub, srt_subs) # noqa: PT009
def test_success_generating_subs_speed_down(self):
sjson_subs = {
@@ -429,7 +429,7 @@ def test_success_generating_subs_speed_down(self):
]
}
srt_subs = transcripts_utils.generate_srt_from_sjson(sjson_subs, 2)
- self.assertTrue(srt_subs)
+ self.assertTrue(srt_subs) # noqa: PT009
expected_subs = [
'00:00:00,200 --> 00:00:00,400\nsubs #1',
@@ -439,7 +439,7 @@ def test_success_generating_subs_speed_down(self):
'00:01:48,000 --> 00:02:36,800\nsubs #5',
]
for sub in expected_subs:
- self.assertIn(sub, srt_subs)
+ self.assertIn(sub, srt_subs) # noqa: PT009
def test_fail_generating_subs(self):
sjson_subs = {
@@ -451,7 +451,7 @@ def test_fail_generating_subs(self):
]
}
srt_subs = transcripts_utils.generate_srt_from_sjson(sjson_subs, 1)
- self.assertFalse(srt_subs)
+ self.assertFalse(srt_subs) # noqa: PT009
class TestYoutubeTranscripts(unittest.TestCase):
@@ -463,7 +463,7 @@ def test_youtube_bad_status_code(self, mock_get):
track_status_code = 404
setup_caption_responses(mock_get, 'en', 'test', track_status_code)
youtube_id = 'bad_youtube_id'
- with self.assertRaises(transcripts_utils.GetTranscriptsFromYouTubeException):
+ with self.assertRaises(transcripts_utils.GetTranscriptsFromYouTubeException): # noqa: PT027
link = transcripts_utils.get_transcript_links_from_youtube(youtube_id, settings, translation)
transcripts_utils.get_transcript_from_youtube(link, youtube_id, translation)
@@ -471,7 +471,7 @@ def test_youtube_bad_status_code(self, mock_get):
def test_youtube_empty_text(self, mock_get):
setup_caption_responses(mock_get, 'en', '')
youtube_id = 'bad_youtube_id'
- with self.assertRaises(transcripts_utils.GetTranscriptsFromYouTubeException):
+ with self.assertRaises(transcripts_utils.GetTranscriptsFromYouTubeException): # noqa: PT027
link = transcripts_utils.get_transcript_links_from_youtube(youtube_id, settings, translation)
transcripts_utils.get_transcript_from_youtube(link, youtube_id, translation)
@@ -496,12 +496,12 @@ def test_youtube_good_result(self):
link = transcripts_utils.get_transcript_links_from_youtube(youtube_id, settings, translation)
transcripts = transcripts_utils.get_transcript_from_youtube(link['en'], youtube_id, translation)
- self.assertEqual(transcripts, expected_transcripts)
- self.assertEqual(2, len(mock_get.mock_calls))
+ self.assertEqual(transcripts, expected_transcripts) # noqa: PT009
+ self.assertEqual(2, len(mock_get.mock_calls)) # noqa: PT009
args, kwargs = mock_get.call_args_list[0]
- self.assertEqual(args[0], f'https://www.youtube.com/watch?v={youtube_id}')
+ self.assertEqual(args[0], f'https://www.youtube.com/watch?v={youtube_id}') # noqa: PT009
args, kwargs = mock_get.call_args_list[1]
- self.assertTrue(re.match(r"^https://www\.youtube\.com/api/timedtext.*", args[0]))
+ self.assertTrue(re.match(r"^https://www\.youtube\.com/api/timedtext.*", args[0])) # noqa: PT009
class TestTranscript(unittest.TestCase):
@@ -547,7 +547,7 @@ def test_convert_srt_to_txt(self):
"""
expected = self.txt_transcript
actual = transcripts_utils.Transcript.convert(self.srt_transcript, 'srt', 'txt')
- self.assertEqual(actual, expected)
+ self.assertEqual(actual, expected) # noqa: PT009
def test_convert_srt_to_srt(self):
"""
@@ -555,7 +555,7 @@ def test_convert_srt_to_srt(self):
"""
expected = self.srt_transcript
actual = transcripts_utils.Transcript.convert(self.srt_transcript, 'srt', 'srt')
- self.assertEqual(actual, expected)
+ self.assertEqual(actual, expected) # noqa: PT009
def test_convert_sjson_to_txt(self):
"""
@@ -563,7 +563,7 @@ def test_convert_sjson_to_txt(self):
"""
expected = self.txt_transcript
actual = transcripts_utils.Transcript.convert(self.sjson_transcript, 'sjson', 'txt')
- self.assertEqual(actual, expected)
+ self.assertEqual(actual, expected) # noqa: PT009
def test_convert_sjson_to_srt(self):
"""
@@ -571,7 +571,7 @@ def test_convert_sjson_to_srt(self):
"""
expected = self.srt_transcript
actual = transcripts_utils.Transcript.convert(self.sjson_transcript, 'sjson', 'srt')
- self.assertEqual(actual, expected)
+ self.assertEqual(actual, expected) # noqa: PT009
def test_convert_srt_to_sjson(self):
"""
@@ -579,7 +579,7 @@ def test_convert_srt_to_sjson(self):
"""
expected = self.sjson_transcript
actual = transcripts_utils.Transcript.convert(self.srt_transcript, 'srt', 'sjson')
- self.assertDictEqual(json.loads(actual), json.loads(expected))
+ self.assertDictEqual(json.loads(actual), json.loads(expected)) # noqa: PT009
def test_convert_invalid_srt_to_sjson(self):
"""
@@ -587,7 +587,7 @@ def test_convert_invalid_srt_to_sjson(self):
to convert invalid srt transcript to sjson.
"""
invalid_srt_transcript = 'invalid SubRip file content'
- with self.assertRaises(TranscriptsGenerationException):
+ with self.assertRaises(TranscriptsGenerationException): # noqa: PT027
transcripts_utils.Transcript.convert(invalid_srt_transcript, 'srt', 'sjson')
def test_convert_invalid_invalid_sjson_to_srt(self):
@@ -600,10 +600,10 @@ def test_dummy_non_existent_transcript(self):
"""
Test `Transcript.asset` raises `NotFoundError` for dummy non-existent transcript.
"""
- with self.assertRaises(NotFoundError):
+ with self.assertRaises(NotFoundError): # noqa: PT027
transcripts_utils.Transcript.asset(None, transcripts_utils.NON_EXISTENT_TRANSCRIPT)
- with self.assertRaises(NotFoundError):
+ with self.assertRaises(NotFoundError): # noqa: PT027
transcripts_utils.Transcript.asset(None, None, filename=transcripts_utils.NON_EXISTENT_TRANSCRIPT)
def test_latin1(self):
@@ -649,9 +649,9 @@ class TestSubsFilename(unittest.TestCase):
def test_unicode(self):
name = transcripts_utils.subs_filename("˙∆©ƒƒƒ")
- self.assertEqual(name, 'subs_˙∆©ƒƒƒ.srt.sjson')
+ self.assertEqual(name, 'subs_˙∆©ƒƒƒ.srt.sjson') # noqa: PT009
name = transcripts_utils.subs_filename("˙∆©ƒƒƒ", 'uk')
- self.assertEqual(name, 'uk_subs_˙∆©ƒƒƒ.srt.sjson')
+ self.assertEqual(name, 'uk_subs_˙∆©ƒƒƒ.srt.sjson') # noqa: PT009
@ddt.ddt
@@ -691,7 +691,7 @@ def test_get_video_ids_info(self, edx_video_id, youtube_id_1_0, html5_sources, e
Verify that `get_video_ids_info` works as expected.
"""
actual_result = transcripts_utils.get_video_ids_info(edx_video_id, youtube_id_1_0, html5_sources)
- self.assertEqual(actual_result, expected_result)
+ self.assertEqual(actual_result, expected_result) # noqa: PT009
@ddt.ddt
@@ -801,7 +801,7 @@ def test_get_transcript_not_found(self, lang):
"""
Verify that `NotFoundError` exception is raised when transcript is not found in both the content store and val.
"""
- with self.assertRaises(NotFoundError):
+ with self.assertRaises(NotFoundError): # noqa: PT027
transcripts_utils.get_transcript(
self.video,
lang=lang
@@ -869,9 +869,9 @@ def test_get_transcript_from_contentstore(
language
)
- self.assertEqual(content, self.subs[language])
- self.assertEqual(file_name, expected_filename)
- self.assertEqual(mimetype, self.srt_mime_type)
+ self.assertEqual(content, self.subs[language]) # noqa: PT009
+ self.assertEqual(file_name, expected_filename) # noqa: PT009
+ self.assertEqual(mimetype, self.srt_mime_type) # noqa: PT009
def test_get_transcript_from_content_store_for_ur(self):
"""
@@ -885,9 +885,9 @@ def test_get_transcript_from_content_store_for_ur(self):
output_format=transcripts_utils.Transcript.SJSON
)
- self.assertEqual(json.loads(content), self.subs_sjson)
- self.assertEqual(filename, 'ur_video_101.sjson')
- self.assertEqual(mimetype, self.sjson_mime_type)
+ self.assertEqual(json.loads(content), self.subs_sjson) # noqa: PT009
+ self.assertEqual(filename, 'ur_video_101.sjson') # noqa: PT009
+ self.assertEqual(mimetype, self.sjson_mime_type) # noqa: PT009
@patch('openedx.core.djangoapps.video_config.transcripts_utils.get_video_transcript_content')
def test_get_transcript_from_val(self, mock_get_video_transcript_content):
@@ -902,15 +902,15 @@ def test_get_transcript_from_val(self, mock_get_video_transcript_content):
content, filename, mimetype = transcripts_utils.get_transcript(
self.video,
)
- self.assertEqual(content, self.subs_srt)
- self.assertEqual(filename, 'edx.srt')
- self.assertEqual(mimetype, self.srt_mime_type)
+ self.assertEqual(content, self.subs_srt) # noqa: PT009
+ self.assertEqual(filename, 'edx.srt') # noqa: PT009
+ self.assertEqual(mimetype, self.srt_mime_type) # noqa: PT009
def test_get_transcript_invalid_format(self):
"""
Verify that `get_transcript` raises correct exception if transcript format is invalid.
"""
- with self.assertRaises(NotFoundError) as invalid_format_exception:
+ with self.assertRaises(NotFoundError) as invalid_format_exception: # noqa: PT027
transcripts_utils.get_transcript(
self.video,
'ur',
@@ -918,7 +918,7 @@ def test_get_transcript_invalid_format(self):
)
exception_message = str(invalid_format_exception.exception)
- self.assertEqual(exception_message, 'Invalid transcript format `mpeg`')
+ self.assertEqual(exception_message, 'Invalid transcript format `mpeg`') # noqa: PT009
def test_get_transcript_no_content(self):
"""
@@ -927,14 +927,14 @@ def test_get_transcript_no_content(self):
self.upload_file(self.create_srt_file(b''), self.video.location, 'ur_video_101.srt')
self.create_transcript('', 'ur', 'ur_video_101.srt')
- with self.assertRaises(NotFoundError) as no_content_exception:
+ with self.assertRaises(NotFoundError) as no_content_exception: # noqa: PT027
transcripts_utils.get_transcript(
self.video,
'ur'
)
exception_message = str(no_content_exception.exception)
- self.assertEqual(exception_message, 'No transcript content')
+ self.assertEqual(exception_message, 'No transcript content') # noqa: PT009
def test_get_transcript_no_en_transcript(self):
"""
@@ -942,14 +942,14 @@ def test_get_transcript_no_en_transcript(self):
"""
self.video.youtube_id_1_0 = ''
self.store.update_item(self.video, self.user.id)
- with self.assertRaises(NotFoundError) as no_en_transcript_exception:
+ with self.assertRaises(NotFoundError) as no_en_transcript_exception: # noqa: PT027
transcripts_utils.get_transcript(
self.video,
'en'
)
exception_message = str(no_en_transcript_exception.exception)
- self.assertEqual(exception_message, 'No transcript for `en` language')
+ self.assertEqual(exception_message, 'No transcript for `en` language') # noqa: PT009
@patch('openedx.core.djangoapps.video_config.transcripts_utils.edxval_api.get_video_transcript_data')
def test_get_transcript_incorrect_json_(self, mock_get_video_transcript_data):
@@ -974,7 +974,7 @@ def test_get_transcript_val_exceptions(self, exception_to_raise, mock_Transcript
transcripts_info = self.video.get_transcripts_info()
lang = self.video.get_default_transcript_language(transcripts_info)
edx_video_id = transcripts_utils.clean_video_id(self.video.edx_video_id)
- with self.assertRaises(NotFoundError):
+ with self.assertRaises(NotFoundError): # noqa: PT027
transcripts_utils.get_transcript_from_val(
edx_video_id,
lang=lang,
@@ -993,7 +993,7 @@ def test_get_transcript_content_store_exceptions(self, exception_to_raise, mock_
mock_Transcript.asset.side_effect = exception_to_raise
transcripts_info = self.video.get_transcripts_info()
lang = self.video.get_default_transcript_language(transcripts_info)
- with self.assertRaises(NotFoundError):
+ with self.assertRaises(NotFoundError): # noqa: PT027
transcripts_utils.get_transcript_from_contentstore(
self.video,
language=lang,
@@ -1021,7 +1021,7 @@ def test_resolve_lang(self, lang, expected):
Test that resolve_language_code_to_transcript_code will successfully match
language codes of different cases, and return None if it isn't found
"""
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
transcripts_utils.resolve_language_code_to_transcript_code(self.TEST_TRANSCRIPTS, lang),
expected
)
@@ -1058,7 +1058,7 @@ def mock_django_get_language_info(self, side_effect=None):
def test_language_in_languages(self):
""" If language is found in LANGUAGE_DICT that value should be returned """
with override_settings(LANGUAGE_DICT=self.TEST_LANGUAGE_DICT):
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
transcripts_utils.get_endonym_or_label(self.LANG_CODE),
self.LANG_ENTONYM
)
@@ -1070,7 +1070,7 @@ def test_language_in_django_lang_info(self):
"""
with override_settings(LANGUAGE_DICT={}):
with self.mock_django_get_language_info() as mock_get_language_info:
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
transcripts_utils.get_endonym_or_label(self.LANG_CODE),
mock_get_language_info.return_value['name_local']
)
@@ -1084,7 +1084,7 @@ def test_language_exact_in_all_languages(self):
with self.mock_django_get_language_info(side_effect=KeyError):
with override_settings(ALL_LANGUAGES=self.TEST_ALL_LANGUAGES):
label = transcripts_utils.get_endonym_or_label(self.LANG_CODE)
- self.assertEqual(label, self.LANG_LABEL)
+ self.assertEqual(label, self.LANG_LABEL) # noqa: PT009
def test_language_generic_in_all_languages(self):
"""
@@ -1101,7 +1101,7 @@ def test_language_generic_in_all_languages(self):
with self.mock_django_get_language_info(side_effect=KeyError):
with override_settings(ALL_LANGUAGES=all_languages):
label = transcripts_utils.get_endonym_or_label(self.LANG_CODE)
- self.assertEqual(label, self.GENERIC_LABEL)
+ self.assertEqual(label, self.GENERIC_LABEL) # noqa: PT009
def test_language_not_found_anywhere(self):
"""
@@ -1111,5 +1111,5 @@ def test_language_not_found_anywhere(self):
with override_settings(LANGUAGE_DICT={}):
with self.mock_django_get_language_info(side_effect=KeyError):
with override_settings(ALL_LANGUAGES=all_languages):
- with self.assertRaises(NotFoundError):
+ with self.assertRaises(NotFoundError): # noqa: PT027
transcripts_utils.get_endonym_or_label(self.LANG_CODE)
diff --git a/cms/djangoapps/contentstore/tests/test_upstream_downstream_links.py b/cms/djangoapps/contentstore/tests/test_upstream_downstream_links.py
index 594036dbd23f..e604735fc354 100644
--- a/cms/djangoapps/contentstore/tests/test_upstream_downstream_links.py
+++ b/cms/djangoapps/contentstore/tests/test_upstream_downstream_links.py
@@ -108,7 +108,7 @@ def _compare_links(self, course_key, expected_component_links, expected_containe
'version_synced',
'version_declined',
))
- self.assertListEqual(links, expected_component_links)
+ self.assertListEqual(links, expected_component_links) # noqa: PT009
container_links = list(ContainerLink.objects.filter(downstream_context_key=course_key).values(
'upstream_container',
'upstream_container_key',
@@ -118,7 +118,7 @@ def _compare_links(self, course_key, expected_component_links, expected_containe
'version_synced',
'version_declined',
))
- self.assertListEqual(container_links, expected_container_links)
+ self.assertListEqual(container_links, expected_container_links) # noqa: PT009
@skip_unless_cms
@@ -167,9 +167,9 @@ def test_call_with_invalid_args(self):
"""
Test command with invalid args.
"""
- with self.assertRaisesRegex(CommandError, 'Either --course or --all argument'):
+ with self.assertRaisesRegex(CommandError, 'Either --course or --all argument'): # noqa: PT027
self.call_command()
- with self.assertRaisesRegex(CommandError, 'Only one of --course or --all argument'):
+ with self.assertRaisesRegex(CommandError, 'Only one of --course or --all argument'): # noqa: PT027
self.call_command('--all', '--course', str(self.course_key_1))
def test_call_for_single_course(self):
@@ -246,7 +246,7 @@ def test_call_for_invalid_course(self):
course_key = "invalid-course"
with self.assertLogs(level="ERROR") as ctx:
self.call_command('--course', course_key)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
f'Invalid course key: {course_key}, skipping..',
ctx.records[0].getMessage()
)
@@ -258,7 +258,7 @@ def test_call_for_nonexistent_course(self):
course_key = "course-v1:unix+ux1+2024_T2"
with self.assertLogs(level="ERROR") as ctx:
self.call_command('--course', course_key)
- self.assertIn(
+ self.assertIn( # noqa: PT009
f'Could not find items for given course: {course_key}',
ctx.records[0].getMessage()
)
diff --git a/cms/djangoapps/contentstore/tests/test_users_default_role.py b/cms/djangoapps/contentstore/tests/test_users_default_role.py
index 3ceb6ddca3d1..2f05801e5010 100644
--- a/cms/djangoapps/contentstore/tests/test_users_default_role.py
+++ b/cms/djangoapps/contentstore/tests/test_users_default_role.py
@@ -60,18 +60,18 @@ def test_user_forum_default_role_on_course_deletion(self):
enrolled even the course is deleted and keeps its "Student" forum role for that course
"""
# check that user has enrollment for this course
- self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key))
+ self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key)) # noqa: PT009
# check that user has his default "Student" forum role for this course
- self.assertTrue(self.user.roles.filter(name="Student", course_id=self.course_key))
+ self.assertTrue(self.user.roles.filter(name="Student", course_id=self.course_key)) # noqa: PT009
delete_course(self.course_key, self.user.id)
# check that user's enrollment for this course is not deleted
- self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key))
+ self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key)) # noqa: PT009
# check that user has forum role for this course even after deleting it
- self.assertTrue(self.user.roles.filter(name="Student", course_id=self.course_key))
+ self.assertTrue(self.user.roles.filter(name="Student", course_id=self.course_key)) # noqa: PT009
def test_user_role_on_course_recreate(self):
"""
@@ -79,19 +79,19 @@ def test_user_role_on_course_recreate(self):
forum role "Student" for that course
"""
# check that user has enrollment and his default "Student" forum role for this course
- self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key))
- self.assertTrue(self.user.roles.filter(name="Student", course_id=self.course_key))
+ self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key)) # noqa: PT009
+ self.assertTrue(self.user.roles.filter(name="Student", course_id=self.course_key)) # noqa: PT009
# delete this course and recreate this course with same user
delete_course(self.course_key, self.user.id)
resp = self._create_course_with_given_location(self.course_key)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# check that user has his enrollment for this course
- self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key))
+ self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key)) # noqa: PT009
# check that user has his default "Student" forum role for this course
- self.assertTrue(self.user.roles.filter(name="Student", course_id=self.course_key))
+ self.assertTrue(self.user.roles.filter(name="Student", course_id=self.course_key)) # noqa: PT009
@skip("OldMongo Deprecation")
# Issue with case-insensitive course keys
@@ -101,17 +101,17 @@ def test_user_role_on_course_recreate_with_change_name_case(self):
his default forum role "Student" for that course
"""
# check that user has enrollment and his default "Student" forum role for this course
- self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key))
+ self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key)) # noqa: PT009
# delete this course and recreate this course with same user
delete_course(self.course_key, self.user.id)
# now create same course with different name case ('uppercase')
new_course_key = self.course_key.replace(course=self.course_key.course.upper())
resp = self._create_course_with_given_location(new_course_key)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# check that user has his default "Student" forum role again for this course (with changed name case)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
self.user.roles.filter(name="Student", course_id=new_course_key)
)
diff --git a/cms/djangoapps/contentstore/tests/test_utils.py b/cms/djangoapps/contentstore/tests/test_utils.py
index aab36e3c4b6e..83edcb87e0c7 100644
--- a/cms/djangoapps/contentstore/tests/test_utils.py
+++ b/cms/djangoapps/contentstore/tests/test_utils.py
@@ -44,12 +44,12 @@ def lms_link_test(self):
course_key = CourseLocator('mitX', '101', 'test')
location = course_key.make_usage_key('vertical', 'contacting_us')
link = utils.get_lms_link_for_item(location, False)
- self.assertEqual(link, "//localhost:8000/courses/course-v1:mitX+101+test/jump_to/block-v1:mitX+101+test+type"
+ self.assertEqual(link, "//localhost:8000/courses/course-v1:mitX+101+test/jump_to/block-v1:mitX+101+test+type" # noqa: PT009 # pylint: disable=line-too-long
"@vertical+block@contacting_us")
# test preview
link = utils.get_lms_link_for_item(location, True)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
link,
"//preview.localhost/courses/course-v1:mitX+101+test/jump_to/block-v1:mitX+101+test+type@vertical+block"
"@contacting_us "
@@ -58,27 +58,27 @@ def lms_link_test(self):
# now test with the course' location
location = course_key.make_usage_key('course', 'test')
link = utils.get_lms_link_for_item(location)
- self.assertEqual(link, "//localhost:8000/courses/course-v1:mitX+101+test/jump_to/block-v1:mitX+101+test+type"
+ self.assertEqual(link, "//localhost:8000/courses/course-v1:mitX+101+test/jump_to/block-v1:mitX+101+test+type" # noqa: PT009 # pylint: disable=line-too-long
"@course+block@test")
def lms_link_for_certificate_web_view_test(self):
""" Tests get_lms_link_for_certificate_web_view. """
course_key = CourseLocator('mitX', '101', 'test')
- dummy_user = ModuleStoreEnum.UserID.test
+ dummy_user = ModuleStoreEnum.UserID.test # noqa: F841
mode = 'professional'
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
utils.get_lms_link_for_certificate_web_view(course_key, mode),
- "//localhost:8000/certificates/course/{course_key}?preview={mode}".format(
+ "//localhost:8000/certificates/course/{course_key}?preview={mode}".format( # noqa: UP032
course_key=course_key,
mode=mode
)
)
with with_site_configuration_context(configuration={"course_org_filter": "mitX", "LMS_BASE": "dummyhost:8000"}):
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
utils.get_lms_link_for_certificate_web_view(course_key, mode),
- "//dummyhost:8000/certificates/course/{course_key}?preview={mode}".format(
+ "//dummyhost:8000/certificates/course/{course_key}?preview={mode}".format( # noqa: UP032
course_key=course_key,
mode=mode
)
@@ -151,7 +151,7 @@ def test_draft_released_xblock(self):
vertical.start = self.future
modulestore().update_item(vertical, self.dummy_user)
- self.assertTrue(utils.is_currently_visible_to_students(vertical))
+ self.assertTrue(utils.is_currently_visible_to_students(vertical)) # noqa: PT009
def _test_visible_to_students(self, expected_visible_without_lock, name, start_date, publish=False):
"""
@@ -159,13 +159,13 @@ def _test_visible_to_students(self, expected_visible_without_lock, name, start_d
with and without visible_to_staff_only set.
"""
no_staff_lock = self._create_xblock_with_start_date(name, start_date, publish, visible_to_staff_only=False)
- self.assertEqual(expected_visible_without_lock, utils.is_currently_visible_to_students(no_staff_lock))
+ self.assertEqual(expected_visible_without_lock, utils.is_currently_visible_to_students(no_staff_lock)) # noqa: PT009 # pylint: disable=line-too-long
# any xblock with visible_to_staff_only set to True should not be visible to students.
staff_lock = self._create_xblock_with_start_date(
name + "_locked", start_date, publish, visible_to_staff_only=True
)
- self.assertFalse(utils.is_currently_visible_to_students(staff_lock))
+ self.assertFalse(utils.is_currently_visible_to_students(staff_lock)) # noqa: PT009
def _create_xblock_with_start_date(self, name, start_date, publish=False, visible_to_staff_only=False):
"""Helper to create an xblock with a start date, optionally publishing it"""
@@ -211,8 +211,8 @@ def _update_release_dates(self, chapter_start, sequential_start, vertical_start)
def _verify_release_date_source(self, item, expected_source):
"""Helper to verify that the release date source of a given item matches the expected source"""
source = utils.find_release_date_source(item)
- self.assertEqual(source.location, expected_source.location)
- self.assertEqual(source.start, expected_source.start)
+ self.assertEqual(source.location, expected_source.location) # noqa: PT009
+ self.assertEqual(source.start, expected_source.start) # noqa: PT009
def test_chapter_source_for_vertical(self):
"""Tests a vertical's release date being set by its chapter"""
@@ -280,8 +280,8 @@ class StaffLockSourceTest(StaffLockTest):
def _verify_staff_lock_source(self, item, expected_source):
"""Helper to verify that the staff lock source of a given item matches the expected source"""
source = utils.find_staff_lock_source(item)
- self.assertEqual(source.location, expected_source.location)
- self.assertTrue(source.visible_to_staff_only)
+ self.assertEqual(source.location, expected_source.location) # noqa: PT009
+ self.assertTrue(source.visible_to_staff_only) # noqa: PT009
def test_chapter_source_for_vertical(self):
"""Tests a vertical's staff lock being set by its chapter"""
@@ -306,12 +306,12 @@ def test_vertical_source_for_vertical(self):
def test_orphan_has_no_source(self):
"""Tests that a orphaned xblock has no staff lock source"""
- self.assertIsNone(utils.find_staff_lock_source(self.orphan))
+ self.assertIsNone(utils.find_staff_lock_source(self.orphan)) # noqa: PT009
def test_no_source_for_vertical(self):
"""Tests a vertical with no staff lock set anywhere"""
self._update_staff_locks(False, False, False)
- self.assertIsNone(utils.find_staff_lock_source(self.vertical))
+ self.assertIsNone(utils.find_staff_lock_source(self.vertical)) # noqa: PT009
class InheritedStaffLockTest(StaffLockTest):
@@ -320,27 +320,27 @@ class InheritedStaffLockTest(StaffLockTest):
def test_no_inheritance(self):
"""Tests that a locked or unlocked vertical with no locked ancestors does not have an inherited lock"""
self._update_staff_locks(False, False, False)
- self.assertFalse(utils.ancestor_has_staff_lock(self.vertical))
+ self.assertFalse(utils.ancestor_has_staff_lock(self.vertical)) # noqa: PT009
self._update_staff_locks(False, False, True)
- self.assertFalse(utils.ancestor_has_staff_lock(self.vertical))
+ self.assertFalse(utils.ancestor_has_staff_lock(self.vertical)) # noqa: PT009
def test_inheritance_in_locked_section(self):
"""Tests that a locked or unlocked vertical in a locked section has an inherited lock"""
self._update_staff_locks(True, False, False)
- self.assertTrue(utils.ancestor_has_staff_lock(self.vertical))
+ self.assertTrue(utils.ancestor_has_staff_lock(self.vertical)) # noqa: PT009
self._update_staff_locks(True, False, True)
- self.assertTrue(utils.ancestor_has_staff_lock(self.vertical))
+ self.assertTrue(utils.ancestor_has_staff_lock(self.vertical)) # noqa: PT009
def test_inheritance_in_locked_subsection(self):
"""Tests that a locked or unlocked vertical in a locked subsection has an inherited lock"""
self._update_staff_locks(False, True, False)
- self.assertTrue(utils.ancestor_has_staff_lock(self.vertical))
+ self.assertTrue(utils.ancestor_has_staff_lock(self.vertical)) # noqa: PT009
self._update_staff_locks(False, True, True)
- self.assertTrue(utils.ancestor_has_staff_lock(self.vertical))
+ self.assertTrue(utils.ancestor_has_staff_lock(self.vertical)) # noqa: PT009
def test_no_inheritance_for_orphan(self):
"""Tests that an orphaned xblock does not inherit staff lock"""
- self.assertFalse(utils.ancestor_has_staff_lock(self.orphan))
+ self.assertFalse(utils.ancestor_has_staff_lock(self.orphan)) # noqa: PT009
class GroupVisibilityTest(CourseTestCase):
@@ -412,8 +412,8 @@ def test_no_visibility_set(self):
def verify_all_components_visible_to_all():
""" Verifies when group_access has not been set on anything. """
for item in (self.sequential, self.vertical, self.html, self.problem):
- self.assertFalse(utils.has_children_visible_to_specific_partition_groups(item))
- self.assertFalse(utils.is_visible_to_specific_partition_groups(item))
+ self.assertFalse(utils.has_children_visible_to_specific_partition_groups(item)) # noqa: PT009
+ self.assertFalse(utils.is_visible_to_specific_partition_groups(item)) # noqa: PT009
verify_all_components_visible_to_all()
@@ -435,15 +435,15 @@ def test_sequential_and_problem_have_group_access(self):
self.problem = self.store.get_item(self.problem.location)
# Note that "has_children_visible_to_specific_partition_groups" only checks immediate children.
- self.assertFalse(utils.has_children_visible_to_specific_partition_groups(self.sequential))
- self.assertTrue(utils.has_children_visible_to_specific_partition_groups(self.vertical))
- self.assertFalse(utils.has_children_visible_to_specific_partition_groups(self.html))
- self.assertFalse(utils.has_children_visible_to_specific_partition_groups(self.problem))
+ self.assertFalse(utils.has_children_visible_to_specific_partition_groups(self.sequential)) # noqa: PT009
+ self.assertTrue(utils.has_children_visible_to_specific_partition_groups(self.vertical)) # noqa: PT009
+ self.assertFalse(utils.has_children_visible_to_specific_partition_groups(self.html)) # noqa: PT009
+ self.assertFalse(utils.has_children_visible_to_specific_partition_groups(self.problem)) # noqa: PT009
- self.assertTrue(utils.is_visible_to_specific_partition_groups(self.sequential))
- self.assertFalse(utils.is_visible_to_specific_partition_groups(self.vertical))
- self.assertFalse(utils.is_visible_to_specific_partition_groups(self.html))
- self.assertTrue(utils.is_visible_to_specific_partition_groups(self.problem))
+ self.assertTrue(utils.is_visible_to_specific_partition_groups(self.sequential)) # noqa: PT009
+ self.assertFalse(utils.is_visible_to_specific_partition_groups(self.vertical)) # noqa: PT009
+ self.assertFalse(utils.is_visible_to_specific_partition_groups(self.html)) # noqa: PT009
+ self.assertTrue(utils.is_visible_to_specific_partition_groups(self.problem)) # noqa: PT009
class GetUserPartitionInfoTest(ModuleStoreTestCase):
@@ -518,12 +518,12 @@ def test_retrieves_partition_info_with_selected_groups(self):
]
}
]
- self.assertEqual(self._get_partition_info(schemes=["cohort", "random"]), expected)
+ self.assertEqual(self._get_partition_info(schemes=["cohort", "random"]), expected) # noqa: PT009
# Update group access and expect that now one group is marked as selected.
self._set_group_access({0: [1]})
expected[0]["groups"][1]["selected"] = True
- self.assertEqual(self._get_partition_info(schemes=["cohort", "random"]), expected)
+ self.assertEqual(self._get_partition_info(schemes=["cohort", "random"]), expected) # noqa: PT009
def test_deleted_groups(self):
# Select a group that is not defined in the partition
@@ -532,8 +532,8 @@ def test_deleted_groups(self):
# Expect that the group appears as selected but is marked as deleted
partitions = self._get_partition_info()
groups = partitions[0]["groups"]
- self.assertEqual(len(groups), 3)
- self.assertEqual(groups[2], {
+ self.assertEqual(len(groups), 3) # noqa: PT009
+ self.assertEqual(groups[2], { # noqa: PT009
"id": 3,
"name": "Deleted Group",
"selected": True,
@@ -557,8 +557,8 @@ def test_singular_deleted_group(self):
self._set_group_access({0: [1]})
partitions = self._get_partition_info()
groups = partitions[0]["groups"]
- self.assertEqual(len(groups), 1)
- self.assertEqual(groups[0], {
+ self.assertEqual(len(groups), 1) # noqa: PT009
+ self.assertEqual(groups[0], { # noqa: PT009
"id": 1,
"name": "Deleted Group",
"selected": True,
@@ -567,8 +567,8 @@ def test_singular_deleted_group(self):
def test_filter_by_partition_scheme(self):
partitions = self._get_partition_info(schemes=["random"])
- self.assertEqual(len(partitions), 1)
- self.assertEqual(partitions[0]["scheme"], "random")
+ self.assertEqual(len(partitions), 1) # noqa: PT009
+ self.assertEqual(partitions[0]["scheme"], "random") # noqa: PT009
def test_exclude_inactive_partitions(self):
# Include an inactive verification scheme
@@ -597,8 +597,8 @@ def test_exclude_inactive_partitions(self):
# Expect that the inactive scheme is excluded from the results
partitions = self._get_partition_info(schemes=["cohort", "verification"])
- self.assertEqual(len(partitions), 1)
- self.assertEqual(partitions[0]["scheme"], "cohort")
+ self.assertEqual(len(partitions), 1) # noqa: PT009
+ self.assertEqual(partitions[0]["scheme"], "cohort") # noqa: PT009
def test_exclude_partitions_with_no_groups(self):
# The cohort partition has no groups defined
@@ -623,8 +623,8 @@ def test_exclude_partitions_with_no_groups(self):
# Expect that the partition with no groups is excluded from the results
partitions = self._get_partition_info(schemes=["cohort", "random"])
- self.assertEqual(len(partitions), 1)
- self.assertEqual(partitions[0]["scheme"], "random")
+ self.assertEqual(len(partitions), 1) # noqa: PT009
+ self.assertEqual(partitions[0]["scheme"], "random") # noqa: PT009
def _set_partitions(self, partitions):
"""Set the user partitions of the course block. """
@@ -661,24 +661,24 @@ def test_with_library_locator(self, mock_olxcleaner_validate):
Tests that olx is validation is skipped with library locator.
"""
library_key = LibraryLocator(org='TestOrg', library='TestProbs')
- self.assertTrue(validate_course_olx(library_key, self.toy_course_path, self.status))
- self.assertFalse(mock_olxcleaner_validate.called)
+ self.assertTrue(validate_course_olx(library_key, self.toy_course_path, self.status)) # noqa: PT009
+ self.assertFalse(mock_olxcleaner_validate.called) # noqa: PT009
def test_config_settings_enabled(self, mock_olxcleaner_validate):
"""
Tests olx validation with config setting is disabled.
"""
with patch.dict(settings.FEATURES, ENABLE_COURSE_OLX_VALIDATION=False):
- self.assertTrue(validate_course_olx(self.course.id, self.toy_course_path, self.status))
- self.assertFalse(mock_olxcleaner_validate.called)
+ self.assertTrue(validate_course_olx(self.course.id, self.toy_course_path, self.status)) # noqa: PT009
+ self.assertFalse(mock_olxcleaner_validate.called) # noqa: PT009
def test_config_settings_disabled(self, mock_olxcleaner_validate):
"""
Tests olx validation with config setting is enabled.
"""
with patch.dict(settings.FEATURES, ENABLE_COURSE_OLX_VALIDATION=True):
- self.assertTrue(validate_course_olx(self.course.id, self.toy_course_path, self.status))
- self.assertTrue(mock_olxcleaner_validate.called)
+ self.assertTrue(validate_course_olx(self.course.id, self.toy_course_path, self.status)) # noqa: PT009
+ self.assertTrue(mock_olxcleaner_validate.called) # noqa: PT009
def test_exception_during_validation(self, mock_olxcleaner_validate):
"""
@@ -689,8 +689,8 @@ def test_exception_during_validation(self, mock_olxcleaner_validate):
"""
mock_olxcleaner_validate.side_effect = Exception
with mock.patch(self.LOGGER) as patched_log:
- self.assertTrue(validate_course_olx(self.course.id, self.toy_course_path, self.status))
- self.assertTrue(mock_olxcleaner_validate.called)
+ self.assertTrue(validate_course_olx(self.course.id, self.toy_course_path, self.status)) # noqa: PT009
+ self.assertTrue(mock_olxcleaner_validate.called) # noqa: PT009
patched_log.exception.assert_called_once_with(
f'Course import {self.course.id}: CourseOlx could not be validated')
@@ -704,10 +704,10 @@ def test_no_errors(self, mock_olxcleaner_validate):
Mock(errors=[], return_error=Mock(return_value=False)),
Mock()
]
- self.assertTrue(validate_course_olx(self.course.id, self.toy_course_path, self.status))
+ self.assertTrue(validate_course_olx(self.course.id, self.toy_course_path, self.status)) # noqa: PT009
task_artifact = UserTaskArtifact.objects.filter(status=self.status, name='OLX_VALIDATION_ERROR').first()
- self.assertIsNone(task_artifact)
- self.assertTrue(mock_olxcleaner_validate.called)
+ self.assertIsNone(task_artifact) # noqa: PT009
+ self.assertTrue(mock_olxcleaner_validate.called) # noqa: PT009
@mock.patch('cms.djangoapps.contentstore.tasks.report_error_summary')
@mock.patch('cms.djangoapps.contentstore.tasks.report_errors')
@@ -728,12 +728,12 @@ def test_creates_artifact(self, mock_report_errors, mock_report_error_summary, m
mock_report_error_summary.return_value = [f'Errors: {len(errors)}']
with patch(self.LOGGER) as patched_log:
- self.assertFalse(validate_course_olx(self.course.id, self.toy_course_path, self.status))
+ self.assertFalse(validate_course_olx(self.course.id, self.toy_course_path, self.status)) # noqa: PT009
patched_log.error.assert_called_once_with(
f'Course import {self.course.id}: CourseOlx validation failed.')
task_artifact = UserTaskArtifact.objects.filter(status=self.status, name='OLX_VALIDATION_ERROR').first()
- self.assertIsNotNone(task_artifact)
+ self.assertIsNotNone(task_artifact) # noqa: PT009
def test_validate_calls_with(self, mock_olxcleaner_validate):
"""
@@ -764,7 +764,7 @@ def test_html_replaced_with_text_for_none(self):
display_name = None
block_type = "html"
result = utils.determine_label(display_name, block_type)
- self.assertEqual(result, "Text")
+ self.assertEqual(result, "Text") # noqa: PT009
def test_html_replaced_with_text_for_empty(self):
"""
@@ -773,7 +773,7 @@ def test_html_replaced_with_text_for_empty(self):
display_name = ""
block_type = "html"
result = utils.determine_label(display_name, block_type)
- self.assertEqual(result, "Text")
+ self.assertEqual(result, "Text") # noqa: PT009
def test_set_titles_not_replaced(self):
"""
@@ -782,7 +782,7 @@ def test_set_titles_not_replaced(self):
display_name = "Something"
block_type = "html"
result = utils.determine_label(display_name, block_type)
- self.assertEqual(result, "Something")
+ self.assertEqual(result, "Something") # noqa: PT009
def test_non_html_blocks_titles_not_replaced(self):
"""
@@ -791,10 +791,10 @@ def test_non_html_blocks_titles_not_replaced(self):
display_name = None
block_type = "something else"
result = utils.determine_label(display_name, block_type)
- self.assertEqual(result, "something else")
+ self.assertEqual(result, "something else") # noqa: PT009
-class AuthorizeStaffTestCase():
+class AuthorizeStaffTestCase(): # noqa: UP039
"""
Test that only staff roles can access an API endpoint.
"""
diff --git a/cms/djangoapps/contentstore/tests/test_video_utils.py b/cms/djangoapps/contentstore/tests/test_video_utils.py
index 5059a399b80c..1fb1ed76ccb7 100644
--- a/cms/djangoapps/contentstore/tests/test_video_utils.py
+++ b/cms/djangoapps/contentstore/tests/test_video_utils.py
@@ -36,7 +36,7 @@ def test_invalid_image_file_info(self):
Test that when no file information is provided to validate_video_image, it gives proper error message.
"""
error = validate_video_image({})
- self.assertEqual(error, 'The image must have name, content type, and size information.')
+ self.assertEqual(error, 'The image must have name, content type, and size information.') # noqa: PT009
def test_corrupt_image_file(self):
"""
@@ -49,7 +49,7 @@ def test_corrupt_image_file(self):
size=settings.VIDEO_IMAGE_SETTINGS['VIDEO_IMAGE_MIN_BYTES']
)
error = validate_video_image(uploaded_image_file)
- self.assertEqual(error, 'There is a problem with this image file. Try to upload a different file.')
+ self.assertEqual(error, 'There is a problem with this image file. Try to upload a different file.') # noqa: PT009 # pylint: disable=line-too-long
@ddt.ddt
@@ -223,8 +223,8 @@ def mocked_youtube_thumbnail_responses(resolutions):
thumbnail_content, thumbnail_content_type = download_youtube_video_thumbnail('test-yt-id')
# Verify that we get the expected thumbnail content.
- self.assertEqual(thumbnail_content, expected_thumbnail_content)
- self.assertEqual(thumbnail_content_type, 'image/jpeg')
+ self.assertEqual(thumbnail_content, expected_thumbnail_content) # noqa: PT009
+ self.assertEqual(thumbnail_content_type, 'image/jpeg') # noqa: PT009
@override_settings(AWS_ACCESS_KEY_ID='test_key_id', AWS_SECRET_ACCESS_KEY='test_secret')
@mock.patch('requests.get')
@@ -241,11 +241,11 @@ def test_scrape_youtube_thumbnail(self, mocked_request):
# Verify that video1 has no image attached.
video1_image_url = get_course_video_image_url(course_id=course_id, edx_video_id=video1_edx_video_id)
- self.assertIsNone(video1_image_url)
+ self.assertIsNone(video1_image_url) # noqa: PT009
# Verify that video2 has already image attached.
video2_image_url = get_course_video_image_url(course_id=course_id, edx_video_id=video2_edx_video_id)
- self.assertIsNotNone(video2_image_url)
+ self.assertIsNotNone(video2_image_url) # noqa: PT009
# Scrape video thumbnails.
scrape_youtube_thumbnail(course_id, video1_edx_video_id, 'test-yt-id')
@@ -253,11 +253,11 @@ def test_scrape_youtube_thumbnail(self, mocked_request):
# Verify that now video1 image is attached.
video1_image_url = get_course_video_image_url(course_id=course_id, edx_video_id=video1_edx_video_id)
- self.assertIsNotNone(video1_image_url)
+ self.assertIsNotNone(video1_image_url) # noqa: PT009
# Also verify that video2's image is not updated.
video2_image_url_latest = get_course_video_image_url(course_id=course_id, edx_video_id=video2_edx_video_id)
- self.assertEqual(video2_image_url, video2_image_url_latest)
+ self.assertEqual(video2_image_url, video2_image_url_latest) # noqa: PT009
@ddt.data(
(
@@ -313,21 +313,21 @@ def test_scrape_youtube_thumbnail_logging(
(
None,
'image/jpeg',
- 'This image file must be larger than {image_min_size}.'.format(
+ 'This image file must be larger than {image_min_size}.'.format( # noqa: UP032
image_min_size=settings.VIDEO_IMAGE_MIN_FILE_SIZE_KB
)
),
(
b'dummy-content',
None,
- 'This image file type is not supported. Supported file types are {supported_file_formats}.'.format(
+ 'This image file type is not supported. Supported file types are {supported_file_formats}.'.format( # noqa: UP032 # pylint: disable=line-too-long
supported_file_formats=list(settings.VIDEO_IMAGE_SUPPORTED_FILE_FORMATS.keys())
)
),
(
None,
None,
- 'This image file type is not supported. Supported file types are {supported_file_formats}.'.format(
+ 'This image file type is not supported. Supported file types are {supported_file_formats}.'.format( # noqa: UP032 # pylint: disable=line-too-long
supported_file_formats=list(settings.VIDEO_IMAGE_SUPPORTED_FILE_FORMATS.keys())
)
),
@@ -352,7 +352,7 @@ def test_no_video_thumbnail_downloaded(
# Verify that video1 has no image attached.
video1_image_url = get_course_video_image_url(course_id=course_id, edx_video_id=video1_edx_video_id)
- self.assertIsNone(video1_image_url)
+ self.assertIsNone(video1_image_url) # noqa: PT009
# Scrape video thumbnail.
scrape_youtube_thumbnail(course_id, video1_edx_video_id, 'test-yt-id')
@@ -366,7 +366,7 @@ def test_no_video_thumbnail_downloaded(
# Verify that no image is attached to video1.
video1_image_url = get_course_video_image_url(course_id=course_id, edx_video_id=video1_edx_video_id)
- self.assertIsNone(video1_image_url)
+ self.assertIsNone(video1_image_url) # noqa: PT009
@ddt.ddt
@@ -387,7 +387,7 @@ def order_dict(self, dictionary):
return dictionary
def test_video_backend(self):
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
S3Boto3Storage,
import_string(
'storages.backends.s3boto3.S3Boto3Storage',
@@ -404,7 +404,7 @@ def test_boto3_backend_with_params(self):
settings.VIDEO_IMAGE_SETTINGS.get('STORAGE_CLASS', {})
)(**settings.VIDEO_IMAGE_SETTINGS.get('STORAGE_KWARGS', {}))
- self.assertEqual(S3Boto3Storage, storage.__class__)
+ self.assertEqual(S3Boto3Storage, storage.__class__) # noqa: PT009
def test_storage_without_global_default_acl_setting(self):
"""
diff --git a/cms/djangoapps/contentstore/tests/test_xblock_handler_permissions.py b/cms/djangoapps/contentstore/tests/test_xblock_handler_permissions.py
index 84a5b51895a5..cc7b53ca0991 100644
--- a/cms/djangoapps/contentstore/tests/test_xblock_handler_permissions.py
+++ b/cms/djangoapps/contentstore/tests/test_xblock_handler_permissions.py
@@ -27,10 +27,10 @@ def setUp(self):
# --- GET /xblock/{blockId} ---
def test_get_block_fields_staff_allowed(self):
- self.assertEqual(self.client.get_json(f'/xblock/{self.html_block.location}').status_code, 200)
+ self.assertEqual(self.client.get_json(f'/xblock/{self.html_block.location}').status_code, 200) # noqa: PT009
def test_get_block_fields_non_staff_forbidden(self):
- self.assertEqual(self.non_staff_client.get_json(f'/xblock/{self.html_block.location}').status_code, 403)
+ self.assertEqual(self.non_staff_client.get_json(f'/xblock/{self.html_block.location}').status_code, 403) # noqa: PT009 # pylint: disable=line-too-long
# --- POST /xblock/{blockId} metadata ---
@@ -38,33 +38,33 @@ def test_post_metadata_staff_allowed(self):
resp = self.client.ajax_post(
f'/xblock/{self.html_block.location}', data={'metadata': {'display_name': 'New Name'}}
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def test_post_metadata_non_staff_forbidden(self):
resp = self.non_staff_client.ajax_post(
f'/xblock/{self.html_block.location}', data={'metadata': {'display_name': 'New Name'}}
)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# --- POST /xblock/{blockId} publish ---
def test_publish_staff_allowed(self):
resp = self.client.ajax_post(f'/xblock/{self.vertical.location}', data={'publish': 'make_public'})
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def test_publish_non_staff_forbidden(self):
resp = self.non_staff_client.ajax_post(f'/xblock/{self.vertical.location}', data={'publish': 'make_public'})
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# --- DELETE /xblock/{blockId} ---
def test_delete_block_staff_allowed(self):
resp = self.client.delete(f'/xblock/{self.html_block.location}', HTTP_ACCEPT='application/json')
- self.assertEqual(resp.status_code, 204)
+ self.assertEqual(resp.status_code, 204) # noqa: PT009
def test_delete_block_non_staff_forbidden(self):
resp = self.non_staff_client.delete(f'/xblock/{self.html_block.location}', HTTP_ACCEPT='application/json')
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# --- POST /xblock/ (create/duplicate) ---
@@ -73,22 +73,22 @@ def test_post_duplicate_staff_allowed(self):
'duplicate_source_locator': str(self.html_block.location),
'parent_locator': str(self.vertical.location),
}
- self.assertEqual(self.client.ajax_post('/xblock/', data=data).status_code, 200)
+ self.assertEqual(self.client.ajax_post('/xblock/', data=data).status_code, 200) # noqa: PT009
def test_post_duplicate_non_staff_forbidden(self):
data = {
'duplicate_source_locator': str(self.html_block.location),
'parent_locator': str(self.vertical.location),
}
- self.assertEqual(self.non_staff_client.ajax_post('/xblock/', data=data).status_code, 403)
+ self.assertEqual(self.non_staff_client.ajax_post('/xblock/', data=data).status_code, 403) # noqa: PT009
def test_post_add_component_staff_allowed(self):
data = {'category': 'html', 'parent_locator': str(self.vertical.location)}
- self.assertEqual(self.client.ajax_post('/xblock/', data=data).status_code, 200)
+ self.assertEqual(self.client.ajax_post('/xblock/', data=data).status_code, 200) # noqa: PT009
def test_post_add_component_non_staff_forbidden(self):
data = {'category': 'html', 'parent_locator': str(self.vertical.location)}
- self.assertEqual(self.non_staff_client.ajax_post('/xblock/', data=data).status_code, 403)
+ self.assertEqual(self.non_staff_client.ajax_post('/xblock/', data=data).status_code, 403) # noqa: PT009
# --- PUT /xblock/{blockId} (reorder) ---
@@ -98,7 +98,7 @@ def test_put_reorder_staff_allowed(self):
f'/xblock/{self.vertical.location}', data=data,
content_type='application/json', HTTP_ACCEPT='application/json',
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def test_put_reorder_non_staff_forbidden(self):
data={'children': [str(self.html_block.location)]}
@@ -106,7 +106,7 @@ def test_put_reorder_non_staff_forbidden(self):
f'/xblock/{self.vertical.location}', data=data,
content_type='application/json', HTTP_ACCEPT='application/json',
)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# --- PATCH /xblock/ (move) ---
@@ -119,7 +119,7 @@ def test_patch_move_component_staff_allowed(self):
resp = self.client.patch(
'/xblock/', data=data, content_type='application/json', HTTP_ACCEPT='application/json',
)
- self.assertNotEqual(resp.status_code, 403)
+ self.assertNotEqual(resp.status_code, 403) # noqa: PT009
def test_patch_move_component_non_staff_forbidden(self):
data={
@@ -129,7 +129,7 @@ def test_patch_move_component_non_staff_forbidden(self):
resp = self.non_staff_client.patch(
'/xblock/', data=data, content_type='application/json', HTTP_ACCEPT='application/json',
)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# --- static_tab and course_info ---
@@ -139,7 +139,7 @@ def test_put_update_custom_page_staff_allowed(self):
f'/xblock/{self.static_tab.location}', data=data,
content_type='application/json', HTTP_ACCEPT='application/json',
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def test_put_update_custom_page_non_staff_forbidden(self):
data={'metadata': {'display_name': 'Updated Page'}}
@@ -147,35 +147,35 @@ def test_put_update_custom_page_non_staff_forbidden(self):
f'/xblock/{self.static_tab.location}', data=data,
content_type='application/json', HTTP_ACCEPT='application/json',
)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
def test_delete_custom_page_staff_allowed(self):
resp = self.client.delete(f'/xblock/{self.static_tab.location}', HTTP_ACCEPT='application/json')
- self.assertEqual(resp.status_code, 204)
+ self.assertEqual(resp.status_code, 204) # noqa: PT009
def test_delete_custom_page_non_staff_forbidden(self):
resp = self.non_staff_client.delete(f'/xblock/{self.static_tab.location}', HTTP_ACCEPT='application/json')
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
def test_post_static_tab_content_staff_allowed(self):
resp = self.client.ajax_post(
f'/xblock/{self.static_tab.location}', data={'data': 'Content
', 'metadata': {'display_name': 'Page'}}
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def test_post_static_tab_content_non_staff_forbidden(self):
resp = self.non_staff_client.ajax_post(
f'/xblock/{self.static_tab.location}', data={'data': 'Content
', 'metadata': {'display_name': 'Page'}}
)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
def test_get_handouts_staff_allowed(self):
handouts = BlockFactory.create(category='course_info', parent_location=self.course.location)
- self.assertEqual(self.client.get_json(f'/xblock/{handouts.location}').status_code, 200)
+ self.assertEqual(self.client.get_json(f'/xblock/{handouts.location}').status_code, 200) # noqa: PT009
def test_get_handouts_non_staff_forbidden(self):
handouts = BlockFactory.create(category='course_info', parent_location=self.course.location)
- self.assertEqual(self.non_staff_client.get_json(f'/xblock/{handouts.location}').status_code, 403)
+ self.assertEqual(self.non_staff_client.get_json(f'/xblock/{handouts.location}').status_code, 403) # noqa: PT009
@patch('cms.djangoapps.contentstore.xblock_storage_handlers.view_handlers.authz_api.is_user_allowed', return_value=True)
@@ -199,7 +199,7 @@ def setUp(self):
# --- GET /xblock/{blockId} ---
- def test_get_regular_block_checks_view_course(self, _mock_flag, mock_is_allowed):
+ def test_get_regular_block_checks_view_course(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""GET on regular block should check courses.view_course permission"""
self.client.get_json(f'/xblock/{self.html_block.location}')
mock_is_allowed.assert_called_with(
@@ -208,7 +208,7 @@ def test_get_regular_block_checks_view_course(self, _mock_flag, mock_is_allowed)
str(self.course.id)
)
- def test_get_course_info_checks_view_course_updates(self, _mock_flag, mock_is_allowed):
+ def test_get_course_info_checks_view_course_updates(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""GET on course_info block should check courses.view_course_updates permission"""
self.client.get_json(f'/xblock/{self.course_info.location}')
mock_is_allowed.assert_called_with(
@@ -217,7 +217,7 @@ def test_get_course_info_checks_view_course_updates(self, _mock_flag, mock_is_al
str(self.course.id)
)
- def test_get_static_tab_checks_view_course(self, _mock_flag, mock_is_allowed):
+ def test_get_static_tab_checks_view_course(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""GET on static_tab should check courses.view_course"""
self.client.get_json(f'/xblock/{self.static_tab.location}')
mock_is_allowed.assert_called_with(
@@ -228,7 +228,7 @@ def test_get_static_tab_checks_view_course(self, _mock_flag, mock_is_allowed):
# --- POST /xblock/{blockId} metadata ---
- def test_post_regular_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed):
+ def test_post_regular_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST on regular block without publish should check courses.edit_course_content"""
self.client.ajax_post(f'/xblock/{self.html_block.location}', data={'metadata': {'display_name': 'New'}})
mock_is_allowed.assert_called_with(
@@ -237,7 +237,7 @@ def test_post_regular_block_checks_edit_course_content(self, _mock_flag, mock_is
str(self.course.id)
)
- def test_post_with_publish_none_and_metadata_checks_edit(self, _mock_flag, mock_is_allowed):
+ def test_post_with_publish_none_and_metadata_checks_edit(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST with publish=None + metadata should check courses.edit_course_content"""
self.client.ajax_post(
f'/xblock/{self.vertical.location}',
@@ -251,7 +251,7 @@ def test_post_with_publish_none_and_metadata_checks_edit(self, _mock_flag, mock_
# --- POST /xblock/{blockId} publish ---
- def test_post_with_publish_checks_publish_course_content(self, _mock_flag, mock_is_allowed):
+ def test_post_with_publish_checks_publish_course_content(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST with publish='make_public' should check courses.publish_course_content"""
self.client.ajax_post(f'/xblock/{self.vertical.location}', data={'publish': 'make_public'})
mock_is_allowed.assert_called_with(
@@ -260,7 +260,7 @@ def test_post_with_publish_checks_publish_course_content(self, _mock_flag, mock_
str(self.course.id)
)
- def test_post_discard_changes_checks_publish(self, _mock_flag, mock_is_allowed):
+ def test_post_discard_changes_checks_publish(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST with publish='discard_changes' should check courses.publish_course_content"""
self.client.ajax_post(f'/xblock/{self.vertical.location}', data={'publish': 'discard_changes'})
mock_is_allowed.assert_called_with(
@@ -269,7 +269,7 @@ def test_post_discard_changes_checks_publish(self, _mock_flag, mock_is_allowed):
str(self.course.id)
)
- def test_post_republish_without_changes_checks_publish(self, _mock_flag, mock_is_allowed):
+ def test_post_republish_without_changes_checks_publish(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST with publish='republish' and no content changes should check courses.publish_course_content"""
self.client.ajax_post(f'/xblock/{self.vertical.location}', data={'publish': 'republish'})
mock_is_allowed.assert_called_with(
@@ -278,7 +278,7 @@ def test_post_republish_without_changes_checks_publish(self, _mock_flag, mock_is
str(self.course.id)
)
- def test_post_make_public_with_content_changes_checks_edit(self, _mock_flag, mock_is_allowed):
+ def test_post_make_public_with_content_changes_checks_edit(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST with publish='make_public' + metadata should check courses.edit_course_content"""
self.client.ajax_post(
f'/xblock/{self.vertical.location}',
@@ -290,7 +290,7 @@ def test_post_make_public_with_content_changes_checks_edit(self, _mock_flag, moc
str(self.course.id)
)
- def test_post_republish_with_metadata_checks_edit(self, _mock_flag, mock_is_allowed):
+ def test_post_republish_with_metadata_checks_edit(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST with publish='republish' + metadata changes should check courses.edit_course_content"""
self.client.ajax_post(
f'/xblock/{self.chapter.location}',
@@ -302,7 +302,7 @@ def test_post_republish_with_metadata_checks_edit(self, _mock_flag, mock_is_allo
str(self.course.id)
)
- def test_post_republish_with_grader_type_checks_edit(self, _mock_flag, mock_is_allowed):
+ def test_post_republish_with_grader_type_checks_edit(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST with publish='republish' + graderType should check courses.edit_course_content"""
self.client.ajax_post(
f'/xblock/{self.sequential.location}',
@@ -316,7 +316,7 @@ def test_post_republish_with_grader_type_checks_edit(self, _mock_flag, mock_is_a
# --- DELETE /xblock/{blockId} ---
- def test_delete_regular_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed):
+ def test_delete_regular_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""DELETE on regular block should check courses.edit_course_content"""
self.client.delete(f'/xblock/{self.html_block.location}', HTTP_ACCEPT='application/json')
mock_is_allowed.assert_called_with(
@@ -325,7 +325,7 @@ def test_delete_regular_block_checks_edit_course_content(self, _mock_flag, mock_
str(self.course.id)
)
- def test_delete_static_tab_checks_manage_pages_and_resources(self, _mock_flag, mock_is_allowed):
+ def test_delete_static_tab_checks_manage_pages_and_resources(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""DELETE on static_tab should check courses.manage_pages_and_resources"""
self.client.delete(f'/xblock/{self.static_tab.location}', HTTP_ACCEPT='application/json')
mock_is_allowed.assert_called_with(
@@ -336,7 +336,7 @@ def test_delete_static_tab_checks_manage_pages_and_resources(self, _mock_flag, m
# --- POST /xblock/ (create/duplicate) ---
- def test_create_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed):
+ def test_create_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST /xblock/ to create block should check courses.edit_course_content"""
self.client.ajax_post('/xblock/', data={'category': 'html', 'parent_locator': str(self.vertical.location)})
mock_is_allowed.assert_called_with(
@@ -345,7 +345,7 @@ def test_create_block_checks_edit_course_content(self, _mock_flag, mock_is_allow
str(self.course.id)
)
- def test_create_static_tab_checks_manage_pages_and_resources(self, _mock_flag, mock_is_allowed):
+ def test_create_static_tab_checks_manage_pages_and_resources(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""PUT /xblock/ to create static_tab should check courses.manage_pages_and_resources"""
self.client.put(
'/xblock/',
@@ -358,7 +358,7 @@ def test_create_static_tab_checks_manage_pages_and_resources(self, _mock_flag, m
str(self.course.id)
)
- def test_duplicate_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed):
+ def test_duplicate_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST /xblock/ to duplicate should check courses.edit_course_content"""
self.client.ajax_post(
'/xblock/',
@@ -375,7 +375,7 @@ def test_duplicate_block_checks_edit_course_content(self, _mock_flag, mock_is_al
# --- PUT /xblock/{blockId} (reorder) ---
- def test_put_reorder_checks_edit_course_content(self, _mock_flag, mock_is_allowed):
+ def test_put_reorder_checks_edit_course_content(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""PUT on regular block (reorder children) should check courses.edit_course_content"""
self.client.put(
f'/xblock/{self.vertical.location}',
@@ -390,7 +390,7 @@ def test_put_reorder_checks_edit_course_content(self, _mock_flag, mock_is_allowe
# --- PATCH /xblock/ (move) ---
- def test_move_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed):
+ def test_move_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""PATCH /xblock/ to move should check courses.edit_course_content"""
vertical2 = BlockFactory.create(category='vertical', parent_location=self.sequential.location)
self.client.patch(
@@ -410,7 +410,7 @@ def test_move_block_checks_edit_course_content(self, _mock_flag, mock_is_allowed
# --- static_tab and course_info ---
- def test_post_static_tab_checks_manage_pages_and_resources(self, _mock_flag, mock_is_allowed):
+ def test_post_static_tab_checks_manage_pages_and_resources(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST on static_tab should check courses.manage_pages_and_resources"""
self.client.ajax_post(f'/xblock/{self.static_tab.location}', data={'metadata': {'display_name': 'Updated'}})
mock_is_allowed.assert_called_with(
@@ -419,7 +419,7 @@ def test_post_static_tab_checks_manage_pages_and_resources(self, _mock_flag, moc
str(self.course.id)
)
- def test_put_static_tab_checks_manage_pages_and_resources(self, _mock_flag, mock_is_allowed):
+ def test_put_static_tab_checks_manage_pages_and_resources(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""PUT on static_tab should check courses.manage_pages_and_resources"""
self.client.put(
f'/xblock/{self.static_tab.location}',
@@ -432,7 +432,7 @@ def test_put_static_tab_checks_manage_pages_and_resources(self, _mock_flag, mock
str(self.course.id)
)
- def test_post_course_info_checks_manage_course_updates(self, _mock_flag, mock_is_allowed):
+ def test_post_course_info_checks_manage_course_updates(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""POST on course_info block should check courses.manage_course_updates"""
self.client.ajax_post(f'/xblock/{self.course_info.location}', data={'data': 'Updated
'})
mock_is_allowed.assert_called_with(
@@ -441,7 +441,7 @@ def test_post_course_info_checks_manage_course_updates(self, _mock_flag, mock_is
str(self.course.id)
)
- def test_put_course_info_checks_manage_course_updates(self, _mock_flag, mock_is_allowed):
+ def test_put_course_info_checks_manage_course_updates(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""PUT on course_info should check courses.manage_course_updates"""
self.client.put(
f'/xblock/{self.course_info.location}',
@@ -457,13 +457,13 @@ def test_put_course_info_checks_manage_course_updates(self, _mock_flag, mock_is_
# --- authz flag behavior ---
- def test_authz_denied_raises_permission_denied(self, _mock_flag, mock_is_allowed):
+ def test_authz_denied_raises_permission_denied(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""When authz denies permission, PermissionDenied should be raised"""
mock_is_allowed.return_value = False
response = self.client.get_json(f'/xblock/{self.html_block.location}')
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
- def test_authz_flag_disabled_uses_legacy_permissions(self, _mock_flag, mock_is_allowed):
+ def test_authz_flag_disabled_uses_legacy_permissions(self, _mock_flag, mock_is_allowed): # noqa: PT019
"""When authz flag is disabled, should use legacy permission checks"""
with patch.object(core_toggles.AUTHZ_COURSE_AUTHORING_FLAG, 'is_enabled', return_value=False):
self.client.get_json(f'/xblock/{self.html_block.location}')
diff --git a/cms/djangoapps/contentstore/tests/tests.py b/cms/djangoapps/contentstore/tests/tests.py
index 6a7a1a2779a5..23403da686ef 100644
--- a/cms/djangoapps/contentstore/tests/tests.py
+++ b/cms/djangoapps/contentstore/tests/tests.py
@@ -48,7 +48,7 @@ def _login(self, email, password):
def login(self, email, password):
"""Login, check that it worked."""
resp = self._login(email, password)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
return resp
def _create_account(self, username, email, password):
@@ -69,12 +69,12 @@ def _create_account(self, username, email, password):
def create_account(self, username, email, password):
"""Create the account and check that it worked"""
resp = self._create_account(username, email, password)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
json_data = parse_json(resp)
- self.assertEqual(json_data['success'], True)
+ self.assertEqual(json_data['success'], True) # noqa: PT009
# Check both that the user is created, and inactive
- self.assertFalse(user(email).is_active)
+ self.assertFalse(user(email).is_active) # noqa: PT009
return resp
@@ -89,9 +89,9 @@ def _activate_user(self, email):
def activate_user(self, email):
resp = self._activate_user(email)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# Now make sure that the user is now actually activated
- self.assertTrue(user(email).is_active)
+ self.assertTrue(user(email).is_active) # noqa: PT009
@ddt
@@ -226,31 +226,31 @@ def test_blackouts(self):
(now + datetime.timedelta(days=24), now + datetime.timedelta(days=30))
]
self.set_blackout_dates(times1)
- self.assertTrue(self.course.forum_posts_allowed)
+ self.assertTrue(self.course.forum_posts_allowed) # noqa: PT009
times2 = [
(now - datetime.timedelta(days=14), now + datetime.timedelta(days=2)),
(now + datetime.timedelta(days=24), now + datetime.timedelta(days=30))
]
self.set_blackout_dates(times2)
- self.assertFalse(self.course.forum_posts_allowed)
+ self.assertFalse(self.course.forum_posts_allowed) # noqa: PT009
# Single date set for allowed forum posts.
self.course.discussion_blackouts = [
now + datetime.timedelta(days=24),
now + datetime.timedelta(days=30)
]
- self.assertTrue(self.course.forum_posts_allowed)
+ self.assertTrue(self.course.forum_posts_allowed) # noqa: PT009
# Single date set for restricted forum posts.
self.course.discussion_blackouts = [
now - datetime.timedelta(days=24),
now + datetime.timedelta(days=30)
]
- self.assertFalse(self.course.forum_posts_allowed)
+ self.assertFalse(self.course.forum_posts_allowed) # noqa: PT009
# test if user gives empty blackout date it should return true for forum_posts_allowed
self.course.discussion_blackouts = [[]]
- self.assertTrue(self.course.forum_posts_allowed)
+ self.assertTrue(self.course.forum_posts_allowed) # noqa: PT009
@ddt
@@ -273,11 +273,11 @@ def test_course_key_decorator(self, course_key, status_code):
"""
url = f'/import/{course_key}'
resp = self.client.get_html(url)
- self.assertEqual(resp.status_code, status_code)
+ self.assertEqual(resp.status_code, status_code) # noqa: PT009
url = '/import_status/{course_key}/{filename}'.format(
course_key=course_key,
filename='xyz.tar.gz'
)
resp = self.client.get_html(url)
- self.assertEqual(resp.status_code, status_code)
+ self.assertEqual(resp.status_code, status_code) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/tests/utils.py b/cms/djangoapps/contentstore/tests/utils.py
index 0b117f1dfa24..9837fa3a0b1e 100644
--- a/cms/djangoapps/contentstore/tests/utils.py
+++ b/cms/djangoapps/contentstore/tests/utils.py
@@ -130,12 +130,12 @@ def assertCoursesEqual(self, course1_id, course2_id):
"""
course1_items = self.store.get_items(course1_id)
course2_items = self.store.get_items(course2_id)
- self.assertGreater(len(course1_items), 0) # ensure it found content instead of [] == []
+ self.assertGreater(len(course1_items), 0) # ensure it found content instead of [] == [] # noqa: PT009
if len(course1_items) != len(course2_items):
course1_block_ids = {item.location.block_id for item in course1_items}
course2_block_ids = {item.location.block_id for item in course2_items}
raise AssertionError(
- "Course1 extra blocks: {}; course2 extra blocks: {}".format(
+ "Course1 extra blocks: {}; course2 extra blocks: {}".format( # noqa: UP032
course1_block_ids - course2_block_ids, course2_block_ids - course1_block_ids
)
)
@@ -151,15 +151,15 @@ def assertCoursesEqual(self, course1_id, course2_id):
course2_item = self.store.get_item(course2_item_loc)
# compare published state
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
self.store.has_published_version(course1_item),
self.store.has_published_version(course2_item)
)
# compare data
- self.assertEqual(hasattr(course1_item, 'data'), hasattr(course2_item, 'data'))
+ self.assertEqual(hasattr(course1_item, 'data'), hasattr(course2_item, 'data')) # noqa: PT009
if hasattr(course1_item, 'data'):
- self.assertEqual(course1_item.data, course2_item.data)
+ self.assertEqual(course1_item.data, course2_item.data) # noqa: PT009
# compare meta-data
course1_metadata = own_metadata(course1_item)
@@ -167,23 +167,23 @@ def assertCoursesEqual(self, course1_id, course2_id):
# Omit edx_video_id as it can be different in case of extrnal video imports.
course1_metadata.pop('edx_video_id', None)
course2_metadata.pop('edx_video_id', None)
- self.assertEqual(course1_metadata, course2_metadata)
+ self.assertEqual(course1_metadata, course2_metadata) # noqa: PT009
# compare children
- self.assertEqual(course1_item.has_children, course2_item.has_children)
+ self.assertEqual(course1_item.has_children, course2_item.has_children) # noqa: PT009
if course1_item.has_children:
expected_children = []
for course1_item_child in course1_item.children:
expected_children.append(
course2_id.make_usage_key(course1_item_child.block_type, course1_item_child.block_id)
)
- self.assertEqual(expected_children, course2_item.children)
+ self.assertEqual(expected_children, course2_item.children) # noqa: PT009
# compare assets
content_store = self.store.contentstore
course1_assets, count_course1_assets = content_store.get_all_content_for_course(course1_id)
_, count_course2_assets = content_store.get_all_content_for_course(course2_id)
- self.assertEqual(count_course1_assets, count_course2_assets)
+ self.assertEqual(count_course1_assets, count_course2_assets) # noqa: PT009
for asset in course1_assets:
asset_son = asset.get('content_son', asset['_id'])
self.assertAssetsEqual(asset_son, course1_id, course2_id)
@@ -191,10 +191,10 @@ def assertCoursesEqual(self, course1_id, course2_id):
def check_verticals(self, items):
""" Test getting the editing HTML for each vertical. """
# assert is here to make sure that the course being tested actually has verticals (units) to check.
- self.assertGreater(len(items), 0, "Course has no verticals (units) to check")
+ self.assertGreater(len(items), 0, "Course has no verticals (units) to check") # noqa: PT009
for block in items:
resp = self.client.get_html(get_url('container_handler', block.location))
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def assertAssetsEqual(self, asset_son, course1_id, course2_id):
"""Verifies the asset of the given key has the same attributes in both given courses."""
@@ -203,12 +203,12 @@ def assertAssetsEqual(self, asset_son, course1_id, course2_id):
filename = asset_son.block_id if hasattr(asset_son, 'block_id') else asset_son['name']
course1_asset_attrs = content_store.get_attrs(course1_id.make_asset_key(category, filename))
course2_asset_attrs = content_store.get_attrs(course2_id.make_asset_key(category, filename))
- self.assertEqual(len(course1_asset_attrs), len(course2_asset_attrs))
+ self.assertEqual(len(course1_asset_attrs), len(course2_asset_attrs)) # noqa: PT009
for key, value in course1_asset_attrs.items():
if key in ['_id', 'filename', 'uploadDate', 'content_son', 'thumbnail_location']:
pass
else:
- self.assertEqual(value, course2_asset_attrs[key])
+ self.assertEqual(value, course2_asset_attrs[key]) # noqa: PT009
class HTTPGetResponse:
diff --git a/cms/djangoapps/contentstore/utils.py b/cms/djangoapps/contentstore/utils.py
index 0dd56a1272a0..b0b37a4a13b2 100644
--- a/cms/djangoapps/contentstore/utils.py
+++ b/cms/djangoapps/contentstore/utils.py
@@ -209,7 +209,7 @@ def get_lms_link_for_item(location, preview=False):
query_string = urlencode(params)
url_parts = list(urlparse(lms_base))
- url_parts[2] = '/courses/{course_key}/jump_to/{location}'.format(
+ url_parts[2] = '/courses/{course_key}/jump_to/{location}'.format( # noqa: UP032
course_key=str(location.course_key),
location=str(location),
)
@@ -230,7 +230,7 @@ def get_lms_link_for_certificate_web_view(course_key, mode):
if lms_base is None:
return None
- return "//{certificate_web_base}/certificates/course/{course_id}?preview={mode}".format(
+ return "//{certificate_web_base}/certificates/course/{course_id}?preview={mode}".format( # noqa: UP032
certificate_web_base=lms_base,
course_id=str(course_key),
mode=mode
@@ -996,7 +996,7 @@ def get_subsections_in_section():
section_subsections = section.get_children()
return section_subsections
except AttributeError:
- log.error("URL Retrieval Error: subsection {subsection} included in section {section}".format(
+ log.error("URL Retrieval Error: subsection {subsection} included in section {section}".format( # noqa: UP032 # pylint: disable=line-too-long
section=section.location,
subsection=subsection.location
))
@@ -1010,7 +1010,7 @@ def get_sections_in_course():
section_subsections = section.get_parent().get_children()
return section_subsections
except AttributeError:
- log.error("URL Retrieval Error: In section {section} in course".format(
+ log.error("URL Retrieval Error: In section {section} in course".format( # noqa: UP032
section=section.location,
))
return None
@@ -1221,7 +1221,7 @@ def duplicate_block(
# .. event_implemented_name: XBLOCK_DUPLICATED
# .. event_type: org.openedx.content_authoring.xblock.duplicated.v1
XBLOCK_DUPLICATED.send_event(
- time=datetime.now(timezone.utc),
+ time=datetime.now(timezone.utc), # noqa: UP017
xblock_info=DuplicatedXBlockData(
usage_key=dest_block.location,
block_type=dest_block.location.block_type,
diff --git a/cms/djangoapps/contentstore/video_storage_handlers.py b/cms/djangoapps/contentstore/video_storage_handlers.py
index b90ae5dd1766..a8eb2b52b1f4 100644
--- a/cms/djangoapps/contentstore/video_storage_handlers.py
+++ b/cms/djangoapps/contentstore/video_storage_handlers.py
@@ -232,7 +232,7 @@ def send_zip(zip_file, size=None):
"""
wrapper = FileWrapper(zip_file, settings.COURSE_EXPORT_DOWNLOAD_CHUNK_SIZE)
response = StreamingHttpResponse(wrapper, content_type='application/zip')
- response['Content-Dispositon'] = 'attachment; filename=%s' % os.path.basename(zip_file.name)
+ response['Content-Dispositon'] = 'attachment; filename=%s' % os.path.basename(zip_file.name) # noqa: UP031
response['Content-Length'] = size
return response
@@ -811,7 +811,7 @@ def videos_post(course, request):
try:
file_name.encode('ascii')
except UnicodeEncodeError:
- error_msg = 'The file name for %s must contain only ASCII characters.' % file_name
+ error_msg = 'The file name for %s must contain only ASCII characters.' % file_name # noqa: UP031
return {'error': error_msg}, 400
edx_video_id = str(uuid4())
@@ -961,8 +961,8 @@ def get_course_youtube_edx_video_ids(course_id):
"""
Get a list of youtube edx_video_ids
"""
- invalid_key_error_msg = "Invalid course_key: '%s'." % course_id
- unexpected_error_msg = "Unexpected error occurred for course_id: '%s'." % course_id
+ invalid_key_error_msg = "Invalid course_key: '%s'." % course_id # noqa: UP031
+ unexpected_error_msg = "Unexpected error occurred for course_id: '%s'." % course_id # noqa: UP031
try: # lint-amnesty, pylint: disable=too-many-nested-blocks
course_key = CourseKey.from_string(course_id)
diff --git a/cms/djangoapps/contentstore/video_utils.py b/cms/djangoapps/contentstore/video_utils.py
index 4681b2d98595..44e216947117 100644
--- a/cms/djangoapps/contentstore/video_utils.py
+++ b/cms/djangoapps/contentstore/video_utils.py
@@ -87,7 +87,7 @@ def download_youtube_video_thumbnail(youtube_id):
thumbnail_content = thumbnail_content_type = None
# Download highest resolution thumbnail available.
for thumbnail_quality in YOUTUBE_THUMBNAIL_SIZES:
- thumbnail_url = urljoin('https://img.youtube.com', '/vi/{youtube_id}/{thumbnail_quality}.jpg'.format(
+ thumbnail_url = urljoin('https://img.youtube.com', '/vi/{youtube_id}/{thumbnail_quality}.jpg'.format( # noqa: UP032 # pylint: disable=line-too-long
youtube_id=youtube_id, thumbnail_quality=thumbnail_quality
))
response = requests.get(thumbnail_url)
diff --git a/cms/djangoapps/contentstore/views/__init__.py b/cms/djangoapps/contentstore/views/__init__.py
index 7c9eec03cdc6..c3e2bce3bc51 100644
--- a/cms/djangoapps/contentstore/views/__init__.py
+++ b/cms/djangoapps/contentstore/views/__init__.py
@@ -1,25 +1,25 @@
"All view functions for contentstore, broken out into submodules"
-from .assets import *
-from .block import *
-from .checklists import *
-from .component import *
-from .course import * # lint-amnesty, pylint: disable=redefined-builtin
-from .entrance_exam import *
-from .error import *
-from .export_git import *
-from .helpers import *
-from .import_export import *
-from .library import *
-from .preview import *
-from .public import *
-from .tabs import *
-from .transcript_settings import *
-from .transcripts_ajax import *
-from .user import *
-from .videos import *
+from .assets import * # noqa: F403
+from .block import * # noqa: F403
+from .checklists import * # noqa: F403
+from .component import * # noqa: F403
+from .course import * # lint-amnesty, pylint: disable=redefined-builtin # noqa: F403
+from .entrance_exam import * # noqa: F403
+from .error import * # noqa: F403
+from .export_git import * # noqa: F403
+from .helpers import * # noqa: F403
+from .import_export import * # noqa: F403
+from .library import * # noqa: F403
+from .preview import * # noqa: F403
+from .public import * # noqa: F403
+from .tabs import * # noqa: F403
+from .transcript_settings import * # noqa: F403
+from .transcripts_ajax import * # noqa: F403
+from .user import * # noqa: F403
+from .videos import * # noqa: F403
try:
- from .dev import *
+ from .dev import * # noqa: F403
except ImportError:
pass
diff --git a/cms/djangoapps/contentstore/views/certificate_manager.py b/cms/djangoapps/contentstore/views/certificate_manager.py
index d0c0d7483174..dda1e172c503 100644
--- a/cms/djangoapps/contentstore/views/certificate_manager.py
+++ b/cms/djangoapps/contentstore/views/certificate_manager.py
@@ -88,7 +88,7 @@ def parse(json_string):
try:
certificate = json.loads(json_string)
except ValueError:
- raise CertificateValidationError(_("invalid JSON")) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CertificateValidationError(_("invalid JSON")) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
# Include the data contract version
certificate["version"] = CERTIFICATE_SCHEMA_VERSION
# Ensure a signatories list is always returned
@@ -155,7 +155,7 @@ def assign_id(course, certificate_data, certificate_id=None):
used_ids
)
- for index, signatory in enumerate(certificate_data['signatories']): # pylint: disable=unused-variable
+ for index, signatory in enumerate(certificate_data['signatories']): # pylint: disable=unused-variable # noqa: B007
if signatory and not signatory.get('id', False):
signatory['id'] = generate_int_id(used_ids=used_ids)
used_ids.append(signatory['id'])
@@ -251,7 +251,7 @@ def remove_certificate(request, store, course, certificate_id):
if int(cert['id']) == int(certificate_id):
certificate = course.certificates['certificates'][index]
# Remove any signatory assets prior to dropping the entire cert record from the course
- for sig_index, signatory in enumerate(certificate.get('signatories')): # pylint: disable=unused-variable
+ for sig_index, signatory in enumerate(certificate.get('signatories')): # pylint: disable=unused-variable # noqa: B007
_delete_asset(course.id, signatory['signature_image_path'])
# Now drop the certificate record
course.certificates['certificates'].pop(index)
@@ -264,7 +264,7 @@ def remove_signatory(request, store, course, certificate_id, signatory_id):
"""
Remove the specified signatory from the provided course certificate
"""
- for cert_index, cert in enumerate(course.certificates['certificates']): # pylint: disable=unused-variable
+ for cert_index, cert in enumerate(course.certificates['certificates']): # pylint: disable=unused-variable # noqa: B007
if int(cert['id']) == int(certificate_id):
for sig_index, signatory in enumerate(cert.get('signatories')):
if int(signatory_id) == int(signatory['id']):
diff --git a/cms/djangoapps/contentstore/views/certificates.py b/cms/djangoapps/contentstore/views/certificates.py
index 0d3d1c23eba4..88f7d113aaa5 100644
--- a/cms/djangoapps/contentstore/views/certificates.py
+++ b/cms/djangoapps/contentstore/views/certificates.py
@@ -292,7 +292,7 @@ def signatory_detail_handler(request, course_key_string, certificate_id, signato
match_cert = None
# pylint: disable=unused-variable
- for index, cert in enumerate(certificates_list):
+ for index, cert in enumerate(certificates_list): # noqa: B007
if certificate_id is not None:
if int(cert['id']) == int(certificate_id):
match_cert = cert
diff --git a/cms/djangoapps/contentstore/views/component.py b/cms/djangoapps/contentstore/views/component.py
index ec24af1a3e7d..9fa38665466f 100644
--- a/cms/djangoapps/contentstore/views/component.py
+++ b/cms/djangoapps/contentstore/views/component.py
@@ -146,7 +146,7 @@ def container_handler(request, usage_key_string): # pylint: disable=too-many-st
try:
usage_key = UsageKey.from_string(usage_key_string)
except InvalidKeyError: # Raise Http404 on invalid 'usage_key_string'
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
with modulestore().bulk_operations(usage_key.course_key):
try:
course, xblock, lms_link, preview_lms_link = _get_item_in_course(request, usage_key)
@@ -194,7 +194,7 @@ def container_embed_handler(request, usage_key_string): # pylint: disable=too-m
try:
course, xblock, lms_link, preview_lms_link = _get_item_in_course(request, usage_key)
except ItemNotFoundError:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
container_handler_context = get_container_handler_context(request, usage_key, course, xblock)
return render_to_response('container_chromeless.html', container_handler_context)
@@ -580,7 +580,7 @@ def component_handler(request, usage_key_string, handler, suffix=''):
resp = handler_block.handle(handler, req, suffix)
except NoSuchHandlerError:
log.info("XBlock %s attempted to access missing handler %r", handler_block, handler, exc_info=True)
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
# unintentional update to handle any side effects of handle call
# could potentially be updating actual course data or simply caching its values
diff --git a/cms/djangoapps/contentstore/views/course.py b/cms/djangoapps/contentstore/views/course.py
index 04d2cd432590..37e344e28c0b 100644
--- a/cms/djangoapps/contentstore/views/course.py
+++ b/cms/djangoapps/contentstore/views/course.py
@@ -7,7 +7,7 @@
import random
import re
import string
-from typing import Dict
+from typing import Dict # noqa: UP035
import django.utils
from ccx_keys.locator import CCXLocator
@@ -334,7 +334,7 @@ def course_handler(request, course_key_string=None):
else:
return HttpResponseNotFound()
except InvalidKeyError:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
@login_required
@@ -1137,7 +1137,7 @@ def _create_or_rerun_course(request):
return JsonResponse({
"ErrMsg": _("Unable to create course '{name}'.\n\n{err}").format(name=display_name, err=str(error))}
)
- except PermissionDenied as error: # pylint: disable=unused-variable
+ except PermissionDenied as error: # pylint: disable=unused-variable # noqa: F841
log.info(
"User does not have the permission to create course in this organization"
"or course creation is disabled."
@@ -1163,7 +1163,7 @@ def create_new_course(user, org, number, run, fields):
try:
org_data = ensure_organization(org)
except InvalidOrganizationException:
- raise ValidationError(_( # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(_( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
'You must link this course to an organization in order to continue. Organization '
'you selected does not exist in the system, you will need to add it to the system'
))
@@ -1272,7 +1272,7 @@ def course_info_handler(request, course_key_string):
try:
course_key = CourseKey.from_string(course_key_string)
except InvalidKeyError:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return redirect(get_updates_url(course_key))
@@ -1525,7 +1525,7 @@ def advanced_settings_handler(request, course_key_string):
return JsonResponseBadRequest(err.detail)
-def update_course_advanced_settings(course_block: CourseBlock, data: Dict, user: User) -> Dict:
+def update_course_advanced_settings(course_block: CourseBlock, data: Dict, user: User) -> Dict: # noqa: UP006
"""
Helper function to update course advanced settings from API data.
@@ -1589,7 +1589,7 @@ def validate_textbooks_json(text):
try:
textbooks = json.loads(text)
except ValueError:
- raise TextbookValidationError("invalid JSON") # lint-amnesty, pylint: disable=raise-missing-from
+ raise TextbookValidationError("invalid JSON") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not isinstance(textbooks, (list, tuple)):
raise TextbookValidationError("must be JSON list")
for textbook in textbooks:
@@ -1612,7 +1612,7 @@ def validate_textbook_json(textbook):
try:
textbook = json.loads(textbook)
except ValueError:
- raise TextbookValidationError("invalid JSON") # lint-amnesty, pylint: disable=raise-missing-from
+ raise TextbookValidationError("invalid JSON") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not isinstance(textbook, dict):
raise TextbookValidationError("must be JSON object")
if not textbook.get("tab_title"):
diff --git a/cms/djangoapps/contentstore/views/import_export.py b/cms/djangoapps/contentstore/views/import_export.py
index 33f44b4de935..fd3b876d8625 100644
--- a/cms/djangoapps/contentstore/views/import_export.py
+++ b/cms/djangoapps/contentstore/views/import_export.py
@@ -301,7 +301,7 @@ def send_tarball(tarball, size):
"""
wrapper = FileWrapper(tarball, settings.COURSE_EXPORT_DOWNLOAD_CHUNK_SIZE)
response = StreamingHttpResponse(wrapper, content_type='application/x-tgz')
- response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(tarball.name)
+ response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(tarball.name) # noqa: UP031
response['Content-Length'] = size
return response
@@ -468,7 +468,7 @@ def export_output_handler(request, course_key_string):
tarball = course_import_export_storage.open(artifact.file.name)
return send_tarball(tarball, artifact.file.storage.size(artifact.file.name))
except UserTaskArtifact.DoesNotExist:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
finally:
if artifact:
artifact.file.close()
diff --git a/cms/djangoapps/contentstore/views/library.py b/cms/djangoapps/contentstore/views/library.py
index 6440fb0526cd..70ae0bce2c2a 100644
--- a/cms/djangoapps/contentstore/views/library.py
+++ b/cms/djangoapps/contentstore/views/library.py
@@ -227,7 +227,7 @@ def _create_library(request):
)
# Give the user admin ("Instructor") role for this library:
add_instructor(new_lib.location.library_key, request.user, request.user)
- except PermissionDenied as error: # pylint: disable=unused-variable
+ except PermissionDenied as error: # pylint: disable=unused-variable # noqa: F841
log.info(
"User does not have the permission to create LIBRARY in this organization."
"User: '%s' Org: '%s' LIBRARY #: '%s'.",
diff --git a/cms/djangoapps/contentstore/views/preview.py b/cms/djangoapps/contentstore/views/preview.py
index 77de2f4f263f..d3ca840c01fd 100644
--- a/cms/djangoapps/contentstore/views/preview.py
+++ b/cms/djangoapps/contentstore/views/preview.py
@@ -75,11 +75,11 @@ def preview_handler(request, usage_key_string, handler, suffix=''):
except NoSuchHandlerError:
log.exception("XBlock %s attempted to access missing handler %r", instance, handler)
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except (XModuleNotFoundError, NotFoundError):
log.exception("Module indicating to user that request doesn't exist")
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except ProcessingError:
log.warning("Module raised an error while processing AJAX request",
diff --git a/cms/djangoapps/contentstore/views/public.py b/cms/djangoapps/contentstore/views/public.py
index 0684d52022ae..d0d782e1be43 100644
--- a/cms/djangoapps/contentstore/views/public.py
+++ b/cms/djangoapps/contentstore/views/public.py
@@ -24,7 +24,7 @@ def register_redirect_to_lms(request):
This view redirects to the LMS register view. It is used to temporarily keep the old
Studio signup url alive.
"""
- register_url = '{register_url}{params}'.format(
+ register_url = '{register_url}{params}'.format( # noqa: UP032
register_url=settings.FRONTEND_REGISTER_URL,
params=_build_next_param(request),
)
@@ -36,7 +36,7 @@ def login_redirect_to_lms(request):
This view redirects to the LMS login view. It is used for Django's LOGIN_URL
setting, which is where unauthenticated requests to protected endpoints are redirected.
"""
- login_url = '{login_url}{params}'.format(
+ login_url = '{login_url}{params}'.format( # noqa: UP032
login_url=settings.FRONTEND_LOGIN_URL,
params=_build_next_param(request),
)
diff --git a/cms/djangoapps/contentstore/views/tabs.py b/cms/djangoapps/contentstore/views/tabs.py
index c4886203630c..86a725bcfc78 100644
--- a/cms/djangoapps/contentstore/views/tabs.py
+++ b/cms/djangoapps/contentstore/views/tabs.py
@@ -1,7 +1,7 @@
"""
Views related to course tabs
"""
-from typing import Dict, Iterable, List, Optional, Union
+from typing import Dict, Iterable, List, Optional, Union # noqa: UP035
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
@@ -92,7 +92,7 @@ def get_course_tabs(course_item: CourseBlock, user: User) -> Iterable[CourseTab]
yield tab
-def update_tabs_handler(course_item: CourseBlock, tabs_data: Dict, user: User) -> None:
+def update_tabs_handler(course_item: CourseBlock, tabs_data: Dict, user: User) -> None: # noqa: UP006
"""
Helper to handle updates to course tabs based on API data.
@@ -155,7 +155,7 @@ def create_new_list(tab_locators, old_tab_list):
return sorted(new_tab_list, key=lambda item: item.priority or float('inf'))
-def edit_tab_handler(course_item: CourseBlock, tabs_data: Dict, user: User):
+def edit_tab_handler(course_item: CourseBlock, tabs_data: Dict, user: User): # noqa: UP006
"""
Helper function for handling requests to edit settings of a single tab
"""
@@ -179,7 +179,7 @@ def edit_tab_handler(course_item: CourseBlock, tabs_data: Dict, user: User):
raise NotImplementedError(f"Unsupported request to edit tab: {tabs_data}")
-def get_tab_by_tab_id_locator(tab_list: List[CourseTab], tab_id_locator: Dict[str, str]) -> Optional[CourseTab]:
+def get_tab_by_tab_id_locator(tab_list: List[CourseTab], tab_id_locator: Dict[str, str]) -> Optional[CourseTab]: # noqa: UP006, UP045 # pylint: disable=line-too-long
"""
Look for a tab with the specified tab_id or locator. Returns the first matching tab.
"""
@@ -191,7 +191,7 @@ def get_tab_by_tab_id_locator(tab_list: List[CourseTab], tab_id_locator: Dict[st
return tab
-def get_tab_by_locator(tab_list: List[CourseTab], tab_location: Union[str, UsageKey]) -> Optional[CourseTab]:
+def get_tab_by_locator(tab_list: List[CourseTab], tab_location: Union[str, UsageKey]) -> Optional[CourseTab]: # noqa: UP006, UP007, UP045 # pylint: disable=line-too-long
"""
Look for a tab with the specified locator. Returns the first matching tab.
"""
diff --git a/cms/djangoapps/contentstore/views/tests/test_access.py b/cms/djangoapps/contentstore/views/tests/test_access.py
index b8c2404cf678..b1eacbab09c7 100644
--- a/cms/djangoapps/contentstore/views/tests/test_access.py
+++ b/cms/djangoapps/contentstore/views/tests/test_access.py
@@ -39,12 +39,12 @@ def test_get_user_role_instructor(self):
Verifies if user is instructor.
"""
add_users(self.global_admin, CourseInstructorRole(self.course_key), self.instructor)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
'instructor',
get_user_role(self.instructor, self.course_key)
)
add_users(self.global_admin, CourseStaffRole(self.course_key), self.staff)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
'instructor',
get_user_role(self.instructor, self.course_key)
)
@@ -54,7 +54,7 @@ def test_get_user_role_staff(self):
Verifies if user is staff.
"""
add_users(self.global_admin, CourseStaffRole(self.course_key), self.staff)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
'staff',
get_user_role(self.staff, self.course_key)
)
diff --git a/cms/djangoapps/contentstore/views/tests/test_assets.py b/cms/djangoapps/contentstore/views/tests/test_assets.py
index 2467e41a9562..4601f27f05f0 100644
--- a/cms/djangoapps/contentstore/views/tests/test_assets.py
+++ b/cms/djangoapps/contentstore/views/tests/test_assets.py
@@ -91,14 +91,14 @@ class BasicAssetsTestCase(AssetsTestCase):
def test_basic(self):
resp = self.client.get(self.url, HTTP_ACCEPT='text/html')
- self.assertEqual(resp.status_code, 302)
+ self.assertEqual(resp.status_code, 302) # noqa: PT009
def test_static_url_generation(self):
course_key = CourseLocator('org', 'class', 'run')
location = course_key.make_asset_key('asset', 'my_file_name.jpg')
path = StaticContent.get_static_path_from_location(location)
- self.assertEqual(path, '/static/my_file_name.jpg')
+ self.assertEqual(path, '/static/my_file_name.jpg') # noqa: PT009
def test_pdf_asset(self):
module_store = modulestore()
@@ -122,7 +122,7 @@ def test_pdf_asset(self):
# Check after import textbook.pdf has valid contentType ('application/pdf')
# Note: Actual contentType for textbook.pdf in asset.json is 'text/pdf'
- self.assertEqual(content.content_type, 'application/pdf')
+ self.assertEqual(content.content_type, 'application/pdf') # noqa: PT009
def test_relative_url_for_split_course(self):
"""
@@ -148,9 +148,9 @@ def test_relative_url_for_split_course(self):
url = asset_url.replace('"', '')
base_url = url.replace(filename, '')
- self.assertIn(f"/{filename}", url)
+ self.assertIn(f"/{filename}", url) # noqa: PT009
resp = self.client.get(url)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# simulation of html page where base_url is up-to asset's main directory
# and relative_path is dom element with its src
@@ -158,9 +158,9 @@ def test_relative_url_for_split_course(self):
# browser append relative_path with base_url
absolute_path = base_url + relative_path
- self.assertIn(f"/{relative_path}", absolute_path)
+ self.assertIn(f"/{relative_path}", absolute_path) # noqa: PT009
resp = self.client.get(absolute_path)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
class PaginationTestCase(AssetsTestCase):
@@ -264,9 +264,9 @@ def assert_correct_asset_response(self, url, expected_start, expected_length, ex
resp = self.client.get(url, HTTP_ACCEPT='application/json')
json_response = json.loads(resp.content.decode('utf-8'))
assets_response = json_response['assets']
- self.assertEqual(json_response['start'], expected_start)
- self.assertEqual(len(assets_response), expected_length)
- self.assertEqual(json_response['totalCount'], expected_total)
+ self.assertEqual(json_response['start'], expected_start) # noqa: PT009
+ self.assertEqual(len(assets_response), expected_length) # noqa: PT009
+ self.assertEqual(json_response['totalCount'], expected_total) # noqa: PT009
def assert_correct_sort_response(self, url, sort, direction):
"""
@@ -276,17 +276,17 @@ def assert_correct_sort_response(self, url, sort, direction):
url + '?sort=' + sort + '&direction=' + direction, HTTP_ACCEPT='application/json')
json_response = json.loads(resp.content.decode('utf-8'))
assets_response = json_response['assets']
- self.assertEqual(sort, json_response['sort'])
- self.assertEqual(direction, json_response['direction'])
+ self.assertEqual(sort, json_response['sort']) # noqa: PT009
+ self.assertEqual(direction, json_response['direction']) # noqa: PT009
name1 = assets_response[0][sort]
name2 = assets_response[1][sort]
name3 = assets_response[2][sort]
if direction == 'asc':
- self.assertLessEqual(name1, name2)
- self.assertLessEqual(name2, name3)
+ self.assertLessEqual(name1, name2) # noqa: PT009
+ self.assertLessEqual(name2, name3) # noqa: PT009
else:
- self.assertGreaterEqual(name1, name2)
- self.assertGreaterEqual(name2, name3)
+ self.assertGreaterEqual(name1, name2) # noqa: PT009
+ self.assertGreaterEqual(name2, name3) # noqa: PT009
def assert_correct_filter_response(self, url, filter_type, filter_value):
"""
@@ -312,7 +312,7 @@ def assert_correct_filter_response(self, url, filter_type, filter_value):
url + '?' + filter_type + '=' + filter_value, HTTP_ACCEPT='application/json')
json_response = json.loads(resp.content.decode('utf-8'))
assets_response = json_response['assets']
- self.assertEqual(filter_value_split, json_response['assetTypes'])
+ self.assertEqual(filter_value_split, json_response['assetTypes']) # noqa: PT009
if filter_value != '':
content_types = [asset['content_type'].lower()
@@ -321,12 +321,12 @@ def assert_correct_filter_response(self, url, filter_type, filter_value):
for content_type in content_types:
# content_type is either not any defined type (i.e. OTHER) or is a defined type (if multiple
# parameters including OTHER are used)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
content_type in requested_file_extensions or content_type not in all_file_extensions
)
else:
for content_type in content_types:
- self.assertIn(content_type, requested_file_extensions)
+ self.assertIn(content_type, requested_file_extensions) # noqa: PT009
def assert_invalid_parameters_error(self, url, filter_type, filter_value):
"""
@@ -334,7 +334,7 @@ def assert_invalid_parameters_error(self, url, filter_type, filter_value):
"""
resp = self.client.get(
url + '?' + filter_type + '=' + filter_value, HTTP_ACCEPT='application/json')
- self.assertEqual(resp.status_code, 400)
+ self.assertEqual(resp.status_code, 400) # noqa: PT009
def assert_correct_text_search_response(self, url, text_search, number_matches):
"""
@@ -344,14 +344,14 @@ def assert_correct_text_search_response(self, url, text_search, number_matches):
url + '?text_search=' + text_search, HTTP_ACCEPT='application/json')
json_response = json.loads(resp.content.decode('utf-8'))
assets_response = json_response['assets']
- self.assertEqual(text_search, json_response['textSearch'])
- self.assertEqual(len(assets_response), number_matches)
+ self.assertEqual(text_search, json_response['textSearch']) # noqa: PT009
+ self.assertEqual(len(assets_response), number_matches) # noqa: PT009
text_search_tokens = text_search.split()
for asset_response in assets_response:
for token in text_search_tokens:
- self.assertIn(token.lower(), asset_response['display_name'].lower())
+ self.assertIn(token.lower(), asset_response['display_name'].lower()) # noqa: PT009
@ddt
@@ -365,11 +365,11 @@ def setUp(self):
def test_happy_path(self):
resp = self.upload_asset()
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def test_upload_image(self):
resp = self.upload_asset("test_image", asset_type="image")
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
@data(
(int(MAX_FILE_SIZE / 2.0), "small.file.test", 200),
@@ -387,7 +387,7 @@ def test_file_size(self, case, get_file_size):
"name": name,
"file": f
})
- self.assertEqual(resp.status_code, status_code)
+ self.assertEqual(resp.status_code, status_code) # noqa: PT009
class DownloadTestCase(AssetsTestCase):
@@ -400,19 +400,19 @@ def setUp(self):
# First, upload something.
self.asset_name = 'download_test'
resp = self.upload_asset(self.asset_name)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
self.uploaded_url = json.loads(resp.content.decode('utf-8'))['asset']['url']
def test_download(self):
# Now, download it.
resp = self.client.get(self.uploaded_url, HTTP_ACCEPT='text/html')
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
self.assertContains(resp, 'This file is generated by python unit test')
def test_download_not_found_throw(self):
url = self.uploaded_url.replace(self.asset_name, 'not_the_asset_name')
resp = self.client.get(url, HTTP_ACCEPT='text/html')
- self.assertEqual(resp.status_code, 404)
+ self.assertEqual(resp.status_code, 404) # noqa: PT009
@patch('xmodule.modulestore.mixed.MixedModuleStore.find_asset_metadata')
def test_pickling_calls(self, patched_find_asset_metadata):
@@ -420,7 +420,7 @@ def test_pickling_calls(self, patched_find_asset_metadata):
"""
patched_find_asset_metadata.return_value = None
self.client.get(self.uploaded_url, HTTP_ACCEPT='text/html')
- self.assertFalse(patched_find_asset_metadata.called)
+ self.assertFalse(patched_find_asset_metadata.called) # noqa: PT009
class AssetToJsonTestCase(AssetsTestCase):
@@ -440,20 +440,20 @@ def test_basic(self):
output = assets._get_asset_json("my_file", content_type, upload_date, location,
thumbnail_location, True, course_key)
- self.assertEqual(output["display_name"], "my_file")
- self.assertEqual(output["date_added"], "Jun 01, 2013 at 10:30 UTC")
- self.assertEqual(output["url"], "/asset-v1:org+class+run+type@asset+block@my_file_name.jpg")
- self.assertEqual(
+ self.assertEqual(output["display_name"], "my_file") # noqa: PT009
+ self.assertEqual(output["date_added"], "Jun 01, 2013 at 10:30 UTC") # noqa: PT009
+ self.assertEqual(output["url"], "/asset-v1:org+class+run+type@asset+block@my_file_name.jpg") # noqa: PT009
+ self.assertEqual( # noqa: PT009
output["external_url"], "https://lms_root_url/asset-v1:org+class+run+type@asset+block@my_file_name.jpg"
)
- self.assertEqual(output["portable_url"], "/static/my_file_name.jpg")
- self.assertEqual(output["thumbnail"], "/asset-v1:org+class+run+type@thumbnail+block@my_file_name_thumb.jpg")
- self.assertEqual(output["id"], str(location))
- self.assertEqual(output['locked'], True)
- self.assertEqual(output['static_full_url'], '/asset-v1:org+class+run+type@asset+block@my_file_name.jpg')
+ self.assertEqual(output["portable_url"], "/static/my_file_name.jpg") # noqa: PT009
+ self.assertEqual(output["thumbnail"], "/asset-v1:org+class+run+type@thumbnail+block@my_file_name_thumb.jpg") # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(output["id"], str(location)) # noqa: PT009
+ self.assertEqual(output['locked'], True) # noqa: PT009
+ self.assertEqual(output['static_full_url'], '/asset-v1:org+class+run+type@asset+block@my_file_name.jpg') # noqa: PT009 # pylint: disable=line-too-long
output = assets._get_asset_json("name", content_type, upload_date, location, None, False, course_key)
- self.assertIsNone(output["thumbnail"])
+ self.assertIsNone(output["thumbnail"]) # noqa: PT009
class LockAssetTestCase(AssetsTestCase):
@@ -470,7 +470,7 @@ def verify_asset_locked_state(locked):
asset_location = StaticContent.get_location_from_path(
'asset-v1:edX+toy+2012_Fall+type@asset+block@sample_static.html')
content = contentstore().find(asset_location)
- self.assertEqual(content.locked, locked)
+ self.assertEqual(content.locked, locked) # noqa: PT009
def post_asset_update(lock, course):
""" Helper method for posting asset update. """
@@ -490,7 +490,7 @@ def post_asset_update(lock, course):
"application/json"
)
- self.assertEqual(resp.status_code, 201)
+ self.assertEqual(resp.status_code, 201) # noqa: PT009
return json.loads(resp.content.decode('utf-8'))
# Load the toy course.
@@ -509,12 +509,12 @@ def post_asset_update(lock, course):
# Lock the asset
resp_asset = post_asset_update(True, course)
- self.assertTrue(resp_asset['locked'])
+ self.assertTrue(resp_asset['locked']) # noqa: PT009
verify_asset_locked_state(True)
# Unlock the asset
resp_asset = post_asset_update(False, course)
- self.assertFalse(resp_asset['locked'])
+ self.assertFalse(resp_asset['locked']) # noqa: PT009
verify_asset_locked_state(False)
@@ -531,7 +531,7 @@ def setUp(self):
self.asset = self.get_sample_asset(self.asset_name)
response = self.client.post(self.url, {"name": self.asset_name, "file": self.asset})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
self.uploaded_id = json.loads(response.content.decode('utf-8'))['asset']['id']
self.asset_location = AssetKey.from_string(self.uploaded_id)
@@ -542,7 +542,7 @@ def test_delete_asset(self):
test_url = reverse_course_url(
'assets_handler', self.course.id, kwargs={'asset_key_string': self.uploaded_id})
resp = self.client.delete(test_url, HTTP_ACCEPT="application/json")
- self.assertEqual(resp.status_code, 204)
+ self.assertEqual(resp.status_code, 204) # noqa: PT009
def test_delete_image_type_asset(self):
""" Tests deletion of image type asset """
@@ -551,12 +551,12 @@ def test_delete_image_type_asset(self):
# upload image
response = self.client.post(self.url, {"name": "delete_image_test", "file": image_asset})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
uploaded_image_url = json.loads(response.content.decode('utf-8'))['asset']['id']
# upload image thumbnail
response = self.client.post(self.url, {"name": "delete_image_thumb_test", "file": thumbnail_image_asset})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
thumbnail_url = json.loads(response.content.decode('utf-8'))['asset']['url']
thumbnail_location = StaticContent.get_location_from_path(thumbnail_url)
@@ -571,7 +571,7 @@ def test_delete_image_type_asset(self):
test_url = reverse_course_url(
'assets_handler', self.course.id, kwargs={'asset_key_string': str(uploaded_image_url)})
resp = self.client.delete(test_url, HTTP_ACCEPT="application/json")
- self.assertEqual(resp.status_code, 204)
+ self.assertEqual(resp.status_code, 204) # noqa: PT009
def test_delete_asset_with_invalid_asset(self):
""" Tests the sad path :( """
@@ -580,7 +580,7 @@ def test_delete_asset_with_invalid_asset(self):
self.course.id, kwargs={'asset_key_string': "asset-v1:edX+toy+2012_Fall+type@asset+block@invalid.pdf"}
)
resp = self.client.delete(test_url, HTTP_ACCEPT="application/json")
- self.assertEqual(resp.status_code, 404)
+ self.assertEqual(resp.status_code, 404) # noqa: PT009
def test_delete_asset_with_invalid_thumbnail(self):
""" Tests the sad path :( """
@@ -590,7 +590,7 @@ def test_delete_asset_with_invalid_thumbnail(self):
'/asset-v1:edX+toy+2012_Fall+type@asset+block@invalid.pdf')
contentstore().save(self.content)
resp = self.client.delete(test_url, HTTP_ACCEPT="application/json")
- self.assertEqual(resp.status_code, 204)
+ self.assertEqual(resp.status_code, 204) # noqa: PT009
class AssetsEndpointsAuthzTestCase(CourseAuthzTestMixin, AssetsTestCase):
@@ -644,23 +644,23 @@ def test_auditor_permissions(self):
# GET assets_handler allowed
resp = client.get(self.asset_url)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# GET asset_usage_path_handler allowed
resp = client.get(self.asset_usage_url)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# POST assets_handler forbidden
resp = client.post(self.url, {"name": "file", "file": self.get_sample_asset('file')})
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# PUT assets_handler forbidden
resp = self._put_asset(client)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# DELETE assets_handler forbidden
resp = self._delete_asset(client)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
def test_editor_permissions(self):
"""Editor: read/create/edit allowed, delete forbidden."""
@@ -671,23 +671,23 @@ def test_editor_permissions(self):
# GET assets_handler allowed
resp = client.get(self.url)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# GET asset_usage_path_handler allowed
resp = client.get(self.asset_usage_url)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# POST assets_handler allowed
resp = client.post(self.url, {"name": "file", "file": self.get_sample_asset('file')})
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# PUT assets_handler allowed
resp = self._put_asset(client)
- self.assertIn(resp.status_code, [200, 201])
+ self.assertIn(resp.status_code, [200, 201]) # noqa: PT009
# DELETE assets_handler forbidden
resp = self._delete_asset(client)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
def test_admin_permissions(self):
"""Admin: full access."""
@@ -698,23 +698,23 @@ def test_admin_permissions(self):
# GET assets_handler allowed
resp = client.get(self.url)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# GET asset_usage_path_handler allowed
resp = client.get(self.asset_usage_url)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# POST assets_handler allowed
resp = client.post(self.url, {"name": "file", "file": self.get_sample_asset('file')})
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
# PUT assets_handler allowed
resp = self._put_asset(client)
- self.assertIn(resp.status_code, [200, 201])
+ self.assertIn(resp.status_code, [200, 201]) # noqa: PT009
# DELETE assets_handler allowed
resp = self._delete_asset(client)
- self.assertEqual(resp.status_code, 204)
+ self.assertEqual(resp.status_code, 204) # noqa: PT009
def test_no_role_permissions(self):
"""No role: all forbidden."""
@@ -724,20 +724,20 @@ def test_no_role_permissions(self):
# GET assets_handler forbidden
resp = client.get(self.url)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# GET asset_usage_path_handler forbidden
resp = client.get(self.asset_usage_url)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# POST assets_handler forbidden
resp = client.post(self.url, {"name": "file", "file": self.get_sample_asset('file')})
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# PUT assets_handler forbidden
resp = self._put_asset(client)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
# DELETE assets_handler forbidden
resp = self._delete_asset(client)
- self.assertEqual(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
diff --git a/cms/djangoapps/contentstore/views/tests/test_block.py b/cms/djangoapps/contentstore/views/tests/test_block.py
index 0f425d325ade..2b99dbb4eb7b 100644
--- a/cms/djangoapps/contentstore/views/tests/test_block.py
+++ b/cms/djangoapps/contentstore/views/tests/test_block.py
@@ -113,7 +113,7 @@ def response_usage_key(self, response):
:param response:
"""
parsed = json.loads(response.content.decode("utf-8"))
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
key = UsageKey.from_string(parsed["locator"])
if key.course_key.run is None:
key = key.map_into_course(CourseKey.from_string(parsed["courseKey"]))
@@ -141,7 +141,7 @@ def _create_vertical(self, parent_usage_key=None):
resp = self.create_xblock(
category="vertical", parent_usage_key=parent_usage_key
)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
return self.response_usage_key(resp)
@@ -163,12 +163,12 @@ def _get_container_preview(self, usage_key, data=None):
Returns the HTML and resources required for the xblock at the specified UsageKey
"""
resp = self._get_preview(usage_key, data)
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
resp_content = json.loads(resp.content.decode("utf-8"))
html = resp_content["html"]
- self.assertTrue(html)
+ self.assertTrue(html) # noqa: PT009
resources = resp_content["resources"]
- self.assertIsNotNone(resources)
+ self.assertIsNotNone(resources) # noqa: PT009
return html, resources
def _get_container_preview_with_error(
@@ -176,7 +176,7 @@ def _get_container_preview_with_error(
):
"""Make request and asserts on response code and response contents"""
resp = self._get_preview(usage_key, data)
- self.assertEqual(resp.status_code, expected_code)
+ self.assertEqual(resp.status_code, expected_code) # noqa: PT009
if content_contains:
self.assertContains(resp, content_contains, status_code=expected_code)
return resp
@@ -188,20 +188,20 @@ def test_get_vertical(self):
# Retrieve it
resp = self.client.get(reverse_usage_url("xblock_handler", usage_key))
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
def test_get_empty_container_fragment(self):
root_usage_key = self._create_vertical()
html, __ = self._get_container_preview(root_usage_key)
# XBlock messages are added by the Studio wrapper.
- self.assertIn("wrapper-xblock-message", html)
+ self.assertIn("wrapper-xblock-message", html) # noqa: PT009
# Make sure that "wrapper-xblock" does not appear by itself (without -message at end).
- self.assertNotRegex(html, r"wrapper-xblock[^-]+")
+ self.assertNotRegex(html, r"wrapper-xblock[^-]+") # noqa: PT009
# Verify that the header and article tags are still added
- self.assertIn('
'
expected_output = 'abc
'\
'abc
'
result = clean_thread_html_body(html_body)
- self.assertEqual(result, expected_output)
+ self.assertEqual(result, expected_output) # noqa: PT009
def test_button_tag_removal(self):
"""
@@ -202,13 +202,13 @@ def test_button_tag_removal(self):
html_body = ''
expected_output = ''
result = clean_thread_html_body(html_body)
- self.assertEqual(result, expected_output)
+ self.assertEqual(result, expected_output) # noqa: PT009
def test_attributes_removal_from_tag(self):
# Tests for removal of attributes from tags
html_body = 'Paragraph
'
result = clean_thread_html_body(html_body)
- self.assertEqual(result, 'Paragraph
')
+ self.assertEqual(result, 'Paragraph
') # noqa: PT009
def test_strip_empty_tags(self):
"""
@@ -216,4 +216,4 @@ def test_strip_empty_tags(self):
"""
html_body = ''
result = clean_thread_html_body(html_body)
- self.assertEqual(result, 'content
')
+ self.assertEqual(result, 'content
') # noqa: PT009
diff --git a/lms/djangoapps/discussion/rest_api/tests/test_serializers_v2.py b/lms/djangoapps/discussion/rest_api/tests/test_serializers_v2.py
index 412501c4fd19..81b0dfe14187 100644
--- a/lms/djangoapps/discussion/rest_api/tests/test_serializers_v2.py
+++ b/lms/djangoapps/discussion/rest_api/tests/test_serializers_v2.py
@@ -114,7 +114,7 @@ def test_create_success(self, parent_id):
parent_id=parent_id
)
saved = self.save_and_reserialize(data)
- expected_url = (
+ expected_url = ( # noqa: F841
f"/api/v1/comments/{parent_id}" if parent_id else
"/api/v1/threads/test_thread/comments"
)
@@ -179,7 +179,7 @@ def test_update_all(self):
)
saved = self.save_and_reserialize(data, instance=self.existing_comment)
- params = {
+ params = { # noqa: F841
'body': 'Edited body',
'course_id': str(self.course.id),
'user_id': str(self.user.id),
diff --git a/lms/djangoapps/discussion/rest_api/tests/test_tasks_v2.py b/lms/djangoapps/discussion/rest_api/tests/test_tasks_v2.py
index 15419c2ce698..7a83e3f96357 100644
--- a/lms/djangoapps/discussion/rest_api/tests/test_tasks_v2.py
+++ b/lms/djangoapps/discussion/rest_api/tests/test_tasks_v2.py
@@ -136,10 +136,10 @@ def test_send_notification_to_thread_creator(self, is_subscribed):
parent_id=None
)
if is_subscribed:
- self.assertEqual(handler.call_count, 2)
+ self.assertEqual(handler.call_count, 2) # noqa: PT009
args = handler.call_args_list[0][1]['notification_data']
- self.assertEqual([int(user_id) for user_id in args.user_ids], [self.user_1.id])
- self.assertEqual(args.notification_type, 'new_response')
+ self.assertEqual([int(user_id) for user_id in args.user_ids], [self.user_1.id]) # noqa: PT009
+ self.assertEqual(args.notification_type, 'new_response') # noqa: PT009
expected_context = {
'replier_name': self.user_2.username,
'post_title': 'test thread',
@@ -152,14 +152,14 @@ def test_send_notification_to_thread_creator(self, is_subscribed):
'comment_id': None,
'group_by_id': '1'
}
- self.assertDictEqual(args.context, expected_context)
- self.assertEqual(
+ self.assertDictEqual(args.context, expected_context) # noqa: PT009
+ self.assertEqual( # noqa: PT009
args.content_url,
_get_mfe_url(self.course.id, self.thread.id)
)
- self.assertEqual(args.app_name, 'discussion')
+ self.assertEqual(args.app_name, 'discussion') # noqa: PT009
else:
- self.assertEqual(handler.call_count, 1)
+ self.assertEqual(handler.call_count, 1) # noqa: PT009
@ddt.data(True, False)
def test_no_signal_on_creators_own_thread(self, is_subscribed):
@@ -179,7 +179,7 @@ def test_no_signal_on_creators_own_thread(self, is_subscribed):
self.user_1.id,
self.comment.id, parent_id=None
)
- self.assertEqual(handler.call_count, 1)
+ self.assertEqual(handler.call_count, 1) # noqa: PT009
@ddt.data(
(None, 'response_on_followed_post'), (1, 'comment_on_followed_post')
@@ -207,11 +207,11 @@ def test_send_notification_to_followers(self, parent_id, notification_type):
comment_id=self.comment.id
)
notification_sender.send_response_on_followed_post_notification()
- self.assertEqual(handler.call_count, 1)
+ self.assertEqual(handler.call_count, 1) # noqa: PT009
args = handler.call_args[1]['notification_data']
# only sent to user_3 because user_2 is the one who created the response
- self.assertEqual([self.user_3.id], args.user_ids)
- self.assertEqual(args.notification_type, notification_type)
+ self.assertEqual([self.user_3.id], args.user_ids) # noqa: PT009
+ self.assertEqual(args.notification_type, notification_type) # noqa: PT009
expected_context = {
'replier_name': self.user_2.username,
'post_title': 'test thread',
@@ -228,12 +228,12 @@ def test_send_notification_to_followers(self, parent_id, notification_type):
if parent_id:
expected_context['author_name'] = 'dummy\'s'
expected_context['author_pronoun'] = 'dummy\'s'
- self.assertDictEqual(args.context, expected_context)
- self.assertEqual(
+ self.assertDictEqual(args.context, expected_context) # noqa: PT009
+ self.assertEqual( # noqa: PT009
args.content_url,
_get_mfe_url(self.course.id, self.thread.id)
)
- self.assertEqual(args.app_name, 'discussion')
+ self.assertEqual(args.app_name, 'discussion') # noqa: PT009
@ddt.data(True, False)
def test_comment_creators_own_response(self, is_subscribed):
@@ -263,12 +263,12 @@ def test_comment_creators_own_response(self, is_subscribed):
)
if is_subscribed:
# check if 1 call is made to the handler i.e. for the thread creator
- self.assertEqual(handler.call_count, 2)
+ self.assertEqual(handler.call_count, 2) # noqa: PT009
# check if the notification is sent to the thread creator
args_comment = handler.call_args_list[0][1]['notification_data']
- self.assertEqual(args_comment.user_ids, [self.user_1.id])
- self.assertEqual(args_comment.notification_type, 'new_comment')
+ self.assertEqual(args_comment.user_ids, [self.user_1.id]) # noqa: PT009
+ self.assertEqual(args_comment.notification_type, 'new_comment') # noqa: PT009
expected_context = {
'replier_name': self.user_3.username,
'post_title': self.thread.title,
@@ -282,14 +282,14 @@ def test_comment_creators_own_response(self, is_subscribed):
'thread_id': 1,
'comment_id': 4,
}
- self.assertDictEqual(args_comment.context, expected_context)
- self.assertEqual(
+ self.assertDictEqual(args_comment.context, expected_context) # noqa: PT009
+ self.assertEqual( # noqa: PT009
args_comment.content_url,
_get_mfe_url(self.course.id, self.thread.id)
)
- self.assertEqual(args_comment.app_name, 'discussion')
+ self.assertEqual(args_comment.app_name, 'discussion') # noqa: PT009
else:
- self.assertEqual(handler.call_count, 1)
+ self.assertEqual(handler.call_count, 1) # noqa: PT009
@ddt.data(True, False)
def test_send_notification_to_parent_threads(self, is_subscribed):
@@ -321,12 +321,12 @@ def test_send_notification_to_parent_threads(self, is_subscribed):
if is_subscribed:
# check if 2 calls are made to the handler i.e. one for the response creator and one for the thread creator
- self.assertEqual(handler.call_count, 2)
+ self.assertEqual(handler.call_count, 2) # noqa: PT009
# check if the notification is sent to the thread creator
args_comment = handler.call_args_list[0][1]['notification_data']
args_comment_on_response = handler.call_args_list[1][1]['notification_data']
- self.assertEqual([int(user_id) for user_id in args_comment.user_ids], [self.user_1.id])
- self.assertEqual(args_comment.notification_type, 'new_comment')
+ self.assertEqual([int(user_id) for user_id in args_comment.user_ids], [self.user_1.id]) # noqa: PT009
+ self.assertEqual(args_comment.notification_type, 'new_comment') # noqa: PT009
expected_context = {
'replier_name': self.user_3.username,
'post_title': self.thread.title,
@@ -340,20 +340,20 @@ def test_send_notification_to_parent_threads(self, is_subscribed):
'thread_id': 1,
'comment_id': 4,
}
- self.assertDictEqual(args_comment.context, expected_context)
- self.assertEqual(
+ self.assertDictEqual(args_comment.context, expected_context) # noqa: PT009
+ self.assertEqual( # noqa: PT009
args_comment.content_url,
_get_mfe_url(self.course.id, self.thread.id)
)
- self.assertEqual(args_comment.app_name, 'discussion')
+ self.assertEqual(args_comment.app_name, 'discussion') # noqa: PT009
else:
# check if 1 call is made to the handler i.e. for the response creator
# because thread creator is not subscribed
args_comment_on_response = handler.call_args_list[0][1]['notification_data']
- self.assertEqual(handler.call_count, 1)
+ self.assertEqual(handler.call_count, 1) # noqa: PT009
# check if the notification is sent to the parent response creator
- self.assertEqual([int(user_id) for user_id in args_comment_on_response.user_ids], [self.user_2.id])
- self.assertEqual(args_comment_on_response.notification_type, 'new_comment_on_response')
+ self.assertEqual([int(user_id) for user_id in args_comment_on_response.user_ids], [self.user_2.id]) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(args_comment_on_response.notification_type, 'new_comment_on_response') # noqa: PT009
expected_context = {
'replier_name': self.user_3.username,
'post_title': self.thread.title,
@@ -365,12 +365,12 @@ def test_send_notification_to_parent_threads(self, is_subscribed):
'thread_id': 1,
'comment_id': 4,
}
- self.assertDictEqual(args_comment_on_response.context, expected_context)
- self.assertEqual(
+ self.assertDictEqual(args_comment_on_response.context, expected_context) # noqa: PT009
+ self.assertEqual( # noqa: PT009
args_comment_on_response.content_url,
_get_mfe_url(self.course.id, self.thread.id)
)
- self.assertEqual(args_comment_on_response.app_name, 'discussion')
+ self.assertEqual(args_comment_on_response.app_name, 'discussion') # noqa: PT009
def _register_subscriptions_endpoint(self):
"""
@@ -483,9 +483,9 @@ def test_new_comment_notification(self, is_subscribed):
if is_subscribed:
handler.assert_called_once()
context = handler.call_args[1]['notification_data'].context
- self.assertEqual(context['author_name'], 'dummy\'s')
- self.assertEqual(context['author_pronoun'], 'their')
- self.assertEqual(context['email_content'], comment.body)
+ self.assertEqual(context['author_name'], 'dummy\'s') # noqa: PT009
+ self.assertEqual(context['author_pronoun'], 'their') # noqa: PT009
+ self.assertEqual(context['email_content'], comment.body) # noqa: PT009
else:
handler.assert_not_called()
@@ -637,7 +637,7 @@ def test_notification_is_send_to_all_enrollments(self, notification_type):
handler = mock.Mock()
COURSE_NOTIFICATION_REQUESTED.connect(handler)
send_thread_created_notification(thread['id'], str(self.course.id), self.author.id)
- self.assertEqual(handler.call_count, 1)
+ self.assertEqual(handler.call_count, 1) # noqa: PT009
course_notification_data = handler.call_args[1]['course_notification_data']
assert notification_type == course_notification_data.notification_type
notification_audience_filters = {}
@@ -682,7 +682,7 @@ def test_notification_is_send_to_cohort_ids(self, cohort_text, notification_type
'discussion_roles': ['Administrator', 'Moderator', 'Community TA'],
}
assert notification_audience_filters == handler.call_args[1]['course_notification_data'].audience_filters
- self.assertEqual(handler.call_count, 1)
+ self.assertEqual(handler.call_count, 1) # noqa: PT009
class TestResponseEndorsedNotifications(DiscussionAPIViewTestMixin, ModuleStoreTestCase):
@@ -742,13 +742,13 @@ def test_response_endorsed_notifications(self):
handler = mock.Mock()
USER_NOTIFICATION_REQUESTED.connect(handler)
send_response_endorsed_notifications(thread.id, response.id, str(self.course.id), self.user_3.id)
- self.assertEqual(handler.call_count, 2)
+ self.assertEqual(handler.call_count, 2) # noqa: PT009
# Test response endorsed on thread notification
notification_data = handler.call_args_list[0][1]['notification_data']
# Target only the thread author
- self.assertEqual([int(user_id) for user_id in notification_data.user_ids], [int(thread.user_id)])
- self.assertEqual(notification_data.notification_type, 'response_endorsed_on_thread')
+ self.assertEqual([int(user_id) for user_id in notification_data.user_ids], [int(thread.user_id)]) # noqa: PT009
+ self.assertEqual(notification_data.notification_type, 'response_endorsed_on_thread') # noqa: PT009
expected_context = {
'replier_name': self.user_2.username,
@@ -761,16 +761,16 @@ def test_response_endorsed_notifications(self):
'thread_id': 1,
'comment_id': 2,
}
- self.assertDictEqual(notification_data.context, expected_context)
- self.assertEqual(notification_data.content_url, _get_mfe_url(self.course.id, thread.id))
- self.assertEqual(notification_data.app_name, 'discussion')
- self.assertEqual('response_endorsed_on_thread', notification_data.notification_type)
+ self.assertDictEqual(notification_data.context, expected_context) # noqa: PT009
+ self.assertEqual(notification_data.content_url, _get_mfe_url(self.course.id, thread.id)) # noqa: PT009
+ self.assertEqual(notification_data.app_name, 'discussion') # noqa: PT009
+ self.assertEqual('response_endorsed_on_thread', notification_data.notification_type) # noqa: PT009
# Test response endorsed notification
notification_data = handler.call_args_list[1][1]['notification_data']
# Target only the response author
- self.assertEqual([int(user_id) for user_id in notification_data.user_ids], [int(response.user_id)])
- self.assertEqual(notification_data.notification_type, 'response_endorsed')
+ self.assertEqual([int(user_id) for user_id in notification_data.user_ids], [int(response.user_id)]) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(notification_data.notification_type, 'response_endorsed') # noqa: PT009
expected_context = {
'replier_name': response.username,
@@ -783,7 +783,7 @@ def test_response_endorsed_notifications(self):
'thread_id': 1,
'comment_id': 2,
}
- self.assertDictEqual(notification_data.context, expected_context)
- self.assertEqual(notification_data.content_url, _get_mfe_url(self.course.id, thread.id))
- self.assertEqual(notification_data.app_name, 'discussion')
- self.assertEqual('response_endorsed', notification_data.notification_type)
+ self.assertDictEqual(notification_data.context, expected_context) # noqa: PT009
+ self.assertEqual(notification_data.content_url, _get_mfe_url(self.course.id, thread.id)) # noqa: PT009
+ self.assertEqual(notification_data.app_name, 'discussion') # noqa: PT009
+ self.assertEqual('response_endorsed', notification_data.notification_type) # noqa: PT009
diff --git a/lms/djangoapps/discussion/rest_api/tests/test_utils.py b/lms/djangoapps/discussion/rest_api/tests/test_utils.py
index b5d769890c92..1794c9135af1 100644
--- a/lms/djangoapps/discussion/rest_api/tests/test_utils.py
+++ b/lms/djangoapps/discussion/rest_api/tests/test_utils.py
@@ -69,9 +69,9 @@ def setUp(self):
CourseInstructorRole(course_key=self.course.id).add_users(self.course_instructor_user)
def test_discussion_open_for_user(self):
- self.assertFalse(discussion_open_for_user(self.course, self.student))
- self.assertTrue(discussion_open_for_user(self.course, self.moderator))
- self.assertTrue(discussion_open_for_user(self.course, self.community_ta))
+ self.assertFalse(discussion_open_for_user(self.course, self.student)) # noqa: PT009
+ self.assertTrue(discussion_open_for_user(self.course, self.moderator)) # noqa: PT009
+ self.assertTrue(discussion_open_for_user(self.course, self.community_ta)) # noqa: PT009
def test_course_staff_users_list(self):
assert len(get_course_staff_users_list(self.course.id)) == 2
@@ -133,7 +133,7 @@ def test_empty_data(self):
# Test that the function can handle an empty list
data = []
result = remove_empty_sequentials(data)
- self.assertEqual(result, [])
+ self.assertEqual(result, []) # noqa: PT009
def test_no_empty_sequentials(self):
# Test that the function does not remove any sequentials if they all have children
@@ -144,7 +144,7 @@ def test_no_empty_sequentials(self):
]}
]
result = remove_empty_sequentials(data)
- self.assertEqual(result, data)
+ self.assertEqual(result, data) # noqa: PT009
def test_remove_empty_sequentials(self):
# Test that the function removes empty sequentials
@@ -177,7 +177,7 @@ def test_remove_empty_sequentials(self):
]}
]
result = remove_empty_sequentials(data)
- self.assertEqual(result, expected_output)
+ self.assertEqual(result, expected_output) # noqa: PT009
@ddt.ddt
@@ -239,7 +239,7 @@ def test_blackout_dates(self, restriction, state):
self._set_discussion_blackouts(date_ranges)
posting_allowed = self._check_posting_allowed(restriction)
- self.assertEqual(state, posting_allowed)
+ self.assertEqual(state, posting_allowed) # noqa: PT009
def test_posting_scheduled_future(self):
"""
@@ -254,4 +254,4 @@ def test_posting_scheduled_future(self):
self._set_discussion_blackouts(date_ranges)
posting_allowed = self._check_posting_allowed(PostingRestriction.SCHEDULED)
- self.assertTrue(posting_allowed)
+ self.assertTrue(posting_allowed) # noqa: PT009
diff --git a/lms/djangoapps/discussion/rest_api/tests/test_views_v2.py b/lms/djangoapps/discussion/rest_api/tests/test_views_v2.py
index 8168c98e3b96..844fbfcd6da6 100644
--- a/lms/djangoapps/discussion/rest_api/tests/test_views_v2.py
+++ b/lms/djangoapps/discussion/rest_api/tests/test_views_v2.py
@@ -1008,7 +1008,7 @@ def test_with_username_param_with_no_matches(self):
self.client.login(username=self.moderator.username, password=self.TEST_PASSWORD)
response = self.client.get(self.url, params)
data = response.json()
- self.assertFalse(data['results'])
+ self.assertFalse(data['results']) # noqa: PT009
assert data['pagination']['count'] == 0
@ddt.data(
@@ -1937,7 +1937,7 @@ def test_with_username_param_with_no_matches(self):
self.client.login(username=self.moderator.username, password=self.TEST_PASSWORD)
response = self.client.get(self.url, params)
data = response.json()
- self.assertFalse(data['results'])
+ self.assertFalse(data['results']) # noqa: PT009
assert data['pagination']['count'] == 0
@ddt.data(
diff --git a/lms/djangoapps/discussion/rest_api/tests/utils.py b/lms/djangoapps/discussion/rest_api/tests/utils.py
index 37512c3573ee..d4dda7ea4cec 100644
--- a/lms/djangoapps/discussion/rest_api/tests/utils.py
+++ b/lms/djangoapps/discussion/rest_api/tests/utils.py
@@ -432,7 +432,7 @@ def register_flag_response(self, content_type, content_id):
for path in ["abuse_flag", "abuse_unflag"]:
httpretty.register_uri(
"PUT",
- "http://localhost:4567/api/v1/{content_type}s/{content_id}/{path}".format(
+ "http://localhost:4567/api/v1/{content_type}s/{content_id}/{path}".format( # noqa: UP032
content_type=content_type,
content_id=content_id,
path=path
@@ -979,7 +979,7 @@ def querystring(request):
return parse_qs(request.path.split('?', 1)[-1])
-class ThreadMock(object):
+class ThreadMock(object): # noqa: UP004
"""
A mock thread object
"""
diff --git a/lms/djangoapps/discussion/rest_api/urls.py b/lms/djangoapps/discussion/rest_api/urls.py
index f102dc41f249..082fdabc608d 100644
--- a/lms/djangoapps/discussion/rest_api/urls.py
+++ b/lms/djangoapps/discussion/rest_api/urls.py
@@ -31,14 +31,14 @@
urlpatterns = [
re_path(
- r"^v1/courses/{}/settings$".format(
+ r"^v1/courses/{}/settings$".format( # noqa: UP032
settings.COURSE_ID_PATTERN
),
CourseDiscussionSettingsAPIView.as_view(),
name="discussion_course_settings",
),
re_path(
- r"^v1/courses/{}/learner/$".format(
+ r"^v1/courses/{}/learner/$".format( # noqa: UP032
settings.COURSE_ID_PATTERN
),
LearnerThreadView.as_view(),
@@ -55,7 +55,7 @@
name="upload_file",
),
re_path(
- r"^v1/courses/{}/roles/(?P[A-Za-z0-9+ _-]+)/?$".format(
+ r"^v1/courses/{}/roles/(?P[A-Za-z0-9+ _-]+)/?$".format( # noqa: UP032
settings.COURSE_ID_PATTERN
),
CourseDiscussionRolesAPIView.as_view(),
diff --git a/lms/djangoapps/discussion/rest_api/utils.py b/lms/djangoapps/discussion/rest_api/utils.py
index 25f7c7bbf09b..a970286ad6e8 100644
--- a/lms/djangoapps/discussion/rest_api/utils.py
+++ b/lms/djangoapps/discussion/rest_api/utils.py
@@ -3,7 +3,7 @@
"""
import logging
from datetime import datetime
-from typing import Callable, Dict, List
+from typing import Callable, Dict, List # noqa: UP035
import requests
from crum import get_current_request
@@ -276,7 +276,7 @@ def create_topics_v3_structure(blocks, topics):
if topic.get('usage_key', '') is None
]
courseware_topics = []
- for key, value in blocks.items():
+ for key, value in blocks.items(): # noqa: B007
if value.get("type") == "chapter":
value['courseware'] = True
courseware_topics.append(value)
@@ -339,7 +339,7 @@ def remove_empty_sequentials(data):
return new_data
-def get_topic_ids_from_topics(topics: List[Dict[str, str]]) -> List[str]:
+def get_topic_ids_from_topics(topics: List[Dict[str, str]]) -> List[str]: # noqa: UP006
"""
This function takes a list of topics and returns a list of the topic ids.
@@ -352,7 +352,7 @@ def get_topic_ids_from_topics(topics: List[Dict[str, str]]) -> List[str]:
return [topic['id'] for topic in topics]
-def get_archived_topics(filtered_topic_ids: List[str], topics: List[Dict[str, str]]) -> List[Dict[str, str]]:
+def get_archived_topics(filtered_topic_ids: List[str], topics: List[Dict[str, str]]) -> List[Dict[str, str]]: # noqa: UP006 # pylint: disable=line-too-long
"""
This function takes a list of topic ids and a list of topics, and returns the list of archived topics.
@@ -374,7 +374,7 @@ def get_archived_topics(filtered_topic_ids: List[str], topics: List[Dict[str, st
return archived_topics
-def is_posting_allowed(posting_restrictions: str, blackout_schedules: List):
+def is_posting_allowed(posting_restrictions: str, blackout_schedules: List): # noqa: UP006
"""
Check if posting is allowed based on the given posting restrictions and blackout schedules.
diff --git a/lms/djangoapps/discussion/tasks.py b/lms/djangoapps/discussion/tasks.py
index e503e6028cfa..ffbc2c12a301 100644
--- a/lms/djangoapps/discussion/tasks.py
+++ b/lms/djangoapps/discussion/tasks.py
@@ -298,7 +298,7 @@ def _get_thread_url(context, domain_url=None): # lint-amnesty, pylint: disable=
scheme = 'https' if settings.HTTPS == 'on' else 'http'
if domain_url is None:
domain_url = context['site'].domain
- base_url = '{}://{}'.format(scheme, domain_url)
+ base_url = '{}://{}'.format(scheme, domain_url) # noqa: UP032
thread_content = {
'type': 'thread',
'course_id': context['course_id'],
diff --git a/lms/djangoapps/discussion/tests/test_signals.py b/lms/djangoapps/discussion/tests/test_signals.py
index ff626396d124..477b8aacd0a3 100644
--- a/lms/djangoapps/discussion/tests/test_signals.py
+++ b/lms/djangoapps/discussion/tests/test_signals.py
@@ -105,4 +105,4 @@ def _assert_discussion_id_map(self, course_key, expected_map):
Verifies the discussion ID map for the given course matches the expected value.
"""
mapping_entry = models.DiscussionsIdMapping.objects.get(course_id=course_key)
- self.assertDictEqual(mapping_entry.mapping, expected_map)
+ self.assertDictEqual(mapping_entry.mapping, expected_map) # noqa: PT009
diff --git a/lms/djangoapps/discussion/tests/test_tasks_v2.py b/lms/djangoapps/discussion/tests/test_tasks_v2.py
index aee9d3d8d22e..195e733b26d0 100644
--- a/lms/djangoapps/discussion/tests/test_tasks_v2.py
+++ b/lms/djangoapps/discussion/tests/test_tasks_v2.py
@@ -363,7 +363,7 @@ def run_should_not_send_email_test(self, thread, comment_dict):
):
comment_created.send(sender=None, user=user, post=comment)
- actual_result = _should_send_message(
+ actual_result = _should_send_message( # noqa: F841
{
"thread_author_id": self.thread_author.id,
"course_id": self.course.id,
diff --git a/lms/djangoapps/discussion/tests/test_views_v2.py b/lms/djangoapps/discussion/tests/test_views_v2.py
index c5ee301d0357..d3068b7c043a 100644
--- a/lms/djangoapps/discussion/tests/test_views_v2.py
+++ b/lms/djangoapps/discussion/tests/test_views_v2.py
@@ -5,29 +5,29 @@
import json
import logging
-from datetime import datetime
-from unittest import mock
-from unittest.mock import ANY, Mock, call, patch
+from datetime import datetime # noqa: F401
+from unittest import mock # noqa: F401
+from unittest.mock import ANY, Mock, call, patch # noqa: F401
import ddt
import pytest
from django.conf import settings
from django.http import Http404
-from django.test.client import Client, RequestFactory
+from django.test.client import Client, RequestFactory # noqa: F401
from django.test.utils import override_settings
from django.urls import reverse
from django.utils import translation
-from edx_django_utils.cache import RequestCache
+from edx_django_utils.cache import RequestCache # noqa: F401
from edx_toggles.toggles.testutils import override_waffle_flag
-from common.djangoapps.course_modes.models import CourseMode
-from common.djangoapps.course_modes.tests.factories import CourseModeFactory
+from common.djangoapps.course_modes.models import CourseMode # noqa: F401
+from common.djangoapps.course_modes.tests.factories import CourseModeFactory # noqa: F401
from common.djangoapps.student.roles import CourseStaffRole, UserBasedRole
from common.djangoapps.student.tests.factories import AdminFactory, CourseEnrollmentFactory, UserFactory
from common.djangoapps.util.testing import EventTestMixin, UrlResetMixin
-from lms.djangoapps.courseware.exceptions import CourseAccessRedirect
+from lms.djangoapps.courseware.exceptions import CourseAccessRedirect # noqa: F401
from lms.djangoapps.discussion import views
-from lms.djangoapps.discussion.django_comment_client.constants import TYPE_ENTRY, TYPE_SUBCATEGORY
+from lms.djangoapps.discussion.django_comment_client.constants import TYPE_ENTRY, TYPE_SUBCATEGORY # noqa: F401
from lms.djangoapps.discussion.django_comment_client.permissions import get_team
from lms.djangoapps.discussion.django_comment_client.tests.group_id import (
CohortedTopicGroupIdTestMixinV2,
@@ -38,32 +38,40 @@
from lms.djangoapps.discussion.django_comment_client.tests.unicode import UnicodeTestMixin
from lms.djangoapps.discussion.django_comment_client.tests.utils import (
CohortedTestCase,
- config_course_discussions,
- topic_name_to_id,
+ config_course_discussions, # noqa: F401
+ topic_name_to_id, # noqa: F401
)
from lms.djangoapps.discussion.django_comment_client.utils import strip_none
from lms.djangoapps.discussion.toggles import ENABLE_DISCUSSIONS_MFE
-from lms.djangoapps.discussion.views import _get_discussion_default_topic_id, course_discussions_settings_handler
+from lms.djangoapps.discussion.views import ( # noqa: F401
+ _get_discussion_default_topic_id,
+ course_discussions_settings_handler,
+)
from lms.djangoapps.teams.tests.factories import CourseTeamFactory, CourseTeamMembershipFactory
from openedx.core.djangoapps.course_groups.models import CourseUserGroup
-from openedx.core.djangoapps.course_groups.tests.helpers import config_course_cohorts
-from openedx.core.djangoapps.course_groups.tests.test_views import CohortViewsTestCase
-from openedx.core.djangoapps.django_comment_common.comment_client.utils import CommentClientPaginatedResult
-from openedx.core.djangoapps.django_comment_common.models import FORUM_ROLE_STUDENT, CourseDiscussionSettings
+from openedx.core.djangoapps.course_groups.tests.helpers import config_course_cohorts # noqa: F401
+from openedx.core.djangoapps.course_groups.tests.test_views import CohortViewsTestCase # noqa: F401
+from openedx.core.djangoapps.django_comment_common.comment_client.utils import (
+ CommentClientPaginatedResult, # noqa: F401
+)
+from openedx.core.djangoapps.django_comment_common.models import ( # noqa: F401
+ FORUM_ROLE_STUDENT,
+ CourseDiscussionSettings,
+)
from openedx.core.djangoapps.django_comment_common.utils import ThreadContext, seed_permissions_roles
from openedx.core.djangoapps.util.testing import ContentGroupTestCase
from openedx.core.djangoapps.waffle_utils.testutils import WAFFLE_TABLES
from openedx.core.lib.teams_config import TeamsConfig
-from openedx.features.content_type_gating.models import ContentTypeGatingConfig
+from openedx.features.content_type_gating.models import ContentTypeGatingConfig # noqa: F401
from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseTestConsentRequired
-from xmodule.modulestore import ModuleStoreEnum
-from xmodule.modulestore.django import modulestore
+from xmodule.modulestore import ModuleStoreEnum # noqa: F401
+from xmodule.modulestore.django import modulestore # noqa: F401
from xmodule.modulestore.tests.django_utils import (
- TEST_DATA_SPLIT_MODULESTORE,
+ TEST_DATA_SPLIT_MODULESTORE, # noqa: F401
ModuleStoreTestCase,
SharedModuleStoreTestCase,
)
-from xmodule.modulestore.tests.factories import BlockFactory, CourseFactory, check_mongo_calls
+from xmodule.modulestore.tests.factories import BlockFactory, CourseFactory, check_mongo_calls # noqa: F401
log = logging.getLogger(__name__)
@@ -426,7 +434,7 @@ def test_not_found(self):
request.user = self.student
# Mock request to return 404 for thread request
self._configure_mock_responses(course=self.course, text="dummy", thread_id=None)
- self.assertRaises(
+ self.assertRaises( # noqa: PT027
Http404,
views.single_thread,
request,
@@ -533,7 +541,7 @@ def test_html(self):
html = response.content.decode('utf-8')
# Verify that the group name is correctly included in the HTML
- self.assertRegex(html, r'"group_name": "student_cohort"')
+ self.assertRegex(html, r'"group_name": "student_cohort"') # noqa: PT009
class SingleThreadAccessTestCase(CohortedTestCase, ForumViewsUtilsMixin): # lint-amnesty, pylint: disable=missing-class-docstring
@@ -1772,16 +1780,16 @@ def check_html(
assert response.status_code == 200
assert response["Content-Type"] == "text/html; charset=utf-8"
html = response.content.decode("utf-8")
- self.assertRegex(html, r'data-page="1"')
- self.assertRegex(html, r'data-num-pages="1"')
- self.assertRegex(
+ self.assertRegex(html, r'data-page="1"') # noqa: PT009
+ self.assertRegex(html, r'data-num-pages="1"') # noqa: PT009
+ self.assertRegex( # noqa: PT009
html, r'1 discussion started'
)
- self.assertRegex(html, r'2 comments')
- self.assertRegex(html, f"'id': '{self.TEST_THREAD_ID}'")
- self.assertRegex(html, f"'title': '{self.TEST_THREAD_TEXT}'")
- self.assertRegex(html, f"'body': '{self.TEST_THREAD_TEXT}'")
- self.assertRegex(html, f"'username': '{self.student.username}'")
+ self.assertRegex(html, r'2 comments') # noqa: PT009
+ self.assertRegex(html, f"'id': '{self.TEST_THREAD_ID}'") # noqa: PT009
+ self.assertRegex(html, f"'title': '{self.TEST_THREAD_TEXT}'") # noqa: PT009
+ self.assertRegex(html, f"'body': '{self.TEST_THREAD_TEXT}'") # noqa: PT009
+ self.assertRegex(html, f"'username': '{self.student.username}'") # noqa: PT009
def check_ajax(
self, **params
@@ -1916,7 +1924,7 @@ def test_thread_viewed_event(self):
thread_id=self.DUMMY_THREAD_ID,
commentable_id=self.category.discussion_id,
)
- url = '/courses/{}/discussion/forum/{}/threads/{}'.format(
+ url = '/courses/{}/discussion/forum/{}/threads/{}'.format( # noqa: UP032
str(self.course.id),
self.category.discussion_id,
self.DUMMY_THREAD_ID
diff --git a/lms/djangoapps/discussion/views.py b/lms/djangoapps/discussion/views.py
index 76bc0f080359..e1c47f3b2ef8 100644
--- a/lms/djangoapps/discussion/views.py
+++ b/lms/djangoapps/discussion/views.py
@@ -496,7 +496,7 @@ def _create_base_discussion_view_context(request, course_key):
def _get_discussion_default_topic_id(course):
- for topic, entry in course.discussion_topics.items(): # lint-amnesty, pylint: disable=unused-variable
+ for topic, entry in course.discussion_topics.items(): # lint-amnesty, pylint: disable=unused-variable # noqa: B007
if entry.get('default') is True:
return entry['id']
@@ -668,7 +668,7 @@ def user_profile(request, course_key, user_id):
return tab_view.get(request, str(course_key), 'discussion', profile_page_context=context)
except User.DoesNotExist:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except ValueError:
return HttpResponseServerError("Invalid group_id")
@@ -751,7 +751,7 @@ def followed_threads(request, course_key, user_id):
return render(request, 'discussion/user_profile.html', context)
except User.DoesNotExist:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def is_course_staff(course_key: CourseKey, user: User):
@@ -805,8 +805,8 @@ def render_to_fragment( # lint-amnesty, pylint: disable=arguments-differ
"""
course_key = CourseKey.from_string(course_id)
# Force using the legacy view if a user profile is requested or the URL contains a specific topic or thread
- force_legacy_view = (profile_page_context or thread_id or discussion_id)
- is_educator_or_staff = is_course_staff(course_key, request.user) or GlobalStaff().has_user(request.user)
+ force_legacy_view = (profile_page_context or thread_id or discussion_id) # noqa: F841
+ is_educator_or_staff = is_course_staff(course_key, request.user) or GlobalStaff().has_user(request.user) # noqa: F841 # pylint: disable=line-too-long
try:
base_context = _create_base_discussion_view_context(request, course_key)
# Note:
@@ -855,7 +855,7 @@ def render_to_fragment( # lint-amnesty, pylint: disable=arguments-differ
return fragment
except TeamDiscussionHiddenFromUserException:
log.warning(
- 'User with id={user_id} tried to view private discussion with id={discussion_id}'.format(
+ 'User with id={user_id} tried to view private discussion with id={discussion_id}'.format( # noqa: UP032
user_id=request.user.id,
discussion_id=discussion_id
)
diff --git a/lms/djangoapps/edxnotes/helpers.py b/lms/djangoapps/edxnotes/helpers.py
index 5e68ae4b2003..c3491e55a2ce 100644
--- a/lms/djangoapps/edxnotes/helpers.py
+++ b/lms/djangoapps/edxnotes/helpers.py
@@ -57,7 +57,7 @@ def get_edxnotes_id_token(user):
try:
notes_application = Application.objects.get(name=settings.EDXNOTES_CLIENT_NAME)
except Application.DoesNotExist:
- raise ImproperlyConfigured( # lint-amnesty, pylint: disable=raise-missing-from
+ raise ImproperlyConfigured( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
f'OAuth2 Client with name [{settings.EDXNOTES_CLIENT_NAME}] does not exist.'
)
return create_jwt_for_user(
@@ -114,7 +114,7 @@ def send_request(user, course_id, page, page_size, path="", text=None):
)
except RequestException:
log.error("Failed to connect to edx-notes-api: url=%s, params=%s", url, str(params))
- raise EdxNotesServiceUnavailable(_("EdxNotes Service is unavailable. Please try again in a few minutes.")) # lint-amnesty, pylint: disable=raise-missing-from
+ raise EdxNotesServiceUnavailable(_("EdxNotes Service is unavailable. Please try again in a few minutes.")) # lint-amnesty, pylint: disable=raise-missing-from,line-too-long # noqa: B904
return response
@@ -145,7 +145,7 @@ def delete_all_notes_for_user(user):
)
except RequestException:
log.error("Failed to connect to edx-notes-api: url=%s, params=%s", url, str(headers))
- raise EdxNotesServiceUnavailable(_("EdxNotes Service is unavailable. Please try again in a few minutes.")) # lint-amnesty, pylint: disable=raise-missing-from
+ raise EdxNotesServiceUnavailable(_("EdxNotes Service is unavailable. Please try again in a few minutes.")) # lint-amnesty, pylint: disable=raise-missing-from,line-too-long # noqa: B904
return response
@@ -338,7 +338,7 @@ def get_notes(request, course, page=DEFAULT_PAGE, page_size=DEFAULT_PAGE_SIZE, t
collection = json.loads(response.content.decode('utf-8'))
except ValueError:
log.error("Invalid JSON response received from notes api: response_content=%s", response.content)
- raise EdxNotesParseError(_("Invalid JSON response received from notes api.")) # lint-amnesty, pylint: disable=raise-missing-from
+ raise EdxNotesParseError(_("Invalid JSON response received from notes api.")) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
# Verify response dict structure
expected_keys = ['total', 'rows', 'num_pages', 'start', 'next', 'previous', 'current_page']
@@ -388,7 +388,7 @@ def get_endpoint(api_url, path=""):
return api_url + path
except (AttributeError, KeyError):
- raise ImproperlyConfigured(_("No endpoint was provided for EdxNotes.")) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ImproperlyConfigured(_("No endpoint was provided for EdxNotes.")) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def get_public_endpoint(path=""):
diff --git a/lms/djangoapps/edxnotes/plugins.py b/lms/djangoapps/edxnotes/plugins.py
index 5269feb08b28..3c590977c762 100644
--- a/lms/djangoapps/edxnotes/plugins.py
+++ b/lms/djangoapps/edxnotes/plugins.py
@@ -1,7 +1,7 @@
"""
Registers the "edX Notes" feature for the edX platform.
"""
-from typing import Dict, Optional
+from typing import Dict, Optional # noqa: UP035
from django.conf import settings
from django.contrib.auth import get_user_model
@@ -91,7 +91,7 @@ def set_enabled(cls, course_key: CourseKey, enabled: bool, user: 'User') -> bool
return enabled
@classmethod
- def get_allowed_operations(cls, course_key: CourseKey, user: Optional[User] = None) -> Dict[str, bool]:
+ def get_allowed_operations(cls, course_key: CourseKey, user: Optional[User] = None) -> Dict[str, bool]: # noqa: UP006, UP045 # pylint: disable=line-too-long
"""
Returns allowed operations for edxnotes app.
"""
diff --git a/lms/djangoapps/edxnotes/tests.py b/lms/djangoapps/edxnotes/tests.py
index f0711cd9a579..3be1376cd39a 100644
--- a/lms/djangoapps/edxnotes/tests.py
+++ b/lms/djangoapps/edxnotes/tests.py
@@ -405,7 +405,7 @@ def test_get_notes_json_error(self, mock_get):
Tests the result if incorrect json is received.
"""
mock_get.return_value.content = b"Error"
- self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course)
+ self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course) # noqa: PT027
@patch("lms.djangoapps.edxnotes.helpers.requests.get", autospec=True)
def test_get_notes_empty_collection(self, mock_get):
@@ -413,7 +413,7 @@ def test_get_notes_empty_collection(self, mock_get):
Tests the result if an empty response is received.
"""
mock_get.return_value.content = json.dumps({}).encode('utf-8')
- self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course)
+ self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course) # noqa: PT027
@patch("lms.djangoapps.edxnotes.helpers.requests.get", autospec=True)
def test_search_correct_data(self, mock_get):
@@ -509,7 +509,7 @@ def test_search_json_error(self, mock_get):
Tests the result if incorrect json is received.
"""
mock_get.return_value.content = b"Error"
- self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course)
+ self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course) # noqa: PT027
@patch("lms.djangoapps.edxnotes.helpers.requests.get", autospec=True)
def test_search_wrong_data_format(self, mock_get):
@@ -517,7 +517,7 @@ def test_search_wrong_data_format(self, mock_get):
Tests the result if incorrect data structure is received.
"""
mock_get.return_value.content = json.dumps({"1": 2}).encode('utf-8')
- self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course)
+ self.assertRaises(EdxNotesParseError, helpers.get_notes, self.request, self.course) # noqa: PT027
@patch("lms.djangoapps.edxnotes.helpers.requests.get", autospec=True)
def test_search_empty_collection(self, mock_get):
@@ -711,7 +711,7 @@ def test_get_block_context_sequential(self):
"""
Tests `get_block_context` method for the sequential.
"""
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
{
"display_name": self.sequential.display_name_with_default,
"location": str(self.sequential.location),
@@ -724,7 +724,7 @@ def test_get_block_context_html_component(self):
"""
Tests `get_block_context` method for the components.
"""
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
{
"display_name": self.html_block_1.display_name_with_default,
"location": str(self.html_block_1.location),
@@ -736,7 +736,7 @@ def test_get_block_context_chapter(self):
"""
Tests `get_block_context` method for the chapters.
"""
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
{
"display_name": self.chapter.display_name_with_default,
"index": 0,
@@ -745,7 +745,7 @@ def test_get_block_context_chapter(self):
},
helpers.get_block_context(self.course, self.chapter)
)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
{
"display_name": self.chapter_2.display_name_with_default,
"index": 1,
diff --git a/lms/djangoapps/experiments/tests/test_views.py b/lms/djangoapps/experiments/tests/test_views.py
index 7f92f6b8a64d..43cc46df99b5 100644
--- a/lms/djangoapps/experiments/tests/test_views.py
+++ b/lms/djangoapps/experiments/tests/test_views.py
@@ -342,7 +342,7 @@ def test_UserMetaDataView_get_missing_course(self):
""" Request fails when not course not found """
lookup_user = UserFactory()
lookup_course = CourseFactory.create(start=now() - timedelta(days=30))
- call_args = [lookup_user.username, lookup_course.id] # lint-amnesty, pylint: disable=unused-variable
+ call_args = [lookup_user.username, lookup_course.id] # lint-amnesty, pylint: disable=unused-variable # noqa: F841
self.client.login(username=lookup_user.username, password=UserFactory._DEFAULT_PASSWORD) # lint-amnesty, pylint: disable=protected-access
bogus_course_name = str(lookup_course.id) + '_FOOBAR'
diff --git a/lms/djangoapps/experiments/urls.py b/lms/djangoapps/experiments/urls.py
index e192e2e971bb..69f26b3e1303 100644
--- a/lms/djangoapps/experiments/urls.py
+++ b/lms/djangoapps/experiments/urls.py
@@ -14,7 +14,7 @@
urlpatterns = [
path('v0/custom/REV-934/', views_custom.Rev934.as_view(), name='rev_934'),
path('v0/', include((router.urls, "api"), namespace='v0')),
- re_path(r'^v0/custom/userMetadata/{username},{course_key}$'.format(
+ re_path(r'^v0/custom/userMetadata/{username},{course_key}$'.format( # noqa: UP032
username=settings.USERNAME_PATTERN,
course_key=settings.COURSE_ID_PATTERN), views.UserMetaDataView.as_view(), name='user_metadata'),
]
diff --git a/lms/djangoapps/experiments/utils.py b/lms/djangoapps/experiments/utils.py
index fdcfd3e24874..b7c853a92c92 100644
--- a/lms/djangoapps/experiments/utils.py
+++ b/lms/djangoapps/experiments/utils.py
@@ -88,7 +88,7 @@ def check_and_get_upgrade_link_and_date(user, enrollment=None, course=None):
if enrollment:
if course and enrollment.course_id != course.id:
- logger.warning('{} refers to a different course than {} which was supplied. Enrollment course id={}, '
+ logger.warning('{} refers to a different course than {} which was supplied. Enrollment course id={}, ' # noqa: UP032 # pylint: disable=line-too-long
'repr={!r}, deprecated={}. Course id={}, repr={!r}, deprecated={}.'
.format(enrollment,
course,
@@ -103,7 +103,7 @@ def check_and_get_upgrade_link_and_date(user, enrollment=None, course=None):
return (None, None, None)
if enrollment.user_id != user.id:
- logger.warning('{} refers to a different user than {} which was supplied. '
+ logger.warning('{} refers to a different user than {} which was supplied. ' # noqa: UP032
'Enrollment user id={}, repr={!r}. '
'User id={}, repr={!r}.'.format(enrollment,
user,
@@ -266,7 +266,7 @@ def get_experiment_user_metadata_context(course, user):
enrollment = None
# TODO: clean up as part of REVO-28 (START)
user_enrollments = None
- audit_enrollments = None # lint-amnesty, pylint: disable=unused-variable
+ audit_enrollments = None # lint-amnesty, pylint: disable=unused-variable # noqa: F841
has_non_audit_enrollments = False
context = {}
if course is not None:
diff --git a/lms/djangoapps/experiments/views.py b/lms/djangoapps/experiments/views.py
index 5a2cc488f838..af8845aa7a7d 100644
--- a/lms/djangoapps/experiments/views.py
+++ b/lms/djangoapps/experiments/views.py
@@ -14,7 +14,7 @@
from common.djangoapps.student.models import get_user_by_username_or_email
from common.djangoapps.util.json_request import JsonResponse # lint-amnesty, pylint: disable=reimported
-from lms.djangoapps.courseware import courses # lint-amnesty, pylint: disable=reimported, unused-import
+from lms.djangoapps.courseware import courses # lint-amnesty, pylint: disable=reimported, unused-import # noqa: F401
from lms.djangoapps.experiments import filters, serializers
from lms.djangoapps.experiments.models import ExperimentData, ExperimentKeyValue
from lms.djangoapps.experiments.permissions import IsStaffOrOwner, IsStaffOrReadOnly, IsStaffOrReadOnlyForSelf
diff --git a/lms/djangoapps/gating/apps.py b/lms/djangoapps/gating/apps.py
index b8c423815bc5..6451605c9a70 100644
--- a/lms/djangoapps/gating/apps.py
+++ b/lms/djangoapps/gating/apps.py
@@ -14,4 +14,4 @@ class GatingConfig(AppConfig):
def ready(self):
# Import signals to wire up the signal handlers contained within
- from lms.djangoapps.gating import signals # pylint: disable=unused-import
+ from lms.djangoapps.gating import signals # pylint: disable=unused-import # noqa: F401
diff --git a/lms/djangoapps/grades/api.py b/lms/djangoapps/grades/api.py
index f3a0fd796aec..7967962cc61b 100644
--- a/lms/djangoapps/grades/api.py
+++ b/lms/djangoapps/grades/api.py
@@ -13,23 +13,28 @@
from common.djangoapps.track.event_transaction_utils import create_new_event_transaction_id, set_event_transaction_type
# Public Grades Modules
-from lms.djangoapps.grades import constants, context, course_data, events
+from lms.djangoapps.grades import constants, context, course_data, events # noqa: F401
# Grades APIs that should NOT belong within the Grades subsystem
# TODO move Gradebook to be an external feature outside of core Grades
-from lms.djangoapps.grades.config.waffle import gradebook_bulk_management_enabled, is_writable_gradebook_enabled
+from lms.djangoapps.grades.config.waffle import ( # noqa: F401
+ gradebook_bulk_management_enabled,
+ is_writable_gradebook_enabled,
+)
# Public Grades Factories
-from lms.djangoapps.grades.course_grade_factory import CourseGradeFactory
-from lms.djangoapps.grades.models_api import *
+from lms.djangoapps.grades.course_grade_factory import CourseGradeFactory # noqa: F401
+from lms.djangoapps.grades.models_api import * # noqa: F403
from lms.djangoapps.grades.signals import signals
# TODO exposing functionality from Grades handlers seems fishy.
-from lms.djangoapps.grades.signals.handlers import disconnect_submissions_signal_receiver
+from lms.djangoapps.grades.signals.handlers import disconnect_submissions_signal_receiver # noqa: F401
from lms.djangoapps.grades.subsection_grade import CreateSubsectionGrade
-from lms.djangoapps.grades.subsection_grade_factory import SubsectionGradeFactory
-from lms.djangoapps.grades.tasks import compute_all_grades_for_course as task_compute_all_grades_for_course
-from lms.djangoapps.grades.util_services import GradesUtilService
+from lms.djangoapps.grades.subsection_grade_factory import SubsectionGradeFactory # noqa: F401
+from lms.djangoapps.grades.tasks import (
+ compute_all_grades_for_course as task_compute_all_grades_for_course, # noqa: F401
+)
+from lms.djangoapps.grades.util_services import GradesUtilService # noqa: F401
from lms.djangoapps.utils import _get_key
@@ -59,11 +64,11 @@ def override_subsection_grade(
usage_key = _get_key(usage_key_or_id, UsageKey)
try:
- grade = get_subsection_grade(user_id, usage_key.course_key, usage_key)
+ grade = get_subsection_grade(user_id, usage_key.course_key, usage_key) # noqa: F405
except ObjectDoesNotExist:
grade = _create_subsection_grade(user_id, course_key, usage_key)
- override = update_or_create_override(
+ override = update_or_create_override( # noqa: F405
grade,
requesting_user=overrider,
subsection_grade_model=grade,
@@ -107,7 +112,7 @@ def undo_override_subsection_grade(user_id, course_key_or_id, usage_key_or_id, f
usage_key = _get_key(usage_key_or_id, UsageKey)
try:
- override = get_subsection_grade_override(user_id, course_key, usage_key)
+ override = get_subsection_grade_override(user_id, course_key, usage_key) # noqa: F405
except ObjectDoesNotExist:
return
diff --git a/lms/djangoapps/grades/apps.py b/lms/djangoapps/grades/apps.py
index c65e8722b6d7..5fd8a5351a6f 100644
--- a/lms/djangoapps/grades/apps.py
+++ b/lms/djangoapps/grades/apps.py
@@ -42,7 +42,7 @@ def ready(self):
"""
# Can't import models at module level in AppConfigs, and models get
# included from the signal handlers
- from .signals import handlers # pylint: disable=unused-import
+ from .signals import handlers # pylint: disable=unused-import # noqa: F401
if settings.FEATURES.get('ENABLE_SPECIAL_EXAMS'):
from .services import GradesService
set_runtime_service('grades', GradesService())
diff --git a/lms/djangoapps/grades/course_data.py b/lms/djangoapps/grades/course_data.py
index 5464c4f88105..78a7a7e8de47 100644
--- a/lms/djangoapps/grades/course_data.py
+++ b/lms/djangoapps/grades/course_data.py
@@ -109,7 +109,7 @@ def __str__(self):
def full_string(self): # lint-amnesty, pylint: disable=missing-function-docstring
if self.effective_structure:
- return 'Course: course_key: {}, version: {}, edited_on: {}, grading_policy: {}'.format(
+ return 'Course: course_key: {}, version: {}, edited_on: {}, grading_policy: {}'.format( # noqa: UP032
self.course_key, self.version, self.edited_on, self.grading_policy_hash,
)
else:
diff --git a/lms/djangoapps/grades/course_grade.py b/lms/djangoapps/grades/course_grade.py
index 1642e7c69759..7b32d4031e5f 100644
--- a/lms/djangoapps/grades/course_grade.py
+++ b/lms/djangoapps/grades/course_grade.py
@@ -45,7 +45,7 @@ def __init__(
self.last_updated = last_updated
def __str__(self):
- return 'Course Grade: percent: {}, letter_grade: {}, passed: {}'.format(
+ return 'Course Grade: percent: {}, letter_grade: {}, passed: {}'.format( # noqa: UP032
str(self.percent),
self.letter_grade,
self.passed,
diff --git a/lms/djangoapps/grades/events.py b/lms/djangoapps/grades/events.py
index 48beb338c026..e386d0bc6326 100644
--- a/lms/djangoapps/grades/events.py
+++ b/lms/djangoapps/grades/events.py
@@ -270,7 +270,7 @@ def fire_segment_event_on_course_grade_passed_first_time(user_id, course_locator
event_properties=event_properties
)
- log.info("Segment event fired for passed learners. Event: [{}], Data: [{}]".format(event_name, event_properties))
+ log.info("Segment event fired for passed learners. Event: [{}], Data: [{}]".format(event_name, event_properties)) # noqa: UP032 # pylint: disable=line-too-long
def _emit_course_passing_status_update(user, course_id, is_passing):
diff --git a/lms/djangoapps/grades/management/commands/compute_grades.py b/lms/djangoapps/grades/management/commands/compute_grades.py
index a1ead12d7fd3..ae3e1986c217 100644
--- a/lms/djangoapps/grades/management/commands/compute_grades.py
+++ b/lms/djangoapps/grades/management/commands/compute_grades.py
@@ -83,7 +83,7 @@ def enqueue_all_shuffled_tasks(self, options):
for seq_id, kwargs in enumerate(self._shuffled_task_kwargs(options)):
kwargs['seq_id'] = seq_id
result = tasks.compute_grades_for_course_v2.apply_async(kwargs=kwargs, **task_options)
- log.info("Grades: Created {task_name}[{task_id}] with arguments {kwargs}".format(
+ log.info("Grades: Created {task_name}[{task_id}] with arguments {kwargs}".format( # noqa: UP032
task_name=tasks.compute_grades_for_course.name,
task_id=result.task_id,
kwargs=kwargs,
@@ -106,7 +106,7 @@ def _shuffled_task_kwargs(self, options):
for task_arg_tuple in tasks._course_task_args(course_key, **options): # lint-amnesty, pylint: disable=protected-access
all_args.append(task_arg_tuple)
- all_args.sort(key=lambda x: hashlib.md5(f'{x!r}'.encode('utf-8')).digest())
+ all_args.sort(key=lambda x: hashlib.md5(f'{x!r}'.encode('utf-8')).digest()) # noqa: UP012
for args in all_args:
yield {
diff --git a/lms/djangoapps/grades/management/commands/send_segment_events_for_failed_learners.py b/lms/djangoapps/grades/management/commands/send_segment_events_for_failed_learners.py
index f621de4f4506..298e143ea221 100644
--- a/lms/djangoapps/grades/management/commands/send_segment_events_for_failed_learners.py
+++ b/lms/djangoapps/grades/management/commands/send_segment_events_for_failed_learners.py
@@ -127,7 +127,7 @@ def handle(self, *args, **options):
stats['failed_course_enrollment_ids'][course_id].append(failed_enrollment_id)
log.info(
- "{} Segment event fired for failed learner. Event: [{}], Data: [{}]".format(
+ "{} Segment event fired for failed learner. Event: [{}], Data: [{}]".format( # noqa: UP032
log_prefix,
EVENT_NAME,
event_properties
diff --git a/lms/djangoapps/grades/models.py b/lms/djangoapps/grades/models.py
index 3e972c1f4b49..9210883953e7 100644
--- a/lms/djangoapps/grades/models.py
+++ b/lms/djangoapps/grades/models.py
@@ -228,7 +228,7 @@ def bulk_create(cls, user_id, course_key, block_record_lists):
with transaction.atomic():
created_visual_blocks = cls.objects.bulk_create(visual_blocks)
except IntegrityError:
- log.warning('Falling back to create VisualBlocks one by one for user {} in course {}'.format(
+ log.warning('Falling back to create VisualBlocks one by one for user {} in course {}'.format( # noqa: UP032
user_id,
course_key
))
@@ -373,7 +373,7 @@ def __str__(self):
"""
Returns a string representation of this model.
"""
- return (
+ return ( # noqa: UP032
"{} user: {}, course version: {}, subsection: {} ({}). {}/{} graded, {}/{} all, first_attempted: {}"
).format(
type(self).__name__,
@@ -647,7 +647,7 @@ def read(cls, user_id, course_id):
except KeyError:
# user's grade is not in the prefetched dict, so
# assume they have no grade
- raise cls.DoesNotExist # lint-amnesty, pylint: disable=raise-missing-from
+ raise cls.DoesNotExist # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except KeyError:
# grades were not prefetched for the course, so fetch it
return cls.objects.get(user_id=user_id, course_id=course_id)
@@ -747,7 +747,7 @@ class PersistentSubsectionGradeOverride(models.Model):
class Meta:
app_label = "grades"
- grade = models.OneToOneField(PersistentSubsectionGrade, related_name='override', on_delete=models.CASCADE)
+ grade = models.OneToOneField(PersistentSubsectionGrade, related_name='override', on_delete=models.CASCADE) # noqa: DJ012 # pylint: disable=line-too-long
# Created/modified timestamps prevent race-conditions when using with async rescoring tasks
created = models.DateTimeField(auto_now_add=True, db_index=True)
@@ -760,9 +760,9 @@ class Meta:
earned_graded_override = models.FloatField(null=True, blank=True)
possible_graded_override = models.FloatField(null=True, blank=True)
# store the source of the system that caused the override
- system = models.CharField(max_length=100, blank=True, null=True)
+ system = models.CharField(max_length=100, blank=True, null=True) # noqa: DJ001
# store the reason for the override
- override_reason = models.CharField(max_length=300, blank=True, null=True)
+ override_reason = models.CharField(max_length=300, blank=True, null=True) # noqa: DJ001
_CACHE_NAMESPACE = "grades.models.PersistentSubsectionGradeOverride"
diff --git a/lms/djangoapps/grades/rest_api/v1/gradebook_views.py b/lms/djangoapps/grades/rest_api/v1/gradebook_views.py
index 95e18631aa6c..42a076d7628e 100644
--- a/lms/djangoapps/grades/rest_api/v1/gradebook_views.py
+++ b/lms/djangoapps/grades/rest_api/v1/gradebook_views.py
@@ -297,7 +297,7 @@ def can_see_bulk_management(self, course_key):
master's track or is enabled with the grades.bulk_management course waffle flag.
"""
course_modes = get_course_enrollment_details(str(course_key), include_expired=True).get('course_modes', [])
- course_has_masters_track = any((course_mode['slug'] == CourseMode.MASTERS for course_mode in course_modes))
+ course_has_masters_track = any((course_mode['slug'] == CourseMode.MASTERS for course_mode in course_modes)) # noqa: UP034 # pylint: disable=line-too-long
return course_has_masters_track or gradebook_bulk_management_enabled(course_key)
def _get_assignment_types(self, course):
@@ -686,7 +686,7 @@ def _get_user_count(self, query_args, cache_time=3600, annotations=None):
queryset = queryset.annotate(**annotations)
queryset = queryset.filter(*query_args)
- cache_key = 'usercount.%s' % queryset.query
+ cache_key = 'usercount.%s' % queryset.query # noqa: UP031
user_count = cache.get(cache_key, None)
if user_count is None:
user_count = queryset.count()
@@ -1063,7 +1063,7 @@ def get(self, request, subsection_id):
try:
usage_key = UsageKey.from_string(subsection_id)
except InvalidKeyError:
- raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from
+ raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
status_code=status.HTTP_404_NOT_FOUND,
developer_message='Invalid UsageKey',
error_code='invalid_usage_key'
@@ -1079,7 +1079,7 @@ def get(self, request, subsection_id):
try:
user_id = int(request.GET.get('user_id'))
except ValueError:
- raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from
+ raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
status_code=status.HTTP_404_NOT_FOUND,
developer_message='Invalid UserID',
error_code='invalid_user_id'
diff --git a/lms/djangoapps/grades/rest_api/v1/tests/test_gradebook_views.py b/lms/djangoapps/grades/rest_api/v1/tests/test_gradebook_views.py
index ae7a36685232..e6e989704a4e 100644
--- a/lms/djangoapps/grades/rest_api/v1/tests/test_gradebook_views.py
+++ b/lms/djangoapps/grades/rest_api/v1/tests/test_gradebook_views.py
@@ -110,7 +110,7 @@ def initialize_course(cls, course):
parent_location=cls.section.location,
category="sequential",
)
- unit2 = BlockFactory.create(
+ unit2 = BlockFactory.create( # noqa: F841
parent_location=cls.subsection2.location,
category="vertical",
)
@@ -1721,7 +1721,7 @@ def test_override_is_created(self, login_method):
the score from the most recent request is recorded.
"""
with override_waffle_flag(self.waffle_flag, active=True):
- request_user = getattr(self, login_method)()
+ request_user = getattr(self, login_method)() # noqa: F841
post_data = [
{
'user_id': self.student.id,
@@ -1997,7 +1997,7 @@ def test_no_override(self, login_method):
def test_with_override_no_modification(self, login_method):
getattr(self, login_method)()
- override = PersistentSubsectionGradeOverride.objects.create(
+ override = PersistentSubsectionGradeOverride.objects.create( # noqa: F841
grade=self.grade,
earned_all_override=0.0,
possible_all_override=12.0,
@@ -2054,7 +2054,7 @@ def test_with_override_with_long_history(self):
self.login_staff()
for i in range(6):
- override = PersistentSubsectionGradeOverride.update_or_create_override(
+ override = PersistentSubsectionGradeOverride.update_or_create_override( # noqa: F841
requesting_user=self.global_staff,
subsection_grade_model=self.grade,
earned_all_override=i,
@@ -2081,7 +2081,7 @@ def test_with_override_with_long_history(self):
def test_with_override_with_history(self, login_method):
getattr(self, login_method)()
- override = PersistentSubsectionGradeOverride.update_or_create_override(
+ override = PersistentSubsectionGradeOverride.update_or_create_override( # noqa: F841
requesting_user=self.global_staff,
subsection_grade_model=self.grade,
earned_all_override=0.0,
@@ -2136,7 +2136,7 @@ def test_comment_appears(self):
"""
proctoring_failure_fake_comment = "Failed Test Proctoring"
self.login_course_staff()
- override = PersistentSubsectionGradeOverride.update_or_create_override(
+ override = PersistentSubsectionGradeOverride.update_or_create_override( # noqa: F841
requesting_user=self.global_staff,
subsection_grade_model=self.grade,
earned_all_override=0.0,
@@ -2183,7 +2183,7 @@ def test_with_invalid_format_user_id(self, login_method):
def test_with_valid_subsection_id_and_valid_user_id_but_no_record(self, login_method):
getattr(self, login_method)()
- override = PersistentSubsectionGradeOverride.update_or_create_override(
+ override = PersistentSubsectionGradeOverride.update_or_create_override( # noqa: F841
requesting_user=self.global_staff,
subsection_grade_model=self.grade,
earned_all_override=0.0,
diff --git a/lms/djangoapps/grades/rest_api/v1/tests/test_grading_policy_view.py b/lms/djangoapps/grades/rest_api/v1/tests/test_grading_policy_view.py
index b55395c01dcd..14732da2e720 100644
--- a/lms/djangoapps/grades/rest_api/v1/tests/test_grading_policy_view.py
+++ b/lms/djangoapps/grades/rest_api/v1/tests/test_grading_policy_view.py
@@ -207,7 +207,7 @@ def test_get(self):
"dropped": 0
}
]
- self.assertListEqual(response.data, expected)
+ self.assertListEqual(response.data, expected) # noqa: PT009
class CourseGradingPolicyMissingFieldsTests(GradingPolicyTestMixin, SharedModuleStoreTestCase):
@@ -262,4 +262,4 @@ def test_get(self):
"dropped": 0
}
]
- self.assertListEqual(response.data, expected)
+ self.assertListEqual(response.data, expected) # noqa: PT009
diff --git a/lms/djangoapps/grades/rest_api/v1/utils.py b/lms/djangoapps/grades/rest_api/v1/utils.py
index f2544d3579a3..e9ebbc59d2cc 100644
--- a/lms/djangoapps/grades/rest_api/v1/utils.py
+++ b/lms/djangoapps/grades/rest_api/v1/utils.py
@@ -104,13 +104,13 @@ def _get_user_or_raise(self, request, course_key):
try:
yield self._get_single_user(request, course_key)
except USER_MODEL.DoesNotExist:
- raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from
+ raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
status_code=status.HTTP_404_NOT_FOUND,
developer_message='The user matching the requested username does not exist.',
error_code='user_does_not_exist'
)
except CourseEnrollment.DoesNotExist:
- raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from
+ raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
status_code=status.HTTP_404_NOT_FOUND,
developer_message='The user matching the requested username is not enrolled in this course',
error_code='user_not_enrolled'
diff --git a/lms/djangoapps/grades/rest_api/v1/views.py b/lms/djangoapps/grades/rest_api/v1/views.py
index b6835fd61ec4..89f5679bc681 100644
--- a/lms/djangoapps/grades/rest_api/v1/views.py
+++ b/lms/djangoapps/grades/rest_api/v1/views.py
@@ -5,7 +5,7 @@
import logging
from collections import defaultdict
from contextlib import contextmanager
-from typing import List
+from typing import List # noqa: UP035
from django.core.exceptions import ValidationError # lint-amnesty, pylint: disable=wrong-import-order
from django.db.models import Q
@@ -196,7 +196,7 @@ def _get_course(self, request, course_id):
try:
course_key = get_course_key(request, course_id)
except InvalidKeyError:
- raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from
+ raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
status_code=status.HTTP_400_BAD_REQUEST,
developer_message='The provided course key cannot be parsed.',
error_code='invalid_course_key'
@@ -420,7 +420,7 @@ def get(self, request, course_id=None):
try:
course_id = get_course_key(request, course_id)
except InvalidKeyError:
- raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from
+ raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
status_code=status.HTTP_400_BAD_REQUEST,
developer_message='The provided course key cannot be parsed.',
error_code='invalid_course_key'
@@ -476,7 +476,7 @@ def get_problem_blocks(course):
return blocks
@staticmethod
- def _get_course_data(course_key: str, course_enrollments: List[CourseEnrollment], course, blocks):
+ def _get_course_data(course_key: str, course_enrollments: List[CourseEnrollment], course, blocks): # noqa: UP006
"""
Extracts the fields needed from course enrollments and course block.
This function maps the ProblemBlock data of the course to it's enrollment.
diff --git a/lms/djangoapps/grades/scores.py b/lms/djangoapps/grades/scores.py
index 7a89a88c794b..70efa28a01b0 100644
--- a/lms/djangoapps/grades/scores.py
+++ b/lms/djangoapps/grades/scores.py
@@ -167,7 +167,7 @@ def _get_score_from_submissions(submissions_scores, block):
first_attempted = submission_value['created_at']
weighted_earned = submission_value['points_earned']
weighted_possible = submission_value['points_possible']
- assert weighted_earned >= 0.0 and weighted_possible > 0.0 # per contract from submissions API
+ assert weighted_earned >= 0.0 and weighted_possible > 0.0 # per contract from submissions API # noqa: PT018 # pylint: disable=line-too-long
return (None, None) + (weighted_earned, weighted_possible) + (first_attempted,)
diff --git a/lms/djangoapps/grades/signals/handlers.py b/lms/djangoapps/grades/signals/handlers.py
index 79d67b740431..38ded9f874f9 100644
--- a/lms/djangoapps/grades/signals/handlers.py
+++ b/lms/djangoapps/grades/signals/handlers.py
@@ -165,7 +165,7 @@ def score_published_handler(sender, block, user, raw_earned, raw_possible, only_
if not is_score_higher_or_equal(prev_raw_earned, prev_raw_possible, raw_earned, raw_possible):
update_score = False
log.warning(
- "Grades: Rescore is not higher than previous: "
+ "Grades: Rescore is not higher than previous: " # noqa: UP032
"user: {}, block: {}, previous: {}/{}, new: {}/{} ".format(
user, block.location, prev_raw_earned, prev_raw_possible, raw_earned, raw_possible,
)
diff --git a/lms/djangoapps/grades/subsection_grade.py b/lms/djangoapps/grades/subsection_grade.py
index 416a8f5d66fe..5d371a689234 100644
--- a/lms/djangoapps/grades/subsection_grade.py
+++ b/lms/djangoapps/grades/subsection_grade.py
@@ -19,7 +19,7 @@
log = getLogger(__name__)
-class SubsectionGradeBase(metaclass=ABCMeta):
+class SubsectionGradeBase(metaclass=ABCMeta): # noqa: B024
"""
Abstract base class for Subsection Grades.
"""
@@ -67,7 +67,7 @@ def show_grades(self, has_staff_access):
# but correctness_available always returns False as we do not want to show correctness
# of problems to the users.
return (self.due is None or
- self.due < datetime.now(timezone.utc))
+ self.due < datetime.now(timezone.utc)) # noqa: UP017
return ShowCorrectness.correctness_available(self.show_correctness, self.due, has_staff_access)
@property
diff --git a/lms/djangoapps/grades/tasks.py b/lms/djangoapps/grades/tasks.py
index 25c5a8187d90..b69e3a1d0f85 100644
--- a/lms/djangoapps/grades/tasks.py
+++ b/lms/djangoapps/grades/tasks.py
@@ -27,7 +27,7 @@
from openedx.core.djangoapps.content.block_structure.api import clear_course_from_cache
from openedx.core.djangoapps.content.block_structure.exceptions import UsageKeyNotInBlockStructure
from openedx.core.djangoapps.content.course_overviews.models import ( # lint-amnesty, pylint: disable=unused-import
- CourseOverview,
+ CourseOverview, # noqa: F401
)
from xmodule.modulestore.django import modulestore # lint-amnesty, pylint: disable=wrong-import-order
@@ -109,7 +109,7 @@ def compute_grades_for_course_v2(self, **kwargs):
try:
return compute_grades_for_course(kwargs['course_key'], kwargs['offset'], kwargs['batch_size'])
except Exception as exc:
- raise self.retry(kwargs=kwargs, exc=exc)
+ raise self.retry(kwargs=kwargs, exc=exc) # noqa: B904
@shared_task(base=LoggedPersistOnFailureTask)
@@ -252,12 +252,12 @@ def _recalculate_subsection_grade(self, **kwargs):
)
except Exception as exc:
if not isinstance(exc, KNOWN_RETRY_ERRORS):
- log.info("tnl-6244 grades unexpected failure: {}. task id: {}. kwargs={}".format(
+ log.info("tnl-6244 grades unexpected failure: {}. task id: {}. kwargs={}".format( # noqa: UP032
repr(exc),
self.request.id,
kwargs,
))
- raise self.retry(kwargs=kwargs, exc=exc)
+ raise self.retry(kwargs=kwargs, exc=exc) # noqa: B904
def _has_db_updated_with_new_score(self, scored_block_usage_key, **kwargs):
@@ -297,7 +297,7 @@ def _has_db_updated_with_new_score(self, scored_block_usage_key, **kwargs):
if not db_is_updated:
log.info(
- "Grades: tasks._has_database_updated_with_new_score is False. Task ID: {}. Kwargs: {}. Found "
+ "Grades: tasks._has_database_updated_with_new_score is False. Task ID: {}. Kwargs: {}. Found " # noqa: UP032 # pylint: disable=line-too-long
"modified time: {}".format(
self.request.id,
kwargs,
@@ -333,7 +333,7 @@ def _update_subsection_grades(
if not subsections_to_update:
clear_course_from_cache(course_usage_key.course_key)
raise UsageKeyNotInBlockStructure(
- "Scored block usage_key '{0}' is not found in the block_structure with root '{1}'".format(
+ "Scored block usage_key '{0}' is not found in the block_structure with root '{1}'".format( # noqa: UP030, UP032 # pylint: disable=line-too-long
str(scored_block_usage_key),
str(course_usage_key)
)
diff --git a/lms/djangoapps/grades/tests/test_api.py b/lms/djangoapps/grades/tests/test_api.py
index eb4c20b4b975..9641f570d659 100644
--- a/lms/djangoapps/grades/tests/test_api.py
+++ b/lms/djangoapps/grades/tests/test_api.py
@@ -177,15 +177,15 @@ def test_clear_user_course_grades(self):
self.subsection.location
)
course_grade = PersistentCourseGrade.read(self.user.id, self.course.id)
- self.assertIsNotNone(course_grade)
- self.assertIsNotNone(override_obj)
+ self.assertIsNotNone(course_grade) # noqa: PT009
+ self.assertIsNotNone(override_obj) # noqa: PT009
api.clear_user_course_grades(self.user.id, self.course.id)
- with self.assertRaises(PersistentCourseGrade.DoesNotExist):
+ with self.assertRaises(PersistentCourseGrade.DoesNotExist): # noqa: PT027
PersistentCourseGrade.read(self.user.id, self.course.id)
- with self.assertRaises(PersistentSubsectionGrade.DoesNotExist):
+ with self.assertRaises(PersistentSubsectionGrade.DoesNotExist): # noqa: PT027
api.get_subsection_grade_override(
self.user.id,
self.course.id,
@@ -220,10 +220,10 @@ def test_clear_other_user_course_grades(self):
# fetch and assert grades are available for both users
user_course_grade = PersistentCourseGrade.read(self.user.id, self.course.id)
other_user_course_grade = PersistentCourseGrade.read(self.user.id, self.course.id)
- self.assertIsNotNone(user_course_grade)
- self.assertIsNotNone(user_override_obj)
- self.assertIsNotNone(other_user_override_obj)
- self.assertIsNotNone(other_user_course_grade)
+ self.assertIsNotNone(user_course_grade) # noqa: PT009
+ self.assertIsNotNone(user_override_obj) # noqa: PT009
+ self.assertIsNotNone(other_user_override_obj) # noqa: PT009
+ self.assertIsNotNone(other_user_course_grade) # noqa: PT009
api.clear_user_course_grades(other_user.id, self.course.id)
@@ -234,10 +234,10 @@ def test_clear_other_user_course_grades(self):
self.subsection.location
)
after_clear_user_course_grade = PersistentCourseGrade.read(self.user.id, self.course.id)
- with self.assertRaises(PersistentCourseGrade.DoesNotExist):
+ with self.assertRaises(PersistentCourseGrade.DoesNotExist): # noqa: PT027
PersistentCourseGrade.read(other_user.id, self.course.id)
- self.assertIsNotNone(after_clear_override_obj)
- self.assertIsNotNone(after_clear_user_course_grade)
+ self.assertIsNotNone(after_clear_override_obj) # noqa: PT009
+ self.assertIsNotNone(after_clear_user_course_grade) # noqa: PT009
@patch('lms.djangoapps.grades.models_api._PersistentSubsectionGrade')
@patch('lms.djangoapps.grades.models_api._PersistentCourseGrade')
diff --git a/lms/djangoapps/grades/tests/test_course_data.py b/lms/djangoapps/grades/tests/test_course_data.py
index 3d0319b4e887..07a2e60397c9 100644
--- a/lms/djangoapps/grades/tests/test_course_data.py
+++ b/lms/djangoapps/grades/tests/test_course_data.py
@@ -63,7 +63,7 @@ def test_fill_course_data(self, mock_get_blocks):
assert expected == actual
def test_properties(self):
- expected_edited_on = getattr( # lint-amnesty, pylint: disable=literal-used-as-attribute
+ expected_edited_on = getattr( # lint-amnesty, pylint: disable=literal-used-as-attribute # noqa: B009
self.one_true_structure[self.one_true_structure.root_block_usage_key],
'subtree_edited_on',
)
@@ -85,7 +85,7 @@ def test_properties(self):
assert 'Course: course_key' in course_data.full_string()
def test_no_data(self):
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
_ = CourseData(self.user)
@patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False})
diff --git a/lms/djangoapps/grades/tests/test_events.py b/lms/djangoapps/grades/tests/test_events.py
index 2c47de903ead..36096c1a200b 100644
--- a/lms/djangoapps/grades/tests/test_events.py
+++ b/lms/djangoapps/grades/tests/test_events.py
@@ -90,7 +90,7 @@ def test_persistent_grade_event_emitted(self):
PERSISTENT_GRADE_SUMMARY_CHANGED.connect(event_receiver)
grade = PersistentCourseGrade.update_or_create(**self.params)
- self.assertTrue(self.receiver_called)
+ self.assertTrue(self.receiver_called) # noqa: PT009
assert_dict_contains_subset(
self,
{
@@ -152,7 +152,7 @@ def test_course_passing_status_updated_emitted(self):
with mock_passing_grade():
grade_factory.update(self.user, self.course)
- self.assertTrue(self.receiver_called)
+ self.assertTrue(self.receiver_called) # noqa: PT009
assert_dict_contains_subset(
self,
{
@@ -226,7 +226,7 @@ def test_ccx_course_passing_status_updated_emitted(self):
with mock_passing_grade():
grade_factory.update(self.user, self.store.get_course(self.ccx_locator))
- self.assertTrue(self.receiver_called)
+ self.assertTrue(self.receiver_called) # noqa: PT009
assert_dict_contains_subset(
self,
{
diff --git a/lms/djangoapps/grades/tests/test_handlers.py b/lms/djangoapps/grades/tests/test_handlers.py
index deddfc28653f..3e7790136ddb 100644
--- a/lms/djangoapps/grades/tests/test_handlers.py
+++ b/lms/djangoapps/grades/tests/test_handlers.py
@@ -72,7 +72,7 @@ def _get_exam_event_metadata(event_signal):
minorversion=0,
source='openedx/lms/web',
sourcehost='lms.test',
- time=datetime.now(timezone.utc)
+ time=datetime.now(timezone.utc) # noqa: UP017
)
@ddt.data(
diff --git a/lms/djangoapps/grades/tests/test_models.py b/lms/djangoapps/grades/tests/test_models.py
index 950d01c3e802..063724f2e9a1 100644
--- a/lms/djangoapps/grades/tests/test_models.py
+++ b/lms/djangoapps/grades/tests/test_models.py
@@ -48,7 +48,7 @@ def setUp(self):
)
def test_empty_block_record_set(self):
- empty_json = '{{"blocks":[],"course_key":"{}","version":{}}}'.format(
+ empty_json = '{{"blocks":[],"course_key":"{}","version":{}}}'.format( # noqa: UP032
str(self.course_key),
BLOCK_RECORD_LIST_VERSION,
)
@@ -351,8 +351,8 @@ def test_clear_subsection_grade(self):
deleted = PersistentSubsectionGrade.delete_subsection_grades_for_learner(
self.user.id, self.course_key
)
- self.assertEqual(deleted, 1)
- self.assertFalse(PersistentSubsectionGrade.objects.filter(
+ self.assertEqual(deleted, 1) # noqa: PT009
+ self.assertFalse(PersistentSubsectionGrade.objects.filter( # noqa: PT009
user_id=self.user.id, course_id=self.course_key).exists()
)
@@ -366,7 +366,7 @@ def test_clear_subsection_grade_override(self):
feature=GradeOverrideFeatureEnum.gradebook,
)
deleted = PersistentSubsectionGrade.delete_subsection_grades_for_learner(self.user.id, self.course_key)
- self.assertEqual(deleted, 2)
+ self.assertEqual(deleted, 2) # noqa: PT009
@ddt.ddt
@@ -452,7 +452,7 @@ def test_passed_timestamp_is_now(self, mock):
with freeze_time(now()):
grade = PersistentCourseGrade.update_or_create(**self.params)
assert now() == grade.passed_timestamp
- self.assertEqual(mock.call_count, 1)
+ self.assertEqual(mock.call_count, 1) # noqa: PT009
def test_create_and_read_grade(self):
created_grade = PersistentCourseGrade.update_or_create(**self.params)
@@ -541,12 +541,12 @@ def test_clear_course_grade(self):
)
# assert after deleteing grade for a single user and course
- with self.assertRaises(PersistentCourseGrade.DoesNotExist):
+ with self.assertRaises(PersistentCourseGrade.DoesNotExist): # noqa: PT027
PersistentCourseGrade.read(self.params['user_id'], self.course_key)
another_user_grade = PersistentCourseGrade.read(other_user_params['user_id'], self.course_key)
- self.assertIsNotNone(another_user_grade)
+ self.assertIsNotNone(another_user_grade) # noqa: PT009
- self.assertTrue(PersistentCourseGrade.objects.filter(
+ self.assertTrue(PersistentCourseGrade.objects.filter( # noqa: PT009
user_id=self.params['user_id'], course_id=other_course_key).exists()
)
diff --git a/lms/djangoapps/grades/tests/test_score_render.py b/lms/djangoapps/grades/tests/test_score_render.py
index bdbadb7b7391..c48c28e3c22f 100644
--- a/lms/djangoapps/grades/tests/test_score_render.py
+++ b/lms/djangoapps/grades/tests/test_score_render.py
@@ -84,7 +84,7 @@ def test_load_xblock_for_external_grader(self, mock_field_data_cache, mock_modul
)
# Assertions
- self.assertIsNotNone(result, "Should return a block instance")
+ self.assertIsNotNone(result, "Should return a block instance") # noqa: PT009
mock_modulestore.return_value.get_item.assert_called_once()
mock_field_data_cache.cache_for_block_descendents.assert_called_once()
mock_get_block.assert_called_once()
@@ -101,7 +101,7 @@ def test_load_xblock_for_external_grader_missing_block(self, mock_anon_user, moc
mock_modulestore.return_value.get_item.side_effect = Exception("Block not found")
# Test that Http404 is raised
- with self.assertRaises(Http404):
+ with self.assertRaises(Http404): # noqa: PT027
load_xblock_for_external_grader(
self.anonymous_user_id, str(self.course.id), str(self.problem.location), self.course
)
@@ -122,7 +122,7 @@ def test_get_block_for_descriptor_without_access_check(self, mock_prepare_runtim
)
# Assertions
- self.assertIsNotNone(result, "Should return a block instance")
+ self.assertIsNotNone(result, "Should return a block instance") # noqa: PT009
mock_prepare_runtime.assert_called_once()
block.bind_for_student.assert_called_once()
@@ -155,20 +155,20 @@ def test_handle_external_grader_score_json_string(self, mock_load_xblock, mock_m
mock_load_xblock.assert_called_once()
call_args, call_kwargs = mock_load_xblock.call_args
- self.assertEqual(call_args[0], score.user_id)
- self.assertIsInstance(call_args[1], CourseKey)
- self.assertEqual(str(call_args[1]), score.course_id)
- self.assertIsInstance(call_args[2], UsageKey)
- self.assertEqual(str(call_args[2]), score.module_id)
+ self.assertEqual(call_args[0], score.user_id) # noqa: PT009
+ self.assertIsInstance(call_args[1], CourseKey) # noqa: PT009
+ self.assertEqual(str(call_args[1]), score.course_id) # noqa: PT009
+ self.assertIsInstance(call_args[2], UsageKey) # noqa: PT009
+ self.assertEqual(str(call_args[2]), score.module_id) # noqa: PT009
- self.assertIn("course", call_kwargs)
+ self.assertIn("course", call_kwargs) # noqa: PT009
mock_instance.handle_ajax.assert_called_once()
ajax_args, _ = mock_instance.handle_ajax.call_args
- self.assertEqual(ajax_args[0], "score_update")
- self.assertIn("xqueue_header", ajax_args[1])
- self.assertIn("xqueue_body", ajax_args[1])
- self.assertIn("queuekey", ajax_args[1])
+ self.assertEqual(ajax_args[0], "score_update") # noqa: PT009
+ self.assertIn("xqueue_header", ajax_args[1]) # noqa: PT009
+ self.assertIn("xqueue_body", ajax_args[1]) # noqa: PT009
+ self.assertIn("queuekey", ajax_args[1]) # noqa: PT009
mock_instance.save.assert_called_once()
@patch("lms.djangoapps.grades.score_render.modulestore")
@@ -195,7 +195,7 @@ def test_handle_external_grader_score_plain_text(self, mock_load_xblock, mock_mo
)
# json.loads must fail BEFORE anything else runs
- with self.assertRaises(json.JSONDecodeError):
+ with self.assertRaises(json.JSONDecodeError): # noqa: PT027
handle_external_grader_score(None, None, score)
# Assertions
@@ -227,7 +227,7 @@ def test_handle_external_grader_score_exception(self, mock_load_xblock, mock_mod
)
# Call the handler and expect exception to be raised
- with self.assertRaises(Exception):
+ with self.assertRaises(Exception): # noqa: B017, PT027
handle_external_grader_score(None, None, score)
@patch("lms.djangoapps.grades.score_render.AnonymousUserId.objects.get")
@@ -249,11 +249,11 @@ def test_load_xblock_for_external_grader_none_instance(
mock_get_block.return_value = None
# Test that Http404 is raised
- with self.assertRaises(Http404) as context:
+ with self.assertRaises(Http404) as context: # noqa: PT027
load_xblock_for_external_grader(self.anonymous_user_id, str(self.course.id), str(self.problem.location))
expected_msg = f"Could not bind XBlock instance for usage key: {str(self.problem.location)}"
- self.assertEqual(str(context.exception), expected_msg)
+ self.assertEqual(str(context.exception), expected_msg) # noqa: PT009
# Verify that all mocks were called
mock_anon_user.assert_called_once()
@@ -313,19 +313,19 @@ def test_end_to_end_grading_flow(self, mock_modulestore): # pylint: disable=unu
# Verify the data structure passed to handle_ajax
handle_ajax_args = mock_instance.handle_ajax.call_args[0]
- self.assertEqual(handle_ajax_args[0], "score_update")
+ self.assertEqual(handle_ajax_args[0], "score_update") # noqa: PT009
data = handle_ajax_args[1]
- self.assertIn("xqueue_header", data)
- self.assertIn("xqueue_body", data)
- self.assertIn("queuekey", data)
+ self.assertIn("xqueue_header", data) # noqa: PT009
+ self.assertIn("xqueue_body", data) # noqa: PT009
+ self.assertIn("queuekey", data) # noqa: PT009
header = json.loads(data["xqueue_header"])
- self.assertEqual(header["lms_key"], "sub_123")
- self.assertEqual(header["queue_name"], "test_queue")
+ self.assertEqual(header["lms_key"], "sub_123") # noqa: PT009
+ self.assertEqual(header["queue_name"], "test_queue") # noqa: PT009
# Verify the body is the correct JSON
body = json.loads(data["xqueue_body"])
- self.assertEqual(body["score"], 1)
- self.assertEqual(body["max_score"], 1)
- self.assertTrue(body["correct"])
+ self.assertEqual(body["score"], 1) # noqa: PT009
+ self.assertEqual(body["max_score"], 1) # noqa: PT009
+ self.assertTrue(body["correct"]) # noqa: PT009
diff --git a/lms/djangoapps/grades/tests/test_services.py b/lms/djangoapps/grades/tests/test_services.py
index 8fc24da059b9..c82cbb0704b3 100644
--- a/lms/djangoapps/grades/tests/test_services.py
+++ b/lms/djangoapps/grades/tests/test_services.py
@@ -98,7 +98,7 @@ def subsection_grade_override_to_dict(self, grade):
}
def test_get_subsection_grade(self):
- self.assertDictEqual(self.subsection_grade_to_dict(self.service.get_subsection_grade(
+ self.assertDictEqual(self.subsection_grade_to_dict(self.service.get_subsection_grade( # noqa: PT009
user_id=self.user.id,
course_key_or_id=self.course.id,
usage_key_or_id=self.subsection.location
@@ -108,7 +108,7 @@ def test_get_subsection_grade(self):
})
# test with id strings as parameters instead
- self.assertDictEqual(self.subsection_grade_to_dict(self.service.get_subsection_grade(
+ self.assertDictEqual(self.subsection_grade_to_dict(self.service.get_subsection_grade( # noqa: PT009
user_id=self.user.id,
course_key_or_id=str(self.course.id),
usage_key_or_id=str(self.subsection.location)
@@ -120,7 +120,7 @@ def test_get_subsection_grade(self):
def test_get_subsection_grade_override(self):
override, _ = PersistentSubsectionGradeOverride.objects.update_or_create(grade=self.grade)
- self.assertDictEqual(self.subsection_grade_override_to_dict(self.service.get_subsection_grade_override(
+ self.assertDictEqual(self.subsection_grade_override_to_dict(self.service.get_subsection_grade_override( # noqa: PT009 # pylint: disable=line-too-long
user_id=self.user.id,
course_key_or_id=self.course.id,
usage_key_or_id=self.subsection.location
@@ -137,7 +137,7 @@ def test_get_subsection_grade_override(self):
)
# test with course key parameter as string instead
- self.assertDictEqual(self.subsection_grade_override_to_dict(self.service.get_subsection_grade_override(
+ self.assertDictEqual(self.subsection_grade_override_to_dict(self.service.get_subsection_grade_override( # noqa: PT009 # pylint: disable=line-too-long
user_id=self.user.id,
course_key_or_id=str(self.course.id),
usage_key_or_id=self.subsection.location
@@ -245,7 +245,7 @@ def test_undo_override_subsection_grade(self):
grade=self.grade,
system=GradeOverrideFeatureEnum.proctoring
)
- override_id = override.id # lint-amnesty, pylint: disable=unused-variable
+ override_id = override.id # lint-amnesty, pylint: disable=unused-variable # noqa: F841
self.service.undo_override_subsection_grade(
user_id=self.user.id,
course_key_or_id=self.course.id,
@@ -301,7 +301,7 @@ def test_undo_override_subsection_grade_without_grade(self):
usage_key_or_id=self.subsection.location,
)
except PersistentSubsectionGrade.DoesNotExist:
- assert False, 'Exception raised unexpectedly'
+ assert False, 'Exception raised unexpectedly' # noqa: B011, PT015
assert not self.mock_signal.called
diff --git a/lms/djangoapps/grades/tests/test_signals.py b/lms/djangoapps/grades/tests/test_signals.py
index 912a7ba00f5c..fb835a5ba516 100644
--- a/lms/djangoapps/grades/tests/test_signals.py
+++ b/lms/djangoapps/grades/tests/test_signals.py
@@ -266,7 +266,7 @@ def test_disconnect_manager_bad_arg(self):
"""
Tests that the disconnect context manager errors when given an invalid signal.
"""
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
with disconnect_submissions_signal_receiver(PROBLEM_RAW_SCORE_CHANGED):
pass
diff --git a/lms/djangoapps/grades/tests/test_tasks.py b/lms/djangoapps/grades/tests/test_tasks.py
index 510dd8ab5315..26844863dea4 100644
--- a/lms/djangoapps/grades/tests/test_tasks.py
+++ b/lms/djangoapps/grades/tests/test_tasks.py
@@ -113,7 +113,7 @@ def setUp(self):
self.user = UserFactory()
@contextmanager
- def mock_csm_get_score(self, score=MagicMock(grade=1.0, max_grade=2.0)):
+ def mock_csm_get_score(self, score=MagicMock(grade=1.0, max_grade=2.0)): # noqa: B008
"""
Mocks the scores needed by the SCORE_PUBLISHED signal
handler. By default, sets the returned score to 1/2.
@@ -208,7 +208,7 @@ def test_other_inaccessible_subsection(self, mock_subsection_signal):
args[1]['subsection_grade'].location
for args in mock_subsection_signal.call_args_list
}
- self.assertSetEqual(
+ self.assertSetEqual( # noqa: PT009
sequentials_signalled,
{self.sequential.location},
)
@@ -383,8 +383,8 @@ def test_no_log_known_error(self, mock_update, mock_retry, mock_log):
def _apply_recalculate_subsection_grade(
self,
- mock_score=MagicMock(
- modified=datetime.utcnow().replace(tzinfo=pytz.UTC) + timedelta(days=1),
+ mock_score=MagicMock( # noqa: B008
+ modified=datetime.utcnow().replace(tzinfo=pytz.UTC) + timedelta(days=1), # noqa: B008
grade=1.0,
max_grade=2.0,
)
@@ -638,7 +638,7 @@ def test_recalculate_subsection_grade_v3(self, freeze_flag_value, end_date_adjus
CourseEnrollment.enroll(user, self.course.id)
with override_waffle_flag(self.freeze_grade_flag, active=freeze_flag_value):
- modified_datetime = datetime.utcnow().replace(tzinfo=pytz.UTC) - timedelta(days=1) # lint-amnesty, pylint: disable=unused-variable
+ modified_datetime = datetime.utcnow().replace(tzinfo=pytz.UTC) - timedelta(days=1) # lint-amnesty, pylint: disable=unused-variable # noqa: F841
with patch('lms.djangoapps.grades.tasks._has_db_updated_with_new_score') as mock_has_db_updated:
result = recalculate_subsection_grade_v3.apply_async(kwargs=self.recalculate_subsection_grade_kwargs)
self._assert_for_freeze_grade_flag(
diff --git a/lms/djangoapps/grades/tests/test_transformer.py b/lms/djangoapps/grades/tests/test_transformer.py
index b1ddde8e5263..b02c23b2dfef 100644
--- a/lms/djangoapps/grades/tests/test_transformer.py
+++ b/lms/djangoapps/grades/tests/test_transformer.py
@@ -208,7 +208,7 @@ def test_collect_containing_subsection(self):
}
blocks = self.build_complicated_hypothetical_course()
block_structure = get_course_blocks(self.student, blocks['course'].location, self.transformers)
- for block_ref, expected_subsections in expected_subsections.items():
+ for block_ref, expected_subsections in expected_subsections.items(): # noqa: B020
actual_subsections = block_structure.get_transformer_block_field(
blocks[block_ref].location,
self.TRANSFORMER_CLASS_TO_TEST,
@@ -458,7 +458,7 @@ def test_modulestore_performance(self, store_type, max_mongo_calls, min_mongo_ca
- '''.format(number=problem_number),
+ '''.format(number=problem_number), # noqa: UP032
}
)
with self.store.default_store(store_type):
diff --git a/lms/djangoapps/instructor/access.py b/lms/djangoapps/instructor/access.py
index a5d25769ca10..08f818aa4d19 100644
--- a/lms/djangoapps/instructor/access.py
+++ b/lms/djangoapps/instructor/access.py
@@ -77,7 +77,7 @@ def _change_access(course, user, level, action, send_email=True):
try:
role = ROLES[level](course.id)
except KeyError:
- raise ValueError(f"unrecognized level '{level}'") # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValueError(f"unrecognized level '{level}'") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if action == 'allow':
if level == 'ccx_coach':
diff --git a/lms/djangoapps/instructor/apps.py b/lms/djangoapps/instructor/apps.py
index d22c8b0aa1ad..8512c3e6fa25 100644
--- a/lms/djangoapps/instructor/apps.py
+++ b/lms/djangoapps/instructor/apps.py
@@ -36,7 +36,7 @@ class InstructorConfig(AppConfig):
}
def ready(self):
- from . import handlers # pylint: disable=unused-import,import-outside-toplevel
+ from . import handlers # pylint: disable=unused-import,import-outside-toplevel # noqa: F401
if settings.FEATURES.get('ENABLE_SPECIAL_EXAMS'):
from .services import InstructorService
set_runtime_service('instructor', InstructorService())
diff --git a/lms/djangoapps/instructor/enrollment.py b/lms/djangoapps/instructor/enrollment.py
index cce858aa76de..2e37a696c4f2 100644
--- a/lms/djangoapps/instructor/enrollment.py
+++ b/lms/djangoapps/instructor/enrollment.py
@@ -90,7 +90,7 @@ def __init__(self, course_id, email):
self.mode = mode
def __repr__(self):
- return "{}(user={}, enrollment={}, allowed={}, auto_enroll={})".format(
+ return "{}(user={}, enrollment={}, allowed={}, auto_enroll={})".format( # noqa: UP032
self.__class__.__name__,
bool(self.user),
self.enrollment,
@@ -255,7 +255,7 @@ def send_beta_role_email(action, user, message_params):
`message_params` parameters used while parsing email templates (a `dict`).
"""
if action in ('add', 'remove'):
- message_params['message_type'] = '%s_beta_tester' % action
+ message_params['message_type'] = '%s_beta_tester' % action # noqa: UP031
message_params['email_address'] = user.email
message_params['user_id'] = user.id
message_params['full_name'] = user.profile.name
diff --git a/lms/djangoapps/instructor/services.py b/lms/djangoapps/instructor/services.py
index 2ab542953601..38190c7466dd 100644
--- a/lms/djangoapps/instructor/services.py
+++ b/lms/djangoapps/instructor/services.py
@@ -155,7 +155,7 @@ def get_proctoring_escalation_email(self, course_id):
course = modulestore().get_course(course_key)
if course is None:
raise ObjectDoesNotExist(
- 'Could not find proctoring escalation email for course_id={course_id}.'
+ 'Could not find proctoring escalation email for course_id={course_id}.' # noqa: UP032
' This course does not exist.'.format(course_id=course_id)
)
diff --git a/lms/djangoapps/instructor/settings/production.py b/lms/djangoapps/instructor/settings/production.py
index 86ec1d6d789b..183bd37c9693 100644
--- a/lms/djangoapps/instructor/settings/production.py
+++ b/lms/djangoapps/instructor/settings/production.py
@@ -15,7 +15,7 @@ def plugin_settings(settings):
)
# Backward compatibility for deprecated feature names
if hasattr(settings, 'ENABLE_S3_GRADE_DOWNLOADS'):
- warnings.warn(
+ warnings.warn( # noqa: B028
"'ENABLE_S3_GRADE_DOWNLOADS' is deprecated. Please use 'ENABLE_GRADE_DOWNLOADS' instead",
DeprecationWarning,
)
diff --git a/lms/djangoapps/instructor/tests/test_access.py b/lms/djangoapps/instructor/tests/test_access.py
index 3273bcf6391d..49000db4839d 100644
--- a/lms/djangoapps/instructor/tests/test_access.py
+++ b/lms/djangoapps/instructor/tests/test_access.py
@@ -93,12 +93,12 @@ def test_allow_beta(self):
def test_allow_badlevel(self):
user = UserFactory()
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
allow_access(self.course, user, 'robot-not-a-level')
def test_allow_noneuser(self):
user = None
- with pytest.raises(Exception):
+ with pytest.raises(Exception): # noqa: B017, PT011
allow_access(self.course, user, 'staff')
@@ -135,7 +135,7 @@ def test_revoke_beta(self):
def test_revoke_badrolename(self):
user = UserFactory()
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
revoke_access(self.course, user, 'robot-not-a-level')
@@ -199,5 +199,5 @@ def test_revoke_badrole(self):
def test_bad_mode(self):
user = UserFactory()
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'robot-not-a-mode')
diff --git a/lms/djangoapps/instructor/tests/test_api.py b/lms/djangoapps/instructor/tests/test_api.py
index a6fb9a331d71..869ea0235a1f 100644
--- a/lms/djangoapps/instructor/tests/test_api.py
+++ b/lms/djangoapps/instructor/tests/test_api.py
@@ -1288,14 +1288,14 @@ def test_enroll_with_email_not_registered(self, protocol):
register_url = f'{protocol}://{self.site_name}/register'
assert text_body.startswith('Dear student,')
- assert 'To finish your registration, please visit {register_url}'.format(
+ assert 'To finish your registration, please visit {register_url}'.format( # noqa: UP032
register_url=register_url,
) in text_body
assert 'Please finish your registration and fill out' in html_body
assert register_url in html_body
for body in [text_body, html_body]:
- assert 'You have been invited to join {course} at edx.org by a member of the course staff.'.format(
+ assert 'You have been invited to join {course} at edx.org by a member of the course staff.'.format( # noqa: UP032 # pylint: disable=line-too-long
course=self.course.display_name
) in body
@@ -1304,7 +1304,7 @@ def test_enroll_with_email_not_registered(self, protocol):
assert 'Once you have registered and activated your account,' in body
- assert '{proto}://{site}{about_path}'.format(
+ assert '{proto}://{site}{about_path}'.format( # noqa: UP032
proto=protocol,
site=self.site_name,
about_path=self.about_path
@@ -1333,11 +1333,11 @@ def test_enroll_email_not_registered_mktgsite(self, protocol):
assert 'Please finish your registration and fill' in html_body
for body in [text_body, html_body]:
- assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format(
+ assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( # noqa: UP032 # pylint: disable=line-too-long
display_name=self.course.display_name
) in body
- assert '{proto}://{site}/register'.format(
+ assert '{proto}://{site}/register'.format( # noqa: UP032
proto=protocol,
site=self.site_name
) in body
@@ -1345,7 +1345,7 @@ def test_enroll_email_not_registered_mktgsite(self, protocol):
assert ('fill out the registration form making sure to use '
'robot-not-an-email-yet@robot.org in the Email field') in body
- assert 'You can then enroll in {display_name}.'.format(
+ assert 'You can then enroll in {display_name}.'.format( # noqa: UP032
display_name=self.course.display_name
) in body
@@ -1370,13 +1370,13 @@ def test_enroll_with_email_not_registered_autoenroll(self, protocol):
text_body = mail.outbox[0].body
html_body = mail.outbox[0].alternatives[0][0]
- register_url = '{proto}://{site}/register'.format(
+ register_url = '{proto}://{site}/register'.format( # noqa: UP032
proto=protocol,
site=self.site_name,
)
assert text_body.startswith('Dear student,')
- assert 'To finish your registration, please visit {register_url}'.format(
+ assert 'To finish your registration, please visit {register_url}'.format( # noqa: UP032
register_url=register_url,
) in text_body
assert 'Please finish your registration and fill out the registration' in html_body
@@ -1384,7 +1384,7 @@ def test_enroll_with_email_not_registered_autoenroll(self, protocol):
assert register_url in html_body
for body in [text_body, html_body]:
- assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format(
+ assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( # noqa: UP032 # pylint: disable=line-too-long
display_name=self.course.display_name
) in body
@@ -1392,7 +1392,7 @@ def test_enroll_with_email_not_registered_autoenroll(self, protocol):
'out the registration form making sure to use robot-not-an-email-yet@robot.org '
'in the Email field') in body
- assert ('Once you have registered and activated your account, '
+ assert ('Once you have registered and activated your account, ' # noqa: UP032
'you will see {display_name} listed on your dashboard.').format(
display_name=self.course.display_name
) in body
@@ -1492,7 +1492,7 @@ def test_unenroll_with_email(self):
assert text_body.startswith('Dear Enrolled Student')
for body in [text_body, html_body]:
- assert 'You have been unenrolled from {display_name} at edx.org by a member of the course staff.'.format(
+ assert 'You have been unenrolled from {display_name} at edx.org by a member of the course staff.'.format( # noqa: UP032 # pylint: disable=line-too-long
display_name=self.course.display_name,
) in body
@@ -1545,7 +1545,7 @@ def test_unenroll_with_email_allowed_student(self):
assert text_body.startswith('Dear Student,')
for body in [text_body, html_body]:
- assert 'You have been unenrolled from the course {display_name} by a member of the course staff.'.format(
+ assert 'You have been unenrolled from the course {display_name} by a member of the course staff.'.format( # noqa: UP032 # pylint: disable=line-too-long
display_name=self.course.display_name,
) in body
@@ -1569,20 +1569,20 @@ def test_enroll_with_email_not_registered_with_shib(self, protocol, mock_uses_sh
text_body = mail.outbox[0].body
html_body = mail.outbox[0].alternatives[0][0]
- course_url = '{proto}://{site}{about_path}'.format(
+ course_url = '{proto}://{site}{about_path}'.format( # noqa: UP032
proto=protocol,
site=self.site_name,
about_path=self.about_path,
)
assert text_body.startswith('Dear student,')
- assert 'To access this course visit {course_url} and register for this course.'.format(
+ assert 'To access this course visit {course_url} and register for this course.'.format( # noqa: UP032
course_url=course_url,
) in text_body
assert 'To access this course visit it and register:' in html_body
assert course_url in html_body
for body in [text_body, html_body]:
- assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format(
+ assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( # noqa: UP032 # pylint: disable=line-too-long
display_name=self.course.display_name,
) in body
@@ -1607,7 +1607,7 @@ def test_enroll_email_not_registered_shib_mktgsite(self, mock_uses_shib):
assert text_body.startswith('Dear student,')
for body in [text_body, html_body]:
- assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format(
+ assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( # noqa: UP032 # pylint: disable=line-too-long
display_name=self.course.display_name,
) in body
@@ -1632,7 +1632,7 @@ def test_enroll_with_email_not_registered_with_shib_autoenroll(self, protocol, m
text_body = mail.outbox[0].body
html_body = mail.outbox[0].alternatives[0][0]
- course_url = '{proto}://{site}{course_path}'.format(
+ course_url = '{proto}://{site}{course_path}'.format( # noqa: UP032
proto=protocol, site=self.site_name, course_path=self.course_path,
)
@@ -1642,7 +1642,7 @@ def test_enroll_with_email_not_registered_with_shib_autoenroll(self, protocol, m
assert 'To access this course click on the button below and login:' in html_body
for body in [text_body, html_body]:
- assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format(
+ assert 'You have been invited to join {display_name} at edx.org by a member of the course staff.'.format( # noqa: UP032 # pylint: disable=line-too-long
display_name=self.course.display_name,
) in body
@@ -2038,20 +2038,20 @@ def test_add_notenrolled_with_email(self, protocol):
assert f'Visit {self.course.display_name}' in html_body
for body in [text_body, html_body]:
- assert 'You have been invited to be a beta tester for {display_name} at edx.org'.format(
+ assert 'You have been invited to be a beta tester for {display_name} at edx.org'.format( # noqa: UP032
display_name=self.course.display_name,
) in body
assert 'by a member of the course staff.' in body
assert 'enroll in this course and begin the beta test' in body
- assert '{proto}://{site}{about_path}'.format(
+ assert '{proto}://{site}{about_path}'.format( # noqa: UP032
proto=protocol,
site=self.site_name,
about_path=self.about_path,
) in body
- assert 'This email was automatically sent from edx.org to {student_email}'.format(
+ assert 'This email was automatically sent from edx.org to {student_email}'.format( # noqa: UP032
student_email=self.notenrolled_student.email,
) in body
@@ -2090,20 +2090,20 @@ def test_add_notenrolled_with_email_autoenroll(self, protocol):
assert text_body.startswith(f'Dear {student_name}')
for body in [text_body, html_body]:
- assert 'You have been invited to be a beta tester for {display_name} at edx.org'.format(
+ assert 'You have been invited to be a beta tester for {display_name} at edx.org'.format( # noqa: UP032
display_name=self.course.display_name,
) in body
assert 'by a member of the course staff' in body
assert 'To start accessing course materials, please visit' in body
- assert '{proto}://{site}{course_path}'.format(
+ assert '{proto}://{site}{course_path}'.format( # noqa: UP032
proto=protocol,
site=self.site_name,
course_path=self.course_path
)
- assert 'This email was automatically sent from edx.org to {student_email}'.format(
+ assert 'This email was automatically sent from edx.org to {student_email}'.format( # noqa: UP032
student_email=self.notenrolled_student.email,
) in body
@@ -2121,14 +2121,14 @@ def test_add_notenrolled_email_mktgsite(self):
assert text_body.startswith(f'Dear {student_name}')
for body in [text_body, html_body]:
- assert 'You have been invited to be a beta tester for {display_name} at edx.org'.format(
+ assert 'You have been invited to be a beta tester for {display_name} at edx.org'.format( # noqa: UP032
display_name=self.course.display_name,
) in body
assert 'by a member of the course staff.' in body
assert 'Visit edx.org' in body
assert 'enroll in this course and begin the beta test' in body
- assert 'This email was automatically sent from edx.org to {student_email}'.format(
+ assert 'This email was automatically sent from edx.org to {student_email}'.format( # noqa: UP032
student_email=self.notenrolled_student.email,
) in body
@@ -2224,7 +2224,7 @@ def test_remove_with_email(self):
assert text_body.startswith(f'Dear {self.beta_tester.profile.name}')
for body in [text_body, html_body]:
- assert 'You have been removed as a beta tester for {display_name} at edx.org'.format(
+ assert 'You have been removed as a beta tester for {display_name} at edx.org'.format( # noqa: UP032
display_name=self.course.display_name,
) in body
@@ -2233,7 +2233,7 @@ def test_remove_with_email(self):
assert 'Your other courses have not been affected.' in body
- assert 'This email was automatically sent from edx.org to {email_address}'.format(
+ assert 'This email was automatically sent from edx.org to {email_address}'.format( # noqa: UP032
email_address=self.beta_tester.email,
) in body
@@ -3089,10 +3089,10 @@ def test_idv_retirement_student_features_report(self):
# assert that if the integrity signature is enabled, the verification
# status is not included as a query feature
args = mock_task_endpoint.call_args.args
- self.assertEqual(len(args), 3)
+ self.assertEqual(len(args), 3) # noqa: PT009
query_features = args[2]
- self.assertNotIn('verification_status', query_features)
+ self.assertNotIn('verification_status', query_features) # noqa: PT009
def test_get_ora2_responses_success(self):
url = reverse('export_ora2_data', kwargs={'course_id': str(self.course.id)})
@@ -3173,8 +3173,8 @@ def test_get_student_progress_url(self):
}
for key, value in expected_data.items():
- self.assertIn(key, res_json)
- self.assertEqual(res_json[key], value)
+ self.assertIn(key, res_json) # noqa: PT009
+ self.assertEqual(res_json[key], value) # noqa: PT009
def test_get_student_progress_url_response_headers(self):
"""
@@ -3196,8 +3196,8 @@ def test_get_student_progress_url_response_headers(self):
}
for key, value in expected_headers.items():
- self.assertIn(key, response.headers)
- self.assertEqual(response.headers[key], value)
+ self.assertIn(key, response.headers) # noqa: PT009
+ self.assertEqual(response.headers[key], value) # noqa: PT009
def test_get_student_progress_url_from_uname(self):
""" Test that progress_url is in the successful response. """
@@ -3213,8 +3213,8 @@ def test_get_student_progress_url_from_uname(self):
}
for key, value in expected_data.items():
- self.assertIn(key, res_json)
- self.assertEqual(res_json[key], value)
+ self.assertIn(key, res_json) # noqa: PT009
+ self.assertEqual(res_json[key], value) # noqa: PT009
def test_get_student_progress_url_noparams(self):
""" Test that the endpoint 404's without the required query params. """
@@ -3317,7 +3317,7 @@ def test_reset_student_attempts_missingmodule(self):
assert response.status_code == 400
@patch('lms.djangoapps.grades.signals.handlers.PROBLEM_WEIGHTED_SCORE_CHANGED.send')
- def test_reset_student_attempts_delete(self, _mock_signal):
+ def test_reset_student_attempts_delete(self, _mock_signal): # noqa: PT019
""" Test delete single student state. """
url = reverse('reset_student_attempts', kwargs={'course_id': str(self.course.id)})
response = self.client.post(url, {
@@ -3974,8 +3974,8 @@ def test_list_instructor_tasks_running(self, endpoint, act):
assert act.called
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content.decode('utf-8'))['tasks']
- for exp_task, act_task in zip(expected_tasks, actual_tasks):
- self.assertDictEqual(exp_task, act_task)
+ for exp_task, act_task in zip(expected_tasks, actual_tasks): # noqa: B905
+ self.assertDictEqual(exp_task, act_task) # noqa: PT009
assert actual_tasks == expected_tasks
@patch('lms.djangoapps.instructor_task.api.get_instructor_task_history')
@@ -3995,8 +3995,8 @@ def test_list_background_email_tasks(self, act):
assert act.called
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content.decode('utf-8'))['tasks']
- for exp_task, act_task in zip(expected_tasks, actual_tasks):
- self.assertDictEqual(exp_task, act_task)
+ for exp_task, act_task in zip(expected_tasks, actual_tasks): # noqa: B905
+ self.assertDictEqual(exp_task, act_task) # noqa: PT009
assert actual_tasks == expected_tasks
@patch('lms.djangoapps.instructor_task.api.get_instructor_task_history')
@@ -4024,8 +4024,8 @@ def test_list_instructor_tasks_problem(self, endpoint, act):
assert act.called
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content.decode('utf-8'))['tasks']
- for exp_task, act_task in zip(expected_tasks, actual_tasks):
- self.assertDictEqual(exp_task, act_task)
+ for exp_task, act_task in zip(expected_tasks, actual_tasks): # noqa: B905
+ self.assertDictEqual(exp_task, act_task) # noqa: PT009
assert actual_tasks == expected_tasks
@patch('lms.djangoapps.instructor_task.api.get_instructor_task_history')
@@ -4055,8 +4055,8 @@ def test_list_instructor_tasks_problem_student(self, endpoint, act):
assert act.called
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content.decode('utf-8'))['tasks']
- for exp_task, act_task in zip(expected_tasks, actual_tasks):
- self.assertDictEqual(exp_task, act_task)
+ for exp_task, act_task in zip(expected_tasks, actual_tasks): # noqa: B905
+ self.assertDictEqual(exp_task, act_task) # noqa: PT009
assert actual_tasks == expected_tasks
@@ -4129,8 +4129,8 @@ def check_emails_sent(self, num_emails, task_history_request, with_failures=Fals
actual_email_info = json.loads(response.content.decode('utf-8'))['emails']
assert len(actual_email_info) == num_emails
- for exp_email, act_email in zip(expected_email_info, actual_email_info):
- self.assertDictEqual(exp_email, act_email)
+ for exp_email, act_email in zip(expected_email_info, actual_email_info): # noqa: B905
+ self.assertDictEqual(exp_email, act_email) # noqa: PT009
assert expected_email_info == actual_email_info
@@ -4208,7 +4208,7 @@ def test_list_email_with_no_successes(self, task_history_request):
assert len(returned_info_list) == 1
returned_info = returned_info_list[0]
expected_info = email_info.to_dict()
- self.assertDictEqual(expected_info, returned_info)
+ self.assertDictEqual(expected_info, returned_info) # noqa: PT009
class TestInstructorAPIHelpers(TestCase):
@@ -4222,7 +4222,7 @@ def test_split_input_list(self):
lists.append(['Lorem@ipsum.dolor', 'sit@amet.consectetur', 'adipiscing@elit.Aenean', 'convallis@at.lacus',
'ut@lacinia.Sed'])
- for (stng, lst) in zip(strings, lists):
+ for (stng, lst) in zip(strings, lists): # noqa: B905
assert _split_input_list(stng) == lst
def test_split_input_list_unicode(self):
@@ -4240,7 +4240,7 @@ def test_msk_from_problem_urlname(self):
def test_msk_from_problem_urlname_error(self):
args = ('notagoodcourse', 'L2Node1')
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
msk_from_problem_urlname(*args)
@@ -4486,7 +4486,7 @@ def test_show_unit_extensions(self):
'Full Name': self.user1.profile.name,
'Username': self.user1.username}],
'header': ['Username', 'Full Name', 'Extended Due Date'],
- 'title': ('Users with due date extensions for %s' % self.week1.display_name)}
+ 'title': ('Users with due date extensions for %s' % self.week1.display_name)} # noqa: UP031
def test_show_student_extensions(self):
self.test_change_due_date()
@@ -4615,7 +4615,7 @@ def test_change_due_date_v2_invalid_block(self):
"""Test error handling for invalid block location"""
url = reverse('instructor_api_v2:change_due_date', kwargs={'course_id': str(self.course.id)})
# Invalid block location should cause an exception (500 error)
- with self.assertRaises(Exception):
+ with self.assertRaises(Exception): # noqa: B017, PT027
self.client.post(url, json.dumps({
'email_or_username': self.user1.username,
'block_id': 'i4x://invalid/block/location',
@@ -4632,7 +4632,7 @@ def test_change_due_date_v2_invalid_date_format(self):
'due_datetime': 'invalid-date-format'
})
- self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.status_code, 400) # noqa: PT009
def test_change_due_date_v2_missing_fields(self):
"""Test error handling for missing required fields"""
@@ -4643,7 +4643,7 @@ def test_change_due_date_v2_missing_fields(self):
# Missing 'block_id' and 'due_datetime'
})
- self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.status_code, 400) # noqa: PT009
def test_change_due_date_v2_unenrolled_user(self):
"""Test error handling for user not enrolled in course"""
@@ -4656,7 +4656,7 @@ def test_change_due_date_v2_unenrolled_user(self):
'due_datetime': '12/30/2013 00:00'
})
- self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.status_code, 400) # noqa: PT009
def test_change_due_date_v2_json_content_type(self):
"""Test that V2 API works with both JSON and form data"""
@@ -4669,9 +4669,9 @@ def test_change_due_date_v2_json_content_type(self):
})
# The V2 endpoint works with form data and should succeed
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
response_data = json.loads(response.content.decode('utf-8'))
- self.assertIn('Successfully changed due date for learner', response_data['message'])
+ self.assertIn('Successfully changed due date for learner', response_data['message']) # noqa: PT009
class TestDueDateExtensionsDeletedDate(ModuleStoreTestCase, LoginEnrollmentTestCase):
@@ -5072,7 +5072,7 @@ def test_get_student_from_request_data_empty_username(self):
"""
Test that we receive an expected error when no learner's username or email is entered
"""
- with pytest.raises(ValueError) as error:
+ with pytest.raises(ValueError) as error: # noqa: PT011
_get_student_from_request_data({"user": ""})
assert str(error.value) == (
@@ -5085,7 +5085,7 @@ def test_get_student_from_request_data_user_dne(self):
Test to verify an expected error message is returned when attempting to retrieve a learner that does not exist
in the LMS.
"""
- with pytest.raises(ValueError) as error:
+ with pytest.raises(ValueError) as error: # noqa: PT011
_get_student_from_request_data({"user": "Neo"})
assert str(error.value) == "Neo does not exist in the LMS. Please check your spelling and retry."
@@ -5109,7 +5109,7 @@ def test_get_certificate_for_user_no_certificate(self):
Test to verify an expected error message is returned when attempting to retrieve a certificate for a learner
that does not exist yet.
"""
- with pytest.raises(ValueError) as error:
+ with pytest.raises(ValueError) as error: # noqa: PT011
_get_certificate_for_user(self.course.id, self.user)
assert str(error.value) == (
diff --git a/lms/djangoapps/instructor/tests/test_api_v2.py b/lms/djangoapps/instructor/tests/test_api_v2.py
index fb05b9a866c3..f0a8999d3e91 100644
--- a/lms/djangoapps/instructor/tests/test_api_v2.py
+++ b/lms/djangoapps/instructor/tests/test_api_v2.py
@@ -109,53 +109,53 @@ def test_get_course_metadata_as_instructor(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
# Verify basic course information
- self.assertEqual(data['course_id'], str(self.course_key))
- self.assertEqual(data['display_name'], 'Demonstration Course')
- self.assertEqual(data['org'], 'edX')
- self.assertEqual(data['course_number'], 'DemoX')
- self.assertEqual(data['course_run'], 'Demo_Course')
- self.assertEqual(data['pacing'], 'instructor')
+ self.assertEqual(data['course_id'], str(self.course_key)) # noqa: PT009
+ self.assertEqual(data['display_name'], 'Demonstration Course') # noqa: PT009
+ self.assertEqual(data['org'], 'edX') # noqa: PT009
+ self.assertEqual(data['course_number'], 'DemoX') # noqa: PT009
+ self.assertEqual(data['course_run'], 'Demo_Course') # noqa: PT009
+ self.assertEqual(data['pacing'], 'instructor') # noqa: PT009
# Verify enrollment counts structure
- self.assertIn('enrollment_counts', data)
- self.assertIn('total', data['enrollment_counts'])
- self.assertIn('total_enrollment', data)
- self.assertGreaterEqual(data['total_enrollment'], 3)
+ self.assertIn('enrollment_counts', data) # noqa: PT009
+ self.assertIn('total', data['enrollment_counts']) # noqa: PT009
+ self.assertIn('total_enrollment', data) # noqa: PT009
+ self.assertGreaterEqual(data['total_enrollment'], 3) # noqa: PT009
# Verify role-based enrollment counts are present
- self.assertIn('learner_count', data)
- self.assertIn('staff_count', data)
- self.assertEqual(data['total_enrollment'], data['learner_count'] + data['staff_count'])
+ self.assertIn('learner_count', data) # noqa: PT009
+ self.assertIn('staff_count', data) # noqa: PT009
+ self.assertEqual(data['total_enrollment'], data['learner_count'] + data['staff_count']) # noqa: PT009
# Verify permissions structure
- self.assertIn('permissions', data)
+ self.assertIn('permissions', data) # noqa: PT009
permissions_data = data['permissions']
- self.assertIn('admin', permissions_data)
- self.assertIn('instructor', permissions_data)
- self.assertIn('staff', permissions_data)
- self.assertIn('forum_admin', permissions_data)
- self.assertIn('finance_admin', permissions_data)
- self.assertIn('sales_admin', permissions_data)
- self.assertIn('data_researcher', permissions_data)
+ self.assertIn('admin', permissions_data) # noqa: PT009
+ self.assertIn('instructor', permissions_data) # noqa: PT009
+ self.assertIn('staff', permissions_data) # noqa: PT009
+ self.assertIn('forum_admin', permissions_data) # noqa: PT009
+ self.assertIn('finance_admin', permissions_data) # noqa: PT009
+ self.assertIn('sales_admin', permissions_data) # noqa: PT009
+ self.assertIn('data_researcher', permissions_data) # noqa: PT009
# Verify sections structure
- self.assertIn('tabs', data)
- self.assertIsInstance(data['tabs'], list)
+ self.assertIn('tabs', data) # noqa: PT009
+ self.assertIsInstance(data['tabs'], list) # noqa: PT009
# Verify other metadata fields
- self.assertIn('num_sections', data)
- self.assertIn('tabs', data)
- self.assertIn('grade_cutoffs', data)
- self.assertIn('course_errors', data)
- self.assertIn('studio_url', data)
- self.assertIn('disable_buttons', data)
- self.assertIn('has_started', data)
- self.assertIn('has_ended', data)
- self.assertIn('analytics_dashboard_message', data)
+ self.assertIn('num_sections', data) # noqa: PT009
+ self.assertIn('tabs', data) # noqa: PT009
+ self.assertIn('grade_cutoffs', data) # noqa: PT009
+ self.assertIn('course_errors', data) # noqa: PT009
+ self.assertIn('studio_url', data) # noqa: PT009
+ self.assertIn('disable_buttons', data) # noqa: PT009
+ self.assertIn('has_started', data) # noqa: PT009
+ self.assertIn('has_ended', data) # noqa: PT009
+ self.assertIn('analytics_dashboard_message', data) # noqa: PT009
def test_get_course_metadata_as_staff(self):
"""
@@ -164,12 +164,12 @@ def test_get_course_metadata_as_staff(self):
self.client.force_authenticate(user=self.staff)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
- self.assertEqual(data['course_id'], str(self.course_key))
- self.assertIn('permissions', data)
+ self.assertEqual(data['course_id'], str(self.course_key)) # noqa: PT009
+ self.assertIn('permissions', data) # noqa: PT009
# Staff should have staff permission
- self.assertTrue(data['permissions']['staff'])
+ self.assertTrue(data['permissions']['staff']) # noqa: PT009
def test_get_course_metadata_unauthorized(self):
"""
@@ -178,16 +178,16 @@ def test_get_course_metadata_unauthorized(self):
self.client.force_authenticate(user=self.student)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
error_code = "You do not have permission to perform this action."
- self.assertEqual(response.data['developer_message'], error_code)
+ self.assertEqual(response.data['developer_message'], error_code) # noqa: PT009
def test_get_course_metadata_unauthenticated(self):
"""
Test that unauthenticated users cannot access the endpoint.
"""
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_get_course_metadata_invalid_course_id(self):
"""
@@ -195,7 +195,7 @@ def test_get_course_metadata_invalid_course_id(self):
"""
self.client.force_authenticate(user=self.instructor)
invalid_course_id = 'invalid-course-id'
- with self.assertRaises(NoReverseMatch):
+ with self.assertRaises(NoReverseMatch): # noqa: PT027
self.client.get(self._get_url(course_id=invalid_course_id))
def test_get_course_metadata_nonexistent_course(self):
@@ -206,9 +206,9 @@ def test_get_course_metadata_nonexistent_course(self):
nonexistent_course_id = 'course-v1:edX+NonExistent+2024'
response = self.client.get(self._get_url(course_id=nonexistent_course_id))
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
error_code = "Course not found: course-v1:edX+NonExistent+2024."
- self.assertEqual(response.data['developer_message'], error_code)
+ self.assertEqual(response.data['developer_message'], error_code) # noqa: PT009
def test_instructor_permissions_reflected(self):
"""
@@ -217,11 +217,11 @@ def test_instructor_permissions_reflected(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
permissions_data = response.data['permissions']
# Instructor should have instructor permission
- self.assertTrue(permissions_data['instructor'])
+ self.assertTrue(permissions_data['instructor']) # noqa: PT009
def test_learner_and_staff_counts(self):
"""
@@ -230,7 +230,7 @@ def test_learner_and_staff_counts(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
total = data['total_enrollment']
@@ -238,12 +238,12 @@ def test_learner_and_staff_counts(self):
staff_count = data['staff_count']
# Counts must be non-negative and sum to total
- self.assertGreaterEqual(learner_count, 0)
- self.assertGreaterEqual(staff_count, 0)
- self.assertEqual(total, learner_count + staff_count)
+ self.assertGreaterEqual(learner_count, 0) # noqa: PT009
+ self.assertGreaterEqual(staff_count, 0) # noqa: PT009
+ self.assertEqual(total, learner_count + staff_count) # noqa: PT009
# The student enrolled in setUp is not staff, so learner_count >= 1
- self.assertGreaterEqual(learner_count, 1)
+ self.assertGreaterEqual(learner_count, 1) # noqa: PT009
def test_enrollment_counts_by_mode(self):
"""
@@ -257,24 +257,24 @@ def test_enrollment_counts_by_mode(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
enrollment_counts = response.data['enrollment_counts']
# All configured modes should be present
- self.assertIn('audit', enrollment_counts)
- self.assertIn('verified', enrollment_counts)
- self.assertIn('honor', enrollment_counts)
- self.assertIn('professional', enrollment_counts)
- self.assertIn('total', enrollment_counts)
+ self.assertIn('audit', enrollment_counts) # noqa: PT009
+ self.assertIn('verified', enrollment_counts) # noqa: PT009
+ self.assertIn('honor', enrollment_counts) # noqa: PT009
+ self.assertIn('professional', enrollment_counts) # noqa: PT009
+ self.assertIn('total', enrollment_counts) # noqa: PT009
# professional has no enrollments but should still appear with 0
- self.assertEqual(enrollment_counts['professional'], 0)
+ self.assertEqual(enrollment_counts['professional'], 0) # noqa: PT009
# Modes with enrollments should have correct counts
- self.assertGreaterEqual(enrollment_counts['audit'], 1)
- self.assertGreaterEqual(enrollment_counts['verified'], 1)
- self.assertGreaterEqual(enrollment_counts['honor'], 1)
- self.assertGreaterEqual(enrollment_counts['total'], 3)
+ self.assertGreaterEqual(enrollment_counts['audit'], 1) # noqa: PT009
+ self.assertGreaterEqual(enrollment_counts['verified'], 1) # noqa: PT009
+ self.assertGreaterEqual(enrollment_counts['honor'], 1) # noqa: PT009
+ self.assertGreaterEqual(enrollment_counts['total'], 3) # noqa: PT009
def test_enrollment_counts_excludes_unconfigured_modes(self):
"""
@@ -288,23 +288,23 @@ def test_enrollment_counts_excludes_unconfigured_modes(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
enrollment_counts = response.data['enrollment_counts']
# Only configured modes should appear
- self.assertIn('audit', enrollment_counts)
- self.assertIn('honor', enrollment_counts)
- self.assertIn('total', enrollment_counts)
+ self.assertIn('audit', enrollment_counts) # noqa: PT009
+ self.assertIn('honor', enrollment_counts) # noqa: PT009
+ self.assertIn('total', enrollment_counts) # noqa: PT009
# verified is not configured, so it should not appear
# (even though there are verified enrollments from setUp)
- self.assertNotIn('verified', enrollment_counts)
+ self.assertNotIn('verified', enrollment_counts) # noqa: PT009
def _get_tabs_from_response(self, user, course_id=None):
"""Helper to get tabs from API response."""
self.client.force_authenticate(user=user)
response = self.client.get(self._get_url(course_id))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
return response.data.get('tabs', [])
def _test_staff_tabs(self, tabs):
@@ -313,7 +313,7 @@ def _test_staff_tabs(self, tabs):
# Staff should see these basic tabs
expected_basic_tabs = ['course_info', 'enrollments', 'course_team', 'grading', 'cohorts']
- self.assertListEqual(tab_ids, expected_basic_tabs)
+ self.assertListEqual(tab_ids, expected_basic_tabs) # noqa: PT009
def test_staff_sees_basic_tabs(self):
"""
@@ -335,7 +335,7 @@ def test_researcher_sees_all_basic_tabs(self):
"""
tabs = self._get_tabs_from_response(self.data_researcher)
tab_ids = [tab['tab_id'] for tab in tabs]
- self.assertEqual(['data_downloads'], tab_ids)
+ self.assertEqual(['data_downloads'], tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.is_enabled_for_course')
def test_date_extensions_tab_when_enabled(self, mock_is_enabled):
@@ -347,7 +347,7 @@ def test_date_extensions_tab_when_enabled(self, mock_is_enabled):
tabs = self._get_tabs_from_response(self.instructor)
tab_ids = [tab['tab_id'] for tab in tabs]
- self.assertIn('date_extensions', tab_ids)
+ self.assertIn('date_extensions', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.modulestore')
def test_open_responses_tab_with_openassessment_blocks(self, mock_modulestore):
@@ -365,7 +365,7 @@ def test_open_responses_tab_with_openassessment_blocks(self, mock_modulestore):
tabs = self._get_tabs_from_response(self.staff)
tab_ids = [tab['tab_id'] for tab in tabs]
- self.assertIn('open_responses', tab_ids)
+ self.assertIn('open_responses', tab_ids) # noqa: PT009
@patch('django.conf.settings.FEATURES', {'ENABLE_SPECIAL_EXAMS': True, 'MAX_ENROLLMENT_INSTR_BUTTONS': 200})
def test_special_exams_tab_with_proctored_exams_enabled(self):
@@ -375,7 +375,7 @@ def test_special_exams_tab_with_proctored_exams_enabled(self):
tabs = self._get_tabs_from_response(self.instructor)
tab_ids = [tab['tab_id'] for tab in tabs]
- self.assertIn('special_exams', tab_ids)
+ self.assertIn('special_exams', tab_ids) # noqa: PT009
@patch('django.conf.settings.FEATURES', {'ENABLE_SPECIAL_EXAMS': True, 'MAX_ENROLLMENT_INSTR_BUTTONS': 200})
def test_special_exams_tab_with_timed_exams_enabled(self):
@@ -392,7 +392,7 @@ def test_special_exams_tab_with_timed_exams_enabled(self):
CourseInstructorRole(timed_course.id).add_users(self.instructor)
tabs = self._get_tabs_from_response(self.instructor, course_id=timed_course.id)
tab_ids = [tab['tab_id'] for tab in tabs]
- self.assertIn('special_exams', tab_ids)
+ self.assertIn('special_exams', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.CertificateGenerationConfiguration.current')
@patch('django.conf.settings.FEATURES', {'ENABLE_CERTIFICATES_INSTRUCTOR_MANAGE': True,
@@ -407,7 +407,7 @@ def test_certificates_tab_for_instructor_when_enabled(self, mock_cert_config):
tabs = self._get_tabs_from_response(self.instructor)
tab_ids = [tab['tab_id'] for tab in tabs]
- self.assertIn('certificates', tab_ids)
+ self.assertIn('certificates', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.CertificateGenerationConfiguration.current')
def test_certificates_tab_for_admin_visible(self, mock_cert_config):
@@ -420,7 +420,7 @@ def test_certificates_tab_for_admin_visible(self, mock_cert_config):
tabs = self._get_tabs_from_response(self.admin)
tab_ids = [tab['tab_id'] for tab in tabs]
- self.assertIn('certificates', tab_ids)
+ self.assertIn('certificates', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.is_bulk_email_feature_enabled')
@ddt.data('staff', 'instructor', 'admin')
@@ -434,7 +434,7 @@ def test_bulk_email_tab_when_enabled(self, user_attribute, mock_bulk_email_enabl
tabs = self._get_tabs_from_response(user)
tab_ids = [tab['tab_id'] for tab in tabs]
- self.assertIn('bulk_email', tab_ids)
+ self.assertIn('bulk_email', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.is_bulk_email_feature_enabled')
@ddt.data(
@@ -455,7 +455,7 @@ def test_bulk_email_tab_not_visible(self, feature_enabled, user_attribute, mock_
tabs = self._get_tabs_from_response(user)
tab_ids = [tab['tab_id'] for tab in tabs]
- self.assertNotIn('bulk_email', tab_ids)
+ self.assertNotIn('bulk_email', tab_ids) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.is_bulk_email_feature_enabled')
@override_settings(COMMUNICATIONS_MICROFRONTEND_URL='http://localhost:1984')
@@ -469,9 +469,9 @@ def test_bulk_email_tab_url_uses_communications_mfe(self, mock_bulk_email_enable
tabs = self._get_tabs_from_response(self.staff)
bulk_email_tab = next((tab for tab in tabs if tab['tab_id'] == 'bulk_email'), None)
- self.assertIsNotNone(bulk_email_tab)
+ self.assertIsNotNone(bulk_email_tab) # noqa: PT009
expected_url = f'http://localhost:1984/courses/{self.course.id}/bulk_email'
- self.assertEqual(bulk_email_tab['url'], expected_url)
+ self.assertEqual(bulk_email_tab['url'], expected_url) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.is_bulk_email_feature_enabled')
@override_settings(COMMUNICATIONS_MICROFRONTEND_URL=None)
@@ -485,12 +485,12 @@ def test_bulk_email_tab_logs_warning_when_communications_mfe_url_not_set(self, m
with self.assertLogs('lms.djangoapps.instructor.views.serializers_v2', level='WARNING') as cm:
tabs = self._get_tabs_from_response(self.staff)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
any('COMMUNICATIONS_MICROFRONTEND_URL is not configured' in msg for msg in cm.output)
)
bulk_email_tab = next((tab for tab in tabs if tab['tab_id'] == 'bulk_email'), None)
- self.assertIsNotNone(bulk_email_tab)
- self.assertFalse(
+ self.assertIsNotNone(bulk_email_tab) # noqa: PT009
+ self.assertFalse( # noqa: PT009
bulk_email_tab['url'].startswith('None'),
f"Tab URL should not start with 'None': {bulk_email_tab['url']}"
)
@@ -502,8 +502,8 @@ def test_tabs_have_sort_order(self):
tabs = self._get_tabs_from_response(self.staff)
for tab in tabs:
- self.assertIn('sort_order', tab)
- self.assertIsInstance(tab['sort_order'], int)
+ self.assertIn('sort_order', tab) # noqa: PT009
+ self.assertIsInstance(tab['sort_order'], int) # noqa: PT009
def test_disable_buttons_false_for_small_course(self):
"""
@@ -512,9 +512,9 @@ def test_disable_buttons_false_for_small_course(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
# With only 3 enrollments, buttons should not be disabled
- self.assertFalse(response.data['disable_buttons'])
+ self.assertFalse(response.data['disable_buttons']) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.modulestore')
def test_course_errors_from_modulestore(self, mock_modulestore):
@@ -529,9 +529,9 @@ def test_course_errors_from_modulestore(self, mock_modulestore):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('course_errors', response.data)
- self.assertIsInstance(response.data['course_errors'], list)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('course_errors', response.data) # noqa: PT009
+ self.assertIsInstance(response.data['course_errors'], list) # noqa: PT009
@patch('lms.djangoapps.instructor.views.serializers_v2.settings.INSTRUCTOR_MICROFRONTEND_URL', None)
def test_tabs_log_warning_when_mfe_url_not_set(self):
@@ -541,13 +541,13 @@ def test_tabs_log_warning_when_mfe_url_not_set(self):
with self.assertLogs('lms.djangoapps.instructor.views.serializers_v2', level='WARNING') as cm:
tabs = self._get_tabs_from_response(self.staff)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
any('INSTRUCTOR_MICROFRONTEND_URL is not configured' in msg for msg in cm.output)
)
# Tab URLs should use empty string as base, not "None"
for tab in tabs:
- self.assertFalse(tab['url'].startswith('None'), f"Tab URL should not start with 'None': {tab['url']}")
- self.assertTrue(
+ self.assertFalse(tab['url'].startswith('None'), f"Tab URL should not start with 'None': {tab['url']}") # noqa: PT009 # pylint: disable=line-too-long
+ self.assertTrue( # noqa: PT009
tab['url'].startswith('/instructor/'),
f"Tab URL should start with '/instructor/': {tab['url']}"
)
@@ -569,8 +569,8 @@ def test_pacing_self_for_self_paced_course(self):
url = reverse('instructor_api_v2:course_metadata', kwargs={'course_id': str(self_paced_course.id)})
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['pacing'], 'self')
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['pacing'], 'self') # noqa: PT009
class BuildTabUrlTest(SimpleTestCase):
@@ -588,19 +588,19 @@ def _build(self, setting_name, *parts):
def test_joins_base_and_path_parts(self):
"""Parts are joined with '/' separators."""
result = self._build('INSTRUCTOR_MICROFRONTEND_URL', 'instructor', 'course-v1:edX+DemoX+Demo', 'grading')
- self.assertEqual(result, 'http://localhost:2003/instructor/course-v1:edX+DemoX+Demo/grading')
+ self.assertEqual(result, 'http://localhost:2003/instructor/course-v1:edX+DemoX+Demo/grading') # noqa: PT009
@override_settings(INSTRUCTOR_MICROFRONTEND_URL='http://localhost:2003/')
def test_strips_trailing_slash_from_base(self):
"""A trailing slash on the base URL does not produce a double slash."""
result = self._build('INSTRUCTOR_MICROFRONTEND_URL', 'instructor', 'course-v1:edX+DemoX+Demo', 'grading')
- self.assertEqual(result, 'http://localhost:2003/instructor/course-v1:edX+DemoX+Demo/grading')
+ self.assertEqual(result, 'http://localhost:2003/instructor/course-v1:edX+DemoX+Demo/grading') # noqa: PT009
@override_settings(INSTRUCTOR_MICROFRONTEND_URL='http://localhost:2003')
def test_strips_slashes_from_path_parts(self):
"""Leading and trailing slashes on path parts are stripped before joining."""
result = self._build('INSTRUCTOR_MICROFRONTEND_URL', '/instructor/', '/course-v1:edX+DemoX+Demo/', '/grading/')
- self.assertEqual(result, 'http://localhost:2003/instructor/course-v1:edX+DemoX+Demo/grading')
+ self.assertEqual(result, 'http://localhost:2003/instructor/course-v1:edX+DemoX+Demo/grading') # noqa: PT009
@override_settings(COMMUNICATIONS_MICROFRONTEND_URL=None)
def test_logs_warning_and_returns_relative_url_when_setting_is_none(self):
@@ -610,23 +610,23 @@ def test_logs_warning_and_returns_relative_url_when_setting_is_none(self):
'COMMUNICATIONS_MICROFRONTEND_URL', 'courses', 'course-v1:edX+DemoX+Demo', 'bulk_email'
)
- self.assertTrue(any('COMMUNICATIONS_MICROFRONTEND_URL is not configured' in msg for msg in cm.output))
- self.assertFalse(result.startswith('None'))
- self.assertEqual(result, '/courses/course-v1:edX+DemoX+Demo/bulk_email')
+ self.assertTrue(any('COMMUNICATIONS_MICROFRONTEND_URL is not configured' in msg for msg in cm.output)) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertFalse(result.startswith('None')) # noqa: PT009
+ self.assertEqual(result, '/courses/course-v1:edX+DemoX+Demo/bulk_email') # noqa: PT009
def test_logs_warning_when_setting_does_not_exist(self):
"""When the setting name is not defined at all, behavior matches the None case."""
with self.assertLogs('lms.djangoapps.instructor.views.serializers_v2', level='WARNING') as cm:
result = self._build('NONEXISTENT_MFE_URL', 'instructor', 'course-v1:edX+DemoX+Demo', 'grading')
- self.assertTrue(any('NONEXISTENT_MFE_URL is not configured' in msg for msg in cm.output))
- self.assertEqual(result, '/instructor/course-v1:edX+DemoX+Demo/grading')
+ self.assertTrue(any('NONEXISTENT_MFE_URL is not configured' in msg for msg in cm.output)) # noqa: PT009
+ self.assertEqual(result, '/instructor/course-v1:edX+DemoX+Demo/grading') # noqa: PT009
@override_settings(COMMUNICATIONS_MICROFRONTEND_URL='http://localhost:1984/communications/')
def test_base_with_subpath_and_trailing_slash(self):
"""Base URL with a subpath and trailing slash is joined cleanly."""
result = self._build('COMMUNICATIONS_MICROFRONTEND_URL', 'courses', 'course-v1:edX+DemoX+Demo', 'bulk_email')
- self.assertEqual(result, 'http://localhost:1984/communications/courses/course-v1:edX+DemoX+Demo/bulk_email')
+ self.assertEqual(result, 'http://localhost:1984/communications/courses/course-v1:edX+DemoX+Demo/bulk_email') # noqa: PT009 # pylint: disable=line-too-long
@ddt.ddt
@@ -699,9 +699,9 @@ def test_get_instructor_tasks_as_instructor(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('tasks', response.data)
- self.assertIsInstance(response.data['tasks'], list)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('tasks', response.data) # noqa: PT009
+ self.assertIsInstance(response.data['tasks'], list) # noqa: PT009
def test_get_instructor_tasks_unauthorized(self):
"""
@@ -710,15 +710,15 @@ def test_get_instructor_tasks_unauthorized(self):
self.client.force_authenticate(user=self.student)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- self.assertIn('You do not have permission to perform this action.', response.data['developer_message'])
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
+ self.assertIn('You do not have permission to perform this action.', response.data['developer_message']) # noqa: PT009 # pylint: disable=line-too-long
def test_get_instructor_tasks_unauthenticated(self):
"""
Test that unauthenticated users cannot access the endpoint.
"""
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_get_instructor_tasks_nonexistent_course(self):
"""
@@ -728,8 +728,8 @@ def test_get_instructor_tasks_nonexistent_course(self):
nonexistent_course_id = 'course-v1:edX+NonExistent+2024'
response = self.client.get(self._get_url(course_id=nonexistent_course_id))
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- self.assertEqual('Course not found: course-v1:edX+NonExistent+2024.', response.data['developer_message'])
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
+ self.assertEqual('Course not found: course-v1:edX+NonExistent+2024.', response.data['developer_message']) # noqa: PT009 # pylint: disable=line-too-long
def test_filter_by_problem_location(self):
"""
@@ -743,8 +743,8 @@ def test_filter_by_problem_location(self):
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('tasks', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('tasks', response.data) # noqa: PT009
def test_filter_requires_problem_location_with_student(self):
"""
@@ -759,9 +759,9 @@ def test_filter_requires_problem_location_with_student(self):
url = f"{self._get_url()}?{urlencode(params)}"
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn('error', response.data)
- self.assertIn('problem_location_str', response.data['error'])
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertIn('error', response.data) # noqa: PT009
+ self.assertIn('problem_location_str', response.data['error']) # noqa: PT009
def test_filter_by_problem_and_student(self):
"""
@@ -797,8 +797,8 @@ def test_filter_by_problem_and_student(self):
}
url = f"{self._get_url()}?{urlencode(params)}"
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('tasks', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('tasks', response.data) # noqa: PT009
def test_invalid_student_identifier(self):
"""
@@ -812,8 +812,8 @@ def test_invalid_student_identifier(self):
url = f"{self._get_url()}?{urlencode(params)}"
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn('error', response.data)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertIn('error', response.data) # noqa: PT009
def test_invalid_problem_location(self):
"""
@@ -824,9 +824,9 @@ def test_invalid_problem_location(self):
url = f"{self._get_url()}?problem_location_str=invalid-location"
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn('error', response.data)
- self.assertIn('Invalid problem location', response.data['error'])
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertIn('error', response.data) # noqa: PT009
+ self.assertIn('Invalid problem location', response.data['error']) # noqa: PT009
@ddt.data(
('grade_problems', 'PROGRESS'),
@@ -851,12 +851,12 @@ def test_various_task_types_and_states(self, task_type, task_state):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('tasks', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('tasks', response.data) # noqa: PT009
if task_state == 'PROGRESS':
- self.assertEqual(task_id, response.data['tasks'][0]['task_id'])
- self.assertEqual(task_type, response.data['tasks'][0]['task_type'])
- self.assertEqual(task_state, response.data['tasks'][0]['task_state'])
+ self.assertEqual(task_id, response.data['tasks'][0]['task_id']) # noqa: PT009
+ self.assertEqual(task_type, response.data['tasks'][0]['task_type']) # noqa: PT009
+ self.assertEqual(task_state, response.data['tasks'][0]['task_state']) # noqa: PT009
def test_task_data_structure(self):
"""
@@ -875,15 +875,15 @@ def test_task_data_structure(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
tasks = response.data['tasks']
if tasks:
task_data = tasks[0]
# Verify key fields are present (these come from extract_task_features)
- self.assertIn('task_type', task_data)
- self.assertIn('task_state', task_data)
- self.assertIn('created', task_data)
+ self.assertIn('task_type', task_data) # noqa: PT009
+ self.assertIn('task_state', task_data) # noqa: PT009
+ self.assertIn('created', task_data) # noqa: PT009
@ddt.ddt
@@ -953,19 +953,19 @@ def test_get_graded_subsections_success(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
response_data = json.loads(response.content)
- self.assertIn('items', response_data)
- self.assertIsInstance(response_data['items'], list)
+ self.assertIn('items', response_data) # noqa: PT009
+ self.assertIsInstance(response_data['items'], list) # noqa: PT009
# Should include subsection with due date
items = response_data['items']
if items: # Only test if there are items with due dates
item = items[0]
- self.assertIn('display_name', item)
- self.assertIn('subsection_id', item)
- self.assertIsInstance(item['display_name'], str)
- self.assertIsInstance(item['subsection_id'], str)
+ self.assertIn('display_name', item) # noqa: PT009
+ self.assertIn('subsection_id', item) # noqa: PT009
+ self.assertIsInstance(item['display_name'], str) # noqa: PT009
+ self.assertIsInstance(item['subsection_id'], str) # noqa: PT009
def test_get_graded_subsections_as_staff(self):
"""
@@ -974,9 +974,9 @@ def test_get_graded_subsections_as_staff(self):
self.client.force_authenticate(user=self.staff)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
response_data = json.loads(response.content)
- self.assertIn('items', response_data)
+ self.assertIn('items', response_data) # noqa: PT009
def test_get_graded_subsections_nonexistent_course(self):
"""
@@ -987,7 +987,7 @@ def test_get_graded_subsections_nonexistent_course(self):
nonexistent_url = self._get_url(nonexistent_course_id)
response = self.client.get(nonexistent_url)
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
def test_get_graded_subsections_empty_course(self):
"""
@@ -1006,10 +1006,10 @@ def test_get_graded_subsections_empty_course(self):
self.client.force_authenticate(user=empty_instructor)
response = self.client.get(self._get_url(str(empty_course.id)))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
response_data = json.loads(response.content)
# An empty course should have no graded subsections with due dates
- self.assertEqual(response_data['items'], [])
+ self.assertEqual(response_data['items'], []) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.get_units_with_due_date')
def test_get_graded_subsections_with_mocked_units(self, mock_get_units):
@@ -1026,12 +1026,12 @@ def test_get_graded_subsections_with_mocked_units(self, mock_get_units):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
response_data = json.loads(response.content)
items = response_data['items']
- self.assertEqual(len(items), 1)
- self.assertEqual(items[0]['display_name'], 'Mocked Assignment')
- self.assertEqual(items[0]['subsection_id'], 'block-v1:Test+Course+2024+type@sequential+block@mock')
+ self.assertEqual(len(items), 1) # noqa: PT009
+ self.assertEqual(items[0]['display_name'], 'Mocked Assignment') # noqa: PT009
+ self.assertEqual(items[0]['subsection_id'], 'block-v1:Test+Course+2024+type@sequential+block@mock') # noqa: PT009 # pylint: disable=line-too-long
@patch('lms.djangoapps.instructor.views.api_v2.title_or_url')
@patch('lms.djangoapps.instructor.views.api_v2.get_units_with_due_date')
@@ -1049,12 +1049,12 @@ def test_get_graded_subsections_title_fallback(self, mock_get_units, mock_title_
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
response_data = json.loads(response.content)
items = response_data['items']
- self.assertEqual(len(items), 1)
- self.assertEqual(items[0]['display_name'], 'block-v1:Test+Course+2024+type@sequential+block@fallback')
- self.assertEqual(items[0]['subsection_id'], 'block-v1:Test+Course+2024+type@sequential+block@fallback')
+ self.assertEqual(len(items), 1) # noqa: PT009
+ self.assertEqual(items[0]['display_name'], 'block-v1:Test+Course+2024+type@sequential+block@fallback') # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(items[0]['subsection_id'], 'block-v1:Test+Course+2024+type@sequential+block@fallback') # noqa: PT009 # pylint: disable=line-too-long
def test_get_graded_subsections_response_format(self):
"""
@@ -1063,19 +1063,19 @@ def test_get_graded_subsections_response_format(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
response_data = json.loads(response.content)
# Verify top-level structure
- self.assertIn('items', response_data)
- self.assertIsInstance(response_data['items'], list)
+ self.assertIn('items', response_data) # noqa: PT009
+ self.assertIsInstance(response_data['items'], list) # noqa: PT009
# Verify each item has required fields
for item in response_data['items']:
- self.assertIn('display_name', item)
- self.assertIn('subsection_id', item)
- self.assertIsInstance(item['display_name'], str)
- self.assertIsInstance(item['subsection_id'], str)
+ self.assertIn('display_name', item) # noqa: PT009
+ self.assertIn('subsection_id', item) # noqa: PT009
+ self.assertIsInstance(item['display_name'], str) # noqa: PT009
+ self.assertIsInstance(item['subsection_id'], str) # noqa: PT009
class ORABaseViewsTest(SharedModuleStoreTestCase, APITestCase):
@@ -1477,7 +1477,7 @@ def test_get_unit_extensions_as_staff(self):
self.client.force_authenticate(user=self.staff)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_get_unit_extensions_unauthorized(self):
"""
@@ -1486,14 +1486,14 @@ def test_get_unit_extensions_unauthorized(self):
self.client.force_authenticate(user=self.student1)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_get_unit_extensions_unauthenticated(self):
"""
Test that unauthenticated users cannot access the endpoint.
"""
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_get_unit_extensions_nonexistent_course(self):
"""
@@ -1503,7 +1503,7 @@ def test_get_unit_extensions_nonexistent_course(self):
nonexistent_course_id = 'course-v1:edX+NonExistent+2024'
response = self.client.get(self._get_url(course_id=nonexistent_course_id))
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
def test_get_unit_extensions(self):
"""
@@ -1536,29 +1536,29 @@ def test_get_unit_extensions(self):
self.client.force_authenticate(user=self.staff)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
results = data['results']
- self.assertEqual(len(results), 2)
+ self.assertEqual(len(results), 2) # noqa: PT009
# Student 1's extension
extension = results[0]
- self.assertEqual(extension['username'], 'student1')
- self.assertIn('Robot', extension['full_name'])
- self.assertEqual(extension['email'], 'student1@example.com')
- self.assertEqual(extension['unit_title'], 'Homework 1') # Should be the top-level unit
- self.assertEqual(extension['unit_location'], 'block-v1:edX+TestX+Test_Course+type@sequential+block@Homework_1')
- self.assertEqual(extension['extended_due_date'], '2025-10-31T23:59:59Z')
+ self.assertEqual(extension['username'], 'student1') # noqa: PT009
+ self.assertIn('Robot', extension['full_name']) # noqa: PT009
+ self.assertEqual(extension['email'], 'student1@example.com') # noqa: PT009
+ self.assertEqual(extension['unit_title'], 'Homework 1') # Should be the top-level unit # noqa: PT009
+ self.assertEqual(extension['unit_location'], 'block-v1:edX+TestX+Test_Course+type@sequential+block@Homework_1') # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(extension['extended_due_date'], '2025-10-31T23:59:59Z') # noqa: PT009
# Student 2's extension
extension = results[1]
- self.assertEqual(extension['username'], 'student2')
- self.assertIn('Robot', extension['full_name'])
- self.assertEqual(extension['email'], 'student2@example.com')
- self.assertEqual(extension['unit_title'], 'Homework 1') # Should be the top-level unit
- self.assertEqual(extension['unit_location'], 'block-v1:edX+TestX+Test_Course+type@sequential+block@Homework_1')
- self.assertEqual(extension['extended_due_date'], '2025-12-31T23:59:59Z')
+ self.assertEqual(extension['username'], 'student2') # noqa: PT009
+ self.assertIn('Robot', extension['full_name']) # noqa: PT009
+ self.assertEqual(extension['email'], 'student2@example.com') # noqa: PT009
+ self.assertEqual(extension['unit_title'], 'Homework 1') # Should be the top-level unit # noqa: PT009
+ self.assertEqual(extension['unit_location'], 'block-v1:edX+TestX+Test_Course+type@sequential+block@Homework_1') # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(extension['extended_due_date'], '2025-12-31T23:59:59Z') # noqa: PT009
@ddt.data(
('student1', True),
@@ -1597,17 +1597,17 @@ def test_filter_by_email_or_username(self, filter_value, is_username, mock_get_u
params = {'email_or_username': filter_value}
response = self.client.get(self._get_url(), params)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
results = data['results']
- self.assertEqual(len(results), 1)
+ self.assertEqual(len(results), 1) # noqa: PT009
# Check that the filter value is in the appropriate field
if is_username:
- self.assertIn(filter_value.lower(), results[0]['username'].lower())
+ self.assertIn(filter_value.lower(), results[0]['username'].lower()) # noqa: PT009
else:
- self.assertIn(filter_value.lower(), results[0]['email'].lower())
+ self.assertIn(filter_value.lower(), results[0]['email'].lower()) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.edx_when_api.get_overrides_for_block')
@patch('lms.djangoapps.instructor.views.api_v2.find_unit')
@@ -1635,21 +1635,21 @@ def test_filter_by_block_id(self, mock_get_units, mock_find_unit, mock_get_overr
params = {'block_id': 'block-v1:Test+Course+2024+type@sequential+block@hw1'}
response = self.client.get(self._get_url(), params)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
results = data['results']
- self.assertEqual(data['count'], 1)
- self.assertEqual(len(results), 1)
+ self.assertEqual(data['count'], 1) # noqa: PT009
+ self.assertEqual(len(results), 1) # noqa: PT009
data = results[0]
- self.assertEqual(data['username'], 'student1')
- self.assertEqual(data['full_name'], 'John Doe')
- self.assertEqual(data['email'], 'john@example.com')
- self.assertEqual(data['unit_title'], 'Homework 1')
- self.assertEqual(data['unit_location'], 'block-v1:Test+Course+2024+type@sequential+block@hw1')
- self.assertEqual(data['extended_due_date'], extended_date.strftime("%Y-%m-%dT%H:%M:%SZ"))
+ self.assertEqual(data['username'], 'student1') # noqa: PT009
+ self.assertEqual(data['full_name'], 'John Doe') # noqa: PT009
+ self.assertEqual(data['email'], 'john@example.com') # noqa: PT009
+ self.assertEqual(data['unit_title'], 'Homework 1') # noqa: PT009
+ self.assertEqual(data['unit_location'], 'block-v1:Test+Course+2024+type@sequential+block@hw1') # noqa: PT009
+ self.assertEqual(data['extended_due_date'], extended_date.strftime("%Y-%m-%dT%H:%M:%SZ")) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.find_unit')
def test_filter_by_invalid_block_id(self, mock_find_unit):
@@ -1663,10 +1663,10 @@ def test_filter_by_invalid_block_id(self, mock_find_unit):
params = {'block_id': 'invalid-block-id'}
response = self.client.get(self._get_url(), params)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
- self.assertEqual(data['count'], 0)
- self.assertEqual(data['results'], [])
+ self.assertEqual(data['count'], 0) # noqa: PT009
+ self.assertEqual(data['results'], []) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.edx_when_api.get_overrides_for_block')
@patch('lms.djangoapps.instructor.views.api_v2.find_unit')
@@ -1696,22 +1696,22 @@ def test_combined_filters(self, mock_find_unit, mock_get_overrides_block):
}
response = self.client.get(self._get_url(), params)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
results = data['results']
- self.assertEqual(data['count'], 1)
- self.assertEqual(len(results), 1)
+ self.assertEqual(data['count'], 1) # noqa: PT009
+ self.assertEqual(len(results), 1) # noqa: PT009
data = results[0]
# Match only the filtered student1
- self.assertEqual(data['username'], 'student1')
- self.assertEqual(data['full_name'], 'John Doe')
- self.assertEqual(data['email'], 'john@example.com')
- self.assertEqual(data['unit_title'], 'Homework 1')
- self.assertEqual(data['unit_location'], 'block-v1:Test+Course+2024+type@sequential+block@hw1')
- self.assertEqual(data['extended_due_date'], extended_date.strftime("%Y-%m-%dT%H:%M:%SZ"))
+ self.assertEqual(data['username'], 'student1') # noqa: PT009
+ self.assertEqual(data['full_name'], 'John Doe') # noqa: PT009
+ self.assertEqual(data['email'], 'john@example.com') # noqa: PT009
+ self.assertEqual(data['unit_title'], 'Homework 1') # noqa: PT009
+ self.assertEqual(data['unit_location'], 'block-v1:Test+Course+2024+type@sequential+block@hw1') # noqa: PT009
+ self.assertEqual(data['extended_due_date'], extended_date.strftime("%Y-%m-%dT%H:%M:%SZ")) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.edx_when_api.get_overrides_for_course')
@patch('lms.djangoapps.instructor.views.api_v2.get_units_with_due_date')
@@ -1742,26 +1742,26 @@ def test_pagination_parameters(self, mock_get_units, mock_get_overrides):
params = {'page': '1', 'page_size': '1'}
response = self.client.get(self._get_url(), params)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
- self.assertIn('count', data)
- self.assertIn('next', data)
- self.assertIn('previous', data)
- self.assertIn('results', data)
+ self.assertIn('count', data) # noqa: PT009
+ self.assertIn('next', data) # noqa: PT009
+ self.assertIn('previous', data) # noqa: PT009
+ self.assertIn('results', data) # noqa: PT009
- self.assertEqual(data['count'], 2)
- self.assertIsNotNone(data['next'])
- self.assertIsNone(data['previous'])
- self.assertEqual(len(data['results']), 1)
+ self.assertEqual(data['count'], 2) # noqa: PT009
+ self.assertIsNotNone(data['next']) # noqa: PT009
+ self.assertIsNone(data['previous']) # noqa: PT009
+ self.assertEqual(len(data['results']), 1) # noqa: PT009
# Test second page
params = {'page': '2', 'page_size': '1'}
response = self.client.get(self._get_url(), params)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
- self.assertIsNone(data['next'])
- self.assertIsNotNone(data['previous'])
- self.assertEqual(len(data['results']), 1)
+ self.assertIsNone(data['next']) # noqa: PT009
+ self.assertIsNotNone(data['previous']) # noqa: PT009
+ self.assertEqual(len(data['results']), 1) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.edx_when_api.get_overrides_for_course')
@patch('lms.djangoapps.instructor.views.api_v2.get_units_with_due_date')
@@ -1776,10 +1776,10 @@ def test_empty_results(self, mock_get_units, mock_get_overrides):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
- self.assertEqual(data['count'], 0)
- self.assertEqual(data['results'], [])
+ self.assertEqual(data['count'], 0) # noqa: PT009
+ self.assertEqual(data['results'], []) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.edx_when_api.get_overrides_for_course')
@patch('lms.djangoapps.instructor.views.api_v2.get_units_with_due_date')
@@ -1809,9 +1809,9 @@ def test_extension_data_structure(self, mock_title_or_url, mock_get_units, mock_
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
- self.assertEqual(data['count'], 1)
+ self.assertEqual(data['count'], 1) # noqa: PT009
extension = data['results'][0]
@@ -1821,14 +1821,14 @@ def test_extension_data_structure(self, mock_title_or_url, mock_get_units, mock_
'unit_title', 'unit_location', 'extended_due_date'
]
for field in required_fields:
- self.assertIn(field, extension)
+ self.assertIn(field, extension) # noqa: PT009
# Verify data types
- self.assertIsInstance(extension['username'], str)
- self.assertIsInstance(extension['full_name'], str)
- self.assertIsInstance(extension['email'], str)
- self.assertIsInstance(extension['unit_title'], str)
- self.assertIsInstance(extension['unit_location'], str)
+ self.assertIsInstance(extension['username'], str) # noqa: PT009
+ self.assertIsInstance(extension['full_name'], str) # noqa: PT009
+ self.assertIsInstance(extension['email'], str) # noqa: PT009
+ self.assertIsInstance(extension['unit_title'], str) # noqa: PT009
+ self.assertIsInstance(extension['unit_location'], str) # noqa: PT009
class CourseEnrollmentsViewTest(SharedModuleStoreTestCase):
@@ -1877,126 +1877,126 @@ def setUp(self):
def test_unauthenticated_returns_401(self):
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_student_returns_403(self):
student = UserFactory()
self.client.force_authenticate(user=student)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_default_pagination(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.data
- self.assertEqual(data['course_id'], str(self.course.id))
- self.assertEqual(data['count'], 30)
- self.assertEqual(data['num_pages'], 3)
- self.assertEqual(data['current_page'], 1)
- self.assertIn('next', data)
- self.assertIsNone(data['previous'])
- self.assertIn('results', data)
+ self.assertEqual(data['course_id'], str(self.course.id)) # noqa: PT009
+ self.assertEqual(data['count'], 30) # noqa: PT009
+ self.assertEqual(data['num_pages'], 3) # noqa: PT009
+ self.assertEqual(data['current_page'], 1) # noqa: PT009
+ self.assertIn('next', data) # noqa: PT009
+ self.assertIsNone(data['previous']) # noqa: PT009
+ self.assertIn('results', data) # noqa: PT009
# DefaultPagination page_size=10
- self.assertEqual(len(data['results']), 10)
+ self.assertEqual(len(data['results']), 10) # noqa: PT009
def test_custom_pagination(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'page': 1, 'page_size': 15})
data = response.data
- self.assertEqual(data['count'], 30)
- self.assertEqual(data['num_pages'], 2)
- self.assertEqual(data['current_page'], 1)
- self.assertEqual(len(data['results']), 15)
+ self.assertEqual(data['count'], 30) # noqa: PT009
+ self.assertEqual(data['num_pages'], 2) # noqa: PT009
+ self.assertEqual(data['current_page'], 1) # noqa: PT009
+ self.assertEqual(len(data['results']), 15) # noqa: PT009
def test_second_page(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'page': 2, 'page_size': 10})
data = response.data
- self.assertEqual(data['current_page'], 2)
- self.assertEqual(len(data['results']), 10)
- self.assertIsNotNone(data['previous'])
+ self.assertEqual(data['current_page'], 2) # noqa: PT009
+ self.assertEqual(len(data['results']), 10) # noqa: PT009
+ self.assertIsNotNone(data['previous']) # noqa: PT009
def test_last_page_partial(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'page': 3, 'page_size': 10})
data = response.data
- self.assertEqual(data['current_page'], 3)
- self.assertEqual(len(data['results']), 10)
- self.assertIsNone(data['next'])
+ self.assertEqual(data['current_page'], 3) # noqa: PT009
+ self.assertEqual(len(data['results']), 10) # noqa: PT009
+ self.assertIsNone(data['next']) # noqa: PT009
def test_search_by_username(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'search': 'student_2', 'page_size': 100})
data = response.data
# Matches student_2, student_20..student_29 = 11
- self.assertEqual(data['count'], 11)
+ self.assertEqual(data['count'], 11) # noqa: PT009
for user in data['results']:
- self.assertIn('student_2', user['username'])
+ self.assertIn('student_2', user['username']) # noqa: PT009
def test_search_by_email(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'search': 'student7@example.com'})
data = response.data
- self.assertEqual(data['count'], 1)
- self.assertEqual(data['results'][0]['email'], 'student7@example.com')
+ self.assertEqual(data['count'], 1) # noqa: PT009
+ self.assertEqual(data['results'][0]['email'], 'student7@example.com') # noqa: PT009
def test_search_case_insensitive(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'search': 'STUDENT_5'})
data = response.data
- self.assertEqual(data['count'], 1)
- self.assertEqual(data['results'][0]['username'], 'student_5')
+ self.assertEqual(data['count'], 1) # noqa: PT009
+ self.assertEqual(data['results'][0]['username'], 'student_5') # noqa: PT009
def test_search_no_results(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'search': 'nonexistent'})
data = response.data
- self.assertEqual(data['count'], 0)
- self.assertEqual(len(data['results']), 0)
+ self.assertEqual(data['count'], 0) # noqa: PT009
+ self.assertEqual(len(data['results']), 0) # noqa: PT009
def test_excludes_inactive_enrollments(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'search': 'inactive'})
data = response.data
- self.assertEqual(data['count'], 0)
+ self.assertEqual(data['count'], 0) # noqa: PT009
def test_invalid_page_returns_404(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'page': 999})
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
def test_ordered_by_username(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'page_size': 5})
data = response.data
usernames = [u['username'] for u in data['results']]
- self.assertEqual(usernames, sorted(usernames))
+ self.assertEqual(usernames, sorted(usernames)) # noqa: PT009
def test_staff_can_access(self):
staff = StaffFactory(course_key=self.course.id)
self.client.force_authenticate(user=staff)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_includes_mode_field(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'page_size': 1})
enrollment = response.data['results'][0]
- self.assertIn('mode', enrollment)
+ self.assertIn('mode', enrollment) # noqa: PT009
def test_includes_full_name_field(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'page_size': 1})
enrollment = response.data['results'][0]
- self.assertIn('full_name', enrollment)
+ self.assertIn('full_name', enrollment) # noqa: PT009
def test_includes_is_beta_tester_field(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'page_size': 100})
for enrollment in response.data['results']:
- self.assertIn('is_beta_tester', enrollment)
- self.assertFalse(enrollment['is_beta_tester'])
+ self.assertIn('is_beta_tester', enrollment) # noqa: PT009
+ self.assertFalse(enrollment['is_beta_tester']) # noqa: PT009
def test_beta_tester_flag_true(self):
beta_role = CourseBetaTesterRole(self.course.id)
@@ -2006,8 +2006,8 @@ def test_beta_tester_flag_true(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'search': target_user.username})
data = response.data
- self.assertEqual(data['count'], 1)
- self.assertTrue(data['results'][0]['is_beta_tester'])
+ self.assertEqual(data['count'], 1) # noqa: PT009
+ self.assertTrue(data['results'][0]['is_beta_tester']) # noqa: PT009
def test_filter_beta_testers_only(self):
beta_role = CourseBetaTesterRole(self.course.id)
@@ -2018,9 +2018,9 @@ def test_filter_beta_testers_only(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'is_beta_tester': 'true', 'page_size': 100})
data = response.data
- self.assertEqual(data['count'], 3)
+ self.assertEqual(data['count'], 3) # noqa: PT009
for enrollment in data['results']:
- self.assertTrue(enrollment['is_beta_tester'])
+ self.assertTrue(enrollment['is_beta_tester']) # noqa: PT009
def test_filter_non_beta_testers_only(self):
beta_role = CourseBetaTesterRole(self.course.id)
@@ -2031,9 +2031,9 @@ def test_filter_non_beta_testers_only(self):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self.url, {'is_beta_tester': 'false', 'page_size': 100})
data = response.data
- self.assertEqual(data['count'], 27)
+ self.assertEqual(data['count'], 27) # noqa: PT009
for enrollment in data['results']:
- self.assertFalse(enrollment['is_beta_tester'])
+ self.assertFalse(enrollment['is_beta_tester']) # noqa: PT009
def test_filter_beta_testers_with_search(self):
beta_role = CourseBetaTesterRole(self.course.id)
@@ -2047,5 +2047,5 @@ def test_filter_beta_testers_with_search(self):
'search': self.enrolled_users[0].username,
})
data = response.data
- self.assertEqual(data['count'], 1)
- self.assertTrue(data['results'][0]['is_beta_tester'])
+ self.assertEqual(data['count'], 1) # noqa: PT009
+ self.assertTrue(data['results'][0]['is_beta_tester']) # noqa: PT009
diff --git a/lms/djangoapps/instructor/tests/test_certificates.py b/lms/djangoapps/instructor/tests/test_certificates.py
index 2abf7227dcd2..9b0299e6e9fe 100644
--- a/lms/djangoapps/instructor/tests/test_certificates.py
+++ b/lms/djangoapps/instructor/tests/test_certificates.py
@@ -1341,7 +1341,7 @@ def test_remove_certificate_invalidation(self):
# Verify that certificate invalidation successfully removed from database
- with pytest.raises(ObjectDoesNotExist):
+ with pytest.raises(ObjectDoesNotExist): # noqa: PT012
certs_filter_args = {
"generated_certificate": self.generated_certificate,
"invalidated_by": self.global_staff,
diff --git a/lms/djangoapps/instructor/tests/test_enrollment.py b/lms/djangoapps/instructor/tests/test_enrollment.py
index ab784685486f..d4ae4c8bb5b7 100644
--- a/lms/djangoapps/instructor/tests/test_enrollment.py
+++ b/lms/djangoapps/instructor/tests/test_enrollment.py
@@ -453,7 +453,7 @@ def module():
assert json.loads(module().state)['attempts'] == 0
@patch('lms.djangoapps.grades.signals.handlers.PROBLEM_WEIGHTED_SCORE_CHANGED.send')
- def test_delete_student_attempts(self, _mock_signal):
+ def test_delete_student_attempts(self, _mock_signal): # noqa: PT019
msk = self.course_key.make_usage_key('dummy', 'module')
original_state = json.dumps({'attempts': 32, 'otherstuff': 'alsorobots'})
StudentModule.objects.create(
@@ -589,7 +589,7 @@ def _assert_student_module(user):
student_module = self.get_student_module(user, team_ora_location)
assert student_module is not None
student_state = json.loads(student_module.state)
- self.assertDictEqual(student_state, attempt_reset_team_state_dict)
+ self.assertDictEqual(student_state, attempt_reset_team_state_dict) # noqa: PT009
_assert_student_module(self.user)
_assert_student_module(self.teammate_a)
@@ -598,7 +598,7 @@ def _assert_student_module(user):
self.assert_no_student_module(self.lazy_teammate, team_ora_location)
@patch('lms.djangoapps.grades.signals.handlers.PROBLEM_WEIGHTED_SCORE_CHANGED.send')
- def test_delete_team_attempts(self, _mock_signal):
+ def test_delete_team_attempts(self, _mock_signal): # noqa: PT019
self.setup_team()
team_ora_location = self.team_enabled_ora.location
# All teammates should have a student module (except lazy_teammate)
@@ -618,7 +618,7 @@ def test_delete_team_attempts(self, _mock_signal):
self.assert_no_student_module(self.lazy_teammate, team_ora_location)
@patch('lms.djangoapps.grades.signals.handlers.PROBLEM_WEIGHTED_SCORE_CHANGED.send')
- def test_delete_team_attempts_no_team_fallthrough(self, _mock_signal):
+ def test_delete_team_attempts_no_team_fallthrough(self, _mock_signal): # noqa: PT019
self.setup_team()
team_ora_location = self.team_enabled_ora.location
@@ -704,8 +704,8 @@ def test_delete_submission_scores_attempts_children(self):
delete_module=True,
)
- self.assertRaises(StudentModule.DoesNotExist, self.get_state, self.parent.location)
- self.assertRaises(StudentModule.DoesNotExist, self.get_state, self.child.location)
+ self.assertRaises(StudentModule.DoesNotExist, self.get_state, self.parent.location) # noqa: PT027
+ self.assertRaises(StudentModule.DoesNotExist, self.get_state, self.child.location) # noqa: PT027
unrelated_state = json.loads(self.get_state(self.unrelated.location))
assert unrelated_state['attempts'] == 12
@@ -774,7 +774,7 @@ def _get_subsection_grade_and_verify(self, all_earned, all_possible, graded_earn
assert grade.graded_total.possible == graded_possible
@patch('crum.get_current_request')
- def test_delete_student_state(self, _crum_mock):
+ def test_delete_student_state(self, _crum_mock): # noqa: PT019
problem_location = self.problem.location
self._get_subsection_grade_and_verify(0, 1, 0, 1)
answer_problem(course=self.course, request=self.request, problem=self.problem, score=1, max_value=1)
@@ -874,7 +874,7 @@ def setUp(self):
def test_bad_action(self):
bad_action = 'beta_tester'
error_msg = f"Unexpected action received '{bad_action}' - expected 'add' or 'remove'"
- with self.assertRaisesRegex(ValueError, error_msg):
+ with self.assertRaisesRegex(ValueError, error_msg): # noqa: PT027
send_beta_role_email(bad_action, self.user, self.email_params)
@@ -898,7 +898,7 @@ def setUp(self):
# Explicitly construct what we expect the course URLs to be
site = settings.SITE_NAME
- self.course_url = 'https://{}/courses/{}/'.format(
+ self.course_url = 'https://{}/courses/{}/'.format( # noqa: UP032
site,
self.course_key
)
@@ -935,7 +935,7 @@ def setUpClass(cls):
# Explicitly construct what we expect the course URLs to be
site = settings.SITE_NAME
- cls.course_url = 'https://{}/courses/{}/'.format(
+ cls.course_url = 'https://{}/courses/{}/'.format( # noqa: UP032
site,
str(cls.course.id)
)
@@ -1074,7 +1074,7 @@ def test_render_enrollment_message_ccx_members(self, body_file_name):
For EDX members.
"""
subject_template = 'instructor/edx_ace/enrollenrolled/email/subject.txt'
- body_template = 'instructor/edx_ace/enrollenrolled/email/{body_file_name}'.format(
+ body_template = 'instructor/edx_ace/enrollenrolled/email/{body_file_name}'.format( # noqa: UP032
body_file_name=body_file_name,
)
@@ -1083,7 +1083,7 @@ def test_render_enrollment_message_ccx_members(self, body_file_name):
assert self.ccx.display_name in subject
assert self.ccx.display_name in message
site = settings.SITE_NAME
- course_url = 'https://{}/courses/{}/'.format(
+ course_url = 'https://{}/courses/{}/'.format( # noqa: UP032
site,
self.course_key
)
@@ -1097,7 +1097,7 @@ def test_render_unenrollment_message_ccx_members(self, body_file_name):
For EDX members.
"""
subject_template = 'instructor/edx_ace/enrolledunenroll/email/subject.txt'
- body_template = 'instructor/edx_ace/enrolledunenroll/email/{body_file_name}'.format(
+ body_template = 'instructor/edx_ace/enrolledunenroll/email/{body_file_name}'.format( # noqa: UP032
body_file_name=body_file_name,
)
@@ -1113,7 +1113,7 @@ def test_render_enrollment_message_ccx_non_members(self, body_file_name):
For non EDX members.
"""
subject_template = 'instructor/edx_ace/allowedenroll/email/subject.txt'
- body_template = 'instructor/edx_ace/allowedenroll/email/{body_file_name}'.format(
+ body_template = 'instructor/edx_ace/allowedenroll/email/{body_file_name}'.format( # noqa: UP032
body_file_name=body_file_name,
)
@@ -1132,7 +1132,7 @@ def test_render_unenrollment_message_ccx_non_members(self, body_file_name):
For non EDX members.
"""
subject_template = 'instructor/edx_ace/allowedunenroll/email/subject.txt'
- body_template = 'instructor/edx_ace/allowedunenroll/email/{body_file_name}'.format(
+ body_template = 'instructor/edx_ace/allowedunenroll/email/{body_file_name}'.format( # noqa: UP032
body_file_name=body_file_name,
)
diff --git a/lms/djangoapps/instructor/tests/test_filters.py b/lms/djangoapps/instructor/tests/test_filters.py
index 979ed1fbf729..4f1324531a59 100644
--- a/lms/djangoapps/instructor/tests/test_filters.py
+++ b/lms/djangoapps/instructor/tests/test_filters.py
@@ -138,7 +138,7 @@ def test_dashboard_render_filter_executed(self):
response.content
)
- self.assertFalse(matches)
+ self.assertFalse(matches) # noqa: PT009
@override_settings(
OPEN_EDX_FILTERS_CONFIG={
@@ -184,8 +184,8 @@ def test_dashboard_redirect(self):
"""
response = self.client.get(self.dashboard_url)
- self.assertEqual(status.HTTP_302_FOUND, response.status_code)
- self.assertEqual("https://custom-dashboard.com", response.url)
+ self.assertEqual(status.HTTP_302_FOUND, response.status_code) # noqa: PT009
+ self.assertEqual("https://custom-dashboard.com", response.url) # noqa: PT009
@override_settings(
OPEN_EDX_FILTERS_CONFIG={
@@ -207,7 +207,7 @@ def test_dashboard_custom_response(self):
"""
response = self.client.get(self.dashboard_url)
- self.assertEqual("This is a custom response.", response.content.decode("utf-8"))
+ self.assertEqual("This is a custom response.", response.content.decode("utf-8")) # noqa: PT009
@override_settings(OPEN_EDX_FILTERS_CONFIG={})
def test_dashboard_render_without_filter_config(self):
@@ -227,5 +227,5 @@ def test_dashboard_render_without_filter_config(self):
response.content
)
- self.assertEqual(status.HTTP_200_OK, response.status_code)
- self.assertTrue(matches)
+ self.assertEqual(status.HTTP_200_OK, response.status_code) # noqa: PT009
+ self.assertTrue(matches) # noqa: PT009
diff --git a/lms/djangoapps/instructor/tests/test_handlers.py b/lms/djangoapps/instructor/tests/test_handlers.py
index ee29e99eea98..ba51b8b1294d 100644
--- a/lms/djangoapps/instructor/tests/test_handlers.py
+++ b/lms/djangoapps/instructor/tests/test_handlers.py
@@ -66,7 +66,7 @@ def _get_exam_event_metadata(event_signal):
minorversion=0,
source='openedx/lms/web',
sourcehost='lms.test',
- time=datetime.now(timezone.utc)
+ time=datetime.now(timezone.utc) # noqa: UP017
)
@mock.patch('lms.djangoapps.instructor.tasks.update_exam_completion_task.apply_async', autospec=True)
diff --git a/lms/djangoapps/instructor/tests/test_proctoring.py b/lms/djangoapps/instructor/tests/test_proctoring.py
index 91ef5d3b7d49..173e2a8a7c05 100644
--- a/lms/djangoapps/instructor/tests/test_proctoring.py
+++ b/lms/djangoapps/instructor/tests/test_proctoring.py
@@ -10,7 +10,6 @@
from django.urls import reverse
from edx_proctoring.api import create_exam
from edx_proctoring.backends.tests.test_backend import TestBackendProvider
-from edx_toggles.toggles.testutils import override_waffle_flag # lint-amnesty, pylint: disable=unused-import
from common.djangoapps.student.roles import CourseInstructorRole, CourseStaffRole
from common.djangoapps.student.tests.factories import AdminFactory
@@ -198,8 +197,8 @@ def test_lti_proctoring_dashboard(self):
self.instructor.is_staff = True
self.instructor.save()
response = self.client.get(self.url)
- self.assertIn('proctoring-mfe-view', response.content.decode('utf-8'))
- self.assertNotIn('proctoring-accordion', response.content.decode('utf-8'))
+ self.assertIn('proctoring-mfe-view', response.content.decode('utf-8')) # noqa: PT009
+ self.assertNotIn('proctoring-accordion', response.content.decode('utf-8')) # noqa: PT009
def test_review_dashboard(self):
"""
diff --git a/lms/djangoapps/instructor/tests/test_reports_api_v2.py b/lms/djangoapps/instructor/tests/test_reports_api_v2.py
index 1fb56f0dd5ca..bffdb399408b 100644
--- a/lms/djangoapps/instructor/tests/test_reports_api_v2.py
+++ b/lms/djangoapps/instructor/tests/test_reports_api_v2.py
@@ -66,17 +66,17 @@ def test_get_report_downloads_as_instructor(self, mock_report_store):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('downloads', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('downloads', response.data) # noqa: PT009
downloads = response.data['downloads']
- self.assertEqual(len(downloads), 2)
+ self.assertEqual(len(downloads), 2) # noqa: PT009
# Verify first report structure
report = downloads[0]
- self.assertIn('report_name', report)
- self.assertIn('report_url', report)
- self.assertIn('date_generated', report)
- self.assertIn('report_type', report)
+ self.assertIn('report_name', report) # noqa: PT009
+ self.assertIn('report_url', report) # noqa: PT009
+ self.assertIn('date_generated', report) # noqa: PT009
+ self.assertIn('report_type', report) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.ReportStore.from_config')
def test_get_report_downloads_as_staff(self, mock_report_store):
@@ -90,8 +90,8 @@ def test_get_report_downloads_as_staff(self, mock_report_store):
self.client.force_authenticate(user=self.staff)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('downloads', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('downloads', response.data) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.ReportStore.from_config')
def test_get_report_downloads_as_data_researcher(self, mock_report_store):
@@ -105,8 +105,8 @@ def test_get_report_downloads_as_data_researcher(self, mock_report_store):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('downloads', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('downloads', response.data) # noqa: PT009
def test_get_report_downloads_unauthorized(self):
"""
@@ -115,14 +115,14 @@ def test_get_report_downloads_unauthorized(self):
self.client.force_authenticate(user=self.student)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_get_report_downloads_unauthenticated(self):
"""
Test that unauthenticated users cannot access the endpoint.
"""
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_get_report_downloads_nonexistent_course(self):
"""
@@ -132,7 +132,7 @@ def test_get_report_downloads_nonexistent_course(self):
nonexistent_course_id = 'course-v1:edX+NonExistent+2024'
response = self.client.get(self._get_url(course_id=nonexistent_course_id))
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.ReportStore.from_config')
@ddt.data(
@@ -206,11 +206,11 @@ def test_report_type_detection(self, filename, expected_type, expected_date, moc
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
downloads = response.data['downloads']
- self.assertEqual(len(downloads), 1)
- self.assertEqual(downloads[0]['report_type'], expected_type)
- self.assertEqual(downloads[0]['date_generated'], expected_date)
+ self.assertEqual(len(downloads), 1) # noqa: PT009
+ self.assertEqual(downloads[0]['report_type'], expected_type) # noqa: PT009
+ self.assertEqual(downloads[0]['date_generated'], expected_date) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.ReportStore.from_config')
def test_report_without_date(self, mock_report_store):
@@ -226,10 +226,10 @@ def test_report_without_date(self, mock_report_store):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
downloads = response.data['downloads']
- self.assertEqual(len(downloads), 1)
- self.assertIsNone(downloads[0]['date_generated'])
+ self.assertEqual(len(downloads), 1) # noqa: PT009
+ self.assertIsNone(downloads[0]['date_generated']) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.ReportStore.from_config')
def test_empty_reports_list(self, mock_report_store):
@@ -243,8 +243,8 @@ def test_empty_reports_list(self, mock_report_store):
self.client.force_authenticate(user=self.instructor)
response = self.client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['downloads'], [])
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['downloads'], []) # noqa: PT009
@ddt.ddt
@@ -288,8 +288,8 @@ def test_generate_grade_report(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='grade'))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('status', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('status', response.data) # noqa: PT009
mock_submit.assert_called_once()
@patch('lms.djangoapps.instructor.views.api_v2.instructor_analytics_basic.get_available_features')
@@ -305,8 +305,8 @@ def test_generate_enrolled_students_report(self, mock_submit, mock_get_features)
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='enrolled_students'))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('status', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('status', response.data) # noqa: PT009
mock_get_features.assert_called_once_with(self.course.id)
mock_submit.assert_called_once()
@@ -320,8 +320,8 @@ def test_generate_pending_enrollments_report(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='pending_enrollments'))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('status', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('status', response.data) # noqa: PT009
mock_submit.assert_called_once()
@patch('lms.djangoapps.instructor.views.api_v2.task_api.submit_calculate_inactive_enrolled_students_csv')
@@ -334,8 +334,8 @@ def test_generate_pending_activations_report(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='pending_activations'))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('status', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('status', response.data) # noqa: PT009
mock_submit.assert_called_once()
@patch('lms.djangoapps.instructor.views.api_v2.task_api.generate_anonymous_ids')
@@ -348,8 +348,8 @@ def test_generate_anonymized_ids_report(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='anonymized_student_ids'))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('status', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('status', response.data) # noqa: PT009
mock_submit.assert_called_once()
@patch('lms.djangoapps.instructor.views.api_v2.task_api.submit_problem_grade_report')
@@ -362,8 +362,8 @@ def test_generate_problem_grade_report(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='problem_grade'))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('status', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('status', response.data) # noqa: PT009
mock_submit.assert_called_once()
def test_generate_problem_responses_report_missing_location(self):
@@ -373,7 +373,7 @@ def test_generate_problem_responses_report_missing_location(self):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='problem_responses'))
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.task_api.submit_calculate_problem_responses_csv')
@patch('lms.djangoapps.instructor.views.api_v2.modulestore')
@@ -397,7 +397,7 @@ def test_generate_problem_responses_with_location(self, mock_modulestore, mock_s
{'problem_location': 'block-v1:edX+GenReportTestX+GenReport_Test_Course+type@problem+block@test'}
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
mock_submit.assert_called_once()
@patch('lms.djangoapps.instructor.views.api_v2.task_api.submit_export_ora2_summary')
@@ -410,8 +410,8 @@ def test_generate_ora2_summary_report(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='ora2_summary'))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('status', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('status', response.data) # noqa: PT009
mock_submit.assert_called_once()
@patch('lms.djangoapps.instructor.views.api_v2.task_api.submit_export_ora2_data')
@@ -424,8 +424,8 @@ def test_generate_ora2_data_report(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='ora2_data'))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('status', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('status', response.data) # noqa: PT009
mock_submit.assert_called_once()
@patch('lms.djangoapps.instructor.views.api_v2.task_api.submit_export_ora2_submission_files')
@@ -438,8 +438,8 @@ def test_generate_ora2_submission_files_report(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='ora2_submission_files'))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('status', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('status', response.data) # noqa: PT009
mock_submit.assert_called_once()
@patch('lms.djangoapps.instructor.views.api_v2.instructor_analytics_basic.issued_certificates')
@@ -458,8 +458,8 @@ def test_generate_issued_certificates_report(self, mock_upload, mock_format, moc
self.client.force_authenticate(user=self.staff)
response = self.client.post(self._get_url(report_type='issued_certificates'))
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('status', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('status', response.data) # noqa: PT009
mock_issued_certs.assert_called_once()
mock_upload.assert_called_once()
@@ -470,8 +470,8 @@ def test_generate_report_invalid_type(self):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='invalid_type'))
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn('error', response.data)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertIn('error', response.data) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.task_api.submit_calculate_grades_csv')
def test_generate_report_already_running(self, mock_submit):
@@ -484,8 +484,8 @@ def test_generate_report_already_running(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='grade'))
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn('error', response.data)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertIn('error', response.data) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.task_api.submit_calculate_grades_csv')
def test_generate_report_queue_connection_error(self, mock_submit):
@@ -498,8 +498,8 @@ def test_generate_report_queue_connection_error(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='grade'))
- self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
- self.assertIn('error', response.data)
+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE) # noqa: PT009
+ self.assertIn('error', response.data) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.task_api.submit_calculate_problem_responses_csv')
def test_generate_report_value_error(self, mock_submit):
@@ -511,8 +511,8 @@ def test_generate_report_value_error(self, mock_submit):
self.client.force_authenticate(user=self.data_researcher)
response = self.client.post(self._get_url(report_type='problem_responses'))
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn('error', response.data)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertIn('error', response.data) # noqa: PT009
def test_generate_report_unauthorized_student(self):
"""
@@ -521,14 +521,14 @@ def test_generate_report_unauthorized_student(self):
self.client.force_authenticate(user=self.student)
response = self.client.post(self._get_url(report_type='grade'))
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_generate_report_unauthenticated(self):
"""
Test that unauthenticated users cannot generate reports.
"""
response = self.client.post(self._get_url(report_type='grade'))
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_generate_report_nonexistent_course(self):
"""
@@ -538,7 +538,7 @@ def test_generate_report_nonexistent_course(self):
nonexistent_course_id = 'course-v1:edX+NonExistent+2024'
response = self.client.post(self._get_url(course_id=nonexistent_course_id, report_type='grade'))
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
@patch('lms.djangoapps.instructor.views.api_v2.modulestore')
@patch('lms.djangoapps.instructor.views.api_v2.task_api.submit_calculate_problem_responses_csv')
@@ -556,4 +556,4 @@ def test_problem_responses_with_invalid_location(self, mock_submit, mock_modules
{'problem_location': 'invalid-location'}
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
diff --git a/lms/djangoapps/instructor/tests/test_services.py b/lms/djangoapps/instructor/tests/test_services.py
index 7080b58bba81..41929b3341c4 100644
--- a/lms/djangoapps/instructor/tests/test_services.py
+++ b/lms/djangoapps/instructor/tests/test_services.py
@@ -52,7 +52,7 @@ def setUp(self):
@mock.patch('lms.djangoapps.grades.signals.handlers.PROBLEM_WEIGHTED_SCORE_CHANGED.send')
@mock.patch('lms.djangoapps.instructor.tasks.update_exam_completion_task.apply_async', autospec=True)
- def test_reset_student_attempts_delete(self, mock_completion_task, _mock_signal):
+ def test_reset_student_attempts_delete(self, mock_completion_task, _mock_signal): # noqa: PT019
"""
Test delete student state.
"""
diff --git a/lms/djangoapps/instructor/tests/test_tools.py b/lms/djangoapps/instructor/tests/test_tools.py
index fe2656e91219..1713c127bb51 100644
--- a/lms/djangoapps/instructor/tests/test_tools.py
+++ b/lms/djangoapps/instructor/tests/test_tools.py
@@ -365,7 +365,7 @@ def test_dump_module_extensions(self):
self.week1.display_name)
assert (
report['header'] == ["Username", "Full Name", "Extended Due Date"])
- self.assertCountEqual(
+ self.assertCountEqual( # noqa: PT009
report['data'],
[
{
@@ -388,7 +388,7 @@ def test_dump_student_extensions(self):
extended)
report = tools.dump_student_extensions(self.course, self.user1)
assert (
- report['title'] == 'Due date extensions for %s (%s)' %
+ report['title'] == 'Due date extensions for %s (%s)' % # noqa: UP031
(self.user1.profile.name, self.user1.username))
assert (
report['header'] == ["Unit", "Extended Due Date"])
diff --git a/lms/djangoapps/instructor/tests/views/test_api_v2.py b/lms/djangoapps/instructor/tests/views/test_api_v2.py
index 68f27e1a9267..8b6fc465d7ea 100644
--- a/lms/djangoapps/instructor/tests/views/test_api_v2.py
+++ b/lms/djangoapps/instructor/tests/views/test_api_v2.py
@@ -46,12 +46,12 @@ def test_get_learner_by_username(self):
'student_id': self.student.id,
})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(data['username'], 'john_harvard')
- self.assertEqual(data['email'], 'john@example.com')
- self.assertEqual(data['full_name'], 'John Harvard')
- self.assertEqual(data['progress_url'], expected_progress_url)
+ self.assertEqual(data['username'], 'john_harvard') # noqa: PT009
+ self.assertEqual(data['email'], 'john@example.com') # noqa: PT009
+ self.assertEqual(data['full_name'], 'John Harvard') # noqa: PT009
+ self.assertEqual(data['progress_url'], expected_progress_url) # noqa: PT009
def test_get_learner_by_email(self):
"""Test retrieving learner info by email"""
@@ -66,11 +66,11 @@ def test_get_learner_by_email(self):
'student_id': self.student.id,
})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(data['username'], 'john_harvard')
- self.assertEqual(data['email'], 'john@example.com')
- self.assertEqual(data['progress_url'], expected_progress_url)
+ self.assertEqual(data['username'], 'john_harvard') # noqa: PT009
+ self.assertEqual(data['email'], 'john@example.com') # noqa: PT009
+ self.assertEqual(data['progress_url'], expected_progress_url) # noqa: PT009
def test_get_learner_requires_authentication(self):
"""Test that endpoint requires authentication"""
@@ -82,7 +82,7 @@ def test_get_learner_requires_authentication(self):
})
response = self.client.get(url)
- self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
+ self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]) # noqa: PT009
class ProblemViewTestCase(ModuleStoreTestCase):
@@ -120,12 +120,12 @@ def test_get_problem_metadata(self):
})
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(data['id'], str(self.problem.location))
- self.assertEqual(data['name'], 'Sample Problem')
- self.assertIn('breadcrumbs', data)
- self.assertIsInstance(data['breadcrumbs'], list)
+ self.assertEqual(data['id'], str(self.problem.location)) # noqa: PT009
+ self.assertEqual(data['name'], 'Sample Problem') # noqa: PT009
+ self.assertIn('breadcrumbs', data) # noqa: PT009
+ self.assertIsInstance(data['breadcrumbs'], list) # noqa: PT009
def test_get_problem_with_breadcrumbs(self):
"""Test that breadcrumbs contain the full course hierarchy"""
@@ -135,17 +135,17 @@ def test_get_problem_with_breadcrumbs(self):
})
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
breadcrumbs = data['breadcrumbs']
# Should contain: course → chapter → sequential → problem
- self.assertEqual(len(breadcrumbs), 4)
- self.assertEqual(breadcrumbs[0]['display_name'], self.course.display_name)
- self.assertIsNone(breadcrumbs[0]['usage_key']) # course-level has no usage_key
- self.assertEqual(breadcrumbs[1]['display_name'], 'Week 1')
- self.assertEqual(breadcrumbs[2]['display_name'], 'Homework 1')
- self.assertEqual(breadcrumbs[3]['display_name'], 'Sample Problem')
+ self.assertEqual(len(breadcrumbs), 4) # noqa: PT009
+ self.assertEqual(breadcrumbs[0]['display_name'], self.course.display_name) # noqa: PT009
+ self.assertIsNone(breadcrumbs[0]['usage_key']) # course-level has no usage_key # noqa: PT009
+ self.assertEqual(breadcrumbs[1]['display_name'], 'Week 1') # noqa: PT009
+ self.assertEqual(breadcrumbs[2]['display_name'], 'Homework 1') # noqa: PT009
+ self.assertEqual(breadcrumbs[3]['display_name'], 'Sample Problem') # noqa: PT009
def test_get_problem_invalid_location(self):
"""Test 400 with invalid problem location"""
@@ -155,8 +155,8 @@ def test_get_problem_invalid_location(self):
})
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertIn('error', response.json())
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertIn('error', response.json()) # noqa: PT009
def test_get_problem_without_learner_has_null_score_and_attempts(self):
"""Test that current_score and attempts are null when no learner is specified"""
@@ -166,10 +166,10 @@ def test_get_problem_without_learner_has_null_score_and_attempts(self):
})
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertIsNone(data['current_score'])
- self.assertIsNone(data['attempts'])
+ self.assertIsNone(data['current_score']) # noqa: PT009
+ self.assertIsNone(data['attempts']) # noqa: PT009
def test_get_problem_with_learner_returns_score_and_attempts(self):
"""Test that current_score and attempts are returned when learner has a StudentModule"""
@@ -190,11 +190,11 @@ def test_get_problem_with_learner_returns_score_and_attempts(self):
})
response = self.client.get(url, {'email_or_username': student.username})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(data['current_score']['score'], 7.0)
- self.assertEqual(data['current_score']['total'], 10.0)
- self.assertEqual(data['attempts']['current'], 3)
+ self.assertEqual(data['current_score']['score'], 7.0) # noqa: PT009
+ self.assertEqual(data['current_score']['total'], 10.0) # noqa: PT009
+ self.assertEqual(data['attempts']['current'], 3) # noqa: PT009
def test_get_problem_with_learner_no_submission_returns_nulls(self):
"""Test that current_score and attempts are null when learner has no StudentModule"""
@@ -205,10 +205,10 @@ def test_get_problem_with_learner_no_submission_returns_nulls(self):
})
response = self.client.get(url, {'email_or_username': student.username})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertIsNone(data['current_score'])
- self.assertIsNone(data['attempts'])
+ self.assertIsNone(data['current_score']) # noqa: PT009
+ self.assertIsNone(data['attempts']) # noqa: PT009
def test_get_problem_with_unknown_learner_returns_404(self):
"""Test that a 404 is returned when learner does not exist"""
@@ -218,7 +218,7 @@ def test_get_problem_with_unknown_learner_returns_404(self):
})
response = self.client.get(url, {'email_or_username': 'nonexistent_user'})
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
def test_get_problem_requires_authentication(self):
"""Test that endpoint requires authentication"""
@@ -230,7 +230,7 @@ def test_get_problem_requires_authentication(self):
})
response = self.client.get(url)
- self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
+ self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]) # noqa: PT009
class TaskStatusViewTestCase(ModuleStoreTestCase):
@@ -271,15 +271,15 @@ def test_get_task_status_completed(self):
})
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(data['task_id'], task_id)
- self.assertEqual(data['state'], 'completed')
- self.assertIn('progress', data)
- self.assertEqual(data['progress']['current'], 150)
- self.assertEqual(data['progress']['total'], 150)
- self.assertIn('result', data)
- self.assertTrue(data['result']['success'])
+ self.assertEqual(data['task_id'], task_id) # noqa: PT009
+ self.assertEqual(data['state'], 'completed') # noqa: PT009
+ self.assertIn('progress', data) # noqa: PT009
+ self.assertEqual(data['progress']['current'], 150) # noqa: PT009
+ self.assertEqual(data['progress']['total'], 150) # noqa: PT009
+ self.assertIn('result', data) # noqa: PT009
+ self.assertTrue(data['result']['success']) # noqa: PT009
def test_get_task_status_running(self):
"""Test retrieving running task status"""
@@ -303,12 +303,12 @@ def test_get_task_status_running(self):
})
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(data['state'], 'running')
- self.assertIn('progress', data)
- self.assertEqual(data['progress']['current'], 75)
- self.assertEqual(data['progress']['total'], 150)
+ self.assertEqual(data['state'], 'running') # noqa: PT009
+ self.assertIn('progress', data) # noqa: PT009
+ self.assertEqual(data['progress']['current'], 75) # noqa: PT009
+ self.assertEqual(data['progress']['total'], 150) # noqa: PT009
def test_get_task_status_failed(self):
"""Test retrieving failed task status"""
@@ -331,12 +331,12 @@ def test_get_task_status_failed(self):
})
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(data['state'], 'failed')
- self.assertIn('error', data)
- self.assertIn('code', data['error'])
- self.assertIn('message', data['error'])
+ self.assertEqual(data['state'], 'failed') # noqa: PT009
+ self.assertIn('error', data) # noqa: PT009
+ self.assertIn('code', data['error']) # noqa: PT009
+ self.assertIn('message', data['error']) # noqa: PT009
def test_get_task_requires_authentication(self):
"""Test that endpoint requires authentication"""
@@ -348,7 +348,7 @@ def test_get_task_requires_authentication(self):
})
response = self.client.get(url)
- self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
+ self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]) # noqa: PT009
class GradingConfigViewTestCase(ModuleStoreTestCase):
@@ -370,12 +370,12 @@ def test_get_grading_config(self):
})
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertIn('graders', data)
- self.assertIn('grade_cutoffs', data)
- self.assertIsInstance(data['graders'], list)
- self.assertIsInstance(data['grade_cutoffs'], dict)
+ self.assertIn('graders', data) # noqa: PT009
+ self.assertIn('grade_cutoffs', data) # noqa: PT009
+ self.assertIsInstance(data['graders'], list) # noqa: PT009
+ self.assertIsInstance(data['grade_cutoffs'], dict) # noqa: PT009
def test_get_grading_config_grader_fields(self):
"""Test that each grader entry has the expected fields"""
@@ -384,13 +384,13 @@ def test_get_grading_config_grader_fields(self):
})
response = self.client.get(url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
for grader in data['graders']:
- self.assertIn('type', grader)
- self.assertIn('min_count', grader)
- self.assertIn('drop_count', grader)
- self.assertIn('weight', grader)
+ self.assertIn('type', grader) # noqa: PT009
+ self.assertIn('min_count', grader) # noqa: PT009
+ self.assertIn('drop_count', grader) # noqa: PT009
+ self.assertIn('weight', grader) # noqa: PT009
def test_get_grading_config_requires_authentication(self):
"""Test that endpoint requires authentication"""
@@ -401,4 +401,4 @@ def test_get_grading_config_requires_authentication(self):
})
response = self.client.get(url)
- self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
+ self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]) # noqa: PT009
diff --git a/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py b/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py
index 6623f9ec9867..8e616423929e 100644
--- a/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py
+++ b/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py
@@ -100,7 +100,7 @@ def get_dashboard_enrollment_message(self):
Returns expected dashboard enrollment message with link to Insights.
"""
return 'Enrollment data is now available in Example.'.format(str(self.course.id))
+ 'rel="noopener" target="_blank">Example.'.format(str(self.course.id)) # noqa: UP032
def get_dashboard_analytics_message(self):
"""
@@ -108,7 +108,7 @@ def get_dashboard_analytics_message(self):
"""
return 'For analytics about your course, go to ExampleOpens in a new tab' \
- '.'.format(str(self.course.id))
+ '.'.format(str(self.course.id)) # noqa: UP032
def test_instructor_tab(self):
"""
@@ -182,7 +182,7 @@ def test_discussion_tab_for_course_staff_role(self, access_role, is_pages_and_re
set_course_cohorted(self.course.id, True)
self.client.login(username=self.user.username, password=self.TEST_PASSWORD)
response = self.client.get(self.url).content.decode('utf-8')
- self.assertEqual(discussion_section in response, is_discussion_tab_available)
+ self.assertEqual(discussion_section in response, is_discussion_tab_available) # noqa: PT009
@ddt.data(
(False, False, True),
@@ -205,7 +205,7 @@ def test_discussion_tab_for_global_user(self, is_pages_and_resources_enabled,
set_course_cohorted(self.course.id, True)
self.client.login(username=user.username, password=self.TEST_PASSWORD)
response = self.client.get(self.url).content.decode('utf-8')
- self.assertEqual(discussion_section in response, is_discussion_tab_available)
+ self.assertEqual(discussion_section in response, is_discussion_tab_available) # noqa: PT009
@ddt.data(
('staff', False, False),
@@ -541,7 +541,7 @@ def test_calculate_page_info(self):
@patch('lms.djangoapps.instructor.views.gradebook_api.MAX_STUDENTS_PER_PAGE_GRADE_BOOK', 1)
def test_spoc_gradebook_pages(self):
for i in range(2):
- username = "user_%d" % i
+ username = "user_%d" % i # noqa: UP031
student = UserFactory.create(username=username)
CourseEnrollmentFactory.create(user=student, course_id=self.course.id)
url = reverse(
@@ -646,7 +646,7 @@ def test_spoc_gradebook_mongo_calls(self):
students = []
for i in range(20):
- username = "user_%d" % i
+ username = "user_%d" % i # noqa: UP031
student = UserFactory.create(username=username)
CourseEnrollmentFactory.create(user=student, course_id=self.course.id)
students.append(student)
@@ -677,7 +677,7 @@ def test_spoc_gradebook_mongo_calls(self):
problem = BlockFactory.create(
category="problem",
parent=vertical,
- display_name="A Problem Block %d" % i,
+ display_name="A Problem Block %d" % i, # noqa: UP031
weight=1,
publish_item=False,
metadata={'rerandomize': 'always'},
diff --git a/lms/djangoapps/instructor/views/api.py b/lms/djangoapps/instructor/views/api.py
index b708a38f66d7..33fa294e8360 100644
--- a/lms/djangoapps/instructor/views/api.py
+++ b/lms/djangoapps/instructor/views/api.py
@@ -78,7 +78,7 @@
store_uploaded_file,
)
from common.djangoapps.util.json_request import JsonResponse, JsonResponseBadRequest
-from common.djangoapps.util.views import require_global_staff # pylint: disable=unused-import
+from common.djangoapps.util.views import require_global_staff # pylint: disable=unused-import # noqa: F401
from lms.djangoapps.bulk_email.api import create_course_email, is_bulk_email_feature_enabled
from lms.djangoapps.certificates import api as certs_api
from lms.djangoapps.course_home_api.toggles import course_home_mfe_progress_tab_is_active
@@ -1689,7 +1689,7 @@ def post(self, request, course_id, csv=False): # pylint: disable=redefined-oute
)
success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)
except Exception as e:
- raise self.api_error(status.HTTP_400_BAD_REQUEST, str(e), 'Requested task is already running')
+ raise self.api_error(status.HTTP_400_BAD_REQUEST, str(e), 'Requested task is already running') # noqa: B904 # pylint: disable=line-too-long
return JsonResponse({"status": success_status})
@@ -1720,7 +1720,7 @@ def post(self, request, course_id):
task_api.submit_calculate_may_enroll_csv(request, course_key, query_features)
success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)
except Exception as e:
- raise self.api_error(status.HTTP_400_BAD_REQUEST, str(e), 'Requested task is already running')
+ raise self.api_error(status.HTTP_400_BAD_REQUEST, str(e), 'Requested task is already running') # noqa: B904
return JsonResponse({"status": success_status})
@@ -1758,7 +1758,7 @@ def post(self, request, course_id):
)
success_status = SUCCESS_MESSAGE_TEMPLATE.format(report_type=report_type)
except Exception as e:
- raise self.api_error(
+ raise self.api_error( # noqa: B904
status.HTTP_400_BAD_REQUEST, str(e), "Requested task is already running"
)
@@ -1865,7 +1865,7 @@ def post(self, request, course_key_string):
)
task_api.submit_cohort_students(request, course_key, file_name)
except (FileValidationException, ValueError) as e:
- raise self.api_error(status.HTTP_400_BAD_REQUEST, str(e), 'failed-validation')
+ raise self.api_error(status.HTTP_400_BAD_REQUEST, str(e), 'failed-validation') # noqa: B904
return Response(status=status.HTTP_204_NO_CONTENT)
@@ -2018,7 +2018,7 @@ def get_progress_url(self, obj): # pylint: disable=unused-argument
if course_home_mfe_progress_tab_is_active(course_id):
progress_url = get_learning_mfe_home_url(course_id, url_fragment='progress')
if user is not None:
- progress_url += '/{}/'.format(user.id)
+ progress_url += '/{}/'.format(user.id) # noqa: UP032
else:
progress_url = reverse('student_progress', kwargs={'course_id': str(course_id), 'student_id': user.id})
@@ -4028,7 +4028,7 @@ def parse_request_data(request):
try:
data = json.loads(request.body.decode('utf8') or '{}')
except ValueError:
- raise ValueError(_('The record is not in the correct format. Please add a valid username or email address.')) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValueError(_('The record is not in the correct format. Please add a valid username or email address.')) # lint-amnesty, pylint: disable=raise-missing-from,line-too-long # noqa: B904
return data
@@ -4045,7 +4045,7 @@ def get_student(username_or_email):
try:
student = get_user_by_username_or_email(username_or_email)
except ObjectDoesNotExist:
- raise ValueError(_("{user} does not exist in the LMS. Please check your spelling and retry.").format( # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValueError(_("{user} does not exist in the LMS. Please check your spelling and retry.").format( # lint-amnesty, pylint: disable=raise-missing-from,line-too-long # noqa: B904
user=username_or_email
))
diff --git a/lms/djangoapps/instructor/views/api_v2.py b/lms/djangoapps/instructor/views/api_v2.py
index 9bfbb270f29a..25c1c7de7ff6 100644
--- a/lms/djangoapps/instructor/views/api_v2.py
+++ b/lms/djangoapps/instructor/views/api_v2.py
@@ -12,7 +12,7 @@
import re
from dataclasses import dataclass
from datetime import datetime
-from typing import Optional, Tuple
+from typing import Optional, Tuple # noqa: UP035
import edx_api_doc_tools as apidocs
from django.conf import settings
@@ -398,10 +398,10 @@ class UnitDueDateExtension:
email: str
unit_title: str
unit_location: str
- extended_due_date: Optional[str]
+ extended_due_date: Optional[str] # noqa: UP045
@classmethod
- def from_block_tuple(cls, row: Tuple, unit):
+ def from_block_tuple(cls, row: Tuple, unit): # noqa: UP006
username, full_name, due_date, email, location = row
unit_title = title_or_url(unit)
return cls(
@@ -414,7 +414,7 @@ def from_block_tuple(cls, row: Tuple, unit):
)
@classmethod
- def from_course_tuple(cls, row: Tuple, units_dict: dict):
+ def from_course_tuple(cls, row: Tuple, units_dict: dict): # noqa: UP006
username, full_name, email, location, due_date = row
unit_title = title_or_url(units_dict[str(location)])
return cls(
diff --git a/lms/djangoapps/instructor/views/instructor_dashboard.py b/lms/djangoapps/instructor/views/instructor_dashboard.py
index 487e4f136f43..70f9b8ef00ed 100644
--- a/lms/djangoapps/instructor/views/instructor_dashboard.py
+++ b/lms/djangoapps/instructor/views/instructor_dashboard.py
@@ -171,7 +171,7 @@ def instructor_dashboard_2(request, course_id): # lint-amnesty, pylint: disable
course_mode_has_price = False # lint-amnesty, pylint: disable=unused-variable
paid_modes = CourseMode.paid_modes_for_course(course_key)
if len(paid_modes) == 1:
- course_mode_has_price = True
+ course_mode_has_price = True # noqa: F841
elif len(paid_modes) > 1:
log.error(
"Course %s has %s course modes with payment options. Course must only have "
diff --git a/lms/djangoapps/instructor/views/tools.py b/lms/djangoapps/instructor/views/tools.py
index 8b32e019db02..2cadf7bdbdec 100644
--- a/lms/djangoapps/instructor/views/tools.py
+++ b/lms/djangoapps/instructor/views/tools.py
@@ -75,7 +75,7 @@ def require_student_from_identifier(unique_student_identifier):
try:
return get_student_from_identifier(unique_student_identifier)
except User.DoesNotExist:
- raise DashboardError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise DashboardError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
_("Could not find student matching identifier: {student_identifier}").format(
student_identifier=unique_student_identifier
)
@@ -90,7 +90,7 @@ def parse_datetime(datestr):
try:
return dateutil.parser.parse(datestr).replace(tzinfo=UTC)
except ValueError:
- raise DashboardError(_("Unable to parse date: ") + datestr) # lint-amnesty, pylint: disable=raise-missing-from
+ raise DashboardError(_("Unable to parse date: ") + datestr) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def find_unit(course, url):
@@ -220,9 +220,9 @@ def dump_block_extensions(course, unit):
"""
header = [_("Username"), _("Full Name"), _("Extended Due Date")]
data = []
- for username, fullname, due_date, *unused in api.get_overrides_for_block(course.id, unit.location):
+ for username, fullname, due_date, *unused in api.get_overrides_for_block(course.id, unit.location): # noqa: B007
due_date = due_date.strftime('%Y-%m-%d %H:%M')
- data.append(dict(list(zip(header, (username, fullname, due_date)))))
+ data.append(dict(list(zip(header, (username, fullname, due_date))))) # noqa: B905
data.sort(key=operator.itemgetter(_("Username")))
return {
"header": header,
@@ -249,7 +249,7 @@ def dump_student_extensions(course, student):
due = override['actual_date']
due = due.strftime("%Y-%m-%d %H:%M")
title = title_or_url(units[location])
- data.append(dict(list(zip(header, (title, due)))))
+ data.append(dict(list(zip(header, (title, due))))) # noqa: B905
data.sort(key=operator.itemgetter(_("Unit")))
return {
"header": header,
diff --git a/lms/djangoapps/instructor_analytics/basic.py b/lms/djangoapps/instructor_analytics/basic.py
index 5ec241ee897e..34581d373e5e 100644
--- a/lms/djangoapps/instructor_analytics/basic.py
+++ b/lms/djangoapps/instructor_analytics/basic.py
@@ -543,7 +543,7 @@ def get_transformer():
except TypeError:
username = response.student.username
err_msg = (
- 'Error occurred while attempting to load learner state '
+ 'Error occurred while attempting to load learner state ' # noqa: UP032
'{username} for state {state}.'.format(
username=username,
state=problem_state
@@ -643,42 +643,42 @@ def dump_grading_context(course):
msg = hbar
msg += "Course grader:\n"
- msg += '%s\n' % course.grader.__class__
+ msg += '%s\n' % course.grader.__class__ # noqa: UP031
graders = {}
if isinstance(course.grader, xmgraders.WeightedSubsectionsGrader):
msg += '\n'
msg += "Graded sections:\n"
for subgrader, category, weight in course.grader.subgraders:
msg += " subgrader=%s, type=%s, category=%s, weight=%s\n"\
- % (subgrader.__class__, subgrader.type, category, weight)
+ % (subgrader.__class__, subgrader.type, category, weight) # noqa: UP031
subgrader.index = 1
graders[subgrader.type] = subgrader
msg += hbar
- msg += "Listing grading context for course %s\n" % str(course.id)
+ msg += "Listing grading context for course %s\n" % str(course.id) # noqa: UP031
gcontext = grades_context.grading_context_for_course(course)
msg += "graded sections:\n"
- msg += '%s\n' % list(gcontext['all_graded_subsections_by_type'].keys())
+ msg += '%s\n' % list(gcontext['all_graded_subsections_by_type'].keys()) # noqa: UP031
for (gsomething, gsvals) in gcontext['all_graded_subsections_by_type'].items():
- msg += "--> Section %s:\n" % (gsomething)
+ msg += "--> Section %s:\n" % (gsomething) # noqa: UP031
for sec in gsvals:
sdesc = sec['subsection_block']
frmat = getattr(sdesc, 'format', None)
aname = ''
if frmat in graders:
gform = graders[frmat]
- aname = '%s %02d' % (gform.short_label, gform.index)
+ aname = '%s %02d' % (gform.short_label, gform.index) # noqa: UP031
gform.index += 1
elif sdesc.display_name in graders:
gform = graders[sdesc.display_name]
- aname = '%s' % gform.short_label
+ aname = '%s' % gform.short_label # noqa: UP031
notes = ''
if getattr(sdesc, 'score_by_attempt', False):
notes = ', score by attempt!'
msg += " %s (format=%s, Assignment=%s%s)\n"\
- % (sdesc.display_name, frmat, aname, notes)
+ % (sdesc.display_name, frmat, aname, notes) # noqa: UP031
msg += "all graded blocks:\n"
- msg += "length=%d\n" % gcontext['count_all_graded_blocks']
+ msg += "length=%d\n" % gcontext['count_all_graded_blocks'] # noqa: UP031
msg = HTML('{}').format(Text(msg))
return msg
diff --git a/lms/djangoapps/instructor_analytics/distributions.py b/lms/djangoapps/instructor_analytics/distributions.py
index 1a91771a2fa2..352c8bdc3066 100644
--- a/lms/djangoapps/instructor_analytics/distributions.py
+++ b/lms/djangoapps/instructor_analytics/distributions.py
@@ -96,7 +96,7 @@ def profile_distribution(course_id, feature):
if feature not in AVAILABLE_PROFILE_FEATURES:
raise ValueError(
- "unsupported feature requested for distribution u'{}'".format(
+ "unsupported feature requested for distribution u'{}'".format( # noqa: UP032
feature)
)
@@ -129,7 +129,7 @@ def get_count(feature, value):
).count()
distribution = {}
- for (short, full) in choices: # lint-amnesty, pylint: disable=unused-variable
+ for (short, full) in choices: # lint-amnesty, pylint: disable=unused-variable # noqa: B007
# handle no data case
if short == 'no_data':
distribution['no_data'] = 0
diff --git a/lms/djangoapps/instructor_analytics/tests/test_basic.py b/lms/djangoapps/instructor_analytics/tests/test_basic.py
index 72b387832b64..3ed91abb9a8f 100644
--- a/lms/djangoapps/instructor_analytics/tests/test_basic.py
+++ b/lms/djangoapps/instructor_analytics/tests/test_basic.py
@@ -184,7 +184,7 @@ def test_enrolled_students_features_keys(self):
userreports = sorted(userreports, key=lambda u: u["username"])
users = sorted(self.users, key=lambda u: u.username)
- for userreport, user in zip(userreports, users):
+ for userreport, user in zip(userreports, users): # noqa: B905
assert set(userreport.keys()) == set(query_features)
assert userreport['username'] == user.username
assert userreport['email'] == user.email
@@ -353,7 +353,7 @@ def get_age(self):
userreports = sorted(userreports, key=lambda u: u["username"])
users = sorted(self.users, key=lambda u: u.username)
- for userreport, user in zip(userreports, users):
+ for userreport, user in zip(userreports, users): # noqa: B905
assert set(userreport.keys()) == set(query_features)
assert userreport['age'] == str(user.age)
diff --git a/lms/djangoapps/instructor_analytics/tests/test_distributions.py b/lms/djangoapps/instructor_analytics/tests/test_distributions.py
index 6134d6041bfe..b570b6980217 100644
--- a/lms/djangoapps/instructor_analytics/tests/test_distributions.py
+++ b/lms/djangoapps/instructor_analytics/tests/test_distributions.py
@@ -29,7 +29,7 @@ def setUp(self):
def test_profile_distribution_bad_feature(self):
feature = 'robot-not-a-real-feature'
assert feature not in AVAILABLE_PROFILE_FEATURES
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
profile_distribution(self.course_id, feature)
def test_profile_distribution_easy_choice(self):
diff --git a/lms/djangoapps/instructor_task/data.py b/lms/djangoapps/instructor_task/data.py
index 7a09f7d08227..ad0fe5764135 100644
--- a/lms/djangoapps/instructor_task/data.py
+++ b/lms/djangoapps/instructor_task/data.py
@@ -4,7 +4,7 @@
from enum import Enum
-class InstructorTaskTypes(str, Enum):
+class InstructorTaskTypes(str, Enum): # noqa: UP042
"""
Enum describing the assortment of instructor tasks supported by edx-platform.
"""
diff --git a/lms/djangoapps/instructor_task/management/commands/fail_old_tasks.py b/lms/djangoapps/instructor_task/management/commands/fail_old_tasks.py
index a1b5f65ab1a5..ffd5afbd14ac 100644
--- a/lms/djangoapps/instructor_task/management/commands/fail_old_tasks.py
+++ b/lms/djangoapps/instructor_task/management/commands/fail_old_tasks.py
@@ -96,7 +96,7 @@ def handle(self, *args, **options):
for task in tasks:
print(
- "{task_state} task '{task_id}', of type '{task_type}', created on '{created}', will be marked as 'FAILURE'".format( # lint-amnesty, pylint: disable=line-too-long
+ "{task_state} task '{task_id}', of type '{task_type}', created on '{created}', will be marked as 'FAILURE'".format( # lint-amnesty, pylint: disable=line-too-long # noqa: UP032
task_state=task.task_state,
task_id=task.task_id,
task_type=task.task_type,
@@ -108,12 +108,12 @@ def handle(self, *args, **options):
tasks_updated = tasks.update(
task_state=FAILURE,
)
- print("{tasks_updated} records updated.".format(
+ print("{tasks_updated} records updated.".format( # noqa: UP032
tasks_updated=tasks_updated
))
else:
print(
- "This was a dry run, so no records were updated. "
+ "This was a dry run, so no records were updated. " # noqa: UP032
"If this command were run for real, {number} records would have been updated.".format(
number=tasks.count()
)
diff --git a/lms/djangoapps/instructor_task/models.py b/lms/djangoapps/instructor_task/models.py
index b903de9ec57c..6a4df7e32760 100644
--- a/lms/djangoapps/instructor_task/models.py
+++ b/lms/djangoapps/instructor_task/models.py
@@ -69,13 +69,13 @@ class InstructorTask(models.Model):
class Meta:
app_label = "instructor_task"
- task_type = models.CharField(max_length=50, db_index=True)
+ task_type = models.CharField(max_length=50, db_index=True) # noqa: DJ012
course_id = CourseKeyField(max_length=255, db_index=True)
task_key = models.CharField(max_length=255, db_index=True)
task_input = models.TextField()
task_id = models.CharField(max_length=255, db_index=True) # max_length from celery_taskmeta
- task_state = models.CharField(max_length=50, null=True, db_index=True) # max_length from celery_taskmeta
- task_output = models.CharField(max_length=1024, null=True)
+ task_state = models.CharField(max_length=50, null=True, db_index=True) # max_length from celery_taskmeta # noqa: DJ001 # pylint: disable=line-too-long
+ task_output = models.CharField(max_length=1024, null=True) # noqa: DJ001
requester = models.ForeignKey(User, db_index=True, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True, null=True)
updated = models.DateTimeField(auto_now=True)
diff --git a/lms/djangoapps/instructor_task/subtasks.py b/lms/djangoapps/instructor_task/subtasks.py
index 8fe1329cd1cf..fb2a06150941 100644
--- a/lms/djangoapps/instructor_task/subtasks.py
+++ b/lms/djangoapps/instructor_task/subtasks.py
@@ -57,10 +57,10 @@ def track_memory_usage(metric, course_id): # lint-amnesty, pylint: disable=unus
baseline_memory_info = process.memory_info()
baseline_usages = [getattr(baseline_memory_info, memory_type) for memory_type in memory_types]
yield
- for memory_type, baseline_usage in zip(memory_types, baseline_usages):
+ for memory_type, baseline_usage in zip(memory_types, baseline_usages): # noqa: B905
total_memory_info = process.memory_info()
total_usage = getattr(total_memory_info, memory_type)
- memory_used = total_usage - baseline_usage # lint-amnesty, pylint: disable=unused-variable
+ memory_used = total_usage - baseline_usage # lint-amnesty, pylint: disable=unused-variable # noqa: F841
def _generate_items_for_subtask(
@@ -245,7 +245,7 @@ def initialize_subtask_info(entry, action_name, total_num, subtask_id_list):
'skipped': 0,
'succeeded': 0,
'total': total_num,
- 'duration_ms': int(0),
+ 'duration_ms': int(0), # noqa: UP018
'start_time': time()
}
entry.task_output = InstructorTask.create_output_for_success(task_progress)
diff --git a/lms/djangoapps/instructor_task/tasks_helper/grades.py b/lms/djangoapps/instructor_task/tasks_helper/grades.py
index bd8c2917444b..f71d07e4d37b 100644
--- a/lms/djangoapps/instructor_task/tasks_helper/grades.py
+++ b/lms/djangoapps/instructor_task/tasks_helper/grades.py
@@ -132,7 +132,7 @@ def graded_assignments(self):
graded_subsections_map = OrderedDict()
for subsection_index, subsection_info in enumerate(subsection_infos, start=1):
subsection = subsection_info['subsection_block']
- header_name = "{assignment_type} {subsection_index}: {subsection_name}".format(
+ header_name = "{assignment_type} {subsection_index}: {subsection_name}".format( # noqa: UP032
assignment_type=assignment_type_name,
subsection_index=subsection_index,
subsection_name=subsection.display_name,
@@ -174,7 +174,7 @@ class _ProblemGradeReportContext:
def __init__(self, _xblock_instance_args, _entry_id, course_id, _task_input, action_name):
task_id = _xblock_instance_args.get('task_id') if _xblock_instance_args is not None else None
- self.task_info_string = (
+ self.task_info_string = ( # noqa: UP032
'Task: {task_id}, '
'InstructorTask ID: {entry_id}, '
'Course: {course_id}, '
@@ -327,7 +327,7 @@ def _compile(self, batched_rows):
the given batched_rows.
"""
# partition and chain successes and errors
- success_rows, error_rows = zip(*batched_rows)
+ success_rows, error_rows = zip(*batched_rows) # noqa: B905
success_rows = list(chain(*success_rows))
error_rows = list(chain(*error_rows))
diff --git a/lms/djangoapps/instructor_task/tasks_helper/module_state.py b/lms/djangoapps/instructor_task/tasks_helper/module_state.py
index 8e27d8930553..00fc99f5b03f 100644
--- a/lms/djangoapps/instructor_task/tasks_helper/module_state.py
+++ b/lms/djangoapps/instructor_task/tasks_helper/module_state.py
@@ -143,7 +143,7 @@ def rescore_problem_module_state(xblock_instance_args, block, student_module, ta
if instance is None:
# Either permissions just changed, or someone is trying to be clever
# and load something they shouldn't have access to.
- msg = "No module {location} for student {student}--access denied?".format(
+ msg = "No module {location} for student {student}--access denied?".format( # noqa: UP032
location=usage_key,
student=student
)
@@ -239,7 +239,7 @@ def override_score_module_state(xblock_instance_args, block, student_module, tas
if instance is None:
# Either permissions just changed, or someone is trying to be clever
# and load something they shouldn't have access to.
- msg = "No module {location} for student {student}--access denied?".format(
+ msg = "No module {location} for student {student}--access denied?".format( # noqa: UP032
location=usage_key,
student=student
)
diff --git a/lms/djangoapps/instructor_task/tests/factories.py b/lms/djangoapps/instructor_task/tests/factories.py
index 1040d45f97f0..1e5b5754002a 100644
--- a/lms/djangoapps/instructor_task/tests/factories.py
+++ b/lms/djangoapps/instructor_task/tests/factories.py
@@ -41,4 +41,4 @@ class Meta:
task = factory.SubFactory(InstructorTaskFactory)
task_args = "{}"
- task_due = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc) - datetime.timedelta(days=1)
+ task_due = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc) - datetime.timedelta(days=1) # noqa: UP017
diff --git a/lms/djangoapps/instructor_task/tests/test_api.py b/lms/djangoapps/instructor_task/tests/test_api.py
index ddd4bf980c5b..f1df593f7f20 100644
--- a/lms/djangoapps/instructor_task/tests/test_api.py
+++ b/lms/djangoapps/instructor_task/tests/test_api.py
@@ -486,7 +486,7 @@ def test_process_scheduled_tasks(self, mock_submit_scheduled_task):
This test generates three scheduled tasks; one that has been processed, one that is due for processing, and one
that is due in the future. In this test, one only of these tasks should be eligible for processing.
"""
- base_date = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc)
+ base_date = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc) # noqa: UP017
executed_instructor_task = self._generate_scheduled_task(task_state=SUCCESS)
executed_instructor_task_due_date = base_date - datetime.timedelta(days=5)
self._generate_scheduled_task_schedule(executed_instructor_task, executed_instructor_task_due_date)
@@ -518,7 +518,7 @@ def test_process_scheduled_tasks_expect_error(self, mock_scheduled_task):
A test that verifies the behavior of the `process_scheduled_tasks` function when there is an error processing
the request.
"""
- base_date = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc)
+ base_date = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc) # noqa: UP017
due_instructor_task = self._generate_scheduled_task()
due_instructor_task_due_date = base_date - datetime.timedelta(days=1)
self._generate_scheduled_task_schedule(due_instructor_task, due_instructor_task_due_date)
diff --git a/lms/djangoapps/instructor_task/tests/test_api_helper.py b/lms/djangoapps/instructor_task/tests/test_api_helper.py
index a40845291f3b..b78ae4c01868 100644
--- a/lms/djangoapps/instructor_task/tests/test_api_helper.py
+++ b/lms/djangoapps/instructor_task/tests/test_api_helper.py
@@ -47,7 +47,7 @@ def setUp(self):
self.request = self.FakeRequest(self.instructor)
self.targets = [BulkEmailTargetChoices.SEND_TO_MYSELF]
self.course_email = self._create_course_email(self.targets)
- self.schedule = datetime.datetime.now(datetime.timezone.utc)
+ self.schedule = datetime.datetime.now(datetime.timezone.utc) # noqa: UP017
self.task_type = InstructorTaskTypes.BULK_COURSE_EMAIL
self.task_input = json.dumps(self._generate_bulk_email_task_input(self.course_email, self.targets))
self.task_key = hashlib.md5(str(self.course_email.id).encode('utf-8')).hexdigest()
@@ -128,7 +128,7 @@ def test_create_scheduled_instructor_task_expect_failure(self, mock_get_xblock_i
"Error occurred during task or schedule creation: boom!",
]
- with self.assertRaises(QueueConnectionError):
+ with self.assertRaises(QueueConnectionError): # noqa: PT027
with LogCapture() as log:
schedule_task(
self.request, self.task_type, self.course.id, self.task_input, self.task_key, self.schedule
@@ -227,7 +227,7 @@ def test_submit_scheduled_instructor_task_with_error(self):
"double quotes: line 1 column 2 (char 1)",
]
- with self.assertRaises(QueueConnectionError):
+ with self.assertRaises(QueueConnectionError): # noqa: PT027
with LogCapture() as log:
submit_scheduled_task(schedule)
diff --git a/lms/djangoapps/instructor_task/tests/test_base.py b/lms/djangoapps/instructor_task/tests/test_base.py
index 04b9579c101c..3b41bfcff4d4 100644
--- a/lms/djangoapps/instructor_task/tests/test_base.py
+++ b/lms/djangoapps/instructor_task/tests/test_base.py
@@ -274,7 +274,7 @@ def get_input_id(response_id):
# Note that this is a capa-specific convention. The form is a version of the problem's
# URL, modified so that it can be easily stored in html, prepended with "input-" and
# appended with a sequence identifier for the particular response the input goes to.
- return 'input_{}_{}'.format(
+ return 'input_{}_{}'.format( # noqa: UP032
problem_url_name,
response_id
)
@@ -367,8 +367,8 @@ def verify_rows_in_csv(self, expected_rows, file_index=0, verify_order=True, ign
assert csv_rows == expected_rows
assert numeric_csv_rows == numeric_expected_rows
else:
- self.assertCountEqual(csv_rows, expected_rows)
- self.assertCountEqual(numeric_csv_rows, numeric_expected_rows)
+ self.assertCountEqual(csv_rows, expected_rows) # noqa: PT009
+ self.assertCountEqual(numeric_csv_rows, numeric_expected_rows) # noqa: PT009
@staticmethod
def _extract_and_round_numeric_items(dictionary):
diff --git a/lms/djangoapps/instructor_task/tests/test_tasks.py b/lms/djangoapps/instructor_task/tests/test_tasks.py
index 3da795541a90..051503da6261 100644
--- a/lms/djangoapps/instructor_task/tests/test_tasks.py
+++ b/lms/djangoapps/instructor_task/tests/test_tasks.py
@@ -107,7 +107,7 @@ def _run_task_with_mock_celery(self, task_class, entry_id, task_id, expected_fai
def _test_missing_current_task(self, task_class):
"""Check that a task_class fails when celery doesn't provide a current_task."""
task_entry = self._create_input_entry()
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
task_class(task_entry.id, self._get_block_instance_args())
def _test_undefined_course(self, task_class):
@@ -167,7 +167,7 @@ def _create_students_with_state(self, num_students, state=None, grade=0, max_gra
def _create_and_enroll_students(self, num_students, mode=CourseMode.DEFAULT_MODE_SLUG):
"""Create & enroll students for testing"""
return [
- self.create_student(username='robot%d' % i, email='robot+test+%d@edx.org' % i, mode=mode)
+ self.create_student(username='robot%d' % i, email='robot+test+%d@edx.org' % i, mode=mode) # noqa: UP031
for i in range(num_students)
]
@@ -334,7 +334,7 @@ def test_overriding_success(self):
Tests score override for a problem in a course, for all students succeeds.
"""
mock_instance = MagicMock()
- getattr(mock_instance, 'override_problem_score').return_value = None # lint-amnesty, pylint: disable=literal-used-as-attribute
+ getattr(mock_instance, 'override_problem_score').return_value = None # lint-amnesty, pylint: disable=literal-used-as-attribute # noqa: B009
num_students = 10
self._create_students_with_state(num_students)
@@ -435,7 +435,7 @@ def test_rescoring_unrescorable(self):
entry = InstructorTask.objects.get(id=task_entry.id)
output = json.loads(entry.task_output)
assert output['exception'] == 'ExceptionWithTraceback'
- assert 'Specified module {} of type {} does not support rescoring.'.format(
+ assert 'Specified module {} of type {} does not support rescoring.'.format( # noqa: UP032
self.location,
mock_instance.__class__,
) in output['message']
@@ -467,7 +467,7 @@ def test_rescoring_success(self):
Tests rescores a problem in a course, for all students succeeds.
"""
mock_instance = MagicMock()
- getattr(mock_instance, 'rescore').return_value = None # lint-amnesty, pylint: disable=literal-used-as-attribute
+ getattr(mock_instance, 'rescore').return_value = None # lint-amnesty, pylint: disable=literal-used-as-attribute # noqa: B009
mock_instance.has_submitted_answer.return_value = True
del mock_instance.done # old CAPA code used to use this value so we delete it here to be sure
diff --git a/lms/djangoapps/instructor_task/tests/test_tasks_helper.py b/lms/djangoapps/instructor_task/tests/test_tasks_helper.py
index 0df7b0a08d7e..9a1bb0be89e8 100644
--- a/lms/djangoapps/instructor_task/tests/test_tasks_helper.py
+++ b/lms/djangoapps/instructor_task/tests/test_tasks_helper.py
@@ -84,7 +84,7 @@
from xmodule.partitions.partitions import Group, UserPartition # lint-amnesty, pylint: disable=wrong-import-order
# noinspection PyUnresolvedReferences
-from xmodule.tests.helpers import override_descriptor_system # pylint: disable=unused-import
+from xmodule.tests.helpers import override_descriptor_system # pylint: disable=unused-import # noqa: F401
from ..models import ReportStore
from ..tasks_helper.utils import UPDATE_STATUS_FAILED, UPDATE_STATUS_SUCCEEDED
@@ -154,7 +154,7 @@ def test_unicode_emails(self, use_tempfile):
@ddt.data(True, False)
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.iter')
- def test_grading_failure(self, use_tempfile, mock_grades_iter, _mock_current_task):
+ def test_grading_failure(self, use_tempfile, mock_grades_iter, _mock_current_task): # noqa: PT019
"""
Test that any grading errors are properly reported in the
progress dict and uploaded to the report store.
@@ -332,7 +332,7 @@ def test_cohort_scheme_partition(self):
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.iter')
- def test_unicode_in_csv_header(self, mock_grades_iter, _mock_current_task):
+ def test_unicode_in_csv_header(self, mock_grades_iter, _mock_current_task): # noqa: PT019
"""
Tests that CSV grade report works if unicode in headers.
"""
@@ -538,7 +538,7 @@ def test_build_student_data_limit(self):
assert len(student_data) == 4
@patch('lms.djangoapps.instructor_task.tasks_helper.grades.list_problem_responses', return_value=[])
- def test_problem_responses_excludes_library_content_transformers(self, _mock_list_problem_responses):
+ def test_problem_responses_excludes_library_content_transformers(self, _mock_list_problem_responses): # noqa: PT019
"""Ensure ProblemResponses bypasses per-user library_content transformers.
The default course block access transformers include library_content transformers
@@ -899,7 +899,7 @@ def setUp(self):
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@ddt.data(True, False)
- def test_no_problems(self, use_tempfile, _):
+ def test_no_problems(self, use_tempfile, _): # noqa: PT019
"""
Verify that we see no grade information for a course with no graded
problems.
@@ -912,11 +912,11 @@ def test_no_problems(self, use_tempfile, _):
result
)
self.verify_rows_in_csv([
- dict(list(zip(
+ dict(list(zip( # noqa: B905
self.csv_header_row,
[str(self.student_1.id), self.student_1.email, self.student_1.username, ENROLLED_IN_COURSE, '0.0']
))),
- dict(list(zip(
+ dict(list(zip( # noqa: B905
self.csv_header_row,
[str(self.student_2.id), self.student_2.email, self.student_2.username, ENROLLED_IN_COURSE, '0.0']
)))
@@ -924,7 +924,7 @@ def test_no_problems(self, use_tempfile, _):
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@ddt.data(True, False)
- def test_single_problem(self, use_tempfile, _):
+ def test_single_problem(self, use_tempfile, _): # noqa: PT019
vertical = BlockFactory.create(
parent_location=self.problem_section.location,
category='vertical',
@@ -944,7 +944,7 @@ def test_single_problem(self, use_tempfile, _):
problem_name = 'Homework 1: Subsection - Problem1'
header_row = self.csv_header_row + [problem_name + ' (Earned)', problem_name + ' (Possible)']
self.verify_rows_in_csv([
- dict(list(zip(
+ dict(list(zip( # noqa: B905
header_row,
[
str(self.student_1.id),
@@ -954,7 +954,7 @@ def test_single_problem(self, use_tempfile, _):
'0.01', '1.0', '2.0',
]
))),
- dict(list(zip(
+ dict(list(zip( # noqa: B905
header_row,
[
str(self.student_2.id),
@@ -968,7 +968,7 @@ def test_single_problem(self, use_tempfile, _):
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@ddt.data(True, False)
- def test_single_problem_verified_student_only(self, use_tempfile, _):
+ def test_single_problem_verified_student_only(self, use_tempfile, _): # noqa: PT019
with patch(
'lms.djangoapps.instructor_task.tasks_helper.grades.problem_grade_report_verified_only',
return_value=True,
@@ -994,7 +994,7 @@ def test_single_problem_verified_student_only(self, use_tempfile, _):
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
@ddt.data(True, False)
- def test_inactive_enrollment_included(self, use_tempfile, _):
+ def test_inactive_enrollment_included(self, use_tempfile, _): # noqa: PT019
"""
Students with inactive enrollments in a course should be included in Problem Grade Report.
"""
@@ -1018,7 +1018,7 @@ def test_inactive_enrollment_included(self, use_tempfile, _):
problem_name = 'Homework 1: Subsection - Problem1'
header_row = self.csv_header_row + [problem_name + ' (Earned)', problem_name + ' (Possible)']
self.verify_rows_in_csv([
- dict(list(zip(
+ dict(list(zip( # noqa: B905
header_row,
[
str(self.student_1.id),
@@ -1028,7 +1028,7 @@ def test_inactive_enrollment_included(self, use_tempfile, _):
'0.01', '1.0', '2.0',
]
))),
- dict(list(zip(
+ dict(list(zip( # noqa: B905
header_row,
[
str(self.student_2.id),
@@ -1038,7 +1038,7 @@ def test_inactive_enrollment_included(self, use_tempfile, _):
'0.0', 'Not Attempted', '2.0',
]
))),
- dict(list(zip(
+ dict(list(zip( # noqa: B905
header_row,
[
str(inactive_student.id),
@@ -1100,7 +1100,7 @@ def test_problem_grade_report(self, use_tempfile):
header_row += [problem + ' (Earned)', problem + ' (Possible)']
self.verify_rows_in_csv([
- dict(list(zip(
+ dict(list(zip( # noqa: B905
header_row,
[
str(self.student_a.id),
@@ -1110,7 +1110,7 @@ def test_problem_grade_report(self, use_tempfile):
'1.0', '2.0', '2.0', 'Not Available', 'Not Available'
]
))),
- dict(list(zip(
+ dict(list(zip( # noqa: B905
header_row,
[
str(self.student_b.id),
@@ -1131,10 +1131,10 @@ def test_problem_grade_report_valid_columns_order(self):
self.course = CourseFactory.create(
grading_policy={
"GRADER": [{
- "type": "Homework %d" % i,
+ "type": "Homework %d" % i, # noqa: UP031
"min_count": 1,
"drop_count": 0,
- "short_label": "HW %d" % i,
+ "short_label": "HW %d" % i, # noqa: UP031
"weight": 1.0
} for i in range(1, grader_num)]
}
@@ -1149,10 +1149,10 @@ def test_problem_grade_report_valid_columns_order(self):
problem_vertical_list = []
for i in range(1, grader_num):
- chapter_name = 'Chapter %d' % i
- problem_section_name = 'Problem section %d' % i
- problem_section_format = 'Homework %d' % i
- problem_vertical_name = 'Problem Unit %d' % i
+ chapter_name = 'Chapter %d' % i # noqa: UP031
+ problem_section_name = 'Problem section %d' % i # noqa: UP031
+ problem_section_format = 'Homework %d' % i # noqa: UP031
+ problem_vertical_name = 'Problem Unit %d' % i # noqa: UP031
chapter = BlockFactory.create(parent_location=self.course.location,
display_name=chapter_name)
@@ -1174,9 +1174,9 @@ def test_problem_grade_report_valid_columns_order(self):
problem_names = []
for i in range(1, grader_num):
- problem_url = 'test_problem_%d' % i
+ problem_url = 'test_problem_%d' % i # noqa: UP031
self.define_option_problem(problem_url, parent=problem_vertical_list[i - 1])
- title = 'Homework %d 1: Problem section %d - %s' % (i, i, problem_url)
+ title = 'Homework %d 1: Problem section %d - %s' % (i, i, problem_url) # noqa: UP031
problem_names.append(title)
header_row = ['Student ID', 'Email', 'Username', 'Enrollment Status', 'Grade']
@@ -1224,7 +1224,7 @@ def _format_user_grade(self, header_row, user, enrollment_status, grade):
user(object): Django user object
grade(list): Users' grade list
"""
- return dict(list(zip(
+ return dict(list(zip( # noqa: B905
header_row,
[
str(user.id),
@@ -1628,8 +1628,8 @@ def test_username(self):
assert_dict_contains_subset(self, {'total': 2, 'attempted': 2, 'succeeded': 2, 'failed': 0}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))),
- dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))), # noqa: B905
+ dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -1643,8 +1643,8 @@ def test_email(self):
assert_dict_contains_subset(self, {'total': 2, 'attempted': 2, 'succeeded': 2, 'failed': 0}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))),
- dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))), # noqa: B905
+ dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -1658,8 +1658,8 @@ def test_username_and_email(self):
assert_dict_contains_subset(self, {'total': 2, 'attempted': 2, 'succeeded': 2, 'failed': 0}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))),
- dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))), # noqa: B905
+ dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -1679,8 +1679,8 @@ def test_prefer_email(self):
assert_dict_contains_subset(self, {'total': 2, 'attempted': 2, 'succeeded': 2, 'failed': 0}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))),
- dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))), # noqa: B905
+ dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -1693,7 +1693,7 @@ def test_non_existent_user(self):
assert_dict_contains_subset(self, {'total': 1, 'attempted': 1, 'succeeded': 0, 'failed': 1}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '0', 'Invalid', '', '']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '0', 'Invalid', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -1707,8 +1707,8 @@ def test_non_existent_cohort(self):
assert_dict_contains_subset(self, {'total': 2, 'attempted': 2, 'succeeded': 1, 'failed': 1}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Does Not Exist', 'False', '0', '', '', '']))),
- dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))),
+ dict(list(zip(self.csv_header_row, ['Does Not Exist', 'False', '0', '', '', '']))), # noqa: B905
+ dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -1725,7 +1725,7 @@ def test_preassigned_user(self):
)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '0', '', '', 'example_email@example.com']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '0', '', '', 'example_email@example.com']))), # noqa: B905 # pylint: disable=line-too-long
],
verify_order=False
)
@@ -1738,7 +1738,7 @@ def test_invalid_email(self):
assert_dict_contains_subset(self, {'total': 1, 'attempted': 1, 'succeeded': 0, 'failed': 1}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '0', '', 'student_1@', '']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '0', '', 'student_1@', '']))), # noqa: B905
],
verify_order=False
)
@@ -1763,7 +1763,7 @@ def test_too_few_commas(self):
assert_dict_contains_subset(self, {'total': 2, 'attempted': 2, 'succeeded': 0, 'failed': 2}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['', 'False', '0', '', '', '']))),
+ dict(list(zip(self.csv_header_row, ['', 'False', '0', '', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -1787,8 +1787,8 @@ def test_carriage_return(self):
assert_dict_contains_subset(self, {'total': 2, 'attempted': 2, 'succeeded': 2, 'failed': 0}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))),
- dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))), # noqa: B905
+ dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -1805,8 +1805,8 @@ def test_carriage_return_line_feed(self):
assert_dict_contains_subset(self, {'total': 2, 'attempted': 2, 'succeeded': 2, 'failed': 0}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))),
- dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))), # noqa: B905
+ dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -1825,8 +1825,8 @@ def test_move_users_to_new_cohort(self):
assert_dict_contains_subset(self, {'total': 2, 'attempted': 2, 'succeeded': 2, 'failed': 0}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))),
- dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '1', '', '', '']))), # noqa: B905
+ dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '1', '', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -1845,8 +1845,8 @@ def test_move_users_to_same_cohort(self):
assert_dict_contains_subset(self, {'total': 2, 'attempted': 2, 'skipped': 2, 'failed': 0}, result)
self.verify_rows_in_csv(
[
- dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '0', '', '', '']))),
- dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '0', '', '', '']))),
+ dict(list(zip(self.csv_header_row, ['Cohort 1', 'True', '0', '', '', '']))), # noqa: B905
+ dict(list(zip(self.csv_header_row, ['Cohort 2', 'True', '0', '', '', '']))), # noqa: B905
],
verify_order=False
)
@@ -2011,7 +2011,7 @@ def test_grade_report_with_overrides(self):
)
@patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task')
- def test_course_grade_with_verified_student_only(self, _get_current_task):
+ def test_course_grade_with_verified_student_only(self, _get_current_task): # noqa: PT019
"""
Tests that course grade report has expected data when it is generated only for
verified learners.
@@ -2694,7 +2694,7 @@ def test_report_fails_if_error(self, data_collector_module, upload_func):
mock_current_task.return_value = self.current_task
response = upload_func(None, None, self.course.id, None, 'generated')
- self.assertEqual(response, UPDATE_STATUS_FAILED)
+ self.assertEqual(response, UPDATE_STATUS_FAILED) # noqa: PT009
def test_report_stores_results(self):
with ExitStack() as stack:
@@ -2776,7 +2776,7 @@ def test_summary_report_stores_results(self):
key = self.course.id
filename = f'{key.org}_{key.course}_{key.run}_ORA_summary_{timestamp_str}.csv'
- self.assertEqual(return_val, UPDATE_STATUS_SUCCEEDED)
+ self.assertEqual(return_val, UPDATE_STATUS_SUCCEEDED) # noqa: PT009
mock_store_rows.assert_called_once_with(self.course.id, filename, [test_header] + test_rows, '')
def test_export_fails_if_error_on_create_zip_step(self):
diff --git a/lms/djangoapps/learner_dashboard/tests/test_programs.py b/lms/djangoapps/learner_dashboard/tests/test_programs.py
index 8755ad154018..262787347641 100644
--- a/lms/djangoapps/learner_dashboard/tests/test_programs.py
+++ b/lms/djangoapps/learner_dashboard/tests/test_programs.py
@@ -88,7 +88,7 @@ def assert_dict_contains_subset(self, superset, subset):
Verify that the dict superset contains the dict subset.
"""
for key, value in subset.items():
- assert key in superset and superset[key] == value, f"{key}: {value} not found in superset or does not match"
+ assert key in superset and superset[key] == value, f"{key}: {value} not found in superset or does not match" # noqa: PT018 # pylint: disable=line-too-long
def test_login_required(self, mock_get_programs):
"""
@@ -110,7 +110,7 @@ def test_login_required(self, mock_get_programs):
response = self.client.get(self.url)
assert response.status_code == 200
- def test_404_if_disabled(self, _mock_get_programs):
+ def test_404_if_disabled(self, _mock_get_programs): # noqa: PT019
"""
Verify that the page 404s if disabled.
"""
@@ -279,7 +279,7 @@ def test_login_required(self, mock_get_programs, mock_get_pathways):
self.assert_program_data_present(response)
self.assert_pathway_data_present(response)
- def test_404_if_disabled(self, _mock_get_programs, _mock_get_pathways):
+ def test_404_if_disabled(self, _mock_get_programs, _mock_get_pathways): # noqa: PT019
"""
Verify that the page 404s if disabled.
"""
@@ -288,7 +288,7 @@ def test_404_if_disabled(self, _mock_get_programs, _mock_get_pathways):
response = self.client.get(self.url)
assert response.status_code == 404
- def test_404_if_no_data(self, mock_get_programs, _mock_get_pathways):
+ def test_404_if_no_data(self, mock_get_programs, _mock_get_pathways): # noqa: PT019
"""Verify that the page 404s if no program data is found."""
self.create_programs_config()
diff --git a/lms/djangoapps/learner_dashboard/tests/test_views.py b/lms/djangoapps/learner_dashboard/tests/test_views.py
index 733a7bb06942..ffb0637091bd 100644
--- a/lms/djangoapps/learner_dashboard/tests/test_views.py
+++ b/lms/djangoapps/learner_dashboard/tests/test_views.py
@@ -53,7 +53,7 @@ def test_program_discussion_not_configured(self):
Verify API returns proper response in case ProgramDiscussions is not Configured.
"""
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
expected_data = {
'tab_view_enabled': True,
'discussion': {
@@ -61,7 +61,7 @@ def test_program_discussion_not_configured(self):
'configured': False
}
}
- self.assertEqual(response.data, expected_data)
+ self.assertEqual(response.data, expected_data) # noqa: PT009
def test_if_user_is_not_authenticated(self):
"""
@@ -69,7 +69,7 @@ def test_if_user_is_not_authenticated(self):
"""
self.client.logout()
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 401)
+ self.assertEqual(response.status_code, 401) # noqa: PT009
def test_program_discussion_disabled(self):
"""
@@ -91,8 +91,8 @@ def test_program_discussion_disabled(self):
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.data, expected_data)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(response.data, expected_data) # noqa: PT009
@ddt.data(True, False)
def test_api_returns_discussions_iframe(self, staff):
@@ -116,9 +116,9 @@ def test_api_returns_discussions_iframe(self, staff):
)
discussion_config.save()
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
- self.assertIsInstance(response.data['discussion']['iframe'], Markup)
- self.assertIn('iframe', str(response.data['discussion']['iframe']), )
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertIsInstance(response.data['discussion']['iframe'], Markup) # noqa: PT009
+ self.assertIn('iframe', str(response.data['discussion']['iframe']), ) # noqa: PT009
def test_program_without_enrollment(self):
"""
@@ -134,5 +134,5 @@ def test_program_without_enrollment(self):
'iframe': ''
}
}
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.data, default_response)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(response.data, default_response) # noqa: PT009
diff --git a/lms/djangoapps/learner_home/mock/mock_views.py b/lms/djangoapps/learner_home/mock/mock_views.py
index 2607aad77a9a..93a96791293e 100644
--- a/lms/djangoapps/learner_home/mock/mock_views.py
+++ b/lms/djangoapps/learner_home/mock/mock_views.py
@@ -18,7 +18,7 @@ class InitializeView(RetrieveAPIView):
"""Returns static JSON authored in MOCK_DATA_FILE"""
def get(self, request, *args, **kwargs): # pylint: disable=unused-argument
- with open(path.join(LEARNER_HOME_DIR, MOCK_DATA_FILE), "r") as mock_data_file:
+ with open(path.join(LEARNER_HOME_DIR, MOCK_DATA_FILE), "r") as mock_data_file: # noqa: UP015
# Edit me to change response data
mock_data = json.load(mock_data_file)
diff --git a/lms/djangoapps/learner_home/test_serializers.py b/lms/djangoapps/learner_home/test_serializers.py
index ec5ac213b46a..6bde2958c482 100644
--- a/lms/djangoapps/learner_home/test_serializers.py
+++ b/lms/djangoapps/learner_home/test_serializers.py
@@ -105,7 +105,7 @@ def create_test_entitlement_and_sessions(self):
# Create related course overviews
course_key_str = pseudo_sessions[str(unfulfilled_entitlement.uuid)]["key"]
course_key = CourseKey.from_string(course_key_str)
- course_overview = CourseOverviewFactory.create(id=course_key)
+ course_overview = CourseOverviewFactory.create(id=course_key) # noqa: F841
return unfulfilled_entitlement, pseudo_sessions, available_sessions
@@ -155,7 +155,7 @@ def test_happy_path(self):
input_data = test_enrollment.course_overview
output_data = CourseProviderSerializer(input_data).data
- self.assertEqual(output_data["name"], test_enrollment.course_overview.org)
+ self.assertEqual(output_data["name"], test_enrollment.course_overview.org) # noqa: PT009
class TestCourseSerializer(LearnerDashboardBaseTest):
@@ -217,7 +217,7 @@ def test_missing_resume_url(self):
output_data = CourseRunSerializer(input_data, context=input_context).data
# Then the resumeUrl is None, which is allowed
- self.assertIsNone(output_data["resumeUrl"])
+ self.assertIsNone(output_data["resumeUrl"]) # noqa: PT009
def is_progress_url_matching_course_home_mfe_progress_tab_is_active(self):
"""
@@ -238,10 +238,10 @@ def test_progress_url(self, mock_course_home_mfe_progress_tab_is_active):
Otherwise, it must point to the legacy progress page.
"""
mock_course_home_mfe_progress_tab_is_active.return_value = True
- self.assertTrue(self.is_progress_url_matching_course_home_mfe_progress_tab_is_active())
+ self.assertTrue(self.is_progress_url_matching_course_home_mfe_progress_tab_is_active()) # noqa: PT009
mock_course_home_mfe_progress_tab_is_active.return_value = False
- self.assertTrue(self.is_progress_url_matching_course_home_mfe_progress_tab_is_active())
+ self.assertTrue(self.is_progress_url_matching_course_home_mfe_progress_tab_is_active()) # noqa: PT009
@ddt.ddt
@@ -268,7 +268,7 @@ def test_unmet_prerequisites(self, has_unmet_prerequisites):
# ... without unmet prerequisites
if has_unmet_prerequisites:
# ... or with unmet prerequisites
- prerequisite_course = CourseFactory()
+ prerequisite_course = CourseFactory() # noqa: F841
input_context.update(
{
"course_access_checks": {
@@ -283,7 +283,7 @@ def test_unmet_prerequisites(self, has_unmet_prerequisites):
output_data = CoursewareAccessSerializer(input_data, context=input_context).data
# Then "hasUnmetPrerequisites" is outputs correctly
- self.assertEqual(output_data["hasUnmetPrerequisites"], has_unmet_prerequisites)
+ self.assertEqual(output_data["hasUnmetPrerequisites"], has_unmet_prerequisites) # noqa: PT009
@ddt.data(True, False)
def test_is_staff(self, is_staff):
@@ -306,7 +306,7 @@ def test_is_staff(self, is_staff):
output_data = CoursewareAccessSerializer(input_data, context=input_context).data
# Then "isStaff" serializes properly
- self.assertEqual(output_data["isStaff"], is_staff)
+ self.assertEqual(output_data["isStaff"], is_staff) # noqa: PT009
@ddt.data(True, False)
def test_is_too_early(self, is_too_early):
@@ -329,7 +329,7 @@ def test_is_too_early(self, is_too_early):
output_data = CoursewareAccessSerializer(input_data, context=input_context).data
# Then "isTooEarly" serializes properly
- self.assertEqual(output_data["isTooEarly"], is_too_early)
+ self.assertEqual(output_data["isTooEarly"], is_too_early) # noqa: PT009
@ddt.ddt
@@ -380,7 +380,7 @@ def test_audit_access_expired(self, expiration_datetime, should_be_expired):
# With/out an expiration date (made timezone aware, if it exists)
expiration_datetime = (
- expiration_datetime.replace(tzinfo=timezone.utc)
+ expiration_datetime.replace(tzinfo=timezone.utc) # noqa: UP017
if expiration_datetime
else None
)
@@ -393,7 +393,7 @@ def test_audit_access_expired(self, expiration_datetime, should_be_expired):
# When I serialize
output = EnrollmentSerializer(input_data, context=input_context).data
- self.assertEqual(output["isAuditAccessExpired"], should_be_expired)
+ self.assertEqual(output["isAuditAccessExpired"], should_be_expired) # noqa: PT009
@ddt.data(
(random_url(), True, uuid4(), True),
@@ -427,7 +427,7 @@ def test_user_can_upgrade(
# Then I correctly return whether or not the user can upgrade
# (If any of the payment page, upsell, or sku aren't provided, this is False)
- self.assertEqual(output["canUpgrade"], expected_can_upgrade)
+ self.assertEqual(output["canUpgrade"], expected_can_upgrade) # noqa: PT009
@ddt.data(None, "", "some_url")
def test_has_started(self, resume_url):
@@ -448,9 +448,9 @@ def test_has_started(self, resume_url):
# If I have a resume URL, "hasStarted" should be True, otherwise False
if resume_url:
- self.assertTrue(output["hasStarted"])
+ self.assertTrue(output["hasStarted"]) # noqa: PT009
else:
- self.assertFalse(output["hasStarted"])
+ self.assertFalse(output["hasStarted"]) # noqa: PT009
@ddt.ddt
@@ -471,7 +471,7 @@ def test_happy_path(self, is_passing):
output_data = GradeDataSerializer(input_data, context=input_context).data
# Then I get the correct data shape out
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
output_data,
{
"isPassing": is_passing,
@@ -531,7 +531,7 @@ def test_with_data(self):
output_data = CertificateSerializer(input_data, context=input_context).data
# Then all the info is provided correctly
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
output_data,
{
"availableDate": datetime_to_django_format(available_date),
@@ -557,7 +557,7 @@ def test_available_date_course_end(self):
# Then the available date is the course end date
expected_available_date = datetime_to_django_format(input_data.course.end)
- self.assertEqual(output_data["availableDate"], expected_available_date)
+ self.assertEqual(output_data["availableDate"], expected_available_date) # noqa: PT009
def test_available_date_specific_end(self):
# Given new cert display settings are enabled
@@ -577,7 +577,7 @@ def test_available_date_specific_end(self):
expected_available_date = datetime_to_django_format(
input_data.course.certificate_available_date
)
- self.assertEqual(output_data["availableDate"], expected_available_date)
+ self.assertEqual(output_data["availableDate"], expected_available_date) # noqa: PT009
@ddt.data(
("downloadable", False),
@@ -599,7 +599,7 @@ def test_is_restricted(self, cert_status, is_restricted_expected):
output_data = CertificateSerializer(input_data, context=input_context).data
# Then isRestricted should be calculated correctly
- self.assertEqual(output_data["isRestricted"], is_restricted_expected)
+ self.assertEqual(output_data["isRestricted"], is_restricted_expected) # noqa: PT009
@ddt.data(
("downloadable", True),
@@ -622,7 +622,7 @@ def test_is_earned(self, cert_status, is_earned_expected):
output_data = CertificateSerializer(input_data, context=input_context).data
# Then isEarned should be calculated correctly
- self.assertEqual(output_data["isEarned"], is_earned_expected)
+ self.assertEqual(output_data["isEarned"], is_earned_expected) # noqa: PT009
@ddt.data(
("downloadable", True),
@@ -645,7 +645,7 @@ def test_is_downloadable(self, cert_status, is_downloadable_expected):
output_data = CertificateSerializer(input_data, context=input_context).data
# Then isDownloadable should be calculated correctly
- self.assertEqual(output_data["isDownloadable"], is_downloadable_expected)
+ self.assertEqual(output_data["isDownloadable"], is_downloadable_expected) # noqa: PT009
@ddt.data(
(True, random_url()),
@@ -672,7 +672,7 @@ def test_cert_preview_url(self, show_cert_web_view, cert_web_view_url):
output_data = CertificateSerializer(input_data, context=input_context).data
# Then certPreviewUrl should be calculated correctly
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
output_data["certPreviewUrl"],
cert_web_view_url if show_cert_web_view else None,
)
@@ -684,7 +684,7 @@ class TestEntitlementSerializer(TestCase):
def _assert_available_sessions(self, input_sessions, output_sessions):
assert len(output_sessions) == len(input_sessions)
- for input_session, output_session in zip(input_sessions, output_sessions):
+ for input_session, output_session in zip(input_sessions, output_sessions): # noqa: B905
assert output_session == {
"startDate": input_session["start"],
"endDate": input_session["end"],
@@ -756,7 +756,7 @@ def test_related_program_serializer(self):
# When I serialize it
output_data = RelatedProgramSerializer(input_data).data
# Then the output should map with the input
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
output_data,
{
"bannerImgSrc": input_data["banner_image"]["small"]["url"],
@@ -785,7 +785,7 @@ def test_programs_serializer(self):
# Test the output
assert output_data["relatedPrograms"]
assert len(output_data["relatedPrograms"]) == len(input_data["relatedPrograms"])
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
output_data,
{
"relatedPrograms": RelatedProgramSerializer(
@@ -807,7 +807,7 @@ def test_empty_source_programs_serializer(self):
output_data = RelatedProgramSerializer(input_data).data
# Test the output
- self.assertEqual(output_data["bannerImgSrc"], None)
+ self.assertEqual(output_data["bannerImgSrc"], None) # noqa: PT009
def test_empty_sessions(self):
input_data = {"relatedPrograms": []}
@@ -850,7 +850,7 @@ def test_serialize_credit(self):
output_data = CreditSerializer(credit_data).data
# Then I get the appropriate data shape
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
output_data,
{
"providerStatusUrl": credit_data["provider_status_url"],
@@ -906,15 +906,15 @@ def test_happy_path(self):
]
# Verify we have all the expected keys in our output
- self.assertEqual(output.keys(), set(expected_keys))
+ self.assertEqual(output.keys(), set(expected_keys)) # noqa: PT009
# Entitlements should be the only empty field for an enrollment
entitlement = output.pop("entitlement")
- self.assertDictEqual(entitlement, {})
+ self.assertDictEqual(entitlement, {}) # noqa: PT009
# All other keys should have some basic info, unless we broke something
for key in output.keys():
- self.assertNotEqual(output[key], {})
+ self.assertNotEqual(output[key], {}) # noqa: PT009
def test_credit_no_credit_option(self):
# Given an enrollment
@@ -929,7 +929,7 @@ def test_credit_no_credit_option(self):
output = LearnerEnrollmentSerializer(input_data, context=input_context).data
# Then I return empty credit info
- self.assertDictEqual(output["credit"], {})
+ self.assertDictEqual(output["credit"], {}) # noqa: PT009
class TestUnfulfilledEntitlementSerializer(LearnerDashboardBaseTest):
@@ -1058,7 +1058,7 @@ def mock_suggested_courses(cls, courses_count=5):
"is_personalized_recommendation": False,
}
- for i in range(courses_count):
+ for i in range(courses_count): # noqa: B007
suggested_courses["courses"].append(
{
"course_key": uuid4(),
@@ -1077,7 +1077,7 @@ def test_happy_path(self):
output_data = SuggestedCourseSerializer(input_data).data
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
output_data,
{
"bannerImgSrc": input_data["logo_image_url"],
@@ -1117,7 +1117,7 @@ def test_happy_path(self):
output_data = EmailConfirmationSerializer(input_data).data
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
output_data,
{
"isNeeded": input_data["isNeeded"],
@@ -1146,7 +1146,7 @@ def test_structure(self):
output_data = EnterpriseDashboardSerializer(input_data).data
expected_keys = ["label", "url", "uuid", "isLearnerPortalEnabled", "authOrgId"]
- self.assertEqual(output_data.keys(), set(expected_keys))
+ self.assertEqual(output_data.keys(), set(expected_keys)) # noqa: PT009
def test_happy_path(self):
"""Test that data serializes correctly"""
@@ -1155,7 +1155,7 @@ def test_happy_path(self):
output_data = EnterpriseDashboardSerializer(input_data).data
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
output_data,
{
"label": input_data["name"],
@@ -1172,7 +1172,7 @@ def test_no_auth_org_id(self):
""" Test for missing auth_org_id """
input_data = self.generate_test_enterprise_customer()
del input_data['auth_org_id']
- self.assertIsNone(EnterpriseDashboardSerializer(input_data).data['authOrgId'])
+ self.assertIsNone(EnterpriseDashboardSerializer(input_data).data['authOrgId']) # noqa: PT009
class TestSocialMediaSettingsSiteSerializer(TestCase):
@@ -1197,7 +1197,7 @@ def test_structure(self):
"socialBrand",
"utmParams",
]
- self.assertEqual(output_data.keys(), set(expected_keys))
+ self.assertEqual(output_data.keys(), set(expected_keys)) # noqa: PT009
class TestSocialShareSettingsSerializer(TestCase):
@@ -1217,7 +1217,7 @@ def test_structure(self):
output_data = SocialShareSettingsSerializer(input_data).data
expected_keys = ["twitter", "facebook"]
- self.assertEqual(output_data.keys(), set(expected_keys))
+ self.assertEqual(output_data.keys(), set(expected_keys)) # noqa: PT009
class TestLearnerDashboardSerializer(LearnerDashboardBaseTest):
@@ -1317,7 +1317,7 @@ def test_empty(self):
}
output_data = LearnerDashboardSerializer(input_data).data
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
output_data,
{
"emailConfirmation": None,
@@ -1414,7 +1414,7 @@ def test_suggested_courses(self):
output_suggested_courses = output_data.pop("suggestedCourses")
- self.assertEqual(len(suggested_courses), len(output_suggested_courses))
+ self.assertEqual(len(suggested_courses), len(output_suggested_courses)) # noqa: PT009
@mock.patch(
"lms.djangoapps.learner_home.serializers.SuggestedCourseSerializer.to_representation"
@@ -1474,7 +1474,7 @@ def test_linkage(
}
output_data = LearnerDashboardSerializer(input_data).data
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
output_data,
{
"emailConfirmation": mock_email_confirmation_serializer,
diff --git a/lms/djangoapps/learner_home/test_utils.py b/lms/djangoapps/learner_home/test_utils.py
index 9039597b52ed..2aed7385c93f 100644
--- a/lms/djangoapps/learner_home/test_utils.py
+++ b/lms/djangoapps/learner_home/test_utils.py
@@ -32,7 +32,7 @@ def random_date(allow_null=False):
return None
d = randint(1, int(time()))
- return datetime.datetime.fromtimestamp(d, tz=datetime.timezone.utc)
+ return datetime.datetime.fromtimestamp(d, tz=datetime.timezone.utc) # noqa: UP017
def random_url(allow_null=False):
@@ -53,7 +53,7 @@ def random_grade():
def decimal_to_grade_format(decimal):
"""Util for matching serialized grade format, pads a decimal to 2 places"""
- return "{:.2f}".format(decimal)
+ return "{:.2f}".format(decimal) # noqa: UP032
def datetime_to_django_format(datetime_obj):
diff --git a/lms/djangoapps/learner_home/test_views.py b/lms/djangoapps/learner_home/test_views.py
index 8057abcd2a01..2328e9e92342 100644
--- a/lms/djangoapps/learner_home/test_views.py
+++ b/lms/djangoapps/learner_home/test_views.py
@@ -65,7 +65,7 @@ def test_happy_path(self, mock_marketing_link):
return_data = get_platform_settings()
# Then I return them in the appropriate format
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
return_data,
{
"supportEmail": self.MOCK_SETTINGS["DEFAULT_FEEDBACK_EMAIL"],
@@ -127,7 +127,7 @@ def test_email_url_support_link(self):
user_account_confirmation_info = get_user_account_confirmation_info(self.user)
# Then that link should be returned as the sendEmailUrl
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
user_account_confirmation_info["sendEmailUrl"],
self.MOCK_SETTINGS["SEND_ACTIVATION_EMAIL_URL"],
)
@@ -142,7 +142,7 @@ def test_email_url_support_fallback_link(self, mock_config_helpers):
user_account_confirmation_info = get_user_account_confirmation_info(self.user)
# Then sendEmailUrl falls back to SUPPORT_SITE_LINK
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
user_account_confirmation_info["sendEmailUrl"],
self.MOCK_SETTINGS["SUPPORT_SITE_LINK"],
)
@@ -177,8 +177,8 @@ def test_empty(self):
returned_enrollments, course_mode_info = get_enrollments(self.user, None, None)
# Then I return an empty list and dict
- self.assertEqual(returned_enrollments, [])
- self.assertEqual(course_mode_info, {})
+ self.assertEqual(returned_enrollments, []) # noqa: PT009
+ self.assertEqual(course_mode_info, {}) # noqa: PT009
class TestGetEntitlements(SharedModuleStoreTestCase):
@@ -308,7 +308,7 @@ def test_basic(self):
course_overviews = get_course_overviews_for_pseudo_sessions(pseudo_sessions)
# Then they map to the correct courses
- self.assertDictEqual(course_overviews, expected_course_overviews)
+ self.assertDictEqual(course_overviews, expected_course_overviews) # noqa: PT009
def test_no_pseudo_sessions(self):
# Given no pseudo sessions
@@ -318,7 +318,7 @@ def test_no_pseudo_sessions(self):
course_overviews = get_course_overviews_for_pseudo_sessions(pseudo_sessions)
# Then I should get an empty dict
- self.assertDictEqual(course_overviews, {})
+ self.assertDictEqual(course_overviews, {}) # noqa: PT009
def test_entitlement_without_pseudo_session(self):
# Given an unfulfilled entitlement which does not have a psuedo session
@@ -330,7 +330,7 @@ def test_entitlement_without_pseudo_session(self):
course_overviews = get_course_overviews_for_pseudo_sessions(pseudo_sessions)
# Then I should gracefully return none for that entitlement
- self.assertDictEqual(course_overviews, {})
+ self.assertDictEqual(course_overviews, {}) # noqa: PT009
class TestGetEmailSettingsInfo(SharedModuleStoreTestCase):
@@ -357,12 +357,12 @@ def test_get_email_settings(self, mock_is_bulk_email_enabled):
)
# Then the email settings show for courses where bulk email is enabled
- self.assertSetEqual(
+ self.assertSetEqual( # noqa: PT009
{course.id for course in courses[0:2]}, show_email_settings_for
)
# ... and course optouts are returned
- self.assertSetEqual(
+ self.assertSetEqual( # noqa: PT009
{optout.course_id for optout in optouts},
set(course_optouts),
)
@@ -401,7 +401,7 @@ def test_suggested_courses(self):
return_data = get_suggested_courses()
# Then I return them in the appropriate response
- self.assertDictEqual(return_data, self.MOCK_SUGGESTED_COURSES)
+ self.assertDictEqual(return_data, self.MOCK_SUGGESTED_COURSES) # noqa: PT009
def test_no_suggested_courses(self):
# Given suggested courses are not found/configured
@@ -409,7 +409,7 @@ def test_no_suggested_courses(self):
return_data = get_suggested_courses()
# Then I return them in the appropriate response
- self.assertDictEqual(return_data, self.EMPTY_SUGGESTED_COURSES)
+ self.assertDictEqual(return_data, self.EMPTY_SUGGESTED_COURSES) # noqa: PT009
@ddt.ddt
@@ -624,7 +624,7 @@ def test_email_confirmation(self, mock_user_conf_info):
assert response.status_code == 200
response_data = json.loads(response.content)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_data["emailConfirmation"],
{
"isNeeded": mock_user_conf_info_response["isNeeded"],
@@ -662,7 +662,7 @@ def test_get_cert_statuses(self, mock_get_cert_info):
assert response.status_code == 200
response_data = json.loads(response.content)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_data["courses"][0]["certificate"],
{
"availableDate": mock_enrollment.course.certificate_available_date,
@@ -682,7 +682,7 @@ def test_get_cert_statuses_exception(self, mock_get_cert_info):
self.log_in()
# (and we have tons of mocks to avoid integration tests)
- mock_enrollment = create_test_enrollment(
+ mock_enrollment = create_test_enrollment( # noqa: F841
self.user, course_mode=CourseMode.VERIFIED
)
@@ -705,7 +705,7 @@ def test_get_cert_statuses_exception(self, mock_get_cert_info):
}
# with empty cert data instead of a break
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_data["courses"][0]["certificate"], empty_cert_data
)
diff --git a/lms/djangoapps/learner_home/test_waffle.py b/lms/djangoapps/learner_home/test_waffle.py
index 2beab790aebc..0fb0bafac1d8 100644
--- a/lms/djangoapps/learner_home/test_waffle.py
+++ b/lms/djangoapps/learner_home/test_waffle.py
@@ -35,4 +35,4 @@ def test_learner_home_mfe_enabled(
is_learner_home_enabled = learner_home_mfe_enabled()
# Then I respects waffle setting.
- self.assertEqual(is_learner_home_enabled, is_waffle_enabled)
+ self.assertEqual(is_learner_home_enabled, is_waffle_enabled) # noqa: PT009
diff --git a/lms/djangoapps/learner_home/utils.py b/lms/djangoapps/learner_home/utils.py
index ad873e1dce91..2099d626917f 100644
--- a/lms/djangoapps/learner_home/utils.py
+++ b/lms/djangoapps/learner_home/utils.py
@@ -40,7 +40,7 @@ def get_masquerade_user(request):
try:
masquerade_user = get_user_by_username_or_email(masquerade_identifier)
except User.DoesNotExist:
- raise NotFound() # pylint: disable=raise-missing-from
+ raise NotFound() # pylint: disable=raise-missing-from # noqa: B904
except MultipleObjectsReturned:
msg = (
f"[Learner Home] {masquerade_identifier} could refer to multiple learners. "
diff --git a/lms/djangoapps/lms_xblock/runtime.py b/lms/djangoapps/lms_xblock/runtime.py
index c902bf8c35fe..c09376cddf93 100644
--- a/lms/djangoapps/lms_xblock/runtime.py
+++ b/lms/djangoapps/lms_xblock/runtime.py
@@ -55,7 +55,7 @@ def handler_url(block, handler_name, suffix='', query='', thirdparty=False):
# If third-party, return fully-qualified url
if thirdparty:
scheme = "https" if settings.HTTPS == "on" else "http"
- url = '{scheme}://{host}{path}'.format(
+ url = '{scheme}://{host}{path}'.format( # noqa: UP032
scheme=scheme,
host=settings.SITE_NAME,
path=url
diff --git a/lms/djangoapps/lti_provider/apps.py b/lms/djangoapps/lti_provider/apps.py
index d2a01b0308aa..42cd037c2ff0 100644
--- a/lms/djangoapps/lti_provider/apps.py
+++ b/lms/djangoapps/lti_provider/apps.py
@@ -15,4 +15,4 @@ class LtiProviderConfig(AppConfig):
def ready(self):
# Import the tasks module to ensure that signal handlers are registered.
- from . import signals # pylint: disable=unused-import
+ from . import signals # pylint: disable=unused-import # noqa: F401
diff --git a/lms/djangoapps/lti_provider/models.py b/lms/djangoapps/lti_provider/models.py
index 621d2bb8d179..8e73b36db660 100644
--- a/lms/djangoapps/lti_provider/models.py
+++ b/lms/djangoapps/lti_provider/models.py
@@ -23,7 +23,7 @@
log = logging.getLogger("edx.lti_provider")
-class LtiConsumer(models.Model):
+class LtiConsumer(models.Model): # noqa: DJ008
"""
Database model representing an LTI consumer. This model stores the consumer
specific settings, such as the OAuth key/secret pair and any LTI fields
@@ -88,7 +88,7 @@ def get_or_supplement(instance_guid, consumer_key):
return consumer
-class OutcomeService(models.Model):
+class OutcomeService(models.Model): # noqa: DJ008
"""
Model for a single outcome service associated with an LTI consumer. Note
that a given consumer may have more than one outcome service URL over its
@@ -112,7 +112,7 @@ class OutcomeService(models.Model):
lti_consumer = models.ForeignKey(LtiConsumer, on_delete=models.CASCADE)
-class GradedAssignment(models.Model):
+class GradedAssignment(models.Model): # noqa: DJ008
"""
Model representing a single launch of a graded assignment by an individual
user. There will be a row created here only if the LTI consumer may require
@@ -139,7 +139,7 @@ class Meta:
unique_together = ('outcome_service', 'lis_result_sourcedid')
-class LtiUser(models.Model):
+class LtiUser(models.Model): # noqa: DJ008
"""
Model mapping the identity of an LTI user to an account on the edX platform.
The LTI user_id field is guaranteed to be unique per LTI consumer (per
diff --git a/lms/djangoapps/lti_provider/tests/test_outcomes.py b/lms/djangoapps/lti_provider/tests/test_outcomes.py
index 869c0128d6a8..a006ba39645b 100644
--- a/lms/djangoapps/lti_provider/tests/test_outcomes.py
+++ b/lms/djangoapps/lti_provider/tests/test_outcomes.py
@@ -211,7 +211,7 @@ class XmlHandlingTest(TestCase):
score = 0.25
@patch('uuid.uuid4', return_value='random_uuid')
- def test_replace_result_message_uuid(self, _uuid_mock):
+ def test_replace_result_message_uuid(self, _uuid_mock): # noqa: PT019
# Pylint doesn't recognize members in the LXML module
xml = outcomes.generate_replace_result_xml(self.result_id, self.score)
tree = etree.fromstring(xml)
diff --git a/lms/djangoapps/lti_provider/tests/test_users.py b/lms/djangoapps/lti_provider/tests/test_users.py
index e94caae5a688..4ea0c4797ea4 100644
--- a/lms/djangoapps/lti_provider/tests/test_users.py
+++ b/lms/djangoapps/lti_provider/tests/test_users.py
@@ -44,12 +44,12 @@ def setUp(self):
)
@patch('django.contrib.auth.authenticate', return_value=None)
- def test_permission_denied_for_unknown_user(self, _authenticate_mock):
+ def test_permission_denied_for_unknown_user(self, _authenticate_mock): # noqa: PT019
with pytest.raises(PermissionDenied):
users.switch_user(self.request, self.lti_user, self.lti_consumer)
@patch('lms.djangoapps.lti_provider.users.login')
- def test_authenticate_called(self, _login_mock):
+ def test_authenticate_called(self, _login_mock): # noqa: PT019
with patch('lms.djangoapps.lti_provider.users.authenticate', return_value=self.new_user) as authenticate:
users.switch_user(self.request, self.lti_user, self.lti_consumer)
authenticate.assert_called_with(
@@ -117,7 +117,7 @@ def create_lti_user_model(self, consumer=None):
lti_user.save()
return lti_user
- def test_authentication_with_new_user(self, _create_user, switch_user):
+ def test_authentication_with_new_user(self, _create_user, switch_user): # noqa: PT019
lti_user = MagicMock()
lti_user.edx_user_id = self.edx_user_id
with patch('lms.djangoapps.lti_provider.users.create_lti_user', return_value=lti_user) as create_user:
@@ -180,14 +180,14 @@ def test_raise_exception_trying_to_auto_link_unauthenticate_user(self, create_us
request = RequestFactory().post("/")
request.user = AnonymousUser()
- with self.assertRaises(PermissionDenied):
+ with self.assertRaises(PermissionDenied): # noqa: PT027
users.authenticate_lti_user(request, self.lti_user_id, self.auto_linking_consumer)
def test_raise_exception_on_mismatched_user_and_lis_email(self, create_user, switch_user):
request = RequestFactory().post("/", {"lis_person_contact_email_primary": "wrong_email@example.com"})
request.user = self.old_user
- with self.assertRaises(PermissionDenied):
+ with self.assertRaises(PermissionDenied): # noqa: PT027
users.authenticate_lti_user(request, self.lti_user_id, self.auto_linking_consumer)
def test_authenticate_unauthenticated_user_after_auto_linking_of_user_account(self, create_user, switch_user):
@@ -270,7 +270,7 @@ def test_create_lti_user_creates_auth_user_model(self):
@patch('uuid.uuid4', return_value='random_uuid')
@patch('lms.djangoapps.lti_provider.users.generate_random_edx_username', return_value='edx_id')
- def test_create_lti_user_creates_correct_user(self, uuid_mock, _username_mock):
+ def test_create_lti_user_creates_correct_user(self, uuid_mock, _username_mock): # noqa: PT019
users.create_lti_user('lti_user_id', self.lti_consumer)
assert User.objects.count() == 2
user = User.objects.get(username='edx_id')
diff --git a/lms/djangoapps/lti_provider/tests/test_views.py b/lms/djangoapps/lti_provider/tests/test_views.py
index 2332ddc46374..36ab94ead27c 100644
--- a/lms/djangoapps/lti_provider/tests/test_views.py
+++ b/lms/djangoapps/lti_provider/tests/test_views.py
@@ -101,7 +101,7 @@ class LtiLaunchTest(LtiTestMixin, TestCase):
@patch('lms.djangoapps.lti_provider.views.LTI_PROVIDER_LAUNCH_SUCCESS.send_event')
@patch('lms.djangoapps.lti_provider.views.render_courseware')
@patch('lms.djangoapps.lti_provider.views.authenticate_lti_user')
- def test_valid_launch(self, _authenticate, render, lti_launch_success_send_event):
+ def test_valid_launch(self, _authenticate, render, lti_launch_success_send_event): # noqa: PT019
"""
Verifies that the LTI launch succeeds when passed a valid request.
"""
@@ -132,7 +132,7 @@ def test_valid_launch(self, _authenticate, render, lti_launch_success_send_event
@patch('lms.djangoapps.lti_provider.views.render_courseware')
@patch('lms.djangoapps.lti_provider.views.store_outcome_parameters')
@patch('lms.djangoapps.lti_provider.views.authenticate_lti_user')
- def test_valid_launch_with_optional_params(self, _authenticate, store_params, _render):
+ def test_valid_launch_with_optional_params(self, _authenticate, store_params, _render): # noqa: PT019
"""
Verifies that the LTI launch succeeds when passed a valid request.
"""
@@ -148,7 +148,7 @@ def test_valid_launch_with_optional_params(self, _authenticate, store_params, _r
@patch('lms.djangoapps.lti_provider.views.store_outcome_parameters')
@patch('lms.djangoapps.lti_provider.views.authenticate_lti_user')
@override_settings(LTI_CUSTOM_PARAMS=["extra_param1", "extra_param2"])
- def test_valid_launch_with_extra_params(self, _authenticate, store_params, _render):
+ def test_valid_launch_with_extra_params(self, _authenticate, store_params, _render): # noqa: PT019
"""
Verifies that the LTI launch succeeds when passed a valid request.
"""
@@ -163,7 +163,7 @@ def test_valid_launch_with_extra_params(self, _authenticate, store_params, _rend
@patch('lms.djangoapps.courseware.views.views.render_xblock')
@patch('lms.djangoapps.lti_provider.views.authenticate_lti_user')
- def test_render_xblock_params(self, _authenticate, render):
+ def test_render_xblock_params(self, _authenticate, render): # noqa: PT019
"""
Verifies that the LTI renders an XBlock without:
1. Checking the enrollment.
@@ -176,7 +176,7 @@ def test_render_xblock_params(self, _authenticate, render):
@patch('lms.djangoapps.lti_provider.views.render_courseware')
@patch('lms.djangoapps.lti_provider.views.store_outcome_parameters')
@patch('lms.djangoapps.lti_provider.views.authenticate_lti_user')
- def test_outcome_service_registered(self, _authenticate, store_params, _render):
+ def test_outcome_service_registered(self, _authenticate, store_params, _render): # noqa: PT019
"""
Verifies that the LTI launch succeeds when passed a valid request.
"""
@@ -227,7 +227,7 @@ def test_forbidden_if_signature_fails(self):
assert response.status_code == 403
@patch('lms.djangoapps.lti_provider.views.render_courseware')
- def test_lti_consumer_record_supplemented_with_guid(self, _render):
+ def test_lti_consumer_record_supplemented_with_guid(self, _render): # noqa: PT019
self.mock_verify.return_value = False
request = build_launch_request(LTI_OPTIONAL_PARAMS)
diff --git a/lms/djangoapps/lti_provider/urls.py b/lms/djangoapps/lti_provider/urls.py
index d3fdd4e78c74..b4f04f2ca2c0 100644
--- a/lms/djangoapps/lti_provider/urls.py
+++ b/lms/djangoapps/lti_provider/urls.py
@@ -10,7 +10,7 @@
urlpatterns = [
re_path(
- r'^courses/{course_id}/{usage_id}$'.format(
+ r'^courses/{course_id}/{usage_id}$'.format( # noqa: UP032
course_id=settings.COURSE_ID_PATTERN,
usage_id=settings.USAGE_ID_PATTERN
),
diff --git a/lms/djangoapps/lti_provider/views.py b/lms/djangoapps/lti_provider/views.py
index 69f81fb5613b..d86604fe0f91 100644
--- a/lms/djangoapps/lti_provider/views.py
+++ b/lms/djangoapps/lti_provider/views.py
@@ -103,7 +103,7 @@ def lti_launch(request, course_id, usage_id):
usage_id,
request.path
)
- raise Http404() # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404() # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
params['course_key'] = course_key
params['usage_key'] = usage_key
diff --git a/lms/djangoapps/mfe_config_api/tests/test_views.py b/lms/djangoapps/mfe_config_api/tests/test_views.py
index 3081a27553ef..ddfc67498f01 100644
--- a/lms/djangoapps/mfe_config_api/tests/test_views.py
+++ b/lms/djangoapps/mfe_config_api/tests/test_views.py
@@ -53,8 +53,8 @@ def side_effect(key, default=None):
configuration_helpers_mock.get_value.side_effect = side_effect
response = self.client.get(self.mfe_config_api_url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json(), {**default_legacy_config, "EXAMPLE_VAR": "value"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.json(), {**default_legacy_config, "EXAMPLE_VAR": "value"}) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_get_mfe_config_with_queryparam(self, configuration_helpers_mock):
@@ -75,11 +75,11 @@ def side_effect(key, default=None):
configuration_helpers_mock.get_value.side_effect = side_effect
response = self.client.get(f"{self.mfe_config_api_url}?mfe=mymfe")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
calls = [call("MFE_CONFIG", settings.MFE_CONFIG),
call("MFE_CONFIG_OVERRIDES", settings.MFE_CONFIG_OVERRIDES)]
configuration_helpers_mock.get_value.assert_has_calls(calls)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
response.json(), {**default_legacy_config, "EXAMPLE_VAR": "mymfe_value", "OTHER": "other"}
)
@@ -151,11 +151,11 @@ def side_effect(key, default=None):
configuration_helpers_mock.get_value.side_effect = side_effect
response = self.client.get(f"{self.mfe_config_api_url}?mfe=mymfe")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
calls = [call("MFE_CONFIG", settings.MFE_CONFIG),
call("MFE_CONFIG_OVERRIDES", settings.MFE_CONFIG_OVERRIDES)]
configuration_helpers_mock.get_value.assert_has_calls(calls)
- self.assertEqual(response.json(), expected_response)
+ self.assertEqual(response.json(), expected_response) # noqa: PT009
def test_get_mfe_config_from_django_settings(self):
"""Test that when there is no site configuration, the API takes the django settings.
@@ -164,8 +164,8 @@ def test_get_mfe_config_from_django_settings(self):
- The status of the response of the request is a HTTP_200_OK.
- The json response is equal to MFE_CONFIG in lms/envs/test.py"""
response = self.client.get(self.mfe_config_api_url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.json(), default_legacy_config | settings.MFE_CONFIG)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.json(), default_legacy_config | settings.MFE_CONFIG) # noqa: PT009
def test_get_mfe_config_with_queryparam_from_django_settings(self):
"""Test that when there is no site configuration, the API with queryparam takes the django settings.
@@ -175,9 +175,9 @@ def test_get_mfe_config_with_queryparam_from_django_settings(self):
- The json response is equal to MFE_CONFIG merged with MFE_CONFIG_OVERRIDES['mymfe']
"""
response = self.client.get(f"{self.mfe_config_api_url}?mfe=mymfe")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
expected = default_legacy_config | settings.MFE_CONFIG | settings.MFE_CONFIG_OVERRIDES["mymfe"]
- self.assertEqual(response.json(), expected)
+ self.assertEqual(response.json(), expected) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
@override_settings(ENABLE_MFE_CONFIG_API=False)
@@ -190,7 +190,7 @@ def test_404_get_mfe_config(self, configuration_helpers_mock):
"""
response = self.client.get(self.mfe_config_api_url)
configuration_helpers_mock.get_value.assert_not_called()
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_get_mfe_config_for_catalog(self, configuration_helpers_mock):
@@ -224,17 +224,17 @@ def side_effect(key, default=None):
configuration_helpers_mock.get_value.side_effect = side_effect
response = self.client.get(f"{self.mfe_config_api_url}?mfe=catalog")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(data["BASE_URL"], "https://catalog.example.com")
- self.assertEqual(data["SOME_SETTING"], "catalog_value")
- self.assertEqual(data["ENABLE_COURSE_SORTING_BY_START_DATE"], True)
- self.assertEqual(data["HOMEPAGE_PROMO_VIDEO_YOUTUBE_ID"], None)
- self.assertEqual(data["HOMEPAGE_COURSE_MAX"], 8)
- self.assertEqual(data["COURSE_ABOUT_TWITTER_ACCOUNT"], "@TestAccount")
- self.assertEqual(data["NON_BROWSABLE_COURSES"], True)
- self.assertEqual(data["ENABLE_COURSE_DISCOVERY"], False)
+ self.assertEqual(data["BASE_URL"], "https://catalog.example.com") # noqa: PT009
+ self.assertEqual(data["SOME_SETTING"], "catalog_value") # noqa: PT009
+ self.assertEqual(data["ENABLE_COURSE_SORTING_BY_START_DATE"], True) # noqa: PT009
+ self.assertEqual(data["HOMEPAGE_PROMO_VIDEO_YOUTUBE_ID"], None) # noqa: PT009
+ self.assertEqual(data["HOMEPAGE_COURSE_MAX"], 8) # noqa: PT009
+ self.assertEqual(data["COURSE_ABOUT_TWITTER_ACCOUNT"], "@TestAccount") # noqa: PT009
+ self.assertEqual(data["NON_BROWSABLE_COURSES"], True) # noqa: PT009
+ self.assertEqual(data["ENABLE_COURSE_DISCOVERY"], False) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_config_order_of_precedence(self, configuration_helpers_mock):
@@ -282,44 +282,44 @@ def side_effect(key, default=None):
):
response = self.client.get(f"{self.mfe_config_api_url}?mfe=catalog")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
# MFE_CONFIG_OVERRIDES from site conf (highest precedence)
- self.assertEqual(data["HOMEPAGE_COURSE_MAX"], 15)
+ self.assertEqual(data["HOMEPAGE_COURSE_MAX"], 15) # noqa: PT009
# MFE_CONFIG from site conf takes precedence over plain site configuration and settings
- self.assertEqual(data["ENABLE_COURSE_SORTING_BY_START_DATE"], False)
+ self.assertEqual(data["ENABLE_COURSE_SORTING_BY_START_DATE"], False) # noqa: PT009
# Plain site configuration takes precedence over plain settings
- self.assertEqual(data["HOMEPAGE_PROMO_VIDEO_YOUTUBE_ID"], "site-conf-youtube-id")
+ self.assertEqual(data["HOMEPAGE_PROMO_VIDEO_YOUTUBE_ID"], "site-conf-youtube-id") # noqa: PT009
# Value in original MFE_CONFIG not overridden by catalog config should be preserved
- self.assertEqual(data["PRESERVED_SETTING"], "preserved")
+ self.assertEqual(data["PRESERVED_SETTING"], "preserved") # noqa: PT009
class MfeNameToAppIdTests(SimpleTestCase):
"""Tests for the mfe_name_to_app_id helper."""
def test_simple_name(self):
- self.assertEqual(mfe_name_to_app_id("authn"), "org.openedx.frontend.app.authn")
+ self.assertEqual(mfe_name_to_app_id("authn"), "org.openedx.frontend.app.authn") # noqa: PT009
def test_kebab_case_name(self):
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
mfe_name_to_app_id("learner-dashboard"),
"org.openedx.frontend.app.learnerDashboard",
)
def test_mapped_alias(self):
"""course-authoring is an alias for authoring in the explicit map."""
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
mfe_name_to_app_id("course-authoring"),
"org.openedx.frontend.app.authoring",
)
def test_fallback_for_unknown_name(self):
"""Unknown names fall back to programmatic kebab-to-camelCase conversion."""
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
mfe_name_to_app_id("admin-portal-enterprise"),
"org.openedx.frontend.app.adminPortalEnterprise",
)
@@ -337,7 +337,7 @@ def setUp(self):
def test_404_when_disabled(self):
"""API returns 404 when ENABLE_MFE_CONFIG_API is False."""
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_site_level_keys_translated(self, configuration_helpers_mock):
@@ -366,25 +366,25 @@ def side_effect(key, default=None):
configuration_helpers_mock.get_value.side_effect = side_effect
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
# RequiredSiteConfig
- self.assertEqual(data["siteName"], "Test Site")
- self.assertEqual(data["baseUrl"], "https://apps.example.com")
- self.assertEqual(data["lmsBaseUrl"], "https://courses.example.com")
- self.assertEqual(data["loginUrl"], "https://courses.example.com/login")
- self.assertEqual(data["logoutUrl"], "https://courses.example.com/logout")
+ self.assertEqual(data["siteName"], "Test Site") # noqa: PT009
+ self.assertEqual(data["baseUrl"], "https://apps.example.com") # noqa: PT009
+ self.assertEqual(data["lmsBaseUrl"], "https://courses.example.com") # noqa: PT009
+ self.assertEqual(data["loginUrl"], "https://courses.example.com/login") # noqa: PT009
+ self.assertEqual(data["logoutUrl"], "https://courses.example.com/logout") # noqa: PT009
# OptionalSiteConfig
- self.assertEqual(data["headerLogoImageUrl"], "https://courses.example.com/logo.png")
- self.assertEqual(data["accessTokenCookieName"], "edx-jwt")
- self.assertEqual(data["languagePreferenceCookieName"], "lang-pref")
- self.assertEqual(data["userInfoCookieName"], "edx-user-info")
- self.assertEqual(data["csrfTokenApiPath"], "/csrf/api/v1/token")
- self.assertEqual(data["refreshAccessTokenApiPath"], "/login_refresh")
- self.assertEqual(data["segmentKey"], "abc123")
+ self.assertEqual(data["headerLogoImageUrl"], "https://courses.example.com/logo.png") # noqa: PT009
+ self.assertEqual(data["accessTokenCookieName"], "edx-jwt") # noqa: PT009
+ self.assertEqual(data["languagePreferenceCookieName"], "lang-pref") # noqa: PT009
+ self.assertEqual(data["userInfoCookieName"], "edx-user-info") # noqa: PT009
+ self.assertEqual(data["csrfTokenApiPath"], "/csrf/api/v1/token") # noqa: PT009
+ self.assertEqual(data["refreshAccessTokenApiPath"], "/login_refresh") # noqa: PT009
+ self.assertEqual(data["segmentKey"], "abc123") # noqa: PT009
# LOGOUT_URL also generates an externalRoute for frontend-base
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
data["externalRoutes"],
[{"role": "org.openedx.frontend.role.logout", "url": "https://courses.example.com/logout"}],
)
@@ -410,15 +410,15 @@ def side_effect(key, default=None):
data = response.json()
# Site-level key translated to top level
- self.assertEqual(data["lmsBaseUrl"], "https://courses.example.com")
+ self.assertEqual(data["lmsBaseUrl"], "https://courses.example.com") # noqa: PT009
# Unmapped MFE_CONFIG keys appear in commonAppConfig (not at the top level)
- self.assertNotIn("CREDENTIALS_BASE_URL", data)
+ self.assertNotIn("CREDENTIALS_BASE_URL", data) # noqa: PT009
common = data["commonAppConfig"]
- self.assertEqual(common["CREDENTIALS_BASE_URL"], "https://credentials.example.com")
- self.assertEqual(common["STUDIO_BASE_URL"], "https://studio.example.com")
+ self.assertEqual(common["CREDENTIALS_BASE_URL"], "https://credentials.example.com") # noqa: PT009
+ self.assertEqual(common["STUDIO_BASE_URL"], "https://studio.example.com") # noqa: PT009
# Legacy config keys also appear in commonAppConfig
for legacy_key in default_legacy_config:
- self.assertIn(legacy_key, common)
+ self.assertIn(legacy_key, common) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_apps_from_overrides(self, configuration_helpers_mock):
@@ -448,28 +448,28 @@ def side_effect(key, default=None):
response = self.client.get(self.url)
data = response.json()
- self.assertIn("apps", data)
- self.assertEqual(len(data["apps"]), 2)
+ self.assertIn("apps", data) # noqa: PT009
+ self.assertEqual(len(data["apps"]), 2) # noqa: PT009
# Shared config (unmapped MFE_CONFIG keys + legacy config) is in commonAppConfig.
common = data["commonAppConfig"]
- self.assertEqual(common["SHARED_SETTING"], "shared_value")
+ self.assertEqual(common["SHARED_SETTING"], "shared_value") # noqa: PT009
for legacy_key in default_legacy_config:
- self.assertIn(legacy_key, common)
+ self.assertIn(legacy_key, common) # noqa: PT009
# Apps should be sorted by MFE name; each carries only its own overrides.
authn = data["apps"][0]
- self.assertEqual(authn["appId"], "org.openedx.frontend.app.authn")
- self.assertEqual(authn["config"]["ALLOW_PUBLIC_ACCOUNT_CREATION"], True)
- self.assertIsNone(authn["config"]["ACTIVATION_EMAIL_SUPPORT_LINK"])
+ self.assertEqual(authn["appId"], "org.openedx.frontend.app.authn") # noqa: PT009
+ self.assertEqual(authn["config"]["ALLOW_PUBLIC_ACCOUNT_CREATION"], True) # noqa: PT009
+ self.assertIsNone(authn["config"]["ACTIVATION_EMAIL_SUPPORT_LINK"]) # noqa: PT009
# Shared keys are NOT duplicated into per-app config
- self.assertNotIn("SHARED_SETTING", authn["config"])
+ self.assertNotIn("SHARED_SETTING", authn["config"]) # noqa: PT009
dashboard = data["apps"][1]
- self.assertEqual(dashboard["appId"], "org.openedx.frontend.app.learnerDashboard")
- self.assertEqual(dashboard["config"]["LEARNING_BASE_URL"], "http://apps.local.openedx.io:2000")
- self.assertEqual(dashboard["config"]["ENABLE_PROGRAMS"], False)
- self.assertNotIn("SHARED_SETTING", dashboard["config"])
+ self.assertEqual(dashboard["appId"], "org.openedx.frontend.app.learnerDashboard") # noqa: PT009
+ self.assertEqual(dashboard["config"]["LEARNING_BASE_URL"], "http://apps.local.openedx.io:2000") # noqa: PT009
+ self.assertEqual(dashboard["config"]["ENABLE_PROGRAMS"], False) # noqa: PT009
+ self.assertNotIn("SHARED_SETTING", dashboard["config"]) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_app_overrides_separate_from_common(self, configuration_helpers_mock):
@@ -485,8 +485,8 @@ def side_effect(key, default=None):
response = self.client.get(self.url)
data = response.json()
- self.assertEqual(data["commonAppConfig"]["SOME_KEY"], "base_value")
- self.assertEqual(data["apps"][0]["config"]["SOME_KEY"], "overridden_value")
+ self.assertEqual(data["commonAppConfig"]["SOME_KEY"], "base_value") # noqa: PT009
+ self.assertEqual(data["apps"][0]["config"]["SOME_KEY"], "overridden_value") # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_site_level_keys_stripped_from_app_overrides(self, configuration_helpers_mock):
@@ -513,13 +513,13 @@ def side_effect(key, default=None):
app_config = data["apps"][0]["config"]
# Site-level keys from overrides must not appear in app config
- self.assertNotIn("BASE_URL", app_config)
- self.assertNotIn("LOGIN_URL", app_config)
+ self.assertNotIn("BASE_URL", app_config) # noqa: PT009
+ self.assertNotIn("LOGIN_URL", app_config) # noqa: PT009
# Non-site-level override keys are kept
- self.assertEqual(app_config["APP_SPECIFIC_KEY"], "app_value")
+ self.assertEqual(app_config["APP_SPECIFIC_KEY"], "app_value") # noqa: PT009
# Site-level keys from overrides also must not appear in commonAppConfig
- self.assertNotIn("BASE_URL", data["commonAppConfig"])
- self.assertNotIn("LOGIN_URL", data["commonAppConfig"])
+ self.assertNotIn("BASE_URL", data["commonAppConfig"]) # noqa: PT009
+ self.assertNotIn("LOGIN_URL", data["commonAppConfig"]) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_no_apps_when_no_overrides(self, configuration_helpers_mock):
@@ -535,11 +535,11 @@ def side_effect(key, default=None):
response = self.client.get(self.url)
data = response.json()
- self.assertNotIn("apps", data)
+ self.assertNotIn("apps", data) # noqa: PT009
# commonAppConfig is still present with legacy keys
- self.assertIn("commonAppConfig", data)
+ self.assertIn("commonAppConfig", data) # noqa: PT009
for legacy_key in default_legacy_config:
- self.assertIn(legacy_key, data["commonAppConfig"])
+ self.assertIn(legacy_key, data["commonAppConfig"]) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_unmapped_keys_in_common_app_config_without_overrides(self, configuration_helpers_mock):
@@ -560,11 +560,11 @@ def side_effect(key, default=None):
data = response.json()
# Site-level key is promoted to the top level
- self.assertEqual(data["lmsBaseUrl"], "https://courses.example.com")
+ self.assertEqual(data["lmsBaseUrl"], "https://courses.example.com") # noqa: PT009
# Unmapped keys are preserved in commonAppConfig
common = data["commonAppConfig"]
- self.assertEqual(common["CREDENTIALS_BASE_URL"], "https://credentials.example.com")
- self.assertEqual(common["STUDIO_BASE_URL"], "https://studio.example.com")
+ self.assertEqual(common["CREDENTIALS_BASE_URL"], "https://credentials.example.com") # noqa: PT009
+ self.assertEqual(common["STUDIO_BASE_URL"], "https://studio.example.com") # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_invalid_override_entry_skipped(self, configuration_helpers_mock):
@@ -585,34 +585,34 @@ def side_effect(key, default=None):
response = self.client.get(self.url)
data = response.json()
- self.assertEqual(len(data["apps"]), 1)
- self.assertEqual(data["apps"][0]["appId"], "org.openedx.frontend.app.authn")
+ self.assertEqual(len(data["apps"]), 1) # noqa: PT009
+ self.assertEqual(data["apps"][0]["appId"], "org.openedx.frontend.app.authn") # noqa: PT009
def test_from_django_settings(self):
"""When there is no site configuration, the API uses django settings."""
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
# settings.MFE_CONFIG in test.py has LANGUAGE_PREFERENCE_COOKIE_NAME and LOGO_URL
- self.assertEqual(data.get("languagePreferenceCookieName"), "example-language-preference")
- self.assertEqual(data.get("headerLogoImageUrl"), "https://courses.example.com/logo.png")
+ self.assertEqual(data.get("languagePreferenceCookieName"), "example-language-preference") # noqa: PT009
+ self.assertEqual(data.get("headerLogoImageUrl"), "https://courses.example.com/logo.png") # noqa: PT009
# Legacy config keys live in commonAppConfig
for legacy_key in default_legacy_config:
- self.assertIn(legacy_key, data["commonAppConfig"])
+ self.assertIn(legacy_key, data["commonAppConfig"]) # noqa: PT009
# MFE_CONFIG_OVERRIDES in test.py has mymfe and yourmfe
- self.assertIn("apps", data)
+ self.assertIn("apps", data) # noqa: PT009
app_ids = [app["appId"] for app in data["apps"]]
- self.assertIn("org.openedx.frontend.app.mymfe", app_ids)
- self.assertIn("org.openedx.frontend.app.yourmfe", app_ids)
+ self.assertIn("org.openedx.frontend.app.mymfe", app_ids) # noqa: PT009
+ self.assertIn("org.openedx.frontend.app.yourmfe", app_ids) # noqa: PT009
# Site-level keys from overrides (LANGUAGE_PREFERENCE_COOKIE_NAME,
# LOGO_URL in test settings) are stripped from per-app config
for app in data["apps"]:
- self.assertNotIn("LANGUAGE_PREFERENCE_COOKIE_NAME", app["config"])
- self.assertNotIn("LOGO_URL", app["config"])
+ self.assertNotIn("LANGUAGE_PREFERENCE_COOKIE_NAME", app["config"]) # noqa: PT009
+ self.assertNotIn("LOGO_URL", app["config"]) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_frontend_site_config_overrides_translated(self, configuration_helpers_mock):
@@ -640,11 +640,11 @@ def side_effect(key, default=None):
data = response.json()
# Translated value is overridden by FRONTEND_SITE_CONFIG
- self.assertEqual(data["logoutUrl"], "https://courses.example.com/custom-logout")
+ self.assertEqual(data["logoutUrl"], "https://courses.example.com/custom-logout") # noqa: PT009
# Translated value not in FRONTEND_SITE_CONFIG is preserved
- self.assertEqual(data["loginUrl"], "https://courses.example.com/login")
+ self.assertEqual(data["loginUrl"], "https://courses.example.com/login") # noqa: PT009
# New keys from FRONTEND_SITE_CONFIG are included
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
data["externalRoutes"],
[{"role": "learnerDashboard", "url": "https://courses.example.com/dashboard"}],
)
@@ -675,12 +675,12 @@ def side_effect(key, default=None):
common = data["commonAppConfig"]
# FRONTEND_SITE_CONFIG overrides individual keys
- self.assertEqual(common["CREDENTIALS_BASE_URL"], "https://new-credentials.example.com")
+ self.assertEqual(common["CREDENTIALS_BASE_URL"], "https://new-credentials.example.com") # noqa: PT009
# New keys from FRONTEND_SITE_CONFIG are added
- self.assertEqual(common["NEW_KEY"], "new_value")
+ self.assertEqual(common["NEW_KEY"], "new_value") # noqa: PT009
# Legacy translated keys are preserved
for legacy_key in default_legacy_config:
- self.assertIn(legacy_key, common)
+ self.assertIn(legacy_key, common) # noqa: PT009
@patch("lms.djangoapps.mfe_config_api.views.configuration_helpers")
def test_frontend_site_config_deep_merges_apps(self, configuration_helpers_mock):
@@ -714,9 +714,9 @@ def side_effect(key, default=None):
apps_by_id = {app["appId"]: app for app in data["apps"]}
# Existing app's config is merged, not replaced
authn = apps_by_id["org.openedx.frontend.app.authn"]["config"]
- self.assertEqual(authn["LEGACY_KEY"], "legacy_value")
- self.assertEqual(authn["SHARED_KEY"], "new_value")
- self.assertEqual(authn["NEW_KEY"], "added")
+ self.assertEqual(authn["LEGACY_KEY"], "legacy_value") # noqa: PT009
+ self.assertEqual(authn["SHARED_KEY"], "new_value") # noqa: PT009
+ self.assertEqual(authn["NEW_KEY"], "added") # noqa: PT009
# Brand new app from FRONTEND_SITE_CONFIG is appended
brand_new = apps_by_id["org.openedx.frontend.app.brand.new"]["config"]
- self.assertEqual(brand_new["BRAND_NEW_KEY"], "value")
+ self.assertEqual(brand_new["BRAND_NEW_KEY"], "value") # noqa: PT009
diff --git a/lms/djangoapps/mobile_api/course_info/serializers.py b/lms/djangoapps/mobile_api/course_info/serializers.py
index 8e32d2c5b14d..2600afa25170 100644
--- a/lms/djangoapps/mobile_api/course_info/serializers.py
+++ b/lms/djangoapps/mobile_api/course_info/serializers.py
@@ -2,7 +2,7 @@
Course Info serializers
"""
-from typing import Dict, Union
+from typing import Dict, Union # noqa: UP035
from rest_framework import serializers
from rest_framework.reverse import reverse
@@ -82,7 +82,7 @@ def get_course_modes(self, course_overview):
for mode in course_modes
]
- def get_course_progress(self, obj: CourseOverview) -> Dict[str, int]:
+ def get_course_progress(self, obj: CourseOverview) -> Dict[str, int]: # noqa: UP006
"""
Gets course progress calculated by course completed assignments.
"""
@@ -132,7 +132,7 @@ def get_is_staff(self, data: dict) -> bool:
"""
return any(administrative_accesses_to_course_for_user(data.get('user'), data.get('course_id')))
- def get_audit_access_expires(self, data: dict) -> Union[str, None]:
+ def get_audit_access_expires(self, data: dict) -> Union[str, None]: # noqa: UP007
"""
Returns expiration date for a course audit expiration, if any or null
"""
diff --git a/lms/djangoapps/mobile_api/course_info/views.py b/lms/djangoapps/mobile_api/course_info/views.py
index 93984babd011..b8791327db2d 100644
--- a/lms/djangoapps/mobile_api/course_info/views.py
+++ b/lms/djangoapps/mobile_api/course_info/views.py
@@ -3,7 +3,7 @@
"""
import logging
-from typing import Dict, List, Optional, Union
+from typing import Dict, List, Optional, Union # noqa: UP035
import django
from django.contrib.auth import get_user_model
@@ -39,7 +39,7 @@
User = get_user_model()
log = logging.getLogger(__name__)
-UserType = Union[django.contrib.auth.models.User, django.contrib.auth.models.AnonymousUser, StudentUser]
+UserType = Union[django.contrib.auth.models.User, django.contrib.auth.models.AnonymousUser, StudentUser] # noqa: UP007
@mobile_view()
@@ -178,7 +178,7 @@ def post(self, request, *args, **kwargs):
)
if not ENABLE_COURSE_GOALS.is_enabled(course_key):
- log.warning('For this mobile request, user activity is not enabled for this user {} and course {}'.format(
+ log.warning('For this mobile request, user activity is not enabled for this user {} and course {}'.format( # noqa: UP032 # pylint: disable=line-too-long
str(user_id), str(course_key))
)
return Response(status=(200))
@@ -291,7 +291,7 @@ class BlocksInfoInCourseView(BlocksInCourseView):
* 404 if the course is not available or cannot be seen.
"""
- def get_requested_user(self, user: UserType, username: Optional[str] = None) -> Union[UserType, None]:
+ def get_requested_user(self, user: UserType, username: Optional[str] = None) -> Union[UserType, None]: # noqa: UP007, UP045 # pylint: disable=line-too-long
"""
Return a user for whom the course blocks are fetched.
@@ -387,7 +387,7 @@ def _extend_sequential_info_with_assignment_progress(
self,
requested_user: User,
course_id: CourseKey,
- blocks_info_data: Dict[str, Dict],
+ blocks_info_data: Dict[str, Dict], # noqa: UP006
) -> None:
"""
Extends sequential xblock info with assignment's name and progress.
@@ -422,7 +422,7 @@ def _extend_sequential_info_with_assignment_progress(
)
@staticmethod
- def _id_to_label(section_breakdown: List[Dict]) -> Dict[str, str]:
+ def _id_to_label(section_breakdown: List[Dict]) -> Dict[str, str]: # noqa: UP006
"""
Get `sequential_id` to assignment `label` mapping.
"""
diff --git a/lms/djangoapps/mobile_api/decorators.py b/lms/djangoapps/mobile_api/decorators.py
index ea309ce23f15..fc6f53223f0c 100644
--- a/lms/djangoapps/mobile_api/decorators.py
+++ b/lms/djangoapps/mobile_api/decorators.py
@@ -54,8 +54,8 @@ def _wrapper(self, request, *args, **kwargs):
if error.access_error is not None:
return Response(data=error.access_error.to_json(), status=status.HTTP_404_NOT_FOUND)
# Raise a 404 if the user does not have course access
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
- return func(self, request, course=course, *args, **kwargs)
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
+ return func(self, request, course=course, *args, **kwargs) # noqa: B026
return _wrapper
return _decorator
diff --git a/lms/djangoapps/mobile_api/mobile_platform.py b/lms/djangoapps/mobile_api/mobile_platform.py
index 4eb722418d8a..ab177e75f83c 100644
--- a/lms/djangoapps/mobile_api/mobile_platform.py
+++ b/lms/djangoapps/mobile_api/mobile_platform.py
@@ -7,7 +7,7 @@
import re
-class MobilePlatform(metaclass=abc.ABCMeta):
+class MobilePlatform(metaclass=abc.ABCMeta): # noqa: B024
"""
MobilePlatform class creates an instance of platform based on user agent and supports platform
related operations.
@@ -79,7 +79,7 @@ def get_user_app_platform(cls, user_agent, user_agent_regex):
sub_regex = r'(3172)(; OS Version [0-9.]+ \(Build [0-9a-zA-Z]*\)\))'
user_agent = re.sub(sub_regex, r'2.26.3\2', user_agent)
- return super(IOS, cls).get_user_app_platform(user_agent, user_agent_regex)
+ return super(IOS, cls).get_user_app_platform(user_agent, user_agent_regex) # noqa: UP008
class Android(MobilePlatform):
diff --git a/lms/djangoapps/mobile_api/models.py b/lms/djangoapps/mobile_api/models.py
index c80126996ace..2f4b51d3503e 100644
--- a/lms/djangoapps/mobile_api/models.py
+++ b/lms/djangoapps/mobile_api/models.py
@@ -82,7 +82,7 @@ def last_supported_date(cls, platform, version):
if utils.parsed_version(config.version) >= parsed_version:
return config.expire_at
- def save(self, *args, **kwargs): # lint-amnesty, pylint: disable=signature-differs
+ def save(self, *args, **kwargs): # lint-amnesty, pylint: disable=signature-differs # noqa: DJ012
""" parses version into major, minor and patch versions before saving """
self.major_version, self.minor_version, self.patch_version = utils.parsed_version(self.version)
super().save(*args, **kwargs)
diff --git a/lms/djangoapps/mobile_api/tests/test_course_info_serializers.py b/lms/djangoapps/mobile_api/tests/test_course_info_serializers.py
index 03044b377743..78a727832aff 100644
--- a/lms/djangoapps/mobile_api/tests/test_course_info_serializers.py
+++ b/lms/djangoapps/mobile_api/tests/test_course_info_serializers.py
@@ -1,7 +1,7 @@
"""
Tests for serializers for the Mobile Course Info
"""
-from typing import Dict, List, Tuple, Union
+from typing import Dict, List, Tuple, Union # noqa: UP035
from unittest.mock import MagicMock, Mock, patch
import ddt
@@ -31,7 +31,7 @@ def setUp(self):
@patch('lms.djangoapps.mobile_api.course_info.serializers.get_pre_requisite_courses_not_completed')
def test_has_unmet_prerequisites(
self,
- mock_return_value: List[Dict],
+ mock_return_value: List[Dict], # noqa: UP006
has_unmet_prerequisites: bool,
mock_get_prerequisites: MagicMock,
) -> None:
@@ -43,7 +43,7 @@ def test_has_unmet_prerequisites(
'course_id': self.course.id,
}).data
- self.assertEqual(output_data['has_unmet_prerequisites'], has_unmet_prerequisites)
+ self.assertEqual(output_data['has_unmet_prerequisites'], has_unmet_prerequisites) # noqa: PT009
mock_get_prerequisites.assert_called_once_with(self.user, [self.course.id])
@ddt.data(
@@ -66,7 +66,7 @@ def test_is_too_early(
'course_id': self.course.id
}).data
- self.assertEqual(output_data['is_too_early'], is_too_early)
+ self.assertEqual(output_data['is_too_early'], is_too_early) # noqa: PT009
mock_check_course_open.assert_called_once_with(self.user, self.course)
@ddt.data(
@@ -78,7 +78,7 @@ def test_is_too_early(
@patch('lms.djangoapps.mobile_api.course_info.serializers.administrative_accesses_to_course_for_user')
def test_is_staff(
self,
- mock_return_value: Tuple[bool],
+ mock_return_value: Tuple[bool], # noqa: UP006
is_staff: bool,
mock_administrative_access: MagicMock,
) -> None:
@@ -90,14 +90,14 @@ def test_is_staff(
'course_id': self.course.id
}).data
- self.assertEqual(output_data['is_staff'], is_staff)
+ self.assertEqual(output_data['is_staff'], is_staff) # noqa: PT009
mock_administrative_access.assert_called_once_with(self.user, self.course.id)
@ddt.data(None, 'mocked_user_course_expiration_date')
@patch('lms.djangoapps.mobile_api.course_info.serializers.get_user_course_expiration_date')
def test_get_audit_access_expires(
self,
- mock_return_value: Union[str, None],
+ mock_return_value: Union[str, None], # noqa: UP007
mock_get_user_course_expiration_date: MagicMock,
) -> None:
mock_get_user_course_expiration_date.return_value = mock_return_value
@@ -108,7 +108,7 @@ def test_get_audit_access_expires(
'course_id': self.course.id
}).data
- self.assertEqual(output_data['audit_access_expires'], mock_return_value)
+ self.assertEqual(output_data['audit_access_expires'], mock_return_value) # noqa: PT009
mock_get_user_course_expiration_date.assert_called_once_with(self.user, self.course)
@patch('lms.djangoapps.mobile_api.course_info.serializers.has_access')
@@ -129,7 +129,7 @@ def test_get_courseware_access(self, mock_has_access: MagicMock) -> None:
'course_id': self.course.id
}).data
- self.assertDictEqual(output_data['courseware_access'], mocked_access)
+ self.assertDictEqual(output_data['courseware_access'], mocked_access) # noqa: PT009
mock_has_access.assert_called_once_with(self.user, 'load_mobile', self.course)
mock_has_access.return_value.to_json.assert_called_once_with()
@@ -148,11 +148,11 @@ def setUp(self):
def test_get_media(self, get_assignments_completions_mock: MagicMock) -> None:
output_data = CourseInfoOverviewSerializer(self.course_overview, context={'user': self.user}).data
- self.assertIn('media', output_data)
- self.assertIn('image', output_data['media'])
- self.assertIn('raw', output_data['media']['image'])
- self.assertIn('small', output_data['media']['image'])
- self.assertIn('large', output_data['media']['image'])
+ self.assertIn('media', output_data) # noqa: PT009
+ self.assertIn('image', output_data['media']) # noqa: PT009
+ self.assertIn('raw', output_data['media']['image']) # noqa: PT009
+ self.assertIn('small', output_data['media']['image']) # noqa: PT009
+ self.assertIn('large', output_data['media']['image']) # noqa: PT009
@patch('lms.djangoapps.mobile_api.course_info.serializers.get_assignments_completions')
@patch(
@@ -166,7 +166,7 @@ def test_get_course_sharing_utm_parameters(
) -> None:
output_data = CourseInfoOverviewSerializer(self.course_overview, context={'user': self.user}).data
- self.assertEqual(output_data['course_about'], mock_get_link_for_about_page.return_value)
+ self.assertEqual(output_data['course_about'], mock_get_link_for_about_page.return_value) # noqa: PT009
mock_get_link_for_about_page.assert_called_once_with(self.course_overview)
@patch('lms.djangoapps.mobile_api.course_info.serializers.get_assignments_completions')
@@ -175,7 +175,7 @@ def test_get_course_modes(self, get_assignments_completions_mock: MagicMock) ->
output_data = CourseInfoOverviewSerializer(self.course_overview, context={'user': self.user}).data
- self.assertListEqual(output_data['course_modes'], expected_course_modes)
+ self.assertListEqual(output_data['course_modes'], expected_course_modes) # noqa: PT009
@patch('lms.djangoapps.courseware.courses.get_course_assignments')
def test_get_course_progress_no_assignments(self, get_course_assignment_mock: MagicMock) -> None:
@@ -183,8 +183,8 @@ def test_get_course_progress_no_assignments(self, get_course_assignment_mock: Ma
output_data = CourseInfoOverviewSerializer(self.course_overview, context={'user': self.user}).data
- self.assertIn('course_progress', output_data)
- self.assertDictEqual(output_data['course_progress'], expected_course_progress)
+ self.assertIn('course_progress', output_data) # noqa: PT009
+ self.assertDictEqual(output_data['course_progress'], expected_course_progress) # noqa: PT009
get_course_assignment_mock.assert_called_once_with(
self.course_overview.id, self.user, include_without_due=True
)
@@ -199,8 +199,8 @@ def test_get_course_progress_with_assignments(self, get_course_assignment_mock:
output_data = CourseInfoOverviewSerializer(self.course_overview, context={'user': self.user}).data
- self.assertIn('course_progress', output_data)
- self.assertDictEqual(output_data['course_progress'], expected_course_progress)
+ self.assertIn('course_progress', output_data) # noqa: PT009
+ self.assertDictEqual(output_data['course_progress'], expected_course_progress) # noqa: PT009
get_course_assignment_mock.assert_called_once_with(
self.course_overview.id, self.user, include_without_due=True
)
diff --git a/lms/djangoapps/mobile_api/tests/test_course_info_utils.py b/lms/djangoapps/mobile_api/tests/test_course_info_utils.py
index e0c3ead08c03..e474556bce0d 100644
--- a/lms/djangoapps/mobile_api/tests/test_course_info_utils.py
+++ b/lms/djangoapps/mobile_api/tests/test_course_info_utils.py
@@ -38,4 +38,4 @@ def test_get_certificate(self, certificate_status_return, expected_output, mock_
certificate_info = get_user_certificate_download_url(
request, self.user, 'course-v1:Test+T101+2021_T1'
)
- self.assertEqual(certificate_info, expected_output)
+ self.assertEqual(certificate_info, expected_output) # noqa: PT009
diff --git a/lms/djangoapps/mobile_api/tests/test_course_info_views.py b/lms/djangoapps/mobile_api/tests/test_course_info_views.py
index 91edc665805c..addb88335017 100644
--- a/lms/djangoapps/mobile_api/tests/test_course_info_views.py
+++ b/lms/djangoapps/mobile_api/tests/test_course_info_views.py
@@ -263,7 +263,7 @@ def test_flag_disabled(self, mock_logger):
response = self.client.post(self.apiUrl, post_data)
assert response.status_code == 200
mock_logger.warning.assert_called_with(
- 'For this mobile request, user activity is not enabled for this user {} and course {}'.format(
+ 'For this mobile request, user activity is not enabled for this user {} and course {}'.format( # noqa: UP032 # pylint: disable=line-too-long
str(self.user.id), str(self.course.id))
)
@@ -315,11 +315,11 @@ def test_get_requested_user(self, user_role, username, expected_username, mock_g
result_user = BlocksInfoInCourseView().get_requested_user(self.request.user, username)
if expected_username:
- self.assertEqual(result_user.username, expected_username)
+ self.assertEqual(result_user.username, expected_username) # noqa: PT009
if username and request_user.username != username:
mock_get.assert_called_with(username=username)
else:
- self.assertIsNone(result_user)
+ self.assertIsNone(result_user) # noqa: PT009
@patch('lms.djangoapps.mobile_api.course_info.utils.certificate_downloadable_status')
def test_additional_info_response(self, mock_certificate_downloadable_status):
@@ -372,8 +372,8 @@ def test_course_access_details(self):
}
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(response.data['course_access_details'], expected_course_access_details)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(response.data['course_access_details'], expected_course_access_details) # noqa: PT009
def test_course_sharing_utm_parameters(self):
response = self.verify_response(url=self.url)
@@ -383,8 +383,8 @@ def test_course_sharing_utm_parameters(self):
'twitter': 'utm_medium=social&utm_campaign=social-sharing-db&utm_source=twitter'
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(response.data['course_sharing_utm_parameters'], expected_course_sharing_utm_parameters)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(response.data['course_sharing_utm_parameters'], expected_course_sharing_utm_parameters) # noqa: PT009 # pylint: disable=line-too-long
def test_course_about_url(self):
response = self.verify_response(url=self.url)
@@ -392,16 +392,16 @@ def test_course_about_url(self):
course_overview = CourseOverview.objects.get(id=self.course.course_id)
expected_course_about_link = get_link_for_about_page(course_overview)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['course_about'], expected_course_about_link)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['course_about'], expected_course_about_link) # noqa: PT009
def test_course_modes(self):
response = self.verify_response(url=self.url)
expected_course_modes = [{'slug': 'audit', 'sku': None, 'android_sku': None, 'ios_sku': None, 'min_price': 0}]
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertListEqual(response.data['course_modes'], expected_course_modes)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertListEqual(response.data['course_modes'], expected_course_modes) # noqa: PT009
def test_extend_sequential_info_with_assignment_progress_get_only_sequential(self) -> None:
response = self.verify_response(url=self.url, params={'block_types_filter': 'sequential'})
@@ -421,17 +421,17 @@ def test_extend_sequential_info_with_assignment_progress_get_only_sequential(sel
},
)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- for sequential_info, assignment_progress in zip(response.data['blocks'].values(), expected_results):
- self.assertDictEqual(sequential_info['assignment_progress'], assignment_progress)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ for sequential_info, assignment_progress in zip(response.data['blocks'].values(), expected_results): # noqa: B905 # pylint: disable=line-too-long
+ self.assertDictEqual(sequential_info['assignment_progress'], assignment_progress) # noqa: PT009
@ddt.data('chapter', 'vertical', 'problem', 'video', 'html')
def test_extend_sequential_info_with_assignment_progress_for_other_types(self, block_type: 'str') -> None:
response = self.verify_response(url=self.url, params={'block_types_filter': block_type})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
for block_info in response.data['blocks'].values():
- self.assertNotEqual('assignment_progress', block_info)
+ self.assertNotEqual('assignment_progress', block_info) # noqa: PT009
class TestCourseEnrollmentDetailsView(MobileAPITestCase, MilestonesTestCaseMixin): # lint-amnesty, pylint: disable=test-inherits-tests
@@ -491,15 +491,15 @@ def verify_course_info_overview(self, response):
'facebook': 'utm_medium=social&utm_campaign=social-sharing-db&utm_source=facebook',
'twitter': 'utm_medium=social&utm_campaign=social-sharing-db&utm_source=twitter'
}
- self.assertDictEqual(course_info['course_sharing_utm_parameters'], expected_course_sharing_utm_parameters)
+ self.assertDictEqual(course_info['course_sharing_utm_parameters'], expected_course_sharing_utm_parameters) # noqa: PT009 # pylint: disable=line-too-long
expected_course_modes = [{'slug': 'audit', 'sku': None, 'android_sku': None, 'ios_sku': None, 'min_price': 0}]
- self.assertListEqual(course_info['course_modes'], expected_course_modes)
+ self.assertListEqual(course_info['course_modes'], expected_course_modes) # noqa: PT009
course_overview = CourseOverview.objects.get(id=self.course.course_id)
expected_course_about_link = get_link_for_about_page(course_overview)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(course_info['course_about'], expected_course_about_link)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(course_info['course_about'], expected_course_about_link) # noqa: PT009
def verify_course_access_details(self, response):
""" Verify access details """
@@ -519,8 +519,8 @@ def verify_course_access_details(self, response):
}
}
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(response.data['course_access_details'], expected_course_access_details)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(response.data['course_access_details'], expected_course_access_details) # noqa: PT009
def verify_certificate(self, response, mock_certificate_downloadable_status):
""" Verify certificate url """
@@ -601,5 +601,5 @@ def test_invalid_course_id(self, mock_certificate_downloadable_status):
response = self.client.get(path=url)
assert response.status_code == 400
- expected_error = "'{}' is not a valid course key.".format(invalid_id)
+ expected_error = "'{}' is not a valid course key.".format(invalid_id) # noqa: UP032
assert response.data['error'] == expected_error
diff --git a/lms/djangoapps/mobile_api/tests/test_model.py b/lms/djangoapps/mobile_api/tests/test_model.py
index 6c2b324817d0..3cdf8d3551b4 100644
--- a/lms/djangoapps/mobile_api/tests/test_model.py
+++ b/lms/djangoapps/mobile_api/tests/test_model.py
@@ -129,7 +129,7 @@ def test_structured_configs(self):
'iap config': 'false iap',
'': 'empty'}
- self.assertDictEqual(configs, expected_result)
+ self.assertDictEqual(configs, expected_result) # noqa: PT009
def test_structured_configs_without_iap_configs(self):
"""Check that configs are structured properly without iap configs"""
@@ -143,4 +143,4 @@ def test_structured_configs_without_iap_configs(self):
'iap config': 'false iap',
'': 'empty'}
- self.assertDictEqual(configs, expected_result)
+ self.assertDictEqual(configs, expected_result) # noqa: PT009
diff --git a/lms/djangoapps/mobile_api/users/serializers.py b/lms/djangoapps/mobile_api/users/serializers.py
index a7ae2707de53..1a05677bfc4a 100644
--- a/lms/djangoapps/mobile_api/users/serializers.py
+++ b/lms/djangoapps/mobile_api/users/serializers.py
@@ -2,7 +2,7 @@
Serializer for user API
"""
-from typing import Dict, List, Optional
+from typing import Dict, List, Optional # noqa: UP035
from completion.exceptions import UnavailableCompletionData
from completion.utilities import get_key_to_last_completed_block
@@ -135,7 +135,7 @@ def get_course_modes(self, obj):
for mode in course_modes
]
- def to_representation(self, instance: CourseEnrollment) -> 'OrderedDict': # lint-amnesty, pylint: disable=unused-variable, line-too-long
+ def to_representation(self, instance: CourseEnrollment) -> 'OrderedDict': # lint-amnesty, pylint: disable=unused-variable, line-too-long # noqa: F821
"""
Override the to_representation method to add the course_status field to the serialized data.
"""
@@ -178,7 +178,7 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.course = modulestore().get_course(self.instance.course.id)
- def get_course_status(self, model: CourseEnrollment) -> Optional[Dict[str, List[str]]]:
+ def get_course_status(self, model: CourseEnrollment) -> Optional[Dict[str, List[str]]]: # noqa: UP006, UP045
"""
Gets course status for the given user's enrollments.
"""
@@ -198,13 +198,13 @@ def get_course_status(self, model: CourseEnrollment) -> Optional[Dict[str, List[
'last_visited_unit_display_name': unit.display_name,
}
- def get_course_progress(self, model: CourseEnrollment) -> Dict[str, int]:
+ def get_course_progress(self, model: CourseEnrollment) -> Dict[str, int]: # noqa: UP006
"""
Returns the progress of the user in the course.
"""
return get_assignments_completions(model.course_id, model.user)
- def get_course_assignments(self, model: CourseEnrollment) -> Dict[str, Optional[List[Dict[str, str]]]]:
+ def get_course_assignments(self, model: CourseEnrollment) -> Dict[str, Optional[List[Dict[str, str]]]]: # noqa: UP006, UP045 # pylint: disable=line-too-long
"""
Returns the future assignment data and past assignments data for the user in the course.
"""
diff --git a/lms/djangoapps/mobile_api/users/tests.py b/lms/djangoapps/mobile_api/users/tests.py
index ae4f7d3c5483..43e32abd9764 100644
--- a/lms/djangoapps/mobile_api/users/tests.py
+++ b/lms/djangoapps/mobile_api/users/tests.py
@@ -311,11 +311,11 @@ def test_filter_by_current_site_orgs(self, api_version, get_current_site_orgs_mo
courses = response.data['enrollments'] if api_version == API_V2 else response.data
# Test for 3 expected courses
- self.assertEqual(len(courses), 3)
+ self.assertEqual(len(courses), 3) # noqa: PT009
# Verify only edX courses are returned
for entry in courses:
- self.assertEqual(entry['course']['org'], 'edX')
+ self.assertEqual(entry['course']['org'], 'edX') # noqa: PT009
def create_enrollment(self, expired):
"""
@@ -416,7 +416,7 @@ def test_enrollment_with_configs(self):
}
response = self.api_response(api_version=API_V2)
- self.assertDictEqual(response.data['configs'], expected_result)
+ self.assertDictEqual(response.data['configs'], expected_result) # noqa: PT009
assert 'enrollments' in response.data
def test_pagination_enrollment(self):
@@ -465,9 +465,9 @@ def test_student_dont_have_enrollments(self):
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_result, response.data)
- self.assertNotIn('primary', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_result, response.data) # noqa: PT009
+ self.assertNotIn('primary', response.data) # noqa: PT009
def test_student_have_one_enrollment(self):
"""
@@ -488,10 +488,10 @@ def test_student_have_one_enrollment(self):
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_enrollments, response.data['enrollments'])
- self.assertIn('primary', response.data)
- self.assertEqual(str(course.id), response.data['primary']['course']['id'])
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_enrollments, response.data['enrollments']) # noqa: PT009
+ self.assertIn('primary', response.data) # noqa: PT009
+ self.assertEqual(str(course.id), response.data['primary']['course']['id']) # noqa: PT009
def test_student_have_two_enrollments(self):
"""
@@ -505,12 +505,12 @@ def test_student_have_two_enrollments(self):
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(len(response.data['enrollments']['results']), 1)
- self.assertEqual(response.data['enrollments']['count'], 1)
- self.assertEqual(response.data['enrollments']['results'][0]['course']['id'], str(course_first.id))
- self.assertIn('primary', response.data)
- self.assertEqual(response.data['primary']['course']['id'], str(course_second.id))
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(len(response.data['enrollments']['results']), 1) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['count'], 1) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['results'][0]['course']['id'], str(course_first.id)) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertIn('primary', response.data) # noqa: PT009
+ self.assertEqual(response.data['primary']['course']['id'], str(course_second.id)) # noqa: PT009
def test_student_have_more_then_ten_enrollments(self):
"""
@@ -525,12 +525,12 @@ def test_student_have_more_then_ten_enrollments(self):
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['enrollments']['count'], 15)
- self.assertEqual(response.data['enrollments']['num_pages'], 3)
- self.assertEqual(len(response.data['enrollments']['results']), 5)
- self.assertIn('primary', response.data)
- self.assertEqual(response.data['primary']['course']['id'], str(latest_enrolment.id))
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['count'], 15) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['num_pages'], 3) # noqa: PT009
+ self.assertEqual(len(response.data['enrollments']['results']), 5) # noqa: PT009
+ self.assertIn('primary', response.data) # noqa: PT009
+ self.assertEqual(response.data['primary']['course']['id'], str(latest_enrolment.id)) # noqa: PT009
def test_student_have_progress_in_old_course_and_enroll_newest_course(self):
"""
@@ -547,12 +547,12 @@ def test_student_have_progress_in_old_course_and_enroll_newest_course(self):
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['enrollments']['count'], 6)
- self.assertEqual(len(response.data['enrollments']['results']), 5)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['count'], 6) # noqa: PT009
+ self.assertEqual(len(response.data['enrollments']['results']), 5) # noqa: PT009
# check that we have the new_course in primary section
- self.assertIn('primary', response.data)
- self.assertEqual(response.data['primary']['course']['id'], str(new_course.id))
+ self.assertIn('primary', response.data) # noqa: PT009
+ self.assertEqual(response.data['primary']['course']['id'], str(new_course.id)) # noqa: PT009
# doing progress in the old_course
StudentModule.objects.create(
@@ -562,12 +562,12 @@ def test_student_have_progress_in_old_course_and_enroll_newest_course(self):
)
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['enrollments']['count'], 6)
- self.assertEqual(len(response.data['enrollments']['results']), 5)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['count'], 6) # noqa: PT009
+ self.assertEqual(len(response.data['enrollments']['results']), 5) # noqa: PT009
# check that now we have the old_course in primary section
- self.assertIn('primary', response.data)
- self.assertEqual(response.data['primary']['course']['id'], str(old_course.id))
+ self.assertIn('primary', response.data) # noqa: PT009
+ self.assertEqual(response.data['primary']['course']['id'], str(old_course.id)) # noqa: PT009
# enroll to the newest course
newest_course = CourseFactory.create(org="edx", mobile_available=True)
@@ -575,12 +575,12 @@ def test_student_have_progress_in_old_course_and_enroll_newest_course(self):
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['enrollments']['count'], 7)
- self.assertEqual(len(response.data['enrollments']['results']), 5)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['count'], 7) # noqa: PT009
+ self.assertEqual(len(response.data['enrollments']['results']), 5) # noqa: PT009
# check that now we have the newest_course in primary section
- self.assertIn('primary', response.data)
- self.assertEqual(response.data['primary']['course']['id'], str(newest_course.id))
+ self.assertIn('primary', response.data) # noqa: PT009
+ self.assertEqual(response.data['primary']['course']['id'], str(newest_course.id)) # noqa: PT009
def test_student_enrolled_only_not_mobile_available_courses(self):
"""
@@ -608,9 +608,9 @@ def test_student_enrolled_only_not_mobile_available_courses(self):
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertDictEqual(expected_result, response.data)
- self.assertNotIn('primary', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertDictEqual(expected_result, response.data) # noqa: PT009
+ self.assertNotIn('primary', response.data) # noqa: PT009
def test_do_progress_in_not_mobile_available_course(self):
"""
@@ -627,12 +627,12 @@ def test_do_progress_in_not_mobile_available_course(self):
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['enrollments']['count'], 5)
- self.assertEqual(len(response.data['enrollments']['results']), 5)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['count'], 5) # noqa: PT009
+ self.assertEqual(len(response.data['enrollments']['results']), 5) # noqa: PT009
# check that we have the new_course in primary section
- self.assertIn('primary', response.data)
- self.assertEqual(response.data['primary']['course']['id'], str(new_course.id))
+ self.assertIn('primary', response.data) # noqa: PT009
+ self.assertEqual(response.data['primary']['course']['id'], str(new_course.id)) # noqa: PT009
# doing progress in the not_mobile_available course
StudentModule.objects.create(
@@ -642,12 +642,12 @@ def test_do_progress_in_not_mobile_available_course(self):
)
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['enrollments']['count'], 5)
- self.assertEqual(len(response.data['enrollments']['results']), 5)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['count'], 5) # noqa: PT009
+ self.assertEqual(len(response.data['enrollments']['results']), 5) # noqa: PT009
# check that we have the new_course in primary section in the same way
- self.assertIn('primary', response.data)
- self.assertEqual(response.data['primary']['course']['id'], str(new_course.id))
+ self.assertIn('primary', response.data) # noqa: PT009
+ self.assertEqual(response.data['primary']['course']['id'], str(new_course.id)) # noqa: PT009
def test_pagination_for_user_enrollments_api_v4(self):
"""
@@ -659,14 +659,14 @@ def test_pagination_for_user_enrollments_api_v4(self):
self.enroll(course.id)
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['enrollments']['count'], 14)
- self.assertEqual(response.data['enrollments']['num_pages'], 3)
- self.assertEqual(response.data['enrollments']['current_page'], 1)
- self.assertEqual(len(response.data['enrollments']['results']), 5)
- self.assertIn('next', response.data['enrollments'])
- self.assertIn('previous', response.data['enrollments'])
- self.assertIn('primary', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['count'], 14) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['num_pages'], 3) # noqa: PT009
+ self.assertEqual(response.data['enrollments']['current_page'], 1) # noqa: PT009
+ self.assertEqual(len(response.data['enrollments']['results']), 5) # noqa: PT009
+ self.assertIn('next', response.data['enrollments']) # noqa: PT009
+ self.assertIn('previous', response.data['enrollments']) # noqa: PT009
+ self.assertIn('primary', response.data) # noqa: PT009
def test_course_status_in_primary_obj_when_student_doesnt_have_progress(self):
"""
@@ -678,8 +678,8 @@ def test_course_status_in_primary_obj_when_student_doesnt_have_progress(self):
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['primary']['course_status'], None)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['primary']['course_status'], None) # noqa: PT009
@patch('lms.djangoapps.mobile_api.users.serializers.get_key_to_last_completed_block')
def test_course_status_in_primary_obj_when_student_have_progress(
@@ -727,8 +727,8 @@ def test_course_status_in_primary_obj_when_student_have_progress(
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['primary']['course_status'], expected_course_status)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['primary']['course_status'], expected_course_status) # noqa: PT009
get_last_completed_block_mock.assert_called_once_with(self.user, course.id)
def test_user_enrollment_api_v4_in_progress_status(self):
@@ -762,11 +762,11 @@ def test_user_enrollment_api_v4_in_progress_status(self):
response = self.api_response(api_version=API_V4, data={'status': EnrollmentStatuses.IN_PROGRESS.value})
enrollments = response.data['enrollments']
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(enrollments['count'], 2)
- self.assertEqual(enrollments['results'][1]['course']['id'], str(actual_course.id))
- self.assertEqual(enrollments['results'][0]['course']['id'], str(infinite_course.id))
- self.assertNotIn('primary', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(enrollments['count'], 2) # noqa: PT009
+ self.assertEqual(enrollments['results'][1]['course']['id'], str(actual_course.id)) # noqa: PT009
+ self.assertEqual(enrollments['results'][0]['course']['id'], str(infinite_course.id)) # noqa: PT009
+ self.assertNotIn('primary', response.data) # noqa: PT009
def test_user_enrollment_api_v4_completed_status(self):
"""
@@ -805,10 +805,10 @@ def test_user_enrollment_api_v4_completed_status(self):
response = self.api_response(api_version=API_V4, data={'status': EnrollmentStatuses.COMPLETED.value})
enrollments = response.data['enrollments']
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(enrollments['count'], 1)
- self.assertEqual(enrollments['results'][0]['course']['id'], str(infinite_course.id))
- self.assertNotIn('primary', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(enrollments['count'], 1) # noqa: PT009
+ self.assertEqual(enrollments['results'][0]['course']['id'], str(infinite_course.id)) # noqa: PT009
+ self.assertNotIn('primary', response.data) # noqa: PT009
def test_user_enrollment_api_v4_expired_status(self):
"""
@@ -840,10 +840,10 @@ def test_user_enrollment_api_v4_expired_status(self):
response = self.api_response(api_version=API_V4, data={'status': EnrollmentStatuses.EXPIRED.value})
enrollments = response.data['enrollments']
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(enrollments['count'], 1)
- self.assertEqual(enrollments['results'][0]['course']['id'], str(old_course.id))
- self.assertNotIn('primary', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(enrollments['count'], 1) # noqa: PT009
+ self.assertEqual(enrollments['results'][0]['course']['id'], str(old_course.id)) # noqa: PT009
+ self.assertNotIn('primary', response.data) # noqa: PT009
def test_user_enrollment_api_v4_expired_course_with_certificate(self):
"""
@@ -876,10 +876,10 @@ def test_user_enrollment_api_v4_expired_course_with_certificate(self):
response = self.api_response(api_version=API_V4, data={'status': EnrollmentStatuses.COMPLETED.value})
enrollments = response.data['enrollments']
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(enrollments['count'], 1)
- self.assertEqual(enrollments['results'][0]['course']['id'], str(expired_course_with_cert.id))
- self.assertNotIn('primary', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(enrollments['count'], 1) # noqa: PT009
+ self.assertEqual(enrollments['results'][0]['course']['id'], str(expired_course_with_cert.id)) # noqa: PT009
+ self.assertNotIn('primary', response.data) # noqa: PT009
def test_user_enrollment_api_v4_status_all(self):
"""
@@ -918,12 +918,12 @@ def test_user_enrollment_api_v4_status_all(self):
response = self.api_response(api_version=API_V4, data={'status': EnrollmentStatuses.ALL.value})
enrollments = response.data['enrollments']
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(enrollments['count'], 3)
- self.assertEqual(enrollments['results'][0]['course']['id'], str(infinite_course.id))
- self.assertEqual(enrollments['results'][1]['course']['id'], str(actual_course.id))
- self.assertEqual(enrollments['results'][2]['course']['id'], str(old_course.id))
- self.assertNotIn('primary', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(enrollments['count'], 3) # noqa: PT009
+ self.assertEqual(enrollments['results'][0]['course']['id'], str(infinite_course.id)) # noqa: PT009
+ self.assertEqual(enrollments['results'][1]['course']['id'], str(actual_course.id)) # noqa: PT009
+ self.assertEqual(enrollments['results'][2]['course']['id'], str(old_course.id)) # noqa: PT009
+ self.assertNotIn('primary', response.data) # noqa: PT009
def test_response_contains_primary_enrollment_assignments_info(self):
self.login()
@@ -932,12 +932,12 @@ def test_response_contains_primary_enrollment_assignments_info(self):
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('course_assignments', response.data['primary'])
- self.assertIn('past_assignments', response.data['primary']['course_assignments'])
- self.assertIn('future_assignments', response.data['primary']['course_assignments'])
- self.assertListEqual(response.data['primary']['course_assignments']['past_assignments'], [])
- self.assertListEqual(response.data['primary']['course_assignments']['future_assignments'], [])
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('course_assignments', response.data['primary']) # noqa: PT009
+ self.assertIn('past_assignments', response.data['primary']['course_assignments']) # noqa: PT009
+ self.assertIn('future_assignments', response.data['primary']['course_assignments']) # noqa: PT009
+ self.assertListEqual(response.data['primary']['course_assignments']['past_assignments'], []) # noqa: PT009
+ self.assertListEqual(response.data['primary']['course_assignments']['future_assignments'], []) # noqa: PT009
@patch('lms.djangoapps.courseware.courses.get_course_assignments', return_value=[])
def test_course_progress_in_primary_enrollment_with_no_assignments(
@@ -951,9 +951,9 @@ def test_course_progress_in_primary_enrollment_with_no_assignments(
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('course_progress', response.data['primary'])
- self.assertDictEqual(response.data['primary']['course_progress'], expected_course_progress)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('course_progress', response.data['primary']) # noqa: PT009
+ self.assertDictEqual(response.data['primary']['course_progress'], expected_course_progress) # noqa: PT009
@patch(
'lms.djangoapps.mobile_api.users.serializers.CourseEnrollmentSerializerModifiedForPrimary'
@@ -981,9 +981,9 @@ def test_course_progress_in_primary_enrollment_with_assignments(
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('course_progress', response.data['primary'])
- self.assertDictEqual(response.data['primary']['course_progress'], expected_course_progress)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('course_progress', response.data['primary']) # noqa: PT009
+ self.assertDictEqual(response.data['primary']['course_progress'], expected_course_progress) # noqa: PT009
@patch('lms.djangoapps.courseware.courses.get_course_assignments')
def test_course_progress_for_secondary_enrollments_no_query_param(
@@ -997,9 +997,9 @@ def test_course_progress_for_secondary_enrollments_no_query_param(
response = self.api_response(api_version=API_V4)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
for enrollment in response.data['enrollments']['results']:
- self.assertNotIn('course_progress', enrollment)
+ self.assertNotIn('course_progress', enrollment) # noqa: PT009
@patch('lms.djangoapps.courseware.courses.get_course_assignments')
def test_course_progress_for_secondary_enrollments_with_query_param(
@@ -1014,10 +1014,10 @@ def test_course_progress_for_secondary_enrollments_with_query_param(
response = self.api_response(api_version=API_V4, data={'requested_fields': 'course_progress'})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
for enrollment in response.data['enrollments']['results']:
- self.assertIn('course_progress', enrollment)
- self.assertDictEqual(enrollment['course_progress'], expected_course_progress)
+ self.assertIn('course_progress', enrollment) # noqa: PT009
+ self.assertDictEqual(enrollment['course_progress'], expected_course_progress) # noqa: PT009
@patch(
'lms.djangoapps.mobile_api.users.serializers.CourseEnrollmentSerializerModifiedForPrimary'
@@ -1046,11 +1046,11 @@ def test_course_progress_for_secondary_enrollments_with_query_param_and_assignme
response = self.api_response(api_version=API_V4, data={'requested_fields': 'course_progress'})
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIn('course_progress', response.data['primary'])
- self.assertDictEqual(response.data['primary']['course_progress'], expected_course_progress)
- self.assertIn('course_progress', response.data['enrollments']['results'][0])
- self.assertDictEqual(response.data['enrollments']['results'][0]['course_progress'], expected_course_progress)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertIn('course_progress', response.data['primary']) # noqa: PT009
+ self.assertDictEqual(response.data['primary']['course_progress'], expected_course_progress) # noqa: PT009
+ self.assertIn('course_progress', response.data['enrollments']['results'][0]) # noqa: PT009
+ self.assertDictEqual(response.data['enrollments']['results'][0]['course_progress'], expected_course_progress) # noqa: PT009 # pylint: disable=line-too-long
@override_settings(MKTG_URLS={'ROOT': 'dummy-root'})
@@ -1087,7 +1087,7 @@ def test_no_certificate(self):
response = self.api_response()
certificate_data = response.data[0]['certificate']
- self.assertDictEqual(certificate_data, {})
+ self.assertDictEqual(certificate_data, {}) # noqa: PT009
@patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': False, 'ENABLE_MKTG_SITE': True})
def test_pdf_certificate_with_html_cert_disabled(self):
@@ -1115,7 +1115,7 @@ def test_web_certificate(self):
response = self.api_response()
certificate_data = response.data[0]['certificate']
- self.assertRegex(
+ self.assertRegex( # noqa: PT009
certificate_data['url'],
r'http.*/certificates/[0-9a-f]{32}'
)
@@ -1353,8 +1353,8 @@ def test_success(self, api_version):
qstwitter = parse_qs('utm_campaign=social-sharing-db&utm_medium=social&utm_source=twitter')
qsfacebook = parse_qs('utm_campaign=social-sharing-db&utm_medium=social&utm_source=facebook')
- self.assertDictEqual(qsfacebook, parse_qs(serialized['course']['course_sharing_utm_parameters']['facebook']))
- self.assertDictEqual(qstwitter, parse_qs(serialized['course']['course_sharing_utm_parameters']['twitter']))
+ self.assertDictEqual(qsfacebook, parse_qs(serialized['course']['course_sharing_utm_parameters']['facebook'])) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertDictEqual(qstwitter, parse_qs(serialized['course']['course_sharing_utm_parameters']['twitter'])) # noqa: PT009 # pylint: disable=line-too-long
@ddt.data(API_V05, API_V1)
def test_with_display_overrides(self, api_version):
@@ -1432,8 +1432,8 @@ def test_no_mobile_available_courses(self) -> None:
response = self.api_response(api_version=API_V1)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertListEqual(response.data, [])
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertListEqual(response.data, []) # noqa: PT009
def test_no_enrollments(self) -> None:
self.login()
@@ -1442,8 +1442,8 @@ def test_no_enrollments(self) -> None:
response = self.api_response(api_version=API_V1)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertListEqual(response.data, [])
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertListEqual(response.data, []) # noqa: PT009
def test_user_have_only_active_enrollments_and_no_completions(self) -> None:
self.login()
@@ -1459,8 +1459,8 @@ def test_user_have_only_active_enrollments_and_no_completions(self) -> None:
{'course_id': str(courses[2].course_id), 'course_name': courses[2].display_name, 'recently_active': True},
]
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertListEqual(response.data, expected_response)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertListEqual(response.data, expected_response) # noqa: PT009
def test_user_have_active_and_inactive_enrollments_and_no_completions(self) -> None:
self.login()
@@ -1482,8 +1482,8 @@ def test_user_have_active_and_inactive_enrollments_and_no_completions(self) -> N
{'course_id': str(old_course.course_id), 'course_name': old_course.display_name, 'recently_active': False}
]
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertListEqual(response.data, expected_response)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertListEqual(response.data, expected_response) # noqa: PT009
@ddt.data(
(27, True),
@@ -1511,8 +1511,8 @@ def test_different_enrollment_dates(self, enrolled_days_ago: int, recently_activ
}
]
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertListEqual(response.data, expected_response)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertListEqual(response.data, expected_response) # noqa: PT009
@ddt.data(
(27, True),
@@ -1554,5 +1554,5 @@ def test_different_completion_dates(self, completed_days_ago: int, recently_acti
}
]
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertListEqual(response.data, expected_response)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertListEqual(response.data, expected_response) # noqa: PT009
diff --git a/lms/djangoapps/mobile_api/users/views.py b/lms/djangoapps/mobile_api/users/views.py
index 8956474d46b4..2509e332ea57 100644
--- a/lms/djangoapps/mobile_api/users/views.py
+++ b/lms/djangoapps/mobile_api/users/views.py
@@ -6,7 +6,7 @@
import datetime
import logging
from functools import cached_property
-from typing import Dict, List, Optional, Set
+from typing import Dict, List, Optional, Set # noqa: UP035
import pytz
from completion.exceptions import UnavailableCompletionData
@@ -29,7 +29,10 @@
from xblock.fields import Scope
from xblock.runtime import KeyValueStore
-from common.djangoapps.student.models import CourseEnrollment, User # lint-amnesty, pylint: disable=reimported
+from common.djangoapps.student.models import ( # lint-amnesty, pylint: disable=reimported # noqa: F811
+ CourseEnrollment,
+ User,
+)
from lms.djangoapps.courseware.access import is_mobile_available_for_user
from lms.djangoapps.courseware.access_utils import ACCESS_GRANTED
from lms.djangoapps.courseware.block_render import get_block_for_descriptor
@@ -473,7 +476,7 @@ def get_user(self) -> User:
"""
return get_object_or_404(User, username=self.kwargs['username'])
- def get_primary_enrollment_by_latest_enrollment_or_progress(self) -> Optional[CourseEnrollment]:
+ def get_primary_enrollment_by_latest_enrollment_or_progress(self) -> Optional[CourseEnrollment]: # noqa: UP045
"""
Gets primary enrollment obj by latest enrollment or latest progress on the course.
"""
@@ -517,7 +520,7 @@ def paginator(self):
Implements solutions from the discussion at
https://www.github.com/encode/django-rest-framework/issues/6397.
"""
- super().paginator # pylint: disable=expression-not-assigned
+ super().paginator # pylint: disable=expression-not-assigned # noqa: B018
api_version = self.kwargs.get('api_version')
if self._paginator is None and api_version == API_V3:
@@ -620,8 +623,8 @@ def _build_enrollments_status_dict(
self,
username: str,
active_status_date: datetime,
- course_ids: Set[CourseLocator],
- ) -> List[Dict[str, bool]]:
+ course_ids: Set[CourseLocator], # noqa: UP006
+ ) -> List[Dict[str, bool]]: # noqa: UP006
"""
Builds list with dictionaries with user's enrolments statuses.
"""
@@ -655,7 +658,7 @@ def _build_enrollments_status_dict(
def _get_course_ids_where_user_has_completions(
username: str,
active_status_date: datetime,
- ) -> Set[CourseLocator]:
+ ) -> Set[CourseLocator]: # noqa: UP006
"""
Gets course keys where user has completions.
"""
diff --git a/lms/djangoapps/ora_staff_grader/mock/utils.py b/lms/djangoapps/ora_staff_grader/mock/utils.py
index 6fd2c328c4bf..f1b29c8fbf9c 100644
--- a/lms/djangoapps/ora_staff_grader/mock/utils.py
+++ b/lms/djangoapps/ora_staff_grader/mock/utils.py
@@ -9,7 +9,7 @@
def read_data_file(file_name):
"""Return data from a JSON file in the /data dir"""
- with open(path.join(DATA_ROOT, file_name), "r") as data_file:
+ with open(path.join(DATA_ROOT, file_name), "r") as data_file: # noqa: UP015
return json.load(data_file)
@@ -54,7 +54,7 @@ def get_submissions(ora_location): # pylint: disable=unused-argument
# For the list view, we don't return grade data
# pylint: disable=unused-variable
- for (submission_id, submission) in submissions.items():
+ for (submission_id, submission) in submissions.items(): # noqa: B007
submission.pop("gradeData")
return submissions
diff --git a/lms/djangoapps/ora_staff_grader/ora_api.py b/lms/djangoapps/ora_staff_grader/ora_api.py
index d958cd15355b..d250a00871f8 100644
--- a/lms/djangoapps/ora_staff_grader/ora_api.py
+++ b/lms/djangoapps/ora_staff_grader/ora_api.py
@@ -83,7 +83,7 @@ def get_submission_info(request, usage_id, submission_uuid):
response = call_xblock_json_handler(request, usage_id, handler_name, data)
if response.status_code != 200:
- details = (
+ details = ( # noqa: F841
json.loads(response.content).get("error", "")
if is_json(response.content)
else ""
diff --git a/lms/djangoapps/ora_staff_grader/tests/test_views.py b/lms/djangoapps/ora_staff_grader/tests/test_views.py
index f457e121eab6..ff6ab2f128c7 100644
--- a/lms/djangoapps/ora_staff_grader/tests/test_views.py
+++ b/lms/djangoapps/ora_staff_grader/tests/test_views.py
@@ -61,7 +61,7 @@ def url_with_params(self, params):
query_dictionary = QueryDict("", mutable=True)
query_dictionary.update(params)
- return "{base_url}?{querystring}".format(
+ return "{base_url}?{querystring}".format( # noqa: UP032
base_url=reverse(self.view_name), querystring=query_dictionary.urlencode()
)
diff --git a/lms/djangoapps/program_enrollments/admin.py b/lms/djangoapps/program_enrollments/admin.py
index 4e48432f5779..52fe638e06f8 100644
--- a/lms/djangoapps/program_enrollments/admin.py
+++ b/lms/djangoapps/program_enrollments/admin.py
@@ -43,7 +43,7 @@ def _pce_pe_id(pce):
"admin:program_enrollments_programenrollment_change",
args=[pe.id],
)
- link_text = "id={pe.id:05} ({pe.status})".format(pe=pe)
+ link_text = "id={pe.id:05} ({pe.status})".format(pe=pe) # noqa: UP032
return format_html("{}", link_url, link_text)
@@ -67,7 +67,7 @@ def _pce_ce(pce):
if not enrollment:
return None
active_string = "Active" if enrollment.is_active else "Inactive"
- return "id={enrollment.id:09} ({active_string})".format(
+ return "id={enrollment.id:09} ({active_string})".format( # noqa: UP032
enrollment=enrollment, active_string=active_string
)
diff --git a/lms/djangoapps/program_enrollments/api/__init__.py b/lms/djangoapps/program_enrollments/api/__init__.py
index afd77d397836..8a356208ab35 100644
--- a/lms/djangoapps/program_enrollments/api/__init__.py
+++ b/lms/djangoapps/program_enrollments/api/__init__.py
@@ -14,30 +14,30 @@
"""
-from .grades import iter_program_course_grades
-from .linking import link_program_enrollment_to_lms_user, link_program_enrollments
+from .grades import iter_program_course_grades # noqa: F401
+from .linking import link_program_enrollment_to_lms_user, link_program_enrollments # noqa: F401
from .reading import (
- fetch_program_course_enrollments,
- fetch_program_course_enrollments_by_students,
- fetch_program_enrollments,
- fetch_program_enrollments_by_student,
- fetch_program_enrollments_by_students,
- get_external_key_by_user_and_course,
- get_org_key_for_program,
- get_program_course_enrollment,
- get_program_enrollment,
- get_provider_slug,
- get_saml_providers_for_organization,
- get_users_by_external_keys,
- get_users_by_external_keys_and_org_key,
- is_course_staff_enrollment,
+ fetch_program_course_enrollments, # noqa: F401
+ fetch_program_course_enrollments_by_students, # noqa: F401
+ fetch_program_enrollments, # noqa: F401
+ fetch_program_enrollments_by_student, # noqa: F401
+ fetch_program_enrollments_by_students, # noqa: F401
+ get_external_key_by_user_and_course, # noqa: F401
+ get_org_key_for_program, # noqa: F401
+ get_program_course_enrollment, # noqa: F401
+ get_program_enrollment, # noqa: F401
+ get_provider_slug, # noqa: F401
+ get_saml_providers_for_organization, # noqa: F401
+ get_users_by_external_keys, # noqa: F401
+ get_users_by_external_keys_and_org_key, # noqa: F401
+ is_course_staff_enrollment, # noqa: F401
)
from .writing import (
- change_program_course_enrollment_status,
- change_program_enrollment_status,
- create_program_course_enrollment,
- create_program_enrollment,
- enroll_in_masters_track,
- write_program_course_enrollments,
- write_program_enrollments,
+ change_program_course_enrollment_status, # noqa: F401
+ change_program_enrollment_status, # noqa: F401
+ create_program_course_enrollment, # noqa: F401
+ create_program_enrollment, # noqa: F401
+ enroll_in_masters_track, # noqa: F401
+ write_program_course_enrollments, # noqa: F401
+ write_program_enrollments, # noqa: F401
)
diff --git a/lms/djangoapps/program_enrollments/api/grades.py b/lms/djangoapps/program_enrollments/api/grades.py
index 932a98cc014e..cd36b5820c84 100644
--- a/lms/djangoapps/program_enrollments/api/grades.py
+++ b/lms/djangoapps/program_enrollments/api/grades.py
@@ -63,7 +63,7 @@ def _generate_grades(course_key, enrollments):
prefetch_course_grades(course_key, users)
try:
grades_iter = CourseGradeFactory().iter(users, course_key=course_key)
- for enrollment, grade_tuple in zip(enrollments, grades_iter):
+ for enrollment, grade_tuple in zip(enrollments, grades_iter): # noqa: B905
user, course_grade, exception = grade_tuple
if course_grade:
yield ProgramCourseGradeOk(enrollment, course_grade)
diff --git a/lms/djangoapps/program_enrollments/api/linking.py b/lms/djangoapps/program_enrollments/api/linking.py
index e4ef0ae66cc6..4cb0feeb7d98 100644
--- a/lms/djangoapps/program_enrollments/api/linking.py
+++ b/lms/djangoapps/program_enrollments/api/linking.py
@@ -107,7 +107,7 @@ def link_program_enrollments(program_uuid, external_keys_to_usernames):
# the requested user, then we should sever the link to the existing edX user before
# linking the ProgramEnrollment to the new user.
if program_enrollment.user and program_enrollment.user != user:
- message = ('Unlinking user with username={old_username} from program enrollment with '
+ message = ('Unlinking user with username={old_username} from program enrollment with ' # noqa: UP032 # pylint: disable=line-too-long
'program uuid={program_uuid} with external_student_key={external_user_key} '
'and linking user with username={new_username} '
'to program enrollment.').format(
@@ -123,7 +123,7 @@ def link_program_enrollments(program_uuid, external_keys_to_usernames):
link_program_enrollment_to_lms_user(program_enrollment, user)
except (CourseEnrollmentException, IntegrityError) as e:
- logger.exception("Rolling back all operations for {}:{}".format(
+ logger.exception("Rolling back all operations for {}:{}".format( # noqa: UP032
external_user_key,
username,
))
@@ -223,7 +223,7 @@ def link_program_enrollment_to_lms_user(program_enrollment, user):
program course enrollment
IntegrityError if we try to create invalid records.
"""
- link_log_info = 'user id={} with external_user_key={} for program uuid={}'.format(
+ link_log_info = 'user id={} with external_user_key={} for program uuid={}'.format( # noqa: UP032
user.id,
program_enrollment.external_user_key,
program_enrollment.program_uuid,
@@ -244,7 +244,7 @@ def link_program_enrollment_to_lms_user(program_enrollment, user):
raise
except CourseEnrollmentException as e:
logger.error(
- "CourseEnrollmentException while linking {}: {}".format(
+ "CourseEnrollmentException while linking {}: {}".format( # noqa: UP032
link_log_info, str(e)
)
)
diff --git a/lms/djangoapps/program_enrollments/api/reading.py b/lms/djangoapps/program_enrollments/api/reading.py
index a2c7b0c1ffd6..6ac0973547a5 100644
--- a/lms/djangoapps/program_enrollments/api/reading.py
+++ b/lms/djangoapps/program_enrollments/api/reading.py
@@ -515,7 +515,7 @@ def get_saml_providers_by_org_key(org_key):
try:
organization = Organization.objects.get(short_name=org_key)
except Organization.DoesNotExist:
- raise BadOrganizationShortNameException(org_key) # lint-amnesty, pylint: disable=raise-missing-from
+ raise BadOrganizationShortNameException(org_key) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return get_saml_providers_for_organization(organization)
diff --git a/lms/djangoapps/program_enrollments/api/tests/test_linking.py b/lms/djangoapps/program_enrollments/api/tests/test_linking.py
index 764820956b66..edb5ea34d05c 100644
--- a/lms/djangoapps/program_enrollments/api/tests/test_linking.py
+++ b/lms/djangoapps/program_enrollments/api/tests/test_linking.py
@@ -123,7 +123,7 @@ def _assert_user_enrolled_in_program_courses(self, user, program_uuid, *course_k
for program_course_enrollment in program_course_enrollments
]
assert all(course_enrollment.is_active for course_enrollment in course_enrollments)
- self.assertCountEqual(
+ self.assertCountEqual( # noqa: PT009
course_keys,
[course_enrollment.course.id for course_enrollment in course_enrollments]
)
@@ -396,7 +396,7 @@ def _program_enrollment_not_found(self):
)
logger.check_present((LOG_PATH, 'WARNING', expected_error_msg))
- self.assertDictEqual(errors, {'0002': expected_error_msg})
+ self.assertDictEqual(errors, {'0002': expected_error_msg}) # noqa: PT009
self._assert_program_enrollment(self.user_1, self.program, '0001')
self._assert_no_program_enrollment(self.user_2, self.program)
@@ -415,7 +415,7 @@ def test_user_not_found(self):
expected_error_msg = NO_LMS_USER_TEMPLATE.format('nonexistant-user')
logger.check_present((LOG_PATH, 'WARNING', expected_error_msg))
- self.assertDictEqual(errors, {'0002': expected_error_msg})
+ self.assertDictEqual(errors, {'0002': expected_error_msg}) # noqa: PT009
self._assert_program_enrollment(self.user_1, self.program, '0001')
self._assert_no_user(enrollment_2)
@@ -440,7 +440,7 @@ def test_enrollment_already_linked_to_target_user(self):
expected_error_msg = _user_already_linked_message(program_enrollment, self.user_2)
logger.check_present((LOG_PATH, 'WARNING', expected_error_msg))
- self.assertDictEqual(errors, {'0002': expected_error_msg})
+ self.assertDictEqual(errors, {'0002': expected_error_msg}) # noqa: PT009
self._assert_program_enrollment(self.user_1, self.program, '0001')
self._assert_program_enrollment(self.user_2, self.program, '0002')
diff --git a/lms/djangoapps/program_enrollments/api/tests/test_writing.py b/lms/djangoapps/program_enrollments/api/tests/test_writing.py
index 9059d229944a..55b48a487f95 100644
--- a/lms/djangoapps/program_enrollments/api/tests/test_writing.py
+++ b/lms/djangoapps/program_enrollments/api/tests/test_writing.py
@@ -147,7 +147,7 @@ def test_write_program_enrollments_status_ended(
}], True, False)
assert ProgramEnrollment.objects.count() == 1
assert ProgramEnrollment.historical_records.count() == 1 # pylint: disable=no-member
- result = write_program_enrollments(self.program_uuid, [{
+ result = write_program_enrollments(self.program_uuid, [{ # noqa: F841
'external_user_key': external_key_2,
'status': target_status,
'curriculum_uuid': self.curriculum_uuid_a,
@@ -222,7 +222,7 @@ def test_create_only(self):
True,
False
)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
{
'learner-1': CourseStatuses.ACTIVE,
'learner-2': CourseStatuses.INACTIVE,
@@ -262,7 +262,7 @@ def test_update_only(self, initial_statuses):
False,
True,
)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
{
'learner-1': CourseStatuses.INACTIVE,
'learner-2': CourseStatuses.ACTIVE,
@@ -303,7 +303,7 @@ def test_create_or_update(self):
True,
True,
)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
{
'learner-1': CourseStatuses.INACTIVE,
'learner-2': CourseStatuses.ACTIVE,
@@ -345,7 +345,7 @@ def test_create_or_update_with_mixed_cased_external_user_key(self):
True,
True,
)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
{
'leaRNER-1': CourseStatuses.INACTIVE,
'LEarner-2': CourseStatuses.ACTIVE,
@@ -373,7 +373,7 @@ def test_create_conflicting_enrollment(self):
True,
False,
)
- self.assertDictEqual({'learner-1': CourseStatuses.CONFLICT}, result)
+ self.assertDictEqual({'learner-1': CourseStatuses.CONFLICT}, result) # noqa: PT009
def test_create_conflicting_enrollment_mixed_case_external_user_key(self):
"""
@@ -389,7 +389,7 @@ def test_create_conflicting_enrollment_mixed_case_external_user_key(self):
True,
False,
)
- self.assertDictEqual({'LeArnER-1': CourseStatuses.CONFLICT}, result)
+ self.assertDictEqual({'LeArnER-1': CourseStatuses.CONFLICT}, result) # noqa: PT009
def test_update_nonexistent_enrollment(self):
self.create_program_enrollment('learner-1')
@@ -400,7 +400,7 @@ def test_update_nonexistent_enrollment(self):
False,
True,
)
- self.assertDictEqual({'learner-1': CourseStatuses.NOT_FOUND}, result)
+ self.assertDictEqual({'learner-1': CourseStatuses.NOT_FOUND}, result) # noqa: PT009
def test_invalid_status(self):
self.create_program_enrollment('learner-1')
@@ -411,7 +411,7 @@ def test_invalid_status(self):
True,
False,
)
- self.assertDictEqual({'learner-1': CourseStatuses.INVALID_STATUS}, result)
+ self.assertDictEqual({'learner-1': CourseStatuses.INVALID_STATUS}, result) # noqa: PT009
def test_duplicate_external_keys(self):
self.create_program_enrollment('learner-1')
@@ -426,7 +426,7 @@ def test_duplicate_external_keys(self):
True,
False,
)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
{
'learner-1': CourseStatuses.DUPLICATED,
},
@@ -441,7 +441,7 @@ def test_learner_not_in_program(self):
True,
False,
)
- self.assertDictEqual({'learner-1': CourseStatuses.NOT_IN_PROGRAM}, result)
+ self.assertDictEqual({'learner-1': CourseStatuses.NOT_IN_PROGRAM}, result) # noqa: PT009
@ddt.data(
'learner',
@@ -462,13 +462,13 @@ def test_create_enrollments_and_assign_staff(self, request_user_key_prefix):
course_enrollment_requests = [
self.course_enrollment_request(
- '{}-1'.format(request_user_key_prefix), CourseStatuses.ACTIVE, True
+ '{}-1'.format(request_user_key_prefix), CourseStatuses.ACTIVE, True # noqa: UP032
),
self.course_enrollment_request(
- '{}-2'.format(request_user_key_prefix), CourseStatuses.ACTIVE, True
+ '{}-2'.format(request_user_key_prefix), CourseStatuses.ACTIVE, True # noqa: UP032
),
self.course_enrollment_request(
- '{}-3'.format(request_user_key_prefix), CourseStatuses.ACTIVE, True
+ '{}-3'.format(request_user_key_prefix), CourseStatuses.ACTIVE, True # noqa: UP032
),
]
write_program_course_enrollments(
@@ -484,7 +484,7 @@ def test_create_enrollments_and_assign_staff(self, request_user_key_prefix):
self.assert_program_course_enrollment('learner-3', CourseStatuses.ACTIVE, True)
# Users linked to either enrollment are given the course staff role
- self.assertListEqual(
+ self.assertListEqual( # noqa: PT009
[self.student_1, self.student_2],
list(course_staff_role.users_with_role())
)
@@ -532,7 +532,7 @@ def test_update_and_assign_or_revoke_staff(self):
True,
)
# Role is revoked for user's with a linked enrollment
- self.assertListEqual(
+ self.assertListEqual( # noqa: PT009
[self.student_1],
list(course_staff_role.users_with_role())
)
diff --git a/lms/djangoapps/program_enrollments/api/writing.py b/lms/djangoapps/program_enrollments/api/writing.py
index ea8865092190..16654d307d78 100644
--- a/lms/djangoapps/program_enrollments/api/writing.py
+++ b/lms/djangoapps/program_enrollments/api/writing.py
@@ -409,7 +409,7 @@ def enroll_in_masters_track(user, course_key, status):
message_template.format(user.id, course_key, course_enrollment.mode)
)
elif course_enrollment.mode != CourseMode.MASTERS:
- error_message = (
+ error_message = ( # noqa: UP032
"Cannot convert CourseEnrollment to Master's from mode {}. "
"user id={}, course_key={}."
).format(
@@ -478,7 +478,7 @@ def _ensure_course_exists(course_key, user_key_or_id):
if CourseOverview.course_exists(course_key):
return
logger.error(
- "Cannot enroll user={} in non-existent course={}".format(
+ "Cannot enroll user={} in non-existent course={}".format( # noqa: UP032
user_key_or_id,
course_key,
)
@@ -554,7 +554,7 @@ def _get_conflicting_active_course_enrollments(
and str(existing_enrollment.program_enrollment.program_uuid) != str(program_uuid)
):
logger.error(
- 'Detected conflicting active ProgramCourseEnrollment. This is happening on'
+ 'Detected conflicting active ProgramCourseEnrollment. This is happening on' # noqa: UP032
' The program_uuid [{}] with course_key [{}] for external_user_key [{}]'.format(
program_uuid,
course_key,
diff --git a/lms/djangoapps/program_enrollments/apps.py b/lms/djangoapps/program_enrollments/apps.py
index 232f40f45107..5abf781767b3 100644
--- a/lms/djangoapps/program_enrollments/apps.py
+++ b/lms/djangoapps/program_enrollments/apps.py
@@ -30,6 +30,6 @@ def ready(self):
Connect handlers to signals.
"""
from lms.djangoapps.program_enrollments import ( # pylint: disable=unused-import
- signals,
- tasks,
+ signals, # noqa: F401
+ tasks, # noqa: F401
)
diff --git a/lms/djangoapps/program_enrollments/exceptions.py b/lms/djangoapps/program_enrollments/exceptions.py
index 818cb04c1eea..0ce7fe8db421 100644
--- a/lms/djangoapps/program_enrollments/exceptions.py
+++ b/lms/djangoapps/program_enrollments/exceptions.py
@@ -28,7 +28,7 @@ def __init__(self, program_uuid):
self.program_uuid = program_uuid
def __str__(self):
- return (
+ return ( # noqa: UP032
'Cannot determine authoring organization key for catalog program {}'
).format(self.program_uuid)
@@ -39,7 +39,7 @@ def __init__(self, organization_short_name):
self.organization_short_name = organization_short_name
def __str__(self):
- return 'Unable to find organization for short_name {}'.format(
+ return 'Unable to find organization for short_name {}'.format( # noqa: UP032
self.organization_short_name
)
@@ -50,6 +50,6 @@ def __init__(self, organization):
self.organization = organization
def __str__(self):
- return 'Unable to find organization for short_name {}'.format(
+ return 'Unable to find organization for short_name {}'.format( # noqa: UP032
self.organization.id
)
diff --git a/lms/djangoapps/program_enrollments/management/commands/link_program_enrollments.py b/lms/djangoapps/program_enrollments/management/commands/link_program_enrollments.py
index 7f2653100860..00ebab3914ea 100644
--- a/lms/djangoapps/program_enrollments/management/commands/link_program_enrollments.py
+++ b/lms/djangoapps/program_enrollments/management/commands/link_program_enrollments.py
@@ -73,14 +73,14 @@ def handle(self, program_uuid, user_items, *args, **options):
try:
parsed_program_uuid = UUID(program_uuid)
except ValueError:
- raise CommandError("supplied program_uuid '{}' is not a valid UUID") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError("supplied program_uuid '{}' is not a valid UUID") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
ext_keys_to_usernames = self.parse_user_items(user_items)
try:
link_program_enrollments(
parsed_program_uuid, ext_keys_to_usernames
)
except Exception as e:
- raise CommandError(str(e)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(str(e)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def parse_user_items(self, user_items):
"""
diff --git a/lms/djangoapps/program_enrollments/management/commands/migrate_saml_uids.py b/lms/djangoapps/program_enrollments/management/commands/migrate_saml_uids.py
index fc055ff62e69..447aebc3d678 100644
--- a/lms/djangoapps/program_enrollments/management/commands/migrate_saml_uids.py
+++ b/lms/djangoapps/program_enrollments/management/commands/migrate_saml_uids.py
@@ -70,7 +70,7 @@ def handle(self, *args, **options):
Performs the re-writing
"""
User = get_user_model()
- with py3_open(options['uid_mapping'], 'r', encoding='utf-8') as f:
+ with py3_open(options['uid_mapping'], 'r', encoding='utf-8') as f: # noqa: UP020
uid_mappings = json.load(f)
slug = options['saml_provider_slug']
@@ -90,7 +90,7 @@ def handle(self, *args, **options):
auths = user.social_auth.filter(uid__startswith=slug + ':')
auth = auths[0]
if auths.count() > 1:
- log.info('User {email} has multiple {slug} UserSocialAuth entries, '
+ log.info('User {email} has multiple {slug} UserSocialAuth entries, ' # noqa: UP032
'updating only one of them'.format(
email=email,
slug=slug
@@ -102,27 +102,27 @@ def handle(self, *args, **options):
self._count_results(email_map, uid_mappings)
log.info(
- 'Number of users with {slug} UserSocialAuth records for which there was '
+ 'Number of users with {slug} UserSocialAuth records for which there was ' # noqa: UP032
'no mapping in the provided file: {missed}'.format(
slug=slug,
missed=missed
)
)
log.info(
- 'Number of users identified in the mapping file without {slug}'
+ 'Number of users identified in the mapping file without {slug}' # noqa: UP032
' UserSocialAuth records: {not_previously_linked}'.format(
slug=slug,
not_previously_linked=not_previously_linked
)
)
log.info(
- 'Number of mappings in the mapping file where the identified'
+ 'Number of mappings in the mapping file where the identified' # noqa: UP032
' user has already been processed: {duplicated_in_mapping}'.format(
duplicated_in_mapping=duplicated_in_mapping
)
)
log.info(
- 'Number of mappings in the mapping file updated: '
+ 'Number of mappings in the mapping file updated: ' # noqa: UP032
'{updated}'.format(
updated=updated
)
diff --git a/lms/djangoapps/program_enrollments/management/commands/send_program_course_nudge_email.py b/lms/djangoapps/program_enrollments/management/commands/send_program_course_nudge_email.py
index af2bfdca752d..df4d99264cd1 100644
--- a/lms/djangoapps/program_enrollments/management/commands/send_program_course_nudge_email.py
+++ b/lms/djangoapps/program_enrollments/management/commands/send_program_course_nudge_email.py
@@ -104,7 +104,7 @@ def get_candidate_programs(self, programs, programs_progress):
Get all programs with candidate courses.
"""
candidate_programs = []
- for program, program_progress in zip(programs, programs_progress):
+ for program, program_progress in zip(programs, programs_progress): # noqa: B905
candidate_programs.append(
self.get_candidate_program_and_courses(program, program_progress)
)
diff --git a/lms/djangoapps/program_enrollments/management/commands/tests/test_expire_waiting_enrollments.py b/lms/djangoapps/program_enrollments/management/commands/tests/test_expire_waiting_enrollments.py
index b7343de32a55..fb57eb554ae2 100644
--- a/lms/djangoapps/program_enrollments/management/commands/tests/test_expire_waiting_enrollments.py
+++ b/lms/djangoapps/program_enrollments/management/commands/tests/test_expire_waiting_enrollments.py
@@ -37,5 +37,5 @@ def test_task_fired_with_args(self, expire_days_argument, mock_task):
@patch('lms.djangoapps.program_enrollments.tasks.expire_waiting_enrollments', autospec=True)
def test_task_failure_fails_command(self, mock_task):
mock_task.side_effect = Exception('BOOM!')
- with pytest.raises(Exception):
+ with pytest.raises(Exception): # noqa: B017, PT011
call_command('expire_waiting_enrollments')
diff --git a/lms/djangoapps/program_enrollments/management/commands/tests/test_link_program_enrollments.py b/lms/djangoapps/program_enrollments/management/commands/tests/test_link_program_enrollments.py
index 070d18b18da3..236a4e437075 100644
--- a/lms/djangoapps/program_enrollments/management/commands/tests/test_link_program_enrollments.py
+++ b/lms/djangoapps/program_enrollments/management/commands/tests/test_link_program_enrollments.py
@@ -39,7 +39,7 @@ def test_good_input_calls_linking(self, mock_link):
)
def test_incorrectly_formatted_input_exception(self):
- with self.assertRaisesRegex(
+ with self.assertRaisesRegex( # noqa: PT027
CommandError,
INCORRECT_PARAMETER_TEMPLATE.format('whoops')
):
@@ -48,7 +48,7 @@ def test_incorrectly_formatted_input_exception(self):
)
def test_missing_external_user_key(self):
- with self.assertRaisesRegex(
+ with self.assertRaisesRegex( # noqa: PT027
CommandError,
INCORRECT_PARAMETER_TEMPLATE.format('whoops: ')
):
@@ -57,7 +57,7 @@ def test_missing_external_user_key(self):
)
def test_missing_username(self):
- with self.assertRaisesRegex(
+ with self.assertRaisesRegex( # noqa: PT027
CommandError,
INCORRECT_PARAMETER_TEMPLATE.format(' :whoops')
):
@@ -66,7 +66,7 @@ def test_missing_username(self):
)
def test_repeated_user_key_exception(self):
- with self.assertRaisesRegex(
+ with self.assertRaisesRegex( # noqa: PT027
CommandError,
DUPLICATE_KEY_TEMPLATE.format('learner-01'),
):
@@ -76,7 +76,7 @@ def test_repeated_user_key_exception(self):
def test_invalid_uuid(self):
error_regex = r"supplied program_uuid '.*' is not a valid UUID"
- with self.assertRaisesRegex(CommandError, error_regex):
+ with self.assertRaisesRegex(CommandError, error_regex): # noqa: PT027
call_command(
Command(), 'notauuid::thisisntauuid', 'learner-0:user-01'
)
diff --git a/lms/djangoapps/program_enrollments/management/commands/tests/test_migrate_saml_uids.py b/lms/djangoapps/program_enrollments/management/commands/tests/test_migrate_saml_uids.py
index 794ad53a08ef..29433473902d 100644
--- a/lms/djangoapps/program_enrollments/management/commands/tests/test_migrate_saml_uids.py
+++ b/lms/djangoapps/program_enrollments/management/commands/tests/test_migrate_saml_uids.py
@@ -29,7 +29,7 @@ def _format_email_uid_pair(self, email, uid):
return f'{{"email":"{email}","student_key":"{uid}"}}'
def _format_single_email_uid_pair_json(self, email, uid):
- return '[{obj}]'.format(
+ return '[{obj}]'.format( # noqa: UP032
obj=self._format_email_uid_pair(email, uid)
)
@@ -109,7 +109,7 @@ def test_learner_without_social_auth_records(self, mock_log):
self._call_command(self._format_single_email_uid_pair_json(email, new_urn))
mock_info.assert_any_call(
- 'Number of users identified in the mapping file without'
+ 'Number of users identified in the mapping file without' # noqa: UP032
' {slug} UserSocialAuth records: 1'.format(
slug=self.provider_slug
)
@@ -126,7 +126,7 @@ def test_learner_missed_by_mapping_file(self, mock_log):
self._call_command(self._format_single_email_uid_pair_json('different' + email, new_urn))
mock_info.assert_any_call(
- 'Number of users with {slug} UserSocialAuth records '
+ 'Number of users with {slug} UserSocialAuth records ' # noqa: UP032
'for which there was no mapping in the provided file: 1'.format(
slug=self.provider_slug
)
diff --git a/lms/djangoapps/program_enrollments/management/commands/tests/test_send_program_course_nudge_email.py b/lms/djangoapps/program_enrollments/management/commands/tests/test_send_program_course_nudge_email.py
index f5a6dcebb846..f0326c6402f7 100644
--- a/lms/djangoapps/program_enrollments/management/commands/tests/test_send_program_course_nudge_email.py
+++ b/lms/djangoapps/program_enrollments/management/commands/tests/test_send_program_course_nudge_email.py
@@ -109,7 +109,7 @@ def enroll_user(self, user, course, create_grade=False):
@patch('lms.djangoapps.program_enrollments.management.commands.send_program_course_nudge_email.get_programs')
@patch('lms.djangoapps.certificates.api.certificates_viewable_for_course', return_value=True)
@override_settings(FEATURES=dict(ENABLE_ENTERPRISE_INTEGRATION=True))
- def test_email_send(self, add_no_commit, __, get_programs_mock, mock_track):
+ def test_email_send(self, add_no_commit, __, get_programs_mock, mock_track): # noqa: PT019
"""
Test Segment fired as expected.
"""
diff --git a/lms/djangoapps/program_enrollments/management/commands/tests/utils.py b/lms/djangoapps/program_enrollments/management/commands/tests/utils.py
index e5f70222c81c..9e7f39fdaee2 100644
--- a/lms/djangoapps/program_enrollments/management/commands/tests/utils.py
+++ b/lms/djangoapps/program_enrollments/management/commands/tests/utils.py
@@ -16,7 +16,7 @@ class UserSocialAuthFactory(DjangoModelFactory):
class Meta:
model = UserSocialAuth
user = SubFactory(UserFactory)
- uid = LazyAttributeSequence(lambda o, n: '%s:%d' % (o.slug, n))
+ uid = LazyAttributeSequence(lambda o, n: '%s:%d' % (o.slug, n)) # noqa: UP031
class Params:
slug = 'gatech'
diff --git a/lms/djangoapps/program_enrollments/models.py b/lms/djangoapps/program_enrollments/models.py
index 4f75c4c5368a..86e5d64699c2 100644
--- a/lms/djangoapps/program_enrollments/models.py
+++ b/lms/djangoapps/program_enrollments/models.py
@@ -42,7 +42,7 @@ class Meta:
null=True,
blank=True, on_delete=models.CASCADE
)
- external_user_key = models.CharField(
+ external_user_key = models.CharField( # noqa: DJ001
db_index=True,
max_length=255,
null=True
@@ -84,7 +84,7 @@ def __str__(self):
return f'[ProgramEnrollment id={self.id}]'
def __repr__(self):
- return ( # lint-amnesty, pylint: disable=missing-format-attribute
+ return ( # lint-amnesty, pylint: disable=missing-format-attribute # noqa: UP032
" MAX_ENROLLMENT_RECORDS:
return Response(
- '{} enrollments requested, but limit is {}.'.format(
+ '{} enrollments requested, but limit is {}.'.format( # noqa: UP032
MAX_ENROLLMENT_RECORDS, num_requests
),
status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
diff --git a/lms/djangoapps/program_enrollments/tests/test_signals.py b/lms/djangoapps/program_enrollments/tests/test_signals.py
index 2228e211e55d..c2bbae3891fb 100644
--- a/lms/djangoapps/program_enrollments/tests/test_signals.py
+++ b/lms/djangoapps/program_enrollments/tests/test_signals.py
@@ -412,7 +412,7 @@ def test_log_on_unexpected_exception(self):
with mock.patch('lms.djangoapps.program_enrollments.api.linking.enroll_in_masters_track') as enrollMock:
enrollMock.side_effect = Exception('unexpected error')
with LogCapture(logger.name) as log:
- with self.assertRaisesRegex(Exception, 'unexpected error'):
+ with self.assertRaisesRegex(Exception, 'unexpected error'): # noqa: PT027
UserSocialAuth.objects.create(
user=self.user,
uid=f'{self.provider_slug}:{self.external_id}',
diff --git a/lms/djangoapps/rss_proxy/views.py b/lms/djangoapps/rss_proxy/views.py
index 9d10f233df72..7abb40bca0bc 100644
--- a/lms/djangoapps/rss_proxy/views.py
+++ b/lms/djangoapps/rss_proxy/views.py
@@ -25,7 +25,7 @@ def proxy(request):
status_code = 200
rss = cache.get(cache_key, '')
print(cache_key)
- print('Cached rss: %s' % rss)
+ print('Cached rss: %s' % rss) # noqa: UP031
if not rss:
# Go get the RSS from the URL if it was not cached
resp = requests.get(url)
diff --git a/lms/djangoapps/static_template_view/tests/test_views.py b/lms/djangoapps/static_template_view/tests/test_views.py
index c8f04fc8c067..ae96ab4380ad 100644
--- a/lms/djangoapps/static_template_view/tests/test_views.py
+++ b/lms/djangoapps/static_template_view/tests/test_views.py
@@ -85,7 +85,7 @@ def test_500(self):
resp = self.client.get(url)
self.assertContains(
resp,
- 'There has been a 500 error on the {platform_name} servers'.format(
+ 'There has been a 500 error on the {platform_name} servers'.format( # noqa: UP032
platform_name=settings.PLATFORM_NAME
),
status_code=500
diff --git a/lms/djangoapps/static_template_view/urls.py b/lms/djangoapps/static_template_view/urls.py
index 231913fbfcc1..aa030ded6b0b 100644
--- a/lms/djangoapps/static_template_view/urls.py
+++ b/lms/djangoapps/static_template_view/urls.py
@@ -44,4 +44,4 @@
# Make the assumption that the URL we want is the lowercased
# version of the map key
- urlpatterns.append(re_path(r'^%s$' % key.lower(), views.render, {'template': template}, name=value))
+ urlpatterns.append(re_path(r'^%s$' % key.lower(), views.render, {'template': template}, name=value)) # noqa: UP031
diff --git a/lms/djangoapps/static_template_view/views.py b/lms/djangoapps/static_template_view/views.py
index f8962897c033..8e27df7215c1 100644
--- a/lms/djangoapps/static_template_view/views.py
+++ b/lms/djangoapps/static_template_view/views.py
@@ -72,9 +72,9 @@ def render(request, template):
result = render_to_response('static_templates/' + template, context, content_type=content_type)
return result
except TopLevelLookupException:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except TemplateDoesNotExist:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
@ensure_csrf_cookie
@@ -91,7 +91,7 @@ def render_press_release(request, slug):
try:
resp = render_to_response('static_templates/press_releases/' + template, {})
except TemplateDoesNotExist:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return resp
@@ -128,7 +128,7 @@ def render_500(request):
"""
try:
return HttpResponseServerError(render_to_string('static_templates/server-error.html', {}, request=request))
- except BaseException as e:
+ except BaseException as e: # noqa: F841
# If we can't render the error page, ensure we don't raise another
# exception -- because if we do, we'll probably just end up back
# at the same rendering error.
diff --git a/lms/djangoapps/support/rest_api/v1/tests/test_views.py b/lms/djangoapps/support/rest_api/v1/tests/test_views.py
index 526aa00bd792..73864f87a1a4 100644
--- a/lms/djangoapps/support/rest_api/v1/tests/test_views.py
+++ b/lms/djangoapps/support/rest_api/v1/tests/test_views.py
@@ -57,32 +57,32 @@ def test_get_api_missing_query_params_returns_400(self):
"""GET API: Returns 400 if no query parameters are provided."""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
resp = self.client.get(self.url)
- self.assertEqual(resp.status_code, 400)
+ self.assertEqual(resp.status_code, 400) # noqa: PT009
def test_get_api_with_username_parameter(self):
"""GET API: Can query by username parameter."""
self.client.login(username=self.staff.username, password=TEST_PASSWORD)
resp = self.client.get(self.url, {"username": self.user.username})
- self.assertEqual(resp.status_code, 200)
- self.assertIsInstance(resp.data, list)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertIsInstance(resp.data, list) # noqa: PT009
def test_get_api_with_user_id_parameter(self):
"""GET API: Can query by user_id parameter."""
self.client.login(username=self.staff.username, password=TEST_PASSWORD)
resp = self.client.get(self.url, {"user_id": self.user.id})
- self.assertEqual(resp.status_code, 200)
- self.assertIsInstance(resp.data, list)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertIsInstance(resp.data, list) # noqa: PT009
def test_get_api_nonexistent_user_returns_404(self):
"""GET API: Returns 404 for a nonexistent user email."""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
resp = self.client.get(self.url, {"email": "notfound@example.com"})
- self.assertEqual(resp.status_code, 404)
+ self.assertEqual(resp.status_code, 404) # noqa: PT009
def test_get_api_unauthenticated_user_returns_401(self):
"""GET API: Unauthenticated users receive 401 Unauthorized."""
resp = self.client.get(self.url, {"email": self.user.email})
- self.assertEqual(resp.status_code, 401)
+ self.assertEqual(resp.status_code, 401) # noqa: PT009
@ddt.data(
("instructor", "instructor"),
@@ -100,23 +100,23 @@ def test_get_api_admin_can_fetch_course_roles(self, assigned_role, expected_role
CourseStaffRole(self.extra_courses[0].id).add_users(self.user)
response = self.client.get(self.url, {"email": self.user.email})
- self.assertEqual(response.status_code, 200)
- self.assertIsInstance(response.data, list)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertIsInstance(response.data, list) # noqa: PT009
course_found = False
for course in response.data:
if course["course_id"] == str(self.extra_courses[0].id):
with self.subTest(role=assigned_role):
- self.assertEqual(course["role"], expected_role)
+ self.assertEqual(course["role"], expected_role) # noqa: PT009
# Verify new fields are present
- self.assertIn("status", course)
- self.assertIn("org", course)
- self.assertIn("run", course)
- self.assertIn("number", course)
- self.assertIn("course_name", course)
- self.assertIn("course_url", course)
+ self.assertIn("status", course) # noqa: PT009
+ self.assertIn("org", course) # noqa: PT009
+ self.assertIn("run", course) # noqa: PT009
+ self.assertIn("number", course) # noqa: PT009
+ self.assertIn("course_name", course) # noqa: PT009
+ self.assertIn("course_url", course) # noqa: PT009
course_found = True
- self.assertTrue(course_found, "Expected course not found in response.")
+ self.assertTrue(course_found, "Expected course not found in response.") # noqa: PT009
def test_get_api_instructor_can_only_see_their_courses(self):
"""GET API: Course instructor sees only courses they have access to."""
@@ -124,19 +124,19 @@ def test_get_api_instructor_can_only_see_their_courses(self):
username=self.instructor_user.username, password=TEST_PASSWORD
)
resp = self.client.get(self.url, {"email": self.user.email})
- self.assertEqual(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
course_ids = [course["course_id"] for course in resp.data]
- self.assertIn(str(self.extra_courses[0].id), course_ids)
+ self.assertIn(str(self.extra_courses[0].id), course_ids) # noqa: PT009
for i in range(1, 3):
- self.assertNotIn(str(self.extra_courses[i].id), course_ids)
+ self.assertNotIn(str(self.extra_courses[i].id), course_ids) # noqa: PT009
def test_get_api_user_with_no_access_sees_no_courses(self):
"""GET API: Non-instructor users see no courses in the response."""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
resp = self.client.get(self.url, {"email": self.user.email})
- self.assertEqual(resp.status_code, 200)
- self.assertEqual(resp.data, [])
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertEqual(resp.data, []) # noqa: PT009
# --- PUT API TEST CASES ---
@@ -145,34 +145,34 @@ def test_put_api_missing_email_returns_400(self):
self.client.login(username=self.user.username, password=TEST_PASSWORD)
data = {"bulk_role_operations": []}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 400)
- self.assertEqual(resp.data["email"], "")
+ self.assertEqual(resp.status_code, 400) # noqa: PT009
+ self.assertEqual(resp.data["email"], "") # noqa: PT009
result = resp.data["results"][0]
- self.assertEqual(result["status"], "failed")
- self.assertIn("error", result)
- self.assertIn("email", result["error"])
+ self.assertEqual(result["status"], "failed") # noqa: PT009
+ self.assertIn("error", result) # noqa: PT009
+ self.assertIn("email", result["error"]) # noqa: PT009
def test_put_api_empty_operations_returns_400(self):
"""PUT API: Sending empty bulk_role_operations returns 400 with an error message."""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
data = {"email": "test@example.com", "bulk_role_operations": []}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 400)
- self.assertEqual(resp.data["email"], "test@example.com")
+ self.assertEqual(resp.status_code, 400) # noqa: PT009
+ self.assertEqual(resp.data["email"], "test@example.com") # noqa: PT009
result = resp.data["results"][0]
- self.assertEqual(result["status"], "failed")
- self.assertIn("error", result)
- self.assertIn("bulk_role_operations", result["error"])
+ self.assertEqual(result["status"], "failed") # noqa: PT009
+ self.assertIn("error", result) # noqa: PT009
+ self.assertIn("bulk_role_operations", result["error"]) # noqa: PT009
def test_put_api_non_dict_input_returns_400(self):
"""PUT API: Sending a non-dict input returns 400 with an error message."""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
resp = self.client.put(self.url, ["invalid"], format="json")
- self.assertEqual(resp.status_code, 400)
+ self.assertEqual(resp.status_code, 400) # noqa: PT009
result = resp.data["results"][0]
- self.assertEqual(result["status"], "failed")
- self.assertIn("error", result)
- self.assertIn("JSON object", result["error"])
+ self.assertEqual(result["status"], "failed") # noqa: PT009
+ self.assertIn("error", result) # noqa: PT009
+ self.assertIn("JSON object", result["error"]) # noqa: PT009
def test_put_api_missing_fields_returns_error(self):
"""PUT API: Request with missing required fields returns field-level errors."""
@@ -184,12 +184,12 @@ def test_put_api_missing_fields_returns_error(self):
"bulk_role_operations": [{"course_id": "", "role": "", "action": ""}],
}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 200)
- self.assertEqual(resp.data["email"], self.user.email)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertEqual(resp.data["email"], self.user.email) # noqa: PT009
result = resp.data["results"][0]
- self.assertEqual(result["status"], "failed")
+ self.assertEqual(result["status"], "failed") # noqa: PT009
for field in ("course_id", "role", "action"):
- self.assertIn(field, result)
+ self.assertIn(field, result) # noqa: PT009
def test_put_api_invalid_user_email_returns_error(self):
"""PUT API: Invalid user email in request returns an error."""
@@ -207,11 +207,11 @@ def test_put_api_invalid_user_email_returns_error(self):
],
}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 404)
- self.assertEqual(resp.data["email"], "notfound@example.com")
+ self.assertEqual(resp.status_code, 404) # noqa: PT009
+ self.assertEqual(resp.data["email"], "notfound@example.com") # noqa: PT009
result = resp.data["results"][0]
- self.assertEqual(result["status"], "failed")
- self.assertIn("User not found", result["error"])
+ self.assertEqual(result["status"], "failed") # noqa: PT009
+ self.assertIn("User not found", result["error"]) # noqa: PT009
def test_put_api_invalid_course_id_returns_error(self):
"""PUT API: Invalid course_id in request returns an error."""
@@ -229,11 +229,11 @@ def test_put_api_invalid_course_id_returns_error(self):
],
}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 200)
- self.assertEqual(resp.data["email"], self.user.email)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertEqual(resp.data["email"], self.user.email) # noqa: PT009
result = resp.data["results"][0]
- self.assertEqual(result["status"], "failed")
- self.assertIn("Invalid course_id", result["error"])
+ self.assertEqual(result["status"], "failed") # noqa: PT009
+ self.assertIn("Invalid course_id", result["error"]) # noqa: PT009
def test_put_api_invalid_action_returns_error(self):
"""PUT API: Invalid action value in request returns an error."""
@@ -251,11 +251,11 @@ def test_put_api_invalid_action_returns_error(self):
],
}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 200)
- self.assertEqual(resp.data["email"], self.user.email)
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertEqual(resp.data["email"], self.user.email) # noqa: PT009
result = resp.data["results"][0]
- self.assertEqual(result["status"], "failed")
- self.assertIn("Invalid action", result["error"])
+ self.assertEqual(result["status"], "failed") # noqa: PT009
+ self.assertIn("Invalid action", result["error"]) # noqa: PT009
def test_put_api_assign_role_enrolls_user(self):
"""PUT API: Assigning a role enrolls user in the course."""
@@ -272,11 +272,11 @@ def test_put_api_assign_role_enrolls_user(self):
],
}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 200)
- self.assertEqual(resp.data["email"], self.user.email)
- self.assertEqual(resp.data["results"][0]["status"], "success")
- self.assertTrue(CourseInstructorRole(course.id).has_user(self.user))
- self.assertTrue(CourseEnrollment.is_enrolled(self.user, course.id))
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertEqual(resp.data["email"], self.user.email) # noqa: PT009
+ self.assertEqual(resp.data["results"][0]["status"], "success") # noqa: PT009
+ self.assertTrue(CourseInstructorRole(course.id).has_user(self.user)) # noqa: PT009
+ self.assertTrue(CourseEnrollment.is_enrolled(self.user, course.id)) # noqa: PT009
def test_put_api_revoke_role_removes_user(self):
"""PUT API: Revoking a role removes user from course team."""
@@ -293,10 +293,10 @@ def test_put_api_revoke_role_removes_user(self):
],
}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 200)
- self.assertEqual(resp.data["email"], self.user.email)
- self.assertEqual(resp.data["results"][0]["status"], "success")
- self.assertFalse(CourseStaffRole(course.id).has_user(self.user))
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertEqual(resp.data["email"], self.user.email) # noqa: PT009
+ self.assertEqual(resp.data["results"][0]["status"], "success") # noqa: PT009
+ self.assertFalse(CourseStaffRole(course.id).has_user(self.user)) # noqa: PT009
def test_put_api_course_instructor_can_manage_own_courses(self):
"""PUT API: Course instructor can assign roles for courses they manage."""
@@ -314,10 +314,10 @@ def test_put_api_course_instructor_can_manage_own_courses(self):
],
}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 200)
- self.assertEqual(resp.data["email"], self.user.email)
- self.assertEqual(resp.data["results"][0]["status"], "success")
- self.assertTrue(CourseStaffRole(self.extra_courses[0].id).has_user(self.user))
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertEqual(resp.data["email"], self.user.email) # noqa: PT009
+ self.assertEqual(resp.data["results"][0]["status"], "success") # noqa: PT009
+ self.assertTrue(CourseStaffRole(self.extra_courses[0].id).has_user(self.user)) # noqa: PT009
def test_put_api_non_instructor_user_forbidden(self):
"""PUT API: Non-instructor users receive 403 Forbidden when assigning roles."""
@@ -333,10 +333,10 @@ def test_put_api_non_instructor_user_forbidden(self):
],
}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 403)
- self.assertEqual(resp.data["email"], self.user.email)
- self.assertEqual(resp.data["results"][0]["status"], "failed")
- self.assertIn("do not have permission", resp.data["results"][0]["error"])
+ self.assertEqual(resp.status_code, 403) # noqa: PT009
+ self.assertEqual(resp.data["email"], self.user.email) # noqa: PT009
+ self.assertEqual(resp.data["results"][0]["status"], "failed") # noqa: PT009
+ self.assertIn("do not have permission", resp.data["results"][0]["error"]) # noqa: PT009
def test_put_api_org_level_instructor_can_manage_all_org_courses(self):
"""PUT API: Org-level instructors can manage roles for all courses in their org."""
@@ -357,10 +357,10 @@ def test_put_api_org_level_instructor_can_manage_all_org_courses(self):
],
}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 200)
- self.assertEqual(resp.data["email"], self.user.email)
- self.assertEqual(resp.data["results"][0]["status"], "success")
- self.assertTrue(CourseStaffRole(self.extra_courses[1].id).has_user(self.user))
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertEqual(resp.data["email"], self.user.email) # noqa: PT009
+ self.assertEqual(resp.data["results"][0]["status"], "success") # noqa: PT009
+ self.assertTrue(CourseStaffRole(self.extra_courses[1].id).has_user(self.user)) # noqa: PT009
def test_put_api_course_instructor_cannot_manage_other_courses(self):
"""PUT API: Course instructor cannot assign roles for courses they don't manage."""
@@ -378,7 +378,7 @@ def test_put_api_course_instructor_cannot_manage_other_courses(self):
],
}
resp = self.client.put(self.url, data, format="json")
- self.assertEqual(resp.status_code, 200)
- self.assertEqual(resp.data["email"], self.user.email)
- self.assertEqual(resp.data["results"][0]["status"], "failed")
- self.assertIn("do not have instructor access", resp.data["results"][0]["error"])
+ self.assertEqual(resp.status_code, 200) # noqa: PT009
+ self.assertEqual(resp.data["email"], self.user.email) # noqa: PT009
+ self.assertEqual(resp.data["results"][0]["status"], "failed") # noqa: PT009
+ self.assertIn("do not have instructor access", resp.data["results"][0]["error"]) # noqa: PT009
diff --git a/lms/djangoapps/support/rest_api/v1/views.py b/lms/djangoapps/support/rest_api/v1/views.py
index 73bbdf04da62..0fe9c3272ca1 100644
--- a/lms/djangoapps/support/rest_api/v1/views.py
+++ b/lms/djangoapps/support/rest_api/v1/views.py
@@ -487,7 +487,7 @@ def _validate_course(self, course_id, cache):
course_key = CourseKey.from_string(course_id)
if not CourseOverview.course_exists(course_key):
course_key = None
- except Exception as exc: # pylint: disable=broad-except
+ except Exception as exc: # pylint: disable=broad-except # noqa: F841
course_key = None
cache[course_id] = course_key
diff --git a/lms/djangoapps/support/tests/test_tasks.py b/lms/djangoapps/support/tests/test_tasks.py
index 9a41c1f794e8..1f89bb6753c8 100644
--- a/lms/djangoapps/support/tests/test_tasks.py
+++ b/lms/djangoapps/support/tests/test_tasks.py
@@ -172,8 +172,8 @@ def test_reset_student_course(self):
self.mock_clear_block_completion.assert_called_once_with(self.student_user, self.course.id)
self.mock_clear_user_course_grades.assert_called_once_with(self.student_user.id, self.course.id)
course_reset_audit = CourseResetAudit.objects.get(course_enrollment=self.enrollment)
- self.assertIsNotNone(course_reset_audit.completed_at)
- self.assertEqual(course_reset_audit.status, CourseResetAudit.CourseResetStatus.COMPLETE)
+ self.assertIsNotNone(course_reset_audit.completed_at) # noqa: PT009
+ self.assertEqual(course_reset_audit.status, CourseResetAudit.CourseResetStatus.COMPLETE) # noqa: PT009
self.assert_email_sent_successfully({
'subject': f'The course { self.course.display_name } has been reset !',
'body': f'Your progress in course { self.course.display_name } has been reset on your behalf.'
@@ -217,9 +217,9 @@ def test_reset_student_course_student_module_not_found(self):
self.mock_clear_block_completion.assert_called_once_with(self.student_user, self.course.id)
self.mock_clear_user_course_grades.assert_called_once_with(self.student_user.id, self.course.id)
course_reset_audit = CourseResetAudit.objects.get(course_enrollment=self.enrollment)
- self.assertRaises(StudentModule.DoesNotExist, mock_reset_student_attempts)
- self.assertIsNotNone(course_reset_audit.completed_at)
- self.assertEqual(course_reset_audit.status, CourseResetAudit.CourseResetStatus.COMPLETE)
+ self.assertRaises(StudentModule.DoesNotExist, mock_reset_student_attempts) # noqa: PT027
+ self.assertIsNotNone(course_reset_audit.completed_at) # noqa: PT009
+ self.assertEqual(course_reset_audit.status, CourseResetAudit.CourseResetStatus.COMPLETE) # noqa: PT009
@patch('lms.djangoapps.support.tasks.reset_student_attempts')
def test_reset_student_course_fail(self, mock_reset_student_attempts):
@@ -232,8 +232,8 @@ def test_reset_student_course_fail(self, mock_reset_student_attempts):
self.mock_clear_block_completion.assert_not_called()
self.mock_clear_user_course_grades.assert_not_called()
course_reset_audit = CourseResetAudit.objects.get(course_enrollment=self.enrollment)
- self.assertIsNone(course_reset_audit.completed_at)
- self.assertEqual(course_reset_audit.status, CourseResetAudit.CourseResetStatus.FAILED)
+ self.assertIsNone(course_reset_audit.completed_at) # noqa: PT009
+ self.assertEqual(course_reset_audit.status, CourseResetAudit.CourseResetStatus.FAILED) # noqa: PT009
def test_reset_student_attempts_raise_exception(self):
with patch(
@@ -246,5 +246,5 @@ def test_reset_student_attempts_raise_exception(self):
self.mock_clear_block_completion.assert_not_called()
self.mock_clear_user_course_grades.assert_not_called()
course_reset_audit = CourseResetAudit.objects.get(course_enrollment=self.enrollment)
- self.assertIsNone(course_reset_audit.completed_at)
- self.assertEqual(course_reset_audit.status, CourseResetAudit.CourseResetStatus.FAILED)
+ self.assertIsNone(course_reset_audit.completed_at) # noqa: PT009
+ self.assertEqual(course_reset_audit.status, CourseResetAudit.CourseResetStatus.FAILED) # noqa: PT009
diff --git a/lms/djangoapps/support/tests/test_views.py b/lms/djangoapps/support/tests/test_views.py
index 3272a340bdd3..b9bdc740c84c 100644
--- a/lms/djangoapps/support/tests/test_views.py
+++ b/lms/djangoapps/support/tests/test_views.py
@@ -371,7 +371,7 @@ def test_order_number_information(self, search_string_type, order_details):
enrollment=self.enrollment,
namespace='order',
name='order_number',
- value='ORD-00{}'.format(count + 1)
+ value='ORD-00{}'.format(count + 1) # noqa: UP032
)
url = reverse(
'support:enrollment_list',
@@ -465,7 +465,7 @@ def test_pacing_type(self, is_self_paced, pacing_type):
assert response.status_code == 200
data = json.loads(response.content.decode('utf-8'))
assert len(data) == 1
- self.assertEqual(data[0]['pacing_type'], pacing_type)
+ self.assertEqual(data[0]['pacing_type'], pacing_type) # noqa: PT009
def test_get_manual_enrollment_history(self):
ManualEnrollmentAudit.create_manual_enrollment_audit(
@@ -968,7 +968,7 @@ def _serialize_datetime(self, dt):
def test_initial_rendering(self):
response = self.client.get(self.url)
content = str(response.content, encoding='utf-8')
- expected_organization_serialized = '"orgKeys": {}'.format(
+ expected_organization_serialized = '"orgKeys": {}'.format( # noqa: UP032
json.dumps(sorted(self.org_key_list))
)
assert response.status_code == 200
@@ -1021,7 +1021,7 @@ def _construct_enrollments(self, program_uuids, course_ids, external_user_key, e
is_active=True
)
- program_course_enrollment = ProgramCourseEnrollmentFactory.create(
+ program_course_enrollment = ProgramCourseEnrollmentFactory.create( # noqa: F841
# lint-amnesty, pylint: disable=unused-variable
program_enrollment=program_enrollment,
course_key=course_id,
@@ -1252,7 +1252,7 @@ def test_search_external_user_not_in_system(self, mocked_render):
'org_key': self.org_key_list[0],
})
- expected_error = 'No user found for external key {} for institution {}'.format(
+ expected_error = 'No user found for external key {} for institution {}'.format( # noqa: UP032
external_user_key, self.org_key_list[0]
)
render_call_dict = mocked_render.call_args[0][1]
@@ -1374,7 +1374,7 @@ def _construct_enrollments(self, program_uuids, course_ids, external_user_key, e
is_active=True
)
- program_course_enrollment = ProgramCourseEnrollmentFactory.create(
+ program_course_enrollment = ProgramCourseEnrollmentFactory.create( # noqa: F841
# lint-amnesty, pylint: disable=unused-variable
program_enrollment=program_enrollment,
course_key=course_id,
@@ -1539,7 +1539,7 @@ def test_search_external_user_not_in_system(self):
self._url + f'?external_user_key={external_user_key}&org_key={self.org_key_list[0]}'
)
response = json.loads(response.content.decode('utf-8'))
- expected_error = 'No user found for external key {} for institution {}'.format(
+ expected_error = 'No user found for external key {} for institution {}'.format( # noqa: UP032
external_user_key, self.org_key_list[0]
)
assert expected_error == response['error']
@@ -1603,7 +1603,7 @@ def test_user_does_not_exist(self):
assert len(data) == 0
def test_response(self):
- user_social_auth = UserSocialAuth.objects.create( # lint-amnesty, pylint: disable=unused-variable
+ user_social_auth = UserSocialAuth.objects.create( # lint-amnesty, pylint: disable=unused-variable # noqa: F841
user=self.student,
uid=self.student.email,
provider='tpa-saml'
@@ -1616,7 +1616,7 @@ def test_response(self):
def test_history_response(self):
'''Tests changes in SSO history for a user'''
- user_social_auth = UserSocialAuth.objects.create( # lint-amnesty, pylint: disable=unused-variable
+ user_social_auth = UserSocialAuth.objects.create( # lint-amnesty, pylint: disable=unused-variable # noqa: F841
user=self.student,
uid=self.student.email,
provider='tpa-saml'
@@ -1842,7 +1842,7 @@ def test_linking_program_enrollment_without_username(self, username, original_us
Tests if enrollment linkages are refused for invalid usernames
"""
external_user_key = '0001'
- linked_user = self._setup_user_from_username(username)
+ linked_user = self._setup_user_from_username(username) # noqa: F841
original_user = self._setup_user_from_username(original_username)
program_enrollment, program_course_enrollment = self._setup_enrollments(
external_user_key,
@@ -1959,24 +1959,24 @@ def test_wrong_username(self):
Test that a request with a username which does not exits returns 404
"""
response = self.client.get(self._url(username='does_not_exist'))
- self.assertEqual(response.status_code, 404)
+ self.assertEqual(response.status_code, 404) # noqa: PT009
response_data = json.loads(response.content.decode('utf-8'))
- self.assertEqual(response_data['verified_in'], None)
- self.assertEqual(response_data['current_status'], None)
+ self.assertEqual(response_data['verified_in'], None) # noqa: PT009
+ self.assertEqual(response_data['current_status'], None) # noqa: PT009
def test_no_record(self):
"""
Test that a request with a username which do not have any onboarding exam returns empty data
"""
response = self.client.get(self._url(username=self.other_user.username))
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
response_data = json.loads(response.content.decode('utf-8'))
- self.assertEqual(response_data['verified_in'], None)
- self.assertEqual(response_data['current_status'], None)
+ self.assertEqual(response_data['verified_in'], None) # noqa: PT009
+ self.assertEqual(response_data['current_status'], None) # noqa: PT009
def test_no_verified_attempts(self):
"""
@@ -1990,10 +1990,10 @@ def test_no_verified_attempts(self):
update_attempt_status(attempt_id, ProctoredExamStudentAttemptStatus.submitted)
response = self.client.get(self._url(username=self.user.username))
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
response_data = json.loads(response.content.decode('utf-8'))
- self.assertEqual(response_data['verified_in'], None)
- self.assertEqual(
+ self.assertEqual(response_data['verified_in'], None) # noqa: PT009
+ self.assertEqual( # noqa: PT009
response_data['current_status']['onboarding_status'],
ProctoredExamStudentAttemptStatus.submitted
)
@@ -2001,11 +2001,11 @@ def test_no_verified_attempts(self):
# Create second attempt and assert that most recent attempt is returned
create_exam_attempt(self.onboarding_exam_id, self.user.id, True)
response = self.client.get(self._url(username=self.user.username))
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
response_data = json.loads(response.content.decode('utf-8'))
- self.assertEqual(response_data['verified_in'], None)
- self.assertEqual(
+ self.assertEqual(response_data['verified_in'], None) # noqa: PT009
+ self.assertEqual( # noqa: PT009
response_data['current_status']['onboarding_status'],
ProctoredExamStudentAttemptStatus.created
)
@@ -2021,14 +2021,14 @@ def test_get_verified_attempt(self):
attempt_id = create_exam_attempt(self.onboarding_exam_id, self.user.id, True)
update_attempt_status(attempt_id, ProctoredExamStudentAttemptStatus.verified)
response = self.client.get(self._url(username=self.user.username))
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
response_data = json.loads(response.content.decode('utf-8'))
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
response_data['verified_in']['onboarding_status'],
ProctoredExamStudentAttemptStatus.verified
)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
response_data['current_status']['onboarding_status'],
ProctoredExamStudentAttemptStatus.verified
)
@@ -2036,14 +2036,14 @@ def test_get_verified_attempt(self):
# Create second attempt and assert that verified attempt is still returned
create_exam_attempt(self.onboarding_exam_id, self.user.id, True)
response = self.client.get(self._url(username=self.user.username))
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
response_data = json.loads(response.content.decode('utf-8'))
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
response_data['verified_in']['onboarding_status'],
ProctoredExamStudentAttemptStatus.verified
)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
response_data['current_status']['onboarding_status'],
ProctoredExamStudentAttemptStatus.verified
)
@@ -2087,16 +2087,16 @@ def test_verified_in_another_course(self):
self._create_enrollment()
response = self.client.get(self._url(username=self.user.username))
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
response_data = json.loads(response.content.decode('utf-8'))
# assert that originally verified enrollment is reflected correctly
- self.assertEqual(response_data['verified_in']['onboarding_status'], 'verified')
- self.assertEqual(response_data['verified_in']['course_id'], other_course_id)
+ self.assertEqual(response_data['verified_in']['onboarding_status'], 'verified') # noqa: PT009
+ self.assertEqual(response_data['verified_in']['course_id'], other_course_id) # noqa: PT009
# assert that most recent enrollment (current status) has other_course_approved status
- self.assertEqual(response_data['current_status']['onboarding_status'], 'other_course_approved')
- self.assertEqual(response_data['current_status']['course_id'], self.course_id)
+ self.assertEqual(response_data['current_status']['onboarding_status'], 'other_course_approved') # noqa: PT009
+ self.assertEqual(response_data['current_status']['course_id'], self.course_id) # noqa: PT009
class ResetCourseViewTestBase(SupportViewTestCase):
@@ -2133,10 +2133,10 @@ def assert_course_ids(self, expected_course_ids, learner=None):
""" Helper that asserts the course ids that will be returned from the listing endpoint """
learner = learner or self.learner
response = self.client.get(self._url(learner))
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
actual_course_ids = [course['course_id'] for course in response.json()]
- self.assertEqual(expected_course_ids, actual_course_ids)
+ self.assertEqual(expected_course_ids, actual_course_ids) # noqa: PT009
def test_no_enrollments(self):
""" When a learner has no enrollments, the endpoint should return an empty list """
@@ -2179,10 +2179,10 @@ def test_deactivated_enrollment(self):
def assertResponse(self, expected_response):
""" Helper to assert the contents of the response from the listing endpoint """
response = self.client.get(self._url(self.learner))
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
actual_response = response.json()
- self.assertEqual(expected_response, actual_response)
+ self.assertEqual(expected_response, actual_response) # noqa: PT009
return actual_response
def test_course_not_started(self):
@@ -2214,7 +2214,7 @@ def test_course_ended(self):
])
@patch('lms.djangoapps.support.views.course_reset.user_has_passing_grade_in_course', return_value=True)
- def test_user_has_passing_grade(self, _):
+ def test_user_has_passing_grade(self, _): # noqa: PT019
""" If a course is opted in but the learner has a passing grade, it should not be resettable """
self.assertResponse([{
'course_id': self.course_id,
@@ -2225,7 +2225,7 @@ def test_user_has_passing_grade(self, _):
}])
@patch('lms.djangoapps.support.views.course_reset.user_has_passing_grade_in_course', return_value=True)
- def test_ended_with_passing_grade(self, _):
+ def test_ended_with_passing_grade(self, _): # noqa: PT019
"""
If a course has ended and the learner has a passing grade,
the passing grade message should override the ended message
@@ -2397,8 +2397,8 @@ def request(self, username=None, course_id=None, comment=None):
def assert_error_response(self, response, expected_status_code, expected_error_message):
""" Helper to assert status code and error message """
- self.assertEqual(response.status_code, expected_status_code)
- self.assertEqual(response.data['error'], expected_error_message)
+ self.assertEqual(response.status_code, expected_status_code) # noqa: PT009
+ self.assertEqual(response.data['error'], expected_error_message) # noqa: PT009
def test_wrong_username(self):
""" A request with a username which does not exits returns 404 """
@@ -2447,8 +2447,8 @@ def test_learner_course_reset(self, mock_reset_student_course):
# A request for a given learner and course with a comment should return a 201
response = self.request(comment=comment)
- self.assertEqual(response.status_code, 201)
- self.assertEqual(response.data, {
+ self.assertEqual(response.status_code, 201) # noqa: PT009
+ self.assertEqual(response.data, { # noqa: PT009
'course_id': self.course_id,
'status': response.data['status'],
'can_reset': False,
@@ -2458,7 +2458,7 @@ def test_learner_course_reset(self, mock_reset_student_course):
# The reset task should be queued
mock_reset_student_course.delay.assert_called_once_with(self.course_id, self.learner.email, self.user.email)
# And an audit should be created as ENQUEUED
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
self.enrollment.courseresetaudit_set.first().status,
CourseResetAudit.CourseResetStatus.ENQUEUED
)
@@ -2473,8 +2473,8 @@ def test_course_reset_failed(self, mock_reset_student_course):
status=CourseResetAudit.CourseResetStatus.FAILED
)
response = self.request()
- self.assertEqual(response.status_code, 201)
- self.assertEqual(response.data, {
+ self.assertEqual(response.status_code, 201) # noqa: PT009
+ self.assertEqual(response.data, { # noqa: PT009
'course_id': self.course_id,
'status': response.data['status'],
'can_reset': False,
diff --git a/lms/djangoapps/support/views/enrollments.py b/lms/djangoapps/support/views/enrollments.py
index fa30f30295a2..e4c95aa92b2d 100644
--- a/lms/djangoapps/support/views/enrollments.py
+++ b/lms/djangoapps/support/views/enrollments.py
@@ -151,7 +151,7 @@ def post(self, request, username_or_email):
return HttpResponseBadRequest('Could not parse course key.')
except User.DoesNotExist:
return HttpResponseBadRequest(
- 'Could not find user {username}.'.format(
+ 'Could not find user {username}.'.format( # noqa: UP032
username=username_or_email
)
)
@@ -207,7 +207,7 @@ def patch(self, request, username_or_email):
return HttpResponseBadRequest('Could not parse course key.')
except (CourseEnrollment.DoesNotExist, User.DoesNotExist):
return HttpResponseBadRequest(
- 'Could not find enrollment for user {username} in course {course}.'.format(
+ 'Could not find enrollment for user {username} in course {course}.'.format( # noqa: UP032
username=username_or_email,
course=str(course_key)
)
diff --git a/lms/djangoapps/support/views/program_enrollments.py b/lms/djangoapps/support/views/program_enrollments.py
index 45a21c8f6dce..31b4e8689377 100644
--- a/lms/djangoapps/support/views/program_enrollments.py
+++ b/lms/djangoapps/support/views/program_enrollments.py
@@ -277,7 +277,7 @@ def get(self, request):
selected_provider,
)
if not learner_program_enrollments:
- search_error = 'No user found for external key {} for institution {}'.format(
+ search_error = 'No user found for external key {} for institution {}'.format( # noqa: UP032
external_user_key, org_key
)
elif not org_key and not external_user_key:
@@ -374,7 +374,7 @@ def get(self, request):
selected_provider,
)
if not learner_program_enrollments:
- search_error = 'No user found for external key {} for institution {}'.format(
+ search_error = 'No user found for external key {} for institution {}'.format( # noqa: UP032
external_user_key, org_key
)
else:
diff --git a/lms/djangoapps/survey/apps.py b/lms/djangoapps/survey/apps.py
index 6f66b551b612..f58a87b23e22 100644
--- a/lms/djangoapps/survey/apps.py
+++ b/lms/djangoapps/survey/apps.py
@@ -17,4 +17,4 @@ def ready(self):
"""
Connect signal handlers.
"""
- from . import signals # pylint: disable=unused-import
+ from . import signals # pylint: disable=unused-import # noqa: F401
diff --git a/lms/djangoapps/survey/models.py b/lms/djangoapps/survey/models.py
index cf085635ef8a..4dd5d89de266 100644
--- a/lms/djangoapps/survey/models.py
+++ b/lms/djangoapps/survey/models.py
@@ -57,7 +57,7 @@ def validate_form_html(cls, html):
fields = cls.get_field_names_from_html(html)
except Exception as ex:
log.exception(f"Cannot parse SurveyForm html: {ex}")
- raise ValidationError(f"Cannot parse SurveyForm as HTML: {ex}") # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(f"Cannot parse SurveyForm as HTML: {ex}") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not len(fields): # lint-amnesty, pylint: disable=len-as-condition
raise ValidationError("SurveyForms must contain at least one form input field")
diff --git a/lms/djangoapps/teams/api.py b/lms/djangoapps/teams/api.py
index 4051a9ba54a2..51068e98d52b 100644
--- a/lms/djangoapps/teams/api.py
+++ b/lms/djangoapps/teams/api.py
@@ -349,7 +349,7 @@ def get_team_for_user_course_topic(user, course_id, topic_id):
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError:
- raise ValueError("The supplied course id {course_id} is not valid.".format( # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValueError("The supplied course id {course_id} is not valid.".format( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904, UP032
course_id=course_id
))
try:
@@ -382,7 +382,7 @@ def get_teams_in_teamset(course_id, topic_id):
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError as exc:
- raise ValueError("The supplied course id {course_id} is not valid.".format(
+ raise ValueError("The supplied course id {course_id} is not valid.".format( # noqa: UP032
course_id=course_id
)) from exc
return CourseTeam.objects.filter(
@@ -402,7 +402,7 @@ def anonymous_user_ids_for_team(user, team):
raise Exception("User and team must be provided for ID lookup")
if not has_course_staff_privileges(user, team.course_id) and not user_is_a_team_member(user, team):
- raise Exception("User {user} is not permitted to access team info for {team}".format(
+ raise Exception("User {user} is not permitted to access team info for {team}".format( # noqa: UP032
user=user.username,
team=team.team_id
))
@@ -417,7 +417,7 @@ def get_assignments_for_team(user, team):
""" Get openassessment XBlocks configured for the current teamset """
# Confirm access
if not has_specific_team_access(user, team):
- raise Exception("User {user} is not permitted to access team info for {team}".format(
+ raise Exception("User {user} is not permitted to access team info for {team}".format( # noqa: UP032
user=user.username,
team=team.team_id
))
diff --git a/lms/djangoapps/teams/api_urls.py b/lms/djangoapps/teams/api_urls.py
index cb1e9f73db07..7aba514de91d 100644
--- a/lms/djangoapps/teams/api_urls.py
+++ b/lms/djangoapps/teams/api_urls.py
@@ -27,14 +27,14 @@
name="teams_list"
),
re_path(
- r'^v0/teams/{team_id_pattern}$'.format(
+ r'^v0/teams/{team_id_pattern}$'.format( # noqa: UP032
team_id_pattern=TEAM_ID_PATTERN,
),
TeamsDetailView.as_view(),
name="teams_detail"
),
re_path(
- r'^v0/teams/{team_id_pattern}/assignments$'.format(
+ r'^v0/teams/{team_id_pattern}/assignments$'.format( # noqa: UP032
team_id_pattern=TEAM_ID_PATTERN,
),
TeamsAssignmentsView.as_view(),
@@ -46,7 +46,7 @@
name="topics_list"
),
re_path(
- r'^v0/topics/{topic_id_pattern},{course_id_pattern}$'.format(
+ r'^v0/topics/{topic_id_pattern},{course_id_pattern}$'.format( # noqa: UP032
topic_id_pattern=TOPIC_ID_PATTERN,
course_id_pattern=settings.COURSE_ID_PATTERN,
),
@@ -59,7 +59,7 @@
name="team_membership_list"
),
re_path(
- r'^v0/team_membership/{team_id_pattern},{username_pattern}$'.format(
+ r'^v0/team_membership/{team_id_pattern},{username_pattern}$'.format( # noqa: UP032
team_id_pattern=TEAM_ID_PATTERN,
username_pattern=settings.USERNAME_PATTERN,
),
@@ -67,7 +67,7 @@
name="team_membership_detail"
),
re_path(
- r'^v0/bulk_team_membership/{course_id_pattern}$'.format(
+ r'^v0/bulk_team_membership/{course_id_pattern}$'.format( # noqa: UP032
course_id_pattern=settings.COURSE_ID_PATTERN,
),
MembershipBulkManagementView.as_view(),
diff --git a/lms/djangoapps/teams/csv.py b/lms/djangoapps/teams/csv.py
index 4a45b4d74529..b9c9a9c15b7c 100644
--- a/lms/djangoapps/teams/csv.py
+++ b/lms/djangoapps/teams/csv.py
@@ -324,7 +324,7 @@ def validate_teams_have_matching_teamsets(self, row):
This method will add a validation error and return False if this is the case.
"""
if None in row:
- error_message = "Team(s) {} don't have matching teamsets.".format(
+ error_message = "Team(s) {} don't have matching teamsets.".format( # noqa: UP032
row[None]
)
if self.add_error_and_check_if_max_exceeded(error_message):
@@ -440,7 +440,7 @@ def validate_team_sizes_not_exceeded(self):
key = (teamset_id, team_name)
if self.user_count_by_team[key] > max_team_size:
self.add_error_and_check_if_max_exceeded(
- 'New membership for team {} would exceed max size of {}.'.format(
+ 'New membership for team {} would exceed max size of {}.'.format( # noqa: UP032
team_name, max_team_size
)
)
diff --git a/lms/djangoapps/teams/management/commands/reindex_course_team.py b/lms/djangoapps/teams/management/commands/reindex_course_team.py
index 486325a5697e..155e25b1f275 100644
--- a/lms/djangoapps/teams/management/commands/reindex_course_team.py
+++ b/lms/djangoapps/teams/management/commands/reindex_course_team.py
@@ -37,7 +37,7 @@ def _get_course_team(self, team_id):
try:
result = CourseTeam.objects.get(team_id=team_id)
except ObjectDoesNotExist:
- raise CommandError(f'Argument {team_id} is not a course_team team_id') # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(f'Argument {team_id} is not a course_team team_id') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return result
diff --git a/lms/djangoapps/teams/management/commands/tests/test_reindex_course_team.py b/lms/djangoapps/teams/management/commands/tests/test_reindex_course_team.py
index 7ddd2f6249b5..9245fdf5c11c 100644
--- a/lms/djangoapps/teams/management/commands/tests/test_reindex_course_team.py
+++ b/lms/djangoapps/teams/management/commands/tests/test_reindex_course_team.py
@@ -40,14 +40,14 @@ def test_given_no_arguments_raises_command_error(self):
"""
Test that raises CommandError for incorrect arguments.
"""
- with self.assertRaisesRegex(CommandError, '.*At least one course_team_id or --all needs to be specified.*'):
+ with self.assertRaisesRegex(CommandError, '.*At least one course_team_id or --all needs to be specified.*'): # noqa: PT027 # pylint: disable=line-too-long
call_command('reindex_course_team')
def test_given_conflicting_arguments_raises_command_error(self):
"""
Test that raises CommandError for incorrect arguments.
"""
- with self.assertRaisesRegex(CommandError, '.*Course teams cannot be specified when --all is also specified.*'):
+ with self.assertRaisesRegex(CommandError, '.*Course teams cannot be specified when --all is also specified.*'): # noqa: PT027 # pylint: disable=line-too-long
call_command('reindex_course_team', self.team1.team_id, all=True)
@patch.dict('django.conf.settings.FEATURES', {'ENABLE_TEAMS': False})
@@ -55,7 +55,7 @@ def test_teams_search_flag_disabled_raises_command_error(self):
"""
Test that raises CommandError for disabled feature flag.
"""
- with self.assertRaisesRegex(CommandError, '.*ENABLE_TEAMS must be enabled.*'):
+ with self.assertRaisesRegex(CommandError, '.*ENABLE_TEAMS must be enabled.*'): # noqa: PT027
call_command('reindex_course_team', self.team1.team_id)
def test_given_invalid_team_id_raises_command_error(self):
@@ -64,7 +64,7 @@ def test_given_invalid_team_id_raises_command_error(self):
"""
team_id = 'team4'
error_str = f'Argument {team_id} is not a course_team team_id'
- with self.assertRaisesRegex(CommandError, error_str):
+ with self.assertRaisesRegex(CommandError, error_str): # noqa: PT027
call_command('reindex_course_team', team_id)
@patch.object(CourseTeamIndexer, 'index')
diff --git a/lms/djangoapps/teams/models.py b/lms/djangoapps/teams/models.py
index f105fa3ba1ed..2320f50c9338 100644
--- a/lms/djangoapps/teams/models.py
+++ b/lms/djangoapps/teams/models.py
@@ -113,7 +113,7 @@ def __str__(self):
return f"{self.name} in {self.course_id}"
def __repr__(self):
- return ( # lint-amnesty, pylint: disable=missing-format-attribute
+ return ( # lint-amnesty, pylint: disable=missing-format-attribute # noqa: UP032
""
).format(self)
- class Meta:
+ class Meta: # noqa: DJ012
app_label = "teams"
- team_id = models.SlugField(max_length=255, unique=True)
+ team_id = models.SlugField(max_length=255, unique=True) # noqa: DJ012
discussion_topic_id = models.SlugField(max_length=255, unique=True)
name = models.CharField(max_length=255, db_index=True)
course_id = CourseKeyField(db_index=True)
@@ -233,7 +233,7 @@ def __str__(self):
return f"{self.user.username} is member of {self.team}"
def __repr__(self):
- return ( # lint-amnesty, pylint: disable=missing-format-attribute
+ return ( # lint-amnesty, pylint: disable=missing-format-attribute # noqa: UP032
""
).format(self)
- class Meta:
+ class Meta: # noqa: DJ012
app_label = "teams"
unique_together = (('user', 'team'),)
- user = models.ForeignKey(User, on_delete=models.CASCADE)
+ user = models.ForeignKey(User, on_delete=models.CASCADE) # noqa: DJ012
team = models.ForeignKey(CourseTeam, related_name='membership', on_delete=models.CASCADE)
date_joined = models.DateTimeField(auto_now_add=True)
last_activity_at = models.DateTimeField()
diff --git a/lms/djangoapps/teams/plugins.py b/lms/djangoapps/teams/plugins.py
index ae155f32f28d..06dd88870cc7 100644
--- a/lms/djangoapps/teams/plugins.py
+++ b/lms/djangoapps/teams/plugins.py
@@ -1,7 +1,7 @@
"""
Definition of the course team feature.
"""
-from typing import Dict, Optional
+from typing import Dict, Optional # noqa: UP035
from django.conf import settings
from django.contrib.auth import get_user_model
@@ -93,7 +93,7 @@ def set_enabled(cls, course_key: CourseKey, enabled: bool, user: User) -> bool:
return enabled
@classmethod
- def get_allowed_operations(cls, course_key: CourseKey, user: Optional[User] = None) -> Dict[str, bool]:
+ def get_allowed_operations(cls, course_key: CourseKey, user: Optional[User] = None) -> Dict[str, bool]: # noqa: UP006, UP045 # pylint: disable=line-too-long
"""
Return allowed operations for teams app.
"""
diff --git a/lms/djangoapps/teams/search_indexes.py b/lms/djangoapps/teams/search_indexes.py
index 349a1ba65aac..44545311af50 100644
--- a/lms/djangoapps/teams/search_indexes.py
+++ b/lms/djangoapps/teams/search_indexes.py
@@ -79,7 +79,7 @@ def content_text(self):
"""
# Always use the English version of any localizable strings (see TNL-3239)
with translation.override('en'):
- return "{name}\n{description}\n{country}\n{language}".format(
+ return "{name}\n{description}\n{country}\n{language}".format( # noqa: UP032
name=self.course_team.name,
description=self.course_team.description,
country=self.course_team.country.name.format(),
@@ -124,7 +124,7 @@ def engine(cls):
return SearchEngine.get_search_engine(index=cls.INDEX_NAME)
except ConnectionError as err:
logging.error('Error connecting to elasticsearch: %s', err)
- raise ElasticSearchConnectionError # lint-amnesty, pylint: disable=raise-missing-from
+ raise ElasticSearchConnectionError # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
@classmethod
def search_is_enabled(cls):
diff --git a/lms/djangoapps/teams/services.py b/lms/djangoapps/teams/services.py
index dce876fc6be4..da2e7ef283bf 100644
--- a/lms/djangoapps/teams/services.py
+++ b/lms/djangoapps/teams/services.py
@@ -28,7 +28,7 @@ def get_team_detail_url(self, team):
""" Returns the url to the detail view for the given team """
teams_dashboard_url = reverse('teams_dashboard', kwargs={'course_id': team.course_id})
# Unfortunately required since this URL resolution is done in a Backbone view
- return "{teams_dashboard_url}#teams/{topic_id}/{team_id}".format(
+ return "{teams_dashboard_url}#teams/{topic_id}/{team_id}".format( # noqa: UP032
teams_dashboard_url=teams_dashboard_url,
topic_id=team.topic_id,
team_id=team.team_id,
diff --git a/lms/djangoapps/teams/tests/test_api.py b/lms/djangoapps/teams/tests/test_api.py
index deb6090f9f45..5f8ffbd10a91 100644
--- a/lms/djangoapps/teams/tests/test_api.py
+++ b/lms/djangoapps/teams/tests/test_api.py
@@ -214,13 +214,13 @@ def test_anonymous_user_ids_for_team_not_on_team(self):
"""
A learner should not be able to get IDs from members of a team they are not a member of
"""
- self.assertRaises(Exception, teams_api.anonymous_user_ids_for_team, self.user1, self.team2)
+ self.assertRaises(Exception, teams_api.anonymous_user_ids_for_team, self.user1, self.team2) # noqa: B017, PT027
def test_anonymous_user_ids_for_team_bad_user_or_team(self):
"""
An exception should be thrown when a bad user or team are passed to the endpoint
"""
- self.assertRaises(Exception, teams_api.anonymous_user_ids_for_team, None, self.team1)
+ self.assertRaises(Exception, teams_api.anonymous_user_ids_for_team, None, self.team1) # noqa: B017, PT027
def test_anonymous_user_ids_for_team_staff(self):
"""
diff --git a/lms/djangoapps/teams/tests/test_csv.py b/lms/djangoapps/teams/tests/test_csv.py
index 0e1312461e82..f0a246883543 100644
--- a/lms/djangoapps/teams/tests/test_csv.py
+++ b/lms/djangoapps/teams/tests/test_csv.py
@@ -205,7 +205,7 @@ def test_load_team_membership_csv(self):
reader = csv_export(self.course)
assert expected_csv_headers == reader.fieldnames
actual_data = _user_keyed_dict(reader)
- self.assertDictEqual(expected_data, actual_data)
+ self.assertDictEqual(expected_data, actual_data) # noqa: PT009
def _add_blanks_to_expected_data(self, expected_data, headers):
""" Helper method to fill in the "blanks" in test data """
@@ -391,7 +391,7 @@ def test_exceed_max_size(self):
assert self.import_manager.validation_errors[0] == 'New membership for team team_1 would exceed max size of 3.'
# Confirm that memberships were not altered
- for i in range(2):
+ for i in range(2): # noqa: B007
assert CourseTeamMembership.is_user_on_team(user, team)
def test_remove_from_team(self):
@@ -408,7 +408,7 @@ def test_remove_from_team(self):
['username', 'mode', 'teamset_1'],
[user.username, mode, ''],
])
- result = self.import_manager.set_team_memberships(csv_data) # lint-amnesty, pylint: disable=unused-variable
+ result = self.import_manager.set_team_memberships(csv_data) # lint-amnesty, pylint: disable=unused-variable # noqa: F841
# Then they are removed from the team and the correct events are issued
assert not CourseTeamMembership.is_user_on_team(user, team)
@@ -461,7 +461,7 @@ def test_create_new_team_from_import(self):
['username', 'mode', 'teamset_1'],
[user.username, mode, 'new_exciting_team'],
])
- result = self.import_manager.set_team_memberships(csv_data) # lint-amnesty, pylint: disable=unused-variable
+ result = self.import_manager.set_team_memberships(csv_data) # lint-amnesty, pylint: disable=unused-variable # noqa: F841
# Then a new team is created
assert CourseTeam.objects.all().count() == 1
@@ -672,4 +672,4 @@ def _assert_test_users_on_team(self, data, no_external_key_value):
(self.user_in_program.username, self.external_user_key)
]
}
- self.assertDictEqual(expected_data, data)
+ self.assertDictEqual(expected_data, data) # noqa: PT009
diff --git a/lms/djangoapps/teams/tests/test_views.py b/lms/djangoapps/teams/tests/test_views.py
index 69723ae8ea91..85efefb7818a 100644
--- a/lms/djangoapps/teams/tests/test_views.py
+++ b/lms/djangoapps/teams/tests/test_views.py
@@ -219,7 +219,7 @@ def test_team_dashboard_user_course_specific_team_list(self):
# Create teams in both courses
course_one_team = CourseTeamFactory.create(name="Course one team", course_id=self.course.id, topic_id=1)
- course_two_team = CourseTeamFactory.create( # pylint: disable=unused-variable
+ course_two_team = CourseTeamFactory.create( # pylint: disable=unused-variable # noqa: F841
name="Course two team", course_id=course_two.id, topic_id=1,
)
@@ -662,7 +662,7 @@ def make_call(self, url, expected_status=200, method='get', data=None, content_t
else:
response = func(url, data=data)
assert expected_status == response.status_code, "Expected status {expected} but got {actual}: {content}" \
- .format(
+ .format( # noqa: UP032
expected=expected_status,
actual=response.status_code,
content=response.content.decode(response.charset),
@@ -811,7 +811,7 @@ def setUp(self): # pylint: disable=arguments-differ
('student_masters', 200, 1)
)
@ddt.unpack
- def test_access(self, user, status, expected_teams_count=0):
+ def test_access(self, user, status, expected_teams_count=0): # noqa: PT028
teams = self.get_teams_list(user=user, expected_status=status)
if status == 200:
assert expected_teams_count == teams['count']
@@ -1717,7 +1717,7 @@ def setUpClass(cls):
parent=subsection,
category="vertical"
)
- off_team_open_assessment = BlockFactory.create( # pylint: disable=unused-variable
+ off_team_open_assessment = BlockFactory.create( # pylint: disable=unused-variable # noqa: F841
parent=unit_2,
category="openassessment",
teams_enabled=True,
@@ -2777,7 +2777,7 @@ class TestElasticSearchErrors(TeamAPITestCase):
ES_ERROR = ConnectionError('N/A', 'connection error', {})
@patch.object(SearchEngine, 'get_search_engine', side_effect=ES_ERROR)
- def test_list_teams(self, __):
+ def test_list_teams(self, __): # noqa: PT019
"""Test that text searches return a 503 when Elasticsearch is down.
The endpoint should still return 200 when a search is not supplied."""
@@ -2793,7 +2793,7 @@ def test_list_teams(self, __):
)
@patch.object(SearchEngine, 'get_search_engine', side_effect=ES_ERROR)
- def test_create_team(self, __):
+ def test_create_team(self, __): # noqa: PT019
"""Test that team creation is robust to Elasticsearch errors."""
self.post_create_team(
expected_status=200,
@@ -2802,12 +2802,12 @@ def test_create_team(self, __):
)
@patch.object(SearchEngine, 'get_search_engine', side_effect=ES_ERROR)
- def test_delete_team(self, __):
+ def test_delete_team(self, __): # noqa: PT019
"""Test that team deletion is robust to Elasticsearch errors."""
self.delete_team(self.wind_team.team_id, 204, user='staff')
@patch.object(SearchEngine, 'get_search_engine', side_effect=ES_ERROR)
- def test_patch_team(self, __):
+ def test_patch_team(self, __): # noqa: PT019
"""Test that team updates are robust to Elasticsearch errors."""
self.patch_team_detail(
self.wind_team.team_id,
@@ -2953,11 +2953,11 @@ def test_upload_only_existing_courses(self):
)
csv_content = 'username,mode,topic_1,topic_2\n'
- csv_content += 'a_user,masters,{},{}\n'.format(
+ csv_content += 'a_user,masters,{},{}\n'.format( # noqa: UP032
existing_team_1.name,
existing_team_2.name
)
- csv_content += 'b_user,masters,{},{}\n'.format(
+ csv_content += 'b_user,masters,{},{}\n'.format( # noqa: UP032
existing_team_1.name,
existing_team_2.name
)
@@ -3208,7 +3208,7 @@ def test_upload_assign_masters_learner_to_non_protected_team(self):
user='staff'
)
response_text = json.loads(response.content.decode('utf-8'))
- expected_message = 'Team {} cannot have Master’s track users mixed with users in other tracks.'.format(
+ expected_message = "Team {} cannot have Master’s track users mixed with users in other tracks.".format( # noqa: UP032 # pylint: disable=line-too-long
team.name
)
assert response_text['errors'][0] == expected_message
diff --git a/lms/djangoapps/teams/views.py b/lms/djangoapps/teams/views.py
index d01f7dddd0fb..45cf53cd9b64 100644
--- a/lms/djangoapps/teams/views.py
+++ b/lms/djangoapps/teams/views.py
@@ -526,7 +526,7 @@ def get(self, request):
if order_by_input not in ordering_schemes:
return Response(
{
- 'developer_message': "unsupported order_by value {ordering}".format(
+ 'developer_message': "unsupported order_by value {ordering}".format( # noqa: UP032
ordering=order_by_input,
),
# Translators: 'ordering' is a string describing a way
@@ -916,7 +916,7 @@ def _display_name_for_ora_block(self, block):
unit = modulestore().get_item(block.parent)
section = modulestore().get_item(unit.parent)
- return "{section}: {unit}".format(
+ return "{section}: {unit}".format( # noqa: UP032
section=section.display_name,
unit=unit.display_name
)
@@ -1594,14 +1594,14 @@ def get_team(self, team_id):
try:
return CourseTeam.objects.get(team_id=team_id)
except CourseTeam.DoesNotExist:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def get_membership(self, username, team):
"""Returns the membership for the given user and team, or throws Http404 if it does not exist."""
try:
return CourseTeamMembership.objects.get(user__username=username, team=team)
except CourseTeamMembership.DoesNotExist:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def get(self, request, team_id, username):
"""GET /api/team/v0/team_membership/{team_id},{username}"""
@@ -1663,7 +1663,7 @@ def get(self, request, **_kwargs):
"""
self.check_access()
response = HttpResponse(content_type='text/csv')
- filename = "team-membership_{}_{}_{}.csv".format(
+ filename = "team-membership_{}_{}_{}.csv".format( # noqa: UP032
self.course.id.org, self.course.id.course, self.course.id.run
)
response['Content-Disposition'] = f'attachment; filename="{filename}"'
@@ -1694,7 +1694,7 @@ def check_access(self):
"""
if not has_course_staff_privileges(self.request.user, self.course.id):
raise PermissionDenied(
- "To manage team membership of {}, you must be course staff.".format(
+ "To manage team membership of {}, you must be course staff.".format( # noqa: UP032
self.course.id
)
)
@@ -1711,7 +1711,7 @@ def course(self):
try:
course_id = CourseKey.from_string(course_id_string)
except InvalidKeyError:
- raise Http404(f'Invalid course key: {course_id_string}') # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404(f'Invalid course key: {course_id_string}') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
course_block = modulestore().get_course(course_id)
if not course_block:
raise Http404(f'Course not found: {course_id}')
diff --git a/lms/djangoapps/user_tours/apps.py b/lms/djangoapps/user_tours/apps.py
index 7ec2de59a973..7d60da23bdd5 100644
--- a/lms/djangoapps/user_tours/apps.py
+++ b/lms/djangoapps/user_tours/apps.py
@@ -10,4 +10,4 @@ class UserTourConfig(AppConfig):
def ready(self):
""" Code to run when getting the app ready. """
# Connect signal handlers.
- from lms.djangoapps.user_tours import handlers # pylint: disable=unused-import
+ from lms.djangoapps.user_tours import handlers # pylint: disable=unused-import # noqa: F401
diff --git a/lms/djangoapps/user_tours/handlers.py b/lms/djangoapps/user_tours/handlers.py
index 60d14827c5cc..ccb16c852389 100644
--- a/lms/djangoapps/user_tours/handlers.py
+++ b/lms/djangoapps/user_tours/handlers.py
@@ -25,5 +25,5 @@ def init_user_tour(sender, instance, created, **kwargs): # pylint: disable=unus
# feel free to remove this try/except.
# The exact error we are catching is
# django.db.utils.ProgrammingError: (1146, "Table 'edxtest.user_tours_usertour' doesn't exist")
- except ProgrammingError as e:
+ except ProgrammingError as e: # noqa: F841
pass
diff --git a/lms/djangoapps/user_tours/models.py b/lms/djangoapps/user_tours/models.py
index 23baacc15e1c..cc6789a07165 100644
--- a/lms/djangoapps/user_tours/models.py
+++ b/lms/djangoapps/user_tours/models.py
@@ -7,7 +7,7 @@
User = get_user_model()
-class UserTour(models.Model):
+class UserTour(models.Model): # noqa: DJ008
"""
Model to track which tours a user needs to be shown.
@@ -27,7 +27,7 @@ class CourseHomeChoices(models.TextChoices):
user = models.OneToOneField(User, related_name='tour', on_delete=models.CASCADE)
-class UserDiscussionsTours(models.Model):
+class UserDiscussionsTours(models.Model): # noqa: DJ008
"""
Model to track which discussions tours a user has seen.
diff --git a/lms/djangoapps/user_tours/v1/tests/test_views.py b/lms/djangoapps/user_tours/v1/tests/test_views.py
index 912b79701053..354b80bb34d0 100644
--- a/lms/djangoapps/user_tours/v1/tests/test_views.py
+++ b/lms/djangoapps/user_tours/v1/tests/test_views.py
@@ -187,20 +187,20 @@ def test_get_tours(self):
# Send a GET request to the view
response = self.client.get(self.url, **headers)
# Check that the response status code is correct
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
# Check that the returned data is correct
- self.assertEqual(len(response.data), 2)
- self.assertEqual(response.data[0]['tour_name'], 'Test Tour')
- self.assertFalse(response.data[0]['show_tour'])
+ self.assertEqual(len(response.data), 2) # noqa: PT009
+ self.assertEqual(response.data[0]['tour_name'], 'Test Tour') # noqa: PT009
+ self.assertFalse(response.data[0]['show_tour']) # noqa: PT009
- self.assertEqual(response.data[1]['tour_name'], 'not_responded_filter')
- self.assertTrue(response.data[1]['show_tour'])
+ self.assertEqual(response.data[1]['tour_name'], 'not_responded_filter') # noqa: PT009
+ self.assertTrue(response.data[1]['show_tour']) # noqa: PT009
# Test that the view can be disabled by a waffle flag.
with override_waffle_flag(USER_TOURS_DISABLED, active=True):
response = self.client.get(self.url, **headers)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_get_tours_unauthenticated(self):
"""
@@ -210,7 +210,7 @@ def test_get_tours_unauthenticated(self):
response = self.client.get(self.url)
# Check that the response status code is correct
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_update_tour(self):
"""
@@ -224,13 +224,13 @@ def test_update_tour(self):
response = self.client.put(url, updated_data, content_type='application/json', **headers)
# Check that the response status code is correct
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
# Check that the tour was updated in the database
updated_tour = UserDiscussionsTours.objects.get(id=self.tour.id)
- self.assertEqual(updated_tour.show_tour, False)
+ self.assertEqual(updated_tour.show_tour, False) # noqa: PT009
# Test that the view can be disabled by a waffle flag.
with override_waffle_flag(USER_TOURS_DISABLED, active=True):
response = self.client.put(url, updated_data, content_type='application/json', **headers)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
diff --git a/lms/djangoapps/user_tours/v1/views.py b/lms/djangoapps/user_tours/v1/views.py
index b2f7d960f13a..4c5ffc8f5baf 100644
--- a/lms/djangoapps/user_tours/v1/views.py
+++ b/lms/djangoapps/user_tours/v1/views.py
@@ -50,7 +50,7 @@ def get(self, request, username): # pylint: disable=arguments-differ
try:
user_tour = UserTour.objects.get(user__username=username)
# Should never really happen, but better safe than sorry.
- except UserTour.DoesNotExist as e:
+ except UserTour.DoesNotExist as e: # noqa: F841
return Response(status=status.HTTP_404_NOT_FOUND)
return Response(self.get_serializer_class()(user_tour).data, status=status.HTTP_200_OK)
diff --git a/lms/djangoapps/verify_student/api.py b/lms/djangoapps/verify_student/api.py
index fc30ff87bb73..2887c654593e 100644
--- a/lms/djangoapps/verify_student/api.py
+++ b/lms/djangoapps/verify_student/api.py
@@ -57,8 +57,8 @@ def create_verification_attempt(
user: User,
name: str,
status: str,
- expiration_datetime: Optional[datetime] = None,
- hide_status_from_user: Optional[bool] = False,
+ expiration_datetime: Optional[datetime] = None, # noqa: UP045
+ hide_status_from_user: Optional[bool] = False, # noqa: UP045
):
"""
Create a verification attempt.
@@ -95,9 +95,9 @@ def create_verification_attempt(
def update_verification_attempt(
attempt_id: int,
- name: Optional[str] = None,
- status: Optional[str] = None,
- expiration_datetime: Optional[datetime] = None,
+ name: Optional[str] = None, # noqa: UP045
+ status: Optional[str] = None, # noqa: UP045
+ expiration_datetime: Optional[datetime] = None, # noqa: UP045
):
"""
Update a verification attempt.
diff --git a/lms/djangoapps/verify_student/apps.py b/lms/djangoapps/verify_student/apps.py
index 71d74e96c4bd..3db6b4f91681 100644
--- a/lms/djangoapps/verify_student/apps.py
+++ b/lms/djangoapps/verify_student/apps.py
@@ -17,5 +17,8 @@ def ready(self):
"""
Connect signal handlers.
"""
- from lms.djangoapps.verify_student import tasks # pylint: disable=unused-import
- from lms.djangoapps.verify_student.signals import handlers, signals # pylint: disable=unused-import
+ from lms.djangoapps.verify_student import tasks # pylint: disable=unused-import # noqa: F401
+ from lms.djangoapps.verify_student.signals import ( # pylint: disable=unused-import # noqa: F401
+ handlers,
+ signals,
+ )
diff --git a/lms/djangoapps/verify_student/image.py b/lms/djangoapps/verify_student/image.py
index 597c74b915a6..8c59b19cd5b7 100644
--- a/lms/djangoapps/verify_student/image.py
+++ b/lms/djangoapps/verify_student/image.py
@@ -34,4 +34,4 @@ def decode_image_data(data):
return base64.b64decode(data.split(",")[1])
except (IndexError, UnicodeEncodeError):
log.exception("Could not decode image data")
- raise InvalidImageData # lint-amnesty, pylint: disable=raise-missing-from
+ raise InvalidImageData # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
diff --git a/lms/djangoapps/verify_student/management/commands/approve_id_verifications.py b/lms/djangoapps/verify_student/management/commands/approve_id_verifications.py
index 52d9ff12e0ad..a0e55a9499ac 100644
--- a/lms/djangoapps/verify_student/management/commands/approve_id_verifications.py
+++ b/lms/djangoapps/verify_student/management/commands/approve_id_verifications.py
@@ -75,7 +75,7 @@ def handle(self, *args, **options):
)
if failed_user_ids:
- log.error('Completed ID verification approvals. {} of {} failed.'.format(
+ log.error('Completed ID verification approvals. {} of {} failed.'.format( # noqa: UP032
len(failed_user_ids),
total_users,
))
diff --git a/lms/djangoapps/verify_student/management/commands/backfill_sso_verifications_for_old_account_links.py b/lms/djangoapps/verify_student/management/commands/backfill_sso_verifications_for_old_account_links.py
index e50c67d11d1f..9d4d4c200b8e 100644
--- a/lms/djangoapps/verify_student/management/commands/backfill_sso_verifications_for_old_account_links.py
+++ b/lms/djangoapps/verify_student/management/commands/backfill_sso_verifications_for_old_account_links.py
@@ -48,8 +48,8 @@ def handle(self, *args, **options):
try:
provider = Registry.get(provider_slug)
- except ValueError as e: # lint-amnesty, pylint: disable=unused-variable
- raise CommandError(f'provider slug {provider_slug} does not exist') # lint-amnesty, pylint: disable=raise-missing-from
+ except ValueError as e: # lint-amnesty, pylint: disable=unused-variable # noqa: F841
+ raise CommandError(f'provider slug {provider_slug} does not exist') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
query_set = UserSocialAuth.objects.select_related('user__profile')
query_set = filter_user_social_auth_queryset_by_provider(query_set, provider)
diff --git a/lms/djangoapps/verify_student/management/commands/manual_verifications.py b/lms/djangoapps/verify_student/management/commands/manual_verifications.py
index d73a49b7429e..67563849364c 100644
--- a/lms/djangoapps/verify_student/management/commands/manual_verifications.py
+++ b/lms/djangoapps/verify_student/management/commands/manual_verifications.py
@@ -66,7 +66,7 @@ def handle(self, *args, **options):
total_emails, failed_emails = self._generate_manual_verification_from_file(email_ids_file, batch_size)
if failed_emails:
- log.error('Completed manual verification. {} of {} failed.'.format(
+ log.error('Completed manual verification. {} of {} failed.'.format( # noqa: UP032
len(failed_emails),
total_emails
))
diff --git a/lms/djangoapps/verify_student/management/commands/send_verification_expiry_email.py b/lms/djangoapps/verify_student/management/commands/send_verification_expiry_email.py
index eea94cccd8f2..5a71f458d376 100644
--- a/lms/djangoapps/verify_student/management/commands/send_verification_expiry_email.py
+++ b/lms/djangoapps/verify_student/management/commands/send_verification_expiry_email.py
@@ -114,11 +114,11 @@ def handle(self, *args, **options):
total_verification = sspv.count()
if not total_verification:
- logger.info("No approved expired entries found in SoftwareSecurePhotoVerification for the "
+ logger.info("No approved expired entries found in SoftwareSecurePhotoVerification for the " # noqa: UP032
"date range {} - {}".format(start_date.date(), now().date()))
return
- logger.info("For the date range {} - {}, total Software Secure Photo verification filtered are {}"
+ logger.info("For the date range {} - {}, total Software Secure Photo verification filtered are {}" # noqa: UP032 # pylint: disable=line-too-long
.format(start_date.date(), now().date(), total_verification))
batch_verifications = []
@@ -184,7 +184,7 @@ def send_verification_expiry_email(self, batch_verifications, email_config):
"""
if email_config['dry_run']:
logger.info(
- "This was a dry run, no email was sent. For the actual run email would have been sent "
+ "This was a dry run, no email was sent. For the actual run email would have been sent " # noqa: UP032
"to {} learner(s)".format(len(batch_verifications))
)
return True
diff --git a/lms/djangoapps/verify_student/management/commands/tests/test_manual_verify_student.py b/lms/djangoapps/verify_student/management/commands/tests/test_manual_verify_student.py
index 704a66dc7bfe..7b69e93c2a76 100644
--- a/lms/djangoapps/verify_student/management/commands/tests/test_manual_verify_student.py
+++ b/lms/djangoapps/verify_student/management/commands/tests/test_manual_verify_student.py
@@ -77,7 +77,7 @@ def test_manual_verifications_created_date(self):
created_at__gte=earliest_allowed_verification_date()
)
- self.assertEqual(list(map(repr, verification1)), list(map(repr, verification2)))
+ self.assertEqual(list(map(repr, verification1)), list(map(repr, verification2))) # noqa: PT009
def test_user_doesnot_exist_log(self):
"""
diff --git a/lms/djangoapps/verify_student/management/commands/tests/test_retry_failed_photo_verifications.py b/lms/djangoapps/verify_student/management/commands/tests/test_retry_failed_photo_verifications.py
index f46f8a0e6aa1..b921789c899b 100644
--- a/lms/djangoapps/verify_student/management/commands/tests/test_retry_failed_photo_verifications.py
+++ b/lms/djangoapps/verify_student/management/commands/tests/test_retry_failed_photo_verifications.py
@@ -163,5 +163,5 @@ def test_resubmit_in_date_range(self, send_idv_update_mock):
photo_id_name=ANY, full_name=ANY
),
]
- self.assertEqual(send_idv_update_mock.call_count, 8)
+ self.assertEqual(send_idv_update_mock.call_count, 8) # noqa: PT009
send_idv_update_mock.assert_has_calls(expected_calls, any_order=True)
diff --git a/lms/djangoapps/verify_student/management/commands/tests/test_send_verification_expiry_email.py b/lms/djangoapps/verify_student/management/commands/tests/test_send_verification_expiry_email.py
index 54f527e2cdd1..b3ae087c8f5b 100644
--- a/lms/djangoapps/verify_student/management/commands/tests/test_send_verification_expiry_email.py
+++ b/lms/djangoapps/verify_student/management/commands/tests/test_send_verification_expiry_email.py
@@ -185,7 +185,7 @@ def test_no_verification_found(self):
call_command('send_verification_expiry_email')
logger.check(
(LOGGER_NAME,
- 'INFO', "No approved expired entries found in SoftwareSecurePhotoVerification for the "
+ 'INFO', "No approved expired entries found in SoftwareSecurePhotoVerification for the " # noqa: UP032
"date range {} - {}".format(start_date.date(), now().date()))
)
@@ -207,12 +207,12 @@ def test_dry_run_flag(self):
logger.check(
(LOGGER_NAME,
'INFO',
- "For the date range {} - {}, total Software Secure Photo verification filtered are {}"
+ "For the date range {} - {}, total Software Secure Photo verification filtered are {}" # noqa: UP032
.format(start_date.date(), now().date(), count)
),
(LOGGER_NAME,
'INFO',
- "This was a dry run, no email was sent. For the actual run email would have been sent "
+ "This was a dry run, no email was sent. For the actual run email would have been sent " # noqa: UP032
"to {} learner(s)".format(count)
))
assert len(mail.outbox) == 0
@@ -272,7 +272,7 @@ def test_number_of_emails_sent(self):
def test_command_error(self):
err_string = "DEFAULT_EMAILS must be a positive integer. If you do not wish to send " \
"emails use --dry-run flag instead."
- with self.assertRaisesRegex(CommandError, err_string):
+ with self.assertRaisesRegex(CommandError, err_string): # noqa: PT027
call_command('send_verification_expiry_email')
def test_one_failed_but_others_succeeded(self):
@@ -290,7 +290,7 @@ def test_one_failed_but_others_succeeded(self):
with patch('lms.djangoapps.verify_student.management.commands.send_verification_expiry_email.ace') as mock_ace:
mock_ace.send.side_effect = (Exception('Aw shucks'), None)
- with self.assertRaisesRegex(CommandError, 'One or more email attempts failed.*'):
+ with self.assertRaisesRegex(CommandError, 'One or more email attempts failed.*'): # noqa: PT027
with LogCapture(LOGGER_NAME) as logger:
call_command('send_verification_expiry_email')
diff --git a/lms/djangoapps/verify_student/management/commands/tests/test_trigger_softwaresecurephotoverifications_post_save_signal.py b/lms/djangoapps/verify_student/management/commands/tests/test_trigger_softwaresecurephotoverifications_post_save_signal.py
index 07102a82b322..483a84ed15a3 100644
--- a/lms/djangoapps/verify_student/management/commands/tests/test_trigger_softwaresecurephotoverifications_post_save_signal.py
+++ b/lms/djangoapps/verify_student/management/commands/tests/test_trigger_softwaresecurephotoverifications_post_save_signal.py
@@ -66,5 +66,5 @@ def test_command(self, send_idv_update_mock):
),
]
print(send_idv_update_mock.mock_calls)
- self.assertEqual(send_idv_update_mock.call_count, 4)
+ self.assertEqual(send_idv_update_mock.call_count, 4) # noqa: PT009
send_idv_update_mock.assert_has_calls(expected_calls, any_order=True)
diff --git a/lms/djangoapps/verify_student/models.py b/lms/djangoapps/verify_student/models.py
index 21ebb1280241..38380d0569de 100644
--- a/lms/djangoapps/verify_student/models.py
+++ b/lms/djangoapps/verify_student/models.py
@@ -80,7 +80,7 @@ def decorator_func(func):
@functools.wraps(func)
def with_status_check(obj, *args, **kwargs):
if obj.status not in valid_start_statuses:
- exception_msg = (
+ exception_msg = ( # noqa: UP032
"Error calling {} {}: status is '{}', must be one of: {}"
).format(func, obj, obj.status, valid_start_statuses)
raise VerificationException(exception_msg)
@@ -180,7 +180,7 @@ class Meta:
app_label = 'verify_student'
def __str__(self):
- return 'ManualIDVerification for {name}, status: {status}'.format(
+ return 'ManualIDVerification for {name}, status: {status}'.format( # noqa: UP032
name=self.name,
status=self.status,
)
@@ -230,7 +230,7 @@ class Meta:
app_label = "verify_student"
def __str__(self):
- return 'SSOIDVerification for {name}, status: {status}'.format(
+ return 'SSOIDVerification for {name}, status: {status}'.format( # noqa: UP032
name=self.name,
status=self.status,
)
@@ -243,7 +243,7 @@ def send_approval_signal(self, approved_by='None'):
"""
Send a signal indicating that this verification was approved.
"""
- log.info("Verification for user '{user_id}' approved by '{reviewer}' SSO.".format(
+ log.info("Verification for user '{user_id}' approved by '{reviewer}' SSO.".format( # noqa: UP032
user_id=self.user, reviewer=approved_by
))
@@ -438,7 +438,7 @@ def approve(self, user_id=None, service=""):
if self.status == self.STATUS.approved:
return
- log.info("Verification for user '{user_id}' approved by '{reviewer}'.".format(
+ log.info("Verification for user '{user_id}' approved by '{reviewer}'.".format( # noqa: UP032
user_id=self.user, reviewer=user_id
))
self.error_msg = "" # reset, in case this attempt was denied before
@@ -541,7 +541,7 @@ def deny(self,
lets you amend the error message in case there were additional
details to be made.
"""
- log.info("Verification for user '{user_id}' denied by '{reviewer}'.".format(
+ log.info("Verification for user '{user_id}' denied by '{reviewer}'.".format( # noqa: UP032
user_id=self.user, reviewer=reviewing_user
))
self.error_msg = error_msg
diff --git a/lms/djangoapps/verify_student/signals/handlers.py b/lms/djangoapps/verify_student/signals/handlers.py
index daaa59c813b5..f5c6c8e588ff 100644
--- a/lms/djangoapps/verify_student/signals/handlers.py
+++ b/lms/djangoapps/verify_student/signals/handlers.py
@@ -8,7 +8,7 @@
from django.dispatch.dispatcher import receiver
from common.djangoapps.student.models_api import get_name, get_pending_name_change
-from lms.djangoapps.verify_student.apps import VerifyStudentConfig # pylint: disable=unused-import
+from lms.djangoapps.verify_student.apps import VerifyStudentConfig # pylint: disable=unused-import # noqa: F401
from lms.djangoapps.verify_student.models import (
SoftwareSecurePhotoVerification,
VerificationAttempt,
@@ -59,7 +59,7 @@ def send_idv_update(sender, instance, **kwargs): # pylint: disable=unused-argum
full_name = get_name(instance.user.id)
log.info(
- 'IDV sending name_affirmation task (idv_id={idv_id}, user_id={user_id}) to update status={status}'.format(
+ 'IDV sending name_affirmation task (idv_id={idv_id}, user_id={user_id}) to update status={status}'.format( # noqa: UP032 # pylint: disable=line-too-long
user_id=instance.user.id,
status=instance.status,
idv_id=instance.id
diff --git a/lms/djangoapps/verify_student/tests/__init__.py b/lms/djangoapps/verify_student/tests/__init__.py
index 015cd354aba7..40d42425068c 100644
--- a/lms/djangoapps/verify_student/tests/__init__.py
+++ b/lms/djangoapps/verify_student/tests/__init__.py
@@ -3,7 +3,7 @@
from datetime import timedelta
from unittest import mock
-from django.conf import settings
+from django.conf import settings # noqa: F401
from django.db import DEFAULT_DB_ALIAS
from django.test import TestCase
from django.utils.timezone import now
diff --git a/lms/djangoapps/verify_student/tests/factories.py b/lms/djangoapps/verify_student/tests/factories.py
index d7eaeaf30211..e1e1648159f2 100644
--- a/lms/djangoapps/verify_student/tests/factories.py
+++ b/lms/djangoapps/verify_student/tests/factories.py
@@ -17,7 +17,7 @@ class Meta:
class SSOVerificationFactory(DjangoModelFactory):
- class Meta():
+ class Meta(): # noqa: UP039
model = SSOVerification
diff --git a/lms/djangoapps/verify_student/tests/test_api.py b/lms/djangoapps/verify_student/tests/test_api.py
index 79d583ee9032..abea28e8dbe3 100644
--- a/lms/djangoapps/verify_student/tests/test_api.py
+++ b/lms/djangoapps/verify_student/tests/test_api.py
@@ -65,39 +65,39 @@ def setUp(self):
user=self.user,
name='Tester McTest',
status=VerificationAttemptStatus.CREATED,
- expiration_datetime=datetime(2024, 12, 31, tzinfo=timezone.utc)
+ expiration_datetime=datetime(2024, 12, 31, tzinfo=timezone.utc) # noqa: UP017
)
self.attempt.save()
@patch('lms.djangoapps.verify_student.api.emit_idv_attempt_created_event')
def test_create_verification_attempt(self, mock_created_event):
expected_id = 2
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
create_verification_attempt(
user=self.user,
name='Tester McTest',
status=VerificationAttemptStatus.CREATED,
- expiration_datetime=datetime(2024, 12, 31, tzinfo=timezone.utc)
+ expiration_datetime=datetime(2024, 12, 31, tzinfo=timezone.utc) # noqa: UP017
),
expected_id
)
verification_attempt = VerificationAttempt.objects.get(id=expected_id)
- self.assertEqual(verification_attempt.user, self.user)
- self.assertEqual(verification_attempt.name, 'Tester McTest')
- self.assertEqual(verification_attempt.status, VerificationAttemptStatus.CREATED)
- self.assertEqual(verification_attempt.expiration_datetime, datetime(2024, 12, 31, tzinfo=timezone.utc))
+ self.assertEqual(verification_attempt.user, self.user) # noqa: PT009
+ self.assertEqual(verification_attempt.name, 'Tester McTest') # noqa: PT009
+ self.assertEqual(verification_attempt.status, VerificationAttemptStatus.CREATED) # noqa: PT009
+ self.assertEqual(verification_attempt.expiration_datetime, datetime(2024, 12, 31, tzinfo=timezone.utc)) # noqa: PT009, UP017 # pylint: disable=line-too-long
mock_created_event.assert_called_with(
attempt_id=verification_attempt.id,
user=self.user,
status=VerificationAttemptStatus.CREATED,
name='Tester McTest',
- expiration_date=datetime(2024, 12, 31, tzinfo=timezone.utc),
+ expiration_date=datetime(2024, 12, 31, tzinfo=timezone.utc), # noqa: UP017
)
def test_create_verification_attempt_no_expiration_datetime(self):
expected_id = 2
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
create_verification_attempt(
user=self.user,
name='Tester McTest',
@@ -107,10 +107,10 @@ def test_create_verification_attempt_no_expiration_datetime(self):
)
verification_attempt = VerificationAttempt.objects.get(id=expected_id)
- self.assertEqual(verification_attempt.user, self.user)
- self.assertEqual(verification_attempt.name, 'Tester McTest')
- self.assertEqual(verification_attempt.status, VerificationAttemptStatus.CREATED)
- self.assertEqual(verification_attempt.expiration_datetime, None)
+ self.assertEqual(verification_attempt.user, self.user) # noqa: PT009
+ self.assertEqual(verification_attempt.name, 'Tester McTest') # noqa: PT009
+ self.assertEqual(verification_attempt.status, VerificationAttemptStatus.CREATED) # noqa: PT009
+ self.assertEqual(verification_attempt.expiration_datetime, None) # noqa: PT009
@ddt.ddt
@@ -127,14 +127,14 @@ def setUp(self):
user=self.user,
name='Tester McTest',
status=VerificationAttemptStatus.CREATED,
- expiration_datetime=datetime(2024, 12, 31, tzinfo=timezone.utc)
+ expiration_datetime=datetime(2024, 12, 31, tzinfo=timezone.utc) # noqa: UP017
)
self.attempt.save()
@ddt.data(
- ('Tester McTest', VerificationAttemptStatus.PENDING, datetime(2024, 12, 31, tzinfo=timezone.utc)),
- ('Tester McTest2', VerificationAttemptStatus.APPROVED, datetime(2025, 12, 31, tzinfo=timezone.utc)),
- ('Tester McTest3', VerificationAttemptStatus.DENIED, datetime(2026, 12, 31, tzinfo=timezone.utc)),
+ ('Tester McTest', VerificationAttemptStatus.PENDING, datetime(2024, 12, 31, tzinfo=timezone.utc)), # noqa: UP017 # pylint: disable=line-too-long
+ ('Tester McTest2', VerificationAttemptStatus.APPROVED, datetime(2025, 12, 31, tzinfo=timezone.utc)), # noqa: UP017 # pylint: disable=line-too-long
+ ('Tester McTest3', VerificationAttemptStatus.DENIED, datetime(2026, 12, 31, tzinfo=timezone.utc)), # noqa: UP017 # pylint: disable=line-too-long
)
@ddt.unpack
@patch('lms.djangoapps.verify_student.api.emit_idv_attempt_pending_event')
@@ -159,10 +159,10 @@ def test_update_verification_attempt(
verification_attempt = VerificationAttempt.objects.get(id=self.attempt.id)
# Values should change as a result of this update.
- self.assertEqual(verification_attempt.user, self.user)
- self.assertEqual(verification_attempt.name, name)
- self.assertEqual(verification_attempt.status, status)
- self.assertEqual(verification_attempt.expiration_datetime, expiration_datetime)
+ self.assertEqual(verification_attempt.user, self.user) # noqa: PT009
+ self.assertEqual(verification_attempt.name, name) # noqa: PT009
+ self.assertEqual(verification_attempt.status, status) # noqa: PT009
+ self.assertEqual(verification_attempt.expiration_datetime, expiration_datetime) # noqa: PT009
if status == VerificationAttemptStatus.PENDING:
mock_pending_event.assert_called_with(
@@ -200,13 +200,13 @@ def test_update_verification_attempt_none_values(self):
verification_attempt = VerificationAttempt.objects.get(id=self.attempt.id)
# Values should not change as a result of the values passed in being None, except for expiration_datetime.
- self.assertEqual(verification_attempt.user, self.user)
- self.assertEqual(verification_attempt.name, self.attempt.name)
- self.assertEqual(verification_attempt.status, self.attempt.status)
- self.assertEqual(verification_attempt.expiration_datetime, None)
+ self.assertEqual(verification_attempt.user, self.user) # noqa: PT009
+ self.assertEqual(verification_attempt.name, self.attempt.name) # noqa: PT009
+ self.assertEqual(verification_attempt.status, self.attempt.status) # noqa: PT009
+ self.assertEqual(verification_attempt.expiration_datetime, None) # noqa: PT009
def test_update_verification_attempt_not_found(self):
- self.assertRaises(
+ self.assertRaises( # noqa: PT027
VerificationAttempt.DoesNotExist,
update_verification_attempt,
attempt_id=999999,
@@ -221,7 +221,7 @@ def test_update_verification_attempt_not_found(self):
'expired',
)
def test_update_verification_attempt_invalid(self, status):
- self.assertRaises(
+ self.assertRaises( # noqa: PT027
VerificationAttemptInvalidStatus,
update_verification_attempt,
attempt_id=self.attempt.id,
diff --git a/lms/djangoapps/verify_student/tests/test_handlers.py b/lms/djangoapps/verify_student/tests/test_handlers.py
index a3d792c1b3c9..e2693f651969 100644
--- a/lms/djangoapps/verify_student/tests/test_handlers.py
+++ b/lms/djangoapps/verify_student/tests/test_handlers.py
@@ -144,7 +144,7 @@ def test_post_save_signal(self, mock_signal):
photo_id_image_url=self.photo_id_image_url,
photo_id_key=self.photo_id_key
)
- self.assertTrue(mock_signal.called)
+ self.assertTrue(mock_signal.called) # noqa: PT009
mock_signal.assert_called_with(
sender='idv_update',
attempt_id=attempt.id,
@@ -157,7 +157,7 @@ def test_post_save_signal(self, mock_signal):
attempt.mark_ready()
- self.assertTrue(mock_signal.called)
+ self.assertTrue(mock_signal.called) # noqa: PT009
mock_signal.assert_called_with(
sender='idv_update',
attempt_id=attempt.id,
@@ -203,10 +203,10 @@ def setUp(self):
def test_retirement_signal(self):
_listen_for_lms_retire_verification_attempts(sender=self.__class__, user=self.user)
- self.assertEqual(len(VerificationAttempt.objects.filter(user=self.user)), 0)
- self.assertEqual(len(VerificationAttempt.objects.filter(user=self.other_user)), 1)
+ self.assertEqual(len(VerificationAttempt.objects.filter(user=self.user)), 0) # noqa: PT009
+ self.assertEqual(len(VerificationAttempt.objects.filter(user=self.other_user)), 1) # noqa: PT009
def test_retirement_signal_no_attempts(self):
no_attempt_user = UserFactory.create()
_listen_for_lms_retire_verification_attempts(sender=self.__class__, user=no_attempt_user)
- self.assertEqual(len(VerificationAttempt.objects.all()), 2)
+ self.assertEqual(len(VerificationAttempt.objects.all()), 2) # noqa: PT009
diff --git a/lms/djangoapps/verify_student/tests/test_services.py b/lms/djangoapps/verify_student/tests/test_services.py
index 7cf68a66295a..608caf223555 100644
--- a/lms/djangoapps/verify_student/tests/test_services.py
+++ b/lms/djangoapps/verify_student/tests/test_services.py
@@ -207,10 +207,10 @@ def test_get_expiration_datetime(self):
user_a = UserFactory.create()
SSOVerification.objects.create(
- user=user_a, status='approved', expiration_date=datetime(2021, 11, 12, 0, 0, tzinfo=timezone.utc)
+ user=user_a, status='approved', expiration_date=datetime(2021, 11, 12, 0, 0, tzinfo=timezone.utc) # noqa: UP017 # pylint: disable=line-too-long
)
newer_record = SSOVerification.objects.create(
- user=user_a, status='approved', expiration_date=datetime(2022, 1, 12, 0, 0, tzinfo=timezone.utc)
+ user=user_a, status='approved', expiration_date=datetime(2022, 1, 12, 0, 0, tzinfo=timezone.utc) # noqa: UP017 # pylint: disable=line-too-long
)
expiration_datetime = IDVerificationService.get_expiration_datetime(user_a, ['approved'])
@@ -224,10 +224,10 @@ def test_get_expiration_datetime_mixed_models(self):
user = UserFactory.create()
SoftwareSecurePhotoVerification.objects.create(
- user=user, status='approved', expiration_date=datetime(2021, 11, 12, 0, 0, tzinfo=timezone.utc)
+ user=user, status='approved', expiration_date=datetime(2021, 11, 12, 0, 0, tzinfo=timezone.utc) # noqa: UP017 # pylint: disable=line-too-long
)
newest = VerificationAttempt.objects.create(
- user=user, status='approved', expiration_datetime=datetime(2022, 1, 12, 0, 0, tzinfo=timezone.utc)
+ user=user, status='approved', expiration_datetime=datetime(2022, 1, 12, 0, 0, tzinfo=timezone.utc) # noqa: UP017 # pylint: disable=line-too-long
)
expiration_datetime = IDVerificationService.get_expiration_datetime(user, ['approved'])
@@ -335,7 +335,7 @@ def test_no_verification(self):
status = IDVerificationService.user_status(self.user)
expected_status = {'status': 'none', 'error': '', 'should_display': True, 'verification_expiry': '',
'status_date': ''}
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
def test_approved_software_secure_verification(self):
with freeze_time('2015-01-02'):
@@ -344,7 +344,7 @@ def test_approved_software_secure_verification(self):
status = IDVerificationService.user_status(self.user)
expected_status = {'status': 'approved', 'error': '', 'should_display': True, 'verification_expiry': '',
'status_date': datetime.now(utc)}
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
def test_denied_software_secure_verification(self):
with freeze_time('2015-2-02'):
@@ -358,7 +358,7 @@ def test_denied_software_secure_verification(self):
'status': 'must_reverify', 'error': ['id_image_missing'],
'should_display': True, 'verification_expiry': '', 'status_date': '',
}
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
def test_approved_verification_attempt_verification(self):
with freeze_time('2015-01-02'):
@@ -367,7 +367,7 @@ def test_approved_verification_attempt_verification(self):
status = IDVerificationService.user_status(self.user)
expected_status = {'status': 'approved', 'error': '', 'should_display': True, 'verification_expiry': '',
'status_date': datetime.now(utc)}
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
def test_denied_verification_attempt_verification(self):
with freeze_time('2015-2-02'):
@@ -381,7 +381,7 @@ def test_denied_verification_attempt_verification(self):
'status': 'must_reverify', 'error': '',
'should_display': True, 'verification_expiry': '', 'status_date': '',
}
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
def test_approved_sso_verification(self):
with freeze_time('2015-03-02'):
@@ -390,7 +390,7 @@ def test_approved_sso_verification(self):
status = IDVerificationService.user_status(self.user)
expected_status = {'status': 'approved', 'error': '', 'should_display': False, 'verification_expiry': '',
'status_date': datetime.now(utc)}
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
def test_denied_sso_verification(self):
with freeze_time('2015-04-02'):
@@ -402,7 +402,7 @@ def test_denied_sso_verification(self):
'status': 'must_reverify', 'error': '', 'should_display': False,
'verification_expiry': '', 'status_date': ''
}
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
def test_manual_verification(self):
with freeze_time('2015-05-02'):
@@ -411,7 +411,7 @@ def test_manual_verification(self):
status = IDVerificationService.user_status(self.user)
expected_status = {'status': 'approved', 'error': '', 'should_display': False, 'verification_expiry': '',
'status_date': datetime.now(utc)}
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
@ddt.idata(itertools.product(
[SoftwareSecurePhotoVerification, VerificationAttempt],
@@ -432,7 +432,7 @@ def test_expiring_software_secure_verification(self, value):
expected_status = {'status': 'approved', 'error': '', 'should_display': True, 'verification_expiry': '',
'status_date': status_date}
status = IDVerificationService.user_status(self.user)
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
@ddt.data(SoftwareSecurePhotoVerification, VerificationAttempt)
def test_expired_verification(self, verification_model):
@@ -456,7 +456,7 @@ def test_expired_verification(self, verification_model):
'status_date': ''
}
status = IDVerificationService.user_status(self.user)
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
@ddt.idata(itertools.product(
[SoftwareSecurePhotoVerification, VerificationAttempt],
@@ -496,7 +496,7 @@ def test_reverify_after_expired(self, value):
expected_status = {'status': check_status, 'error': '', 'should_display': True, 'verification_expiry': '',
'status_date': status_date}
status = IDVerificationService.user_status(self.user)
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
@ddt.data(
SSOVerification,
@@ -525,7 +525,7 @@ def test_override_verification(self, verification_model):
'verification_expiry': '', 'status_date': now()
}
status = IDVerificationService.user_status(self.user)
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
@ddt.data(
SSOVerification,
@@ -554,4 +554,4 @@ def test_denied_after_approved_verification(self, verification_model):
'verification_expiry': '', 'status_date': expected_date
}
status = IDVerificationService.user_status(self.user)
- self.assertDictEqual(status, expected_status)
+ self.assertDictEqual(status, expected_status) # noqa: PT009
diff --git a/lms/djangoapps/verify_student/tests/test_utils.py b/lms/djangoapps/verify_student/tests/test_utils.py
index f8f6b24d4706..936664a68780 100644
--- a/lms/djangoapps/verify_student/tests/test_utils.py
+++ b/lms/djangoapps/verify_student/tests/test_utils.py
@@ -11,7 +11,7 @@
import ddt
from django.conf import settings
from django.utils import timezone
-from pytest import mark
+from pytest import mark # noqa: PT013
from common.djangoapps.student.tests.factories import UserFactory
from lms.djangoapps.verify_student.models import ManualVerification, SoftwareSecurePhotoVerification, SSOVerification
diff --git a/lms/djangoapps/verify_student/tests/test_views.py b/lms/djangoapps/verify_student/tests/test_views.py
index 5645b0b90b7c..465bd2e2214d 100644
--- a/lms/djangoapps/verify_student/tests/test_views.py
+++ b/lms/djangoapps/verify_student/tests/test_views.py
@@ -860,7 +860,7 @@ def _set_verification_status(self, status):
attempt.system_error("Error!")
if status == "expired":
- days_good_for = settings.VERIFY_STUDENT["DAYS_GOOD_FOR"] # lint-amnesty, pylint: disable=unused-variable
+ days_good_for = settings.VERIFY_STUDENT["DAYS_GOOD_FOR"] # lint-amnesty, pylint: disable=unused-variable # noqa: F841
attempt.expiration_date = now() - timedelta(days=1)
attempt.save()
@@ -1183,7 +1183,7 @@ def make_sku(self):
def _get_checkout_args(self, patched_create_order):
""" Assuming patched_create_order was called, return a mapping containing the call arguments."""
- return dict(list(zip(('user', 'course_key', 'course_mode', 'processor'), patched_create_order.call_args[0])))
+ return dict(list(zip(('user', 'course_key', 'course_mode', 'processor'), patched_create_order.call_args[0]))) # noqa: B905 # pylint: disable=line-too-long
class TestCheckoutWithEcommerceService(ModuleStoreTestCase):
@@ -1272,7 +1272,7 @@ def test_submit_photos_and_change_name(self, flag_on):
# Since we are giving a full name, it should be written into the attempt
# whether or not the user name was updated
attempt = SoftwareSecurePhotoVerification.objects.get(user=self.user)
- self.assertEqual(attempt.name, self.FULL_NAME)
+ self.assertEqual(attempt.name, self.FULL_NAME) # noqa: PT009
def test_submit_photos_sends_confirmation_email(self):
self._submit_photos(
@@ -1584,7 +1584,7 @@ def test_wrong_edx_id(self):
)
@patch('lms.djangoapps.verify_student.views.log.error')
@patch('lms.djangoapps.verify_student.views.segment.track')
- def test_passed_status_template(self, mock_segment_track, _mock_log_error):
+ def test_passed_status_template(self, mock_segment_track, _mock_log_error): # noqa: PT019
"""
Test for verification passed.
"""
@@ -1649,7 +1649,7 @@ def test_approved_email_without_ace(self):
)
@patch('lms.djangoapps.verify_student.views.log.error')
@patch('lms.djangoapps.verify_student.views.segment.track')
- def test_first_time_verification(self, mock_segment_track, _mock_log_error):
+ def test_first_time_verification(self, mock_segment_track, _mock_log_error): # noqa: PT019
"""
Test for verification passed if the learner does not have any previous verification
"""
@@ -1683,7 +1683,7 @@ def test_first_time_verification(self, mock_segment_track, _mock_log_error):
)
@patch('lms.djangoapps.verify_student.views.log.error')
@patch('lms.djangoapps.verify_student.views.segment.track')
- def test_failed_status_template(self, mock_segment_track, _mock_log_error):
+ def test_failed_status_template(self, mock_segment_track, _mock_log_error): # noqa: PT019
"""
Test for failed verification.
"""
@@ -1955,9 +1955,9 @@ def test_photo_url_view_returns_data(self):
assert response.status_code == 200
assert response.data['EdX-ID'] == self.receipt_id
assert response.data['PhotoID'] == 'https://{bucket}/photo_id/{receipt_id}'\
- .format(bucket=settings.AWS_S3_CUSTOM_DOMAIN, receipt_id=self.receipt_id)
+ .format(bucket=settings.AWS_S3_CUSTOM_DOMAIN, receipt_id=self.receipt_id) # noqa: UP032
assert response.data['UserPhoto'] == 'https://{bucket}/face/{receipt_id}'\
- .format(bucket=settings.AWS_S3_CUSTOM_DOMAIN, receipt_id=self.receipt_id)
+ .format(bucket=settings.AWS_S3_CUSTOM_DOMAIN, receipt_id=self.receipt_id) # noqa: UP032
def test_photo_url_view_returns_404_if_invalid_receipt_id(self):
url = reverse('verification_photo_urls',
@@ -2049,7 +2049,7 @@ def _decode_image(self, receipt_id, img_type):
@ddt.data("face", "photo_id")
@patch.object(SoftwareSecurePhotoVerification, '_get_image_from_storage')
- def test_download_image_response(self, img_type, _mock_get_storage):
+ def test_download_image_response(self, img_type, _mock_get_storage): # noqa: PT019
_mock_get_storage.return_value = encrypt_and_encode(
b'\xd7m\xf8',
codecs.decode(settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["FACE_IMAGE_AES_KEY"], "hex")
@@ -2111,7 +2111,7 @@ def test_404_if_invalid_receipt_id(self, img_type):
@ddt.data("face", "photo_id")
@patch.object(SoftwareSecurePhotoVerification, '_get_image_from_storage')
- def test_404_for_decryption_error(self, img_type, _mock_get_storage):
+ def test_404_for_decryption_error(self, img_type, _mock_get_storage): # noqa: PT019
_mock_get_storage.return_value = None
# create verification with no img data
attempt = SoftwareSecurePhotoVerification(
diff --git a/lms/djangoapps/verify_student/views.py b/lms/djangoapps/verify_student/views.py
index 1655f224c10d..3222802af75e 100644
--- a/lms/djangoapps/verify_student/views.py
+++ b/lms/djangoapps/verify_student/views.py
@@ -916,7 +916,7 @@ def _validate_parameters(self, request, has_initial_verification):
# The face image is always required.
if "face_image" not in params:
msg = _("Missing required parameter face_image")
- log.error(("User {user_id} missing required parameter face_image").format(user_id=request.user.id))
+ log.error(("User {user_id} missing required parameter face_image").format(user_id=request.user.id)) # noqa: UP032 # pylint: disable=line-too-long
return None, HttpResponseBadRequest(msg)
return params, None
@@ -942,12 +942,12 @@ def _validate_and_decode_image_data(self, request, face_data, photo_id_data=None
data_type = image_data.split(',')[0]
if data_type:
log.error(
- "Image data for user_id={user_id} was uploaded in an unsupported "
+ "Image data for user_id={user_id} was uploaded in an unsupported " # noqa: UP032
"format: {data_type}".format(user_id=request.user.id, data_type=data_type)
)
else:
log.error(
- "Image data type for user_id={user_id} could not be identified.".format(
+ "Image data type for user_id={user_id} could not be identified.".format( # noqa: UP032
user_id=request.user.id
)
)
@@ -967,7 +967,7 @@ def _validate_and_decode_image_data(self, request, face_data, photo_id_data=None
except InvalidImageData:
msg = _("Image data is not valid.")
- log.error(("Image data for user {user_id} is not valid").format(user_id=request.user.id))
+ log.error(("Image data for user {user_id} is not valid").format(user_id=request.user.id)) # noqa: UP032
return None, None, HttpResponseBadRequest(msg)
def _submit_attempt(self, user, face_image, photo_id_image=None, initial_verification=None, provided_name=None):
@@ -1077,7 +1077,7 @@ def results_callback(request): # lint-amnesty, pylint: disable=too-many-stateme
# TODO: These logs must be removed once the investigation in COSMO-184 is complete.
# COSMO-196 was created to track the cleanup of these logs.
log.info(
- "[COSMO-184] Software Secure review received for receipt_id={receipt_id}, "
+ "[COSMO-184] Software Secure review received for receipt_id={receipt_id}, " # noqa: UP032
"with result={result} and reason={reason}."
.format(
receipt_id=receipt_id,
@@ -1116,7 +1116,7 @@ def results_callback(request): # lint-amnesty, pylint: disable=too-many-stateme
# TODO: These logs must be removed once the investigation in COSMO-184 is complete.
# COSMO-196 was created to track the cleanup of these logs.
- log.info("[COSMO-184] Approved verification for receipt_id={receipt_id}.".format(receipt_id=receipt_id))
+ log.info("[COSMO-184] Approved verification for receipt_id={receipt_id}.".format(receipt_id=receipt_id)) # noqa: UP032
attempt.approve()
send_approval_email(attempt)
@@ -1125,7 +1125,7 @@ def results_callback(request): # lint-amnesty, pylint: disable=too-many-stateme
# TODO: These logs must be removed once the investigation in COSMO-184 is complete.
# COSMO-196 was created to track the cleanup of these logs.
- log.info("[COSMO-184] Denied verification for receipt_id={receipt_id}.".format(receipt_id=receipt_id))
+ log.info("[COSMO-184] Denied verification for receipt_id={receipt_id}.".format(receipt_id=receipt_id)) # noqa: UP032
attempt.deny(json.dumps(reason), error_code=error_code)
account_base_url = (
diff --git a/lms/envs/common.py b/lms/envs/common.py
index e5f7bde8df13..0015f3f170f5 100644
--- a/lms/envs/common.py
+++ b/lms/envs/common.py
@@ -66,7 +66,7 @@
from openedx.core.djangoapps.plugins.constants import ProjectType, SettingsType
from openedx.core.lib.derived import Derived
from openedx.core.lib.features_setting_proxy import FeaturesProxy
-from openedx.envs.common import * # pylint: disable=wildcard-import
+from openedx.envs.common import * # pylint: disable=wildcard-import # noqa: F403
# A proxy for feature flags stored in the settings namespace
FEATURES = FeaturesProxy(globals())
@@ -778,14 +778,14 @@
############################# SET PATH INFORMATION #############################
PROJECT_ROOT = path(__file__).abspath().dirname().dirname() # /edx-platform/lms
-NODE_MODULES_ROOT = REPO_ROOT / "node_modules"
+NODE_MODULES_ROOT = REPO_ROOT / "node_modules" # noqa: F405
# Where to look for a status message
-STATUS_MESSAGE_PATH = ENV_ROOT / "status_message.json"
+STATUS_MESSAGE_PATH = ENV_ROOT / "status_message.json" # noqa: F405
############################ Global Database Configuration #####################
-DATABASE_ROUTERS.append('edx_django_utils.db.read_replica.ReadReplicaRouter')
+DATABASE_ROUTERS.append('edx_django_utils.db.read_replica.ReadReplicaRouter') # noqa: F405
################################## DJANGO OAUTH TOOLKIT #######################################
@@ -842,10 +842,10 @@
################################## TEMPLATE CONFIGURATION #####################################
-MAKO_TEMPLATE_DIRS_BASE = lms_mako_template_dirs_base
+MAKO_TEMPLATE_DIRS_BASE = lms_mako_template_dirs_base # noqa: F405
-CONTEXT_PROCESSORS.remove('django.contrib.messages.context_processors.messages')
-CONTEXT_PROCESSORS[5:5] = [
+CONTEXT_PROCESSORS.remove('django.contrib.messages.context_processors.messages') # noqa: F405
+CONTEXT_PROCESSORS[5:5] = [ # noqa: F405
# Added for django-wiki
'django.template.context_processors.media',
'django.template.context_processors.tz',
@@ -858,7 +858,7 @@
# Timezone processor (sends language and time_zone preference)
'lms.djangoapps.courseware.context_processor.user_timezone_locale_prefs',
]
-CONTEXT_PROCESSORS += [
+CONTEXT_PROCESSORS += [ # noqa: F405
# Mobile App processor (Detects if request is from the mobile app)
'lms.djangoapps.mobile_api.context_processor.is_from_mobile_app',
@@ -890,8 +890,8 @@
EDX_API_KEY = None
-LOGIN_REDIRECT_URL = EDX_ROOT_URL + '/login'
-LOGIN_URL = EDX_ROOT_URL + '/login'
+LOGIN_REDIRECT_URL = EDX_ROOT_URL + '/login' # noqa: F405
+LOGIN_URL = EDX_ROOT_URL + '/login' # noqa: F405
CERT_QUEUE = 'test-pull'
@@ -920,7 +920,7 @@
DEBUG_TRACK_LOG = False
-TRACKING_IGNORE_URL_PATTERNS += [r'^/segmentio/event', r'^/performance']
+TRACKING_IGNORE_URL_PATTERNS += [r'^/segmentio/event', r'^/performance'] # noqa: F405
TRACKING_SEGMENTIO_WEBHOOK_SECRET = None
TRACKING_SEGMENTIO_ALLOWED_TYPES = ['track']
@@ -947,8 +947,8 @@
############# ModuleStore Configuration ##########
-CONTENTSTORE['DOC_STORE_CONFIG']['password'] = 'password'
-CONTENTSTORE['DOC_STORE_CONFIG']['read_preference'] = 'SECONDARY_PREFERRED'
+CONTENTSTORE['DOC_STORE_CONFIG']['password'] = 'password' # noqa: F405
+CONTENTSTORE['DOC_STORE_CONFIG']['read_preference'] = 'SECONDARY_PREFERRED' # noqa: F405
MODULESTORE_BRANCH = 'published-only'
@@ -1025,9 +1025,9 @@
# Static content
STATIC_URL = '/static/'
-STATIC_ROOT = os.environ.get('STATIC_ROOT_LMS', ENV_ROOT / "staticfiles")
+STATIC_ROOT = os.environ.get('STATIC_ROOT_LMS', ENV_ROOT / "staticfiles") # noqa: F405
-STATICFILES_DIRS.insert(2, NODE_MODULES_ROOT / "@edx")
+STATICFILES_DIRS.insert(2, NODE_MODULES_ROOT / "@edx") # noqa: F405
# Guidelines for translators
TRANSLATORS_GUIDE = 'https://docs.openedx.org/en/latest/translators/index.html'
@@ -1289,7 +1289,7 @@
############################### PIPELINE #######################################
-PIPELINE['JS_COMPRESSOR'] = 'pipeline.compressors.uglifyjs.UglifyJSCompressor'
+PIPELINE['JS_COMPRESSOR'] = 'pipeline.compressors.uglifyjs.UglifyJSCompressor' # noqa: F405
from openedx.core.lib.rooted_paths import rooted_glob # pylint: disable=wrong-import-position
@@ -1359,7 +1359,7 @@
rooted_glob(PROJECT_ROOT / 'static', 'js/customwmd.js') +
rooted_glob(PROJECT_ROOT / 'static', 'js/mathjax_accessible.js') +
rooted_glob(PROJECT_ROOT / 'static', 'js/mathjax_delay_renderer.js') +
- sorted(rooted_glob(COMMON_ROOT / 'static', 'common/js/discussion/**/*.js'))
+ sorted(rooted_glob(COMMON_ROOT / 'static', 'common/js/discussion/**/*.js')) # noqa: F405
)
discussion_vendor_js = [
@@ -1433,7 +1433,7 @@
'js/src/logger.js',
]
-PIPELINE['STYLESHEETS'] = {
+PIPELINE['STYLESHEETS'] = { # noqa: F405
'style-vendor': {
'source_filenames': [
'css/vendor/font-awesome.css',
@@ -1571,7 +1571,7 @@
'js/main.js',
]
-PIPELINE['JAVASCRIPT'] = {
+PIPELINE['JAVASCRIPT'] = { # noqa: F405
'base_application': {
'source_filenames': base_application_js,
'output_filename': 'js/lms-base-application.js',
@@ -1753,7 +1753,7 @@
############################# Email Opt In ####################################
# Minimum age for organization-wide email opt in
-EMAIL_OPTIN_MINIMUM_AGE = PARENTAL_CONSENT_AGE_LIMIT
+EMAIL_OPTIN_MINIMUM_AGE = PARENTAL_CONSENT_AGE_LIMIT # noqa: F405
################################### APPS ######################################
@@ -2103,7 +2103,7 @@
]
# Add LMS specific optional apps
-OPTIONAL_APPS += [
+OPTIONAL_APPS += [ # noqa: F405
# Channel Integrations Apps
('channel_integrations.integrated_channel', None),
('channel_integrations.degreed2', None),
@@ -2118,7 +2118,7 @@
('django_object_actions', None), # https://github.com/crccheck/django-object-actions
]
-add_optional_apps(OPTIONAL_APPS, INSTALLED_APPS)
+add_optional_apps(OPTIONAL_APPS, INSTALLED_APPS) # noqa: F405
######################### Django Rest Framework ########################
@@ -2129,7 +2129,7 @@
######################### MARKETING SITE ###############################
-MKTG_URL_LINK_MAP.update({
+MKTG_URL_LINK_MAP.update({ # noqa: F405
'ABOUT': 'about',
'CONTACT': 'contact',
'FAQ': 'help',
@@ -2164,7 +2164,7 @@
############################# SOCIAL MEDIA SHARING #############################
# Social Media Sharing on Student Dashboard
-SOCIAL_SHARING_SETTINGS.update({
+SOCIAL_SHARING_SETTINGS.update({ # noqa: F405
'FACEBOOK_BRAND': None,
'CERTIFICATE_FACEBOOK_TEXT': None,
'TWITTER_BRAND': None,
@@ -2601,7 +2601,7 @@
################################ Settings for JWTs ################################
# Allows JWT authentication to find the LMS user id for verification
-EDX_DRF_EXTENSIONS['VERIFY_LMS_USER_ID_PROPERTY_NAME'] = 'id'
+EDX_DRF_EXTENSIONS['VERIFY_LMS_USER_ID_PROPERTY_NAME'] = 'id' # noqa: F405
################################ Settings for rss_proxy ################################
@@ -3138,7 +3138,7 @@
def _should_send_certificate_events(settings):
return settings.SEND_LEARNING_CERTIFICATE_LIFECYCLE_EVENTS_TO_BUS
-EVENT_BUS_PRODUCER_CONFIG.update({
+EVENT_BUS_PRODUCER_CONFIG.update({ # noqa: F405
'org.openedx.learning.certificate.created.v1': {
'learning-certificate-lifecycle':
{'event_key_field': 'certificate.course.course_key', 'enabled': Derived(_should_send_certificate_events)},
diff --git a/lms/envs/devstack.py b/lms/envs/devstack.py
index 5289d5c0b595..ab04c9af33f1 100644
--- a/lms/envs/devstack.py
+++ b/lms/envs/devstack.py
@@ -16,11 +16,11 @@
from openedx.core.djangoapps.plugins.constants import ProjectType, SettingsType
from openedx.core.lib.features_setting_proxy import FeaturesProxy
-from .production import * # pylint: disable=wildcard-import, unused-wildcard-import
+from .production import * # pylint: disable=wildcard-import, unused-wildcard-import # noqa: F403
FEATURES = FeaturesProxy(globals())
# Don't use S3 in devstack, fall back to filesystem
-STORAGES['default']['BACKEND'] = 'django.core.files.storage.FileSystemStorage'
+STORAGES['default']['BACKEND'] = 'django.core.files.storage.FileSystemStorage' # noqa: F405
ORA2_FILEUPLOAD_BACKEND = 'django'
@@ -28,7 +28,7 @@
INTERNAL_IPS = ('127.0.0.1',)
USE_I18N = True
-DEFAULT_TEMPLATE_ENGINE['OPTIONS']['debug'] = True
+DEFAULT_TEMPLATE_ENGINE['OPTIONS']['debug'] = True # noqa: F405
LMS_BASE = 'localhost:18000'
CMS_BASE = 'localhost:18010'
SITE_NAME = LMS_BASE
@@ -64,11 +64,11 @@
logging.getLogger(log_name).setLevel(log_level)
# Docker does not support the syslog socket at /dev/log. Rely on the console.
-LOGGING['handlers']['local'] = LOGGING['handlers']['tracking'] = {
+LOGGING['handlers']['local'] = LOGGING['handlers']['tracking'] = { # noqa: F405
'class': 'logging.NullHandler',
}
-LOGGING['loggers']['tracking']['handlers'] = ['console']
+LOGGING['loggers']['tracking']['handlers'] = ['console'] # noqa: F405
################################ EMAIL ########################################
@@ -125,8 +125,8 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
########################### PIPELINE #################################
-PIPELINE['PIPELINE_ENABLED'] = False
-STORAGES['staticfiles']['BACKEND'] = 'openedx.core.storage.DevelopmentStorage'
+PIPELINE['PIPELINE_ENABLED'] = False # noqa: F405
+STORAGES['staticfiles']['BACKEND'] = 'openedx.core.storage.DevelopmentStorage' # noqa: F405
# Revert to the default set of finders as we don't want the production pipeline
STATICFILES_FINDERS = [
@@ -136,12 +136,12 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
]
# Disable JavaScript compression in development
-PIPELINE['JS_COMPRESSOR'] = None
+PIPELINE['JS_COMPRESSOR'] = None # noqa: F405
# Whether to run django-require in debug mode.
REQUIRE_DEBUG = DEBUG
-PIPELINE['SASS_ARGUMENTS'] = '--debug-info'
+PIPELINE['SASS_ARGUMENTS'] = '--debug-info' # noqa: F405
########################### VERIFIED CERTIFICATES #################################
@@ -190,7 +190,7 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
########################## Course Discovery #######################
LANGUAGE_MAP = {
- 'terms': dict(ALL_LANGUAGES),
+ 'terms': dict(ALL_LANGUAGES), # noqa: F405
'name': 'Language',
}
COURSE_DISCOVERY_MEANINGS = {
@@ -217,7 +217,7 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
ENABLE_SOFTWARE_SECURE_FAKE = True
# Setting for the testing of Software Secure Result Callback
-VERIFY_STUDENT["SOFTWARE_SECURE"] = {
+VERIFY_STUDENT["SOFTWARE_SECURE"] = { # noqa: F405
"API_ACCESS_KEY": "BBBBBBBBBBBBBBBBBBBB",
"API_SECRET_KEY": "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC",
}
@@ -235,10 +235,10 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
########################## Third Party Auth #######################
-if ENABLE_THIRD_PARTY_AUTH and (
- 'common.djangoapps.third_party_auth.dummy.DummyBackend' not in AUTHENTICATION_BACKENDS
+if ENABLE_THIRD_PARTY_AUTH and ( # noqa: F405
+ 'common.djangoapps.third_party_auth.dummy.DummyBackend' not in AUTHENTICATION_BACKENDS # noqa: F405
):
- AUTHENTICATION_BACKENDS = ['common.djangoapps.third_party_auth.dummy.DummyBackend'] + list(AUTHENTICATION_BACKENDS)
+ AUTHENTICATION_BACKENDS = ['common.djangoapps.third_party_auth.dummy.DummyBackend'] + list(AUTHENTICATION_BACKENDS) # noqa: F405 # pylint: disable=line-too-long
########################## Authn MFE Context API #######################
ENABLE_DYNAMIC_REGISTRATION_FIELDS = True
@@ -257,7 +257,7 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
############## Exams CONFIGURATION SETTINGS ####################
EXAMS_SERVICE_URL = 'http://localhost:8740/api/v1'
-TOKEN_SIGNING.update({
+TOKEN_SIGNING.update({ # noqa: F405
'JWT_PUBLIC_SIGNING_JWK_SET': (
'{"keys": [{"kid": "localdev_exam_token_key", "e": "AQAB", "kty": "RSA", "n": "o5cn3ljSRi6FaDEKTn0PS-oL9EFyv1pI'
'7dRgffQLD1qf5D6sprmYfWWokSsrWig8u2y0HChSygR6Jn5KXBqQn6FpM0dDJLnWQDRXHLl3Ey1iPYgDSmOIsIGrV9ZyNCQwk03wAgWbfdBTig'
@@ -291,8 +291,8 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
########################## LEARNING MFE ##############################
# pylint: disable=line-too-long
-LEARNING_MICROFRONTEND_URL = os.environ.get("LEARNING_MICROFRONTEND_URL", "http://localhost:2000")
-LEARNING_MICROFRONTEND_NETLOC = os.environ.get("LEARNING_MICROFRONTEND_NETLOC", urlparse(LEARNING_MICROFRONTEND_URL).netloc)
+LEARNING_MICROFRONTEND_URL = os.environ.get("LEARNING_MICROFRONTEND_URL", "http://localhost:2000") # noqa: F405
+LEARNING_MICROFRONTEND_NETLOC = os.environ.get("LEARNING_MICROFRONTEND_NETLOC", urlparse(LEARNING_MICROFRONTEND_URL).netloc) # noqa: F405
###################### Cross-domain requests ######################
ENABLE_CORS_HEADERS = True
@@ -300,7 +300,7 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
CORS_ORIGIN_WHITELIST = ()
CORS_ORIGIN_ALLOW_ALL = True
-LOGIN_REDIRECT_WHITELIST.extend([
+LOGIN_REDIRECT_WHITELIST.extend([ # noqa: F405
CMS_BASE,
# Allow redirection to all micro-frontends.
# Please add your MFE if is not already listed here.
@@ -324,7 +324,7 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
])
###################### JWTs ######################
-JWT_AUTH.update({
+JWT_AUTH.update({ # noqa: F405
'JWT_AUDIENCE': 'lms-key',
'JWT_ISSUER': f'{LMS_ROOT_URL}/oauth2',
'JWT_ISSUERS': [{
@@ -363,7 +363,7 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
######################### Django Rest Framework ########################
-REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] += (
+REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] += ( # noqa: F405
'rest_framework.renderers.BrowsableAPIRenderer',
)
@@ -371,18 +371,18 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
#####################################################################
# set replica set of contentstore to none as we haven't setup any for lms in devstack
-CONTENTSTORE['DOC_STORE_CONFIG']['replicaSet'] = None
+CONTENTSTORE['DOC_STORE_CONFIG']['replicaSet'] = None # noqa: F405
#####################################################################
# set replica sets of moduelstore to none as we haven't setup any for lms in devstack
-for store in MODULESTORE['default']['OPTIONS']['stores']:
+for store in MODULESTORE['default']['OPTIONS']['stores']: # noqa: F405
if 'DOC_STORE_CONFIG' in store and 'replicaSet' in store['DOC_STORE_CONFIG']:
store['DOC_STORE_CONFIG']['replicaSet'] = None
#####################################################################
# Lastly, run any migrations, if needed.
-MODULESTORE = convert_module_store_setting_if_needed(MODULESTORE)
+MODULESTORE = convert_module_store_setting_if_needed(MODULESTORE) # noqa: F405
SECRET_KEY = '85920908f28904ed733fe576320db18cabd7b6cd'
@@ -421,8 +421,8 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
# Toggle this off if you don't want anything to do with enterprise in devstack.
ENABLE_ENTERPRISE_INTEGRATION = True
-ENABLE_MKTG_SITE = os.environ.get('ENABLE_MARKETING_SITE', False)
-MARKETING_SITE_ROOT = os.environ.get('MARKETING_SITE_ROOT', 'http://localhost:8080')
+ENABLE_MKTG_SITE = os.environ.get('ENABLE_MARKETING_SITE', False) # noqa: F405
+MARKETING_SITE_ROOT = os.environ.get('MARKETING_SITE_ROOT', 'http://localhost:8080') # noqa: F405
MKTG_URLS = {
'ABOUT': '/about',
@@ -460,7 +460,7 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
COURSE_CATALOG_URL_ROOT = 'http://edx.devstack.discovery:18381'
COURSE_CATALOG_API_URL = f'{COURSE_CATALOG_URL_ROOT}/api/v1'
-SYSTEM_WIDE_ROLE_CLASSES = os.environ.get("SYSTEM_WIDE_ROLE_CLASSES", SYSTEM_WIDE_ROLE_CLASSES)
+SYSTEM_WIDE_ROLE_CLASSES = os.environ.get("SYSTEM_WIDE_ROLE_CLASSES", SYSTEM_WIDE_ROLE_CLASSES) # noqa: F405
SYSTEM_WIDE_ROLE_CLASSES.append(
'system_wide_roles.SystemWideRoleAssignment',
)
@@ -508,7 +508,7 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
PROCTORING_USER_OBFUSCATION_KEY = '85920908f28904ed733fe576320db18cabd7b6cd'
#################### Webpack Configuration Settings ##############################
-WEBPACK_LOADER['DEFAULT']['TIMEOUT'] = 5
+WEBPACK_LOADER['DEFAULT']['TIMEOUT'] = 5 # noqa: F405
#################### Network configuration ####################
# Devstack is directly exposed to the caller
@@ -520,22 +520,22 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
EVENT_BUS_TOPIC_PREFIX = 'dev'
EVENT_BUS_CONSUMER = 'edx_event_bus_redis.RedisEventConsumer'
-certificate_revoked_event_config = EVENT_BUS_PRODUCER_CONFIG['org.openedx.learning.certificate.revoked.v1']
+certificate_revoked_event_config = EVENT_BUS_PRODUCER_CONFIG['org.openedx.learning.certificate.revoked.v1'] # noqa: F405
certificate_revoked_event_config['learning-certificate-lifecycle']['enabled'] = True
-certificate_created_event_config = EVENT_BUS_PRODUCER_CONFIG['org.openedx.learning.certificate.created.v1']
+certificate_created_event_config = EVENT_BUS_PRODUCER_CONFIG['org.openedx.learning.certificate.created.v1'] # noqa: F405
certificate_created_event_config['learning-certificate-lifecycle']['enabled'] = True
-course_access_role_added_event_setting = EVENT_BUS_PRODUCER_CONFIG[
+course_access_role_added_event_setting = EVENT_BUS_PRODUCER_CONFIG[ # noqa: F405
'org.openedx.learning.user.course_access_role.added.v1'
]
course_access_role_added_event_setting['learning-course-access-role-lifecycle']['enabled'] = True
-course_access_role_removed_event_setting = EVENT_BUS_PRODUCER_CONFIG[
+course_access_role_removed_event_setting = EVENT_BUS_PRODUCER_CONFIG[ # noqa: F405
'org.openedx.learning.user.course_access_role.removed.v1'
]
course_access_role_removed_event_setting['learning-course-access-role-lifecycle']['enabled'] = True
lc_enrollment_revoked_setting = \
- EVENT_BUS_PRODUCER_CONFIG['org.openedx.enterprise.learner_credit_course_enrollment.revoked.v1']
+ EVENT_BUS_PRODUCER_CONFIG['org.openedx.enterprise.learner_credit_course_enrollment.revoked.v1'] # noqa: F405
lc_enrollment_revoked_setting['learner-credit-course-enrollment-lifecycle']['enabled'] = True
# API access management
@@ -583,5 +583,5 @@ def should_show_debug_toolbar(request): # lint-amnesty, pylint: disable=missing
################# New settings must go ABOVE this line #################
########################################################################
# See if the developer has any local overrides.
-if os.path.isfile(join(dirname(abspath(__file__)), 'private.py')):
- from .private import * # pylint: disable=import-error,wildcard-import
+if os.path.isfile(join(dirname(abspath(__file__)), 'private.py')): # noqa: F405
+ from .private import * # pylint: disable=import-error,wildcard-import # noqa: F403
diff --git a/lms/envs/pact.py b/lms/envs/pact.py
index df3e3ee51a54..b14acf90ba67 100644
--- a/lms/envs/pact.py
+++ b/lms/envs/pact.py
@@ -2,7 +2,7 @@
Settings for Pact Verification Tests.
"""
-from .test import * # pylint: disable=wildcard-import, unused-wildcard-import
+from .test import * # pylint: disable=wildcard-import, unused-wildcard-import # noqa: F403
#### Allow Pact Provider States URL ####
PROVIDER_STATES_URL = True
@@ -11,4 +11,4 @@
MOCK_USERNAME = 'Mock User'
######################### Add Authentication Middleware for Pact Verification Calls #########################
-MIDDLEWARE = MIDDLEWARE + ['common.test.pacts.middleware.AuthenticationMiddleware', ]
+MIDDLEWARE = MIDDLEWARE + ['common.test.pacts.middleware.AuthenticationMiddleware', ] # noqa: F405
diff --git a/lms/envs/production.py b/lms/envs/production.py
index 3eefa7ac4276..d0daca682b6a 100644
--- a/lms/envs/production.py
+++ b/lms/envs/production.py
@@ -33,7 +33,7 @@
from xmodule.modulestore.modulestore_settings import \
convert_module_store_setting_if_needed # lint-amnesty, pylint: disable=wrong-import-order
-from .common import *
+from .common import * # noqa: F403
# A proxy for feature flags stored in the settings namespace
FEATURES = FeaturesProxy(globals())
@@ -44,8 +44,8 @@ def get_env_setting(setting):
try:
return os.environ[setting]
except KeyError:
- error_msg = "Set the %s env variable" % setting
- raise ImproperlyConfigured(error_msg) # lint-amnesty, pylint: disable=raise-missing-from
+ error_msg = "Set the %s env variable" % setting # noqa: UP031
+ raise ImproperlyConfigured(error_msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
#######################################################################################################################
#### YAML LOADING
@@ -102,7 +102,7 @@ def get_env_setting(setting):
REVISION_CONFIG = {}
# Do NOT calculate this dynamically at startup with git because it's *slow*.
-EDX_PLATFORM_REVISION = REVISION_CONFIG.get('EDX_PLATFORM_REVISION', EDX_PLATFORM_REVISION)
+EDX_PLATFORM_REVISION = REVISION_CONFIG.get('EDX_PLATFORM_REVISION', EDX_PLATFORM_REVISION) # noqa: F405
#######################################################################################################################
@@ -121,34 +121,34 @@ def get_env_setting(setting):
# STATIC_ROOT specifies the directory where static files are
# collected
-if STATIC_ROOT_BASE:
- STATIC_ROOT = path(STATIC_ROOT_BASE)
+if STATIC_ROOT_BASE: # noqa: F405
+ STATIC_ROOT = path(STATIC_ROOT_BASE) # noqa: F405
# STATIC_URL_BASE specifies the base url to use for static files
-if STATIC_URL_BASE:
- STATIC_URL = STATIC_URL_BASE
+if STATIC_URL_BASE: # noqa: F405
+ STATIC_URL = STATIC_URL_BASE # noqa: F405
if not STATIC_URL.endswith("/"):
STATIC_URL += "/"
-DATA_DIR = path(DATA_DIR)
+DATA_DIR = path(DATA_DIR) # noqa: F405
# TODO: This was for backwards compatibility back when installed django-cookie-samesite (not since 2022).
# The DCS_ version of the setting can be DEPR'd at this point.
-SESSION_COOKIE_SAMESITE = DCS_SESSION_COOKIE_SAMESITE
+SESSION_COOKIE_SAMESITE = DCS_SESSION_COOKIE_SAMESITE # noqa: F405
for feature, value in _YAML_TOKENS.get('FEATURES', {}).items():
FEATURES[feature] = value
# Cache used for location mapping -- called many times with the same key/value
# in a given request.
-if 'loc_cache' not in CACHES:
- CACHES['loc_cache'] = {
+if 'loc_cache' not in CACHES: # noqa: F405
+ CACHES['loc_cache'] = { # noqa: F405
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'edx_location_mem_cache',
}
-if 'staticfiles' in CACHES:
- CACHES['staticfiles']['KEY_PREFIX'] = EDX_PLATFORM_REVISION
+if 'staticfiles' in CACHES: # noqa: F405
+ CACHES['staticfiles']['KEY_PREFIX'] = EDX_PLATFORM_REVISION # noqa: F405
# In order to transition from local disk asset storage to S3 backed asset storage,
# we need to run asset collection twice, once for local disk and once for S3.
@@ -163,7 +163,7 @@ def get_env_setting(setting):
# Then add alternate environment queues
_YAML_ALTERNATE_WORKER_QUEUES = _YAML_TOKENS.get('ALTERNATE_WORKER_QUEUES', '').split()
ALTERNATE_QUEUES = [
- DEFAULT_PRIORITY_QUEUE.replace(SERVICE_VARIANT, alternate)
+ DEFAULT_PRIORITY_QUEUE.replace(SERVICE_VARIANT, alternate) # noqa: F405
for alternate in _YAML_ALTERNATE_WORKER_QUEUES
]
@@ -175,28 +175,28 @@ def get_env_setting(setting):
}
)
-MKTG_URL_LINK_MAP.update(_YAML_TOKENS.get('MKTG_URL_LINK_MAP', {}))
+MKTG_URL_LINK_MAP.update(_YAML_TOKENS.get('MKTG_URL_LINK_MAP', {})) # noqa: F405
# Timezone overrides
-TIME_ZONE = CELERY_TIMEZONE
+TIME_ZONE = CELERY_TIMEZONE # noqa: F405
# Translation overrides
-LANGUAGE_DICT = dict(LANGUAGES)
+LANGUAGE_DICT = dict(LANGUAGES) # noqa: F405
-LANGUAGE_COOKIE_NAME = _YAML_TOKENS.get('LANGUAGE_COOKIE') or LANGUAGE_COOKIE_NAME
+LANGUAGE_COOKIE_NAME = _YAML_TOKENS.get('LANGUAGE_COOKIE') or LANGUAGE_COOKIE_NAME # noqa: F405
# Additional installed apps
for app in _YAML_TOKENS.get('ADDL_INSTALLED_APPS', []):
- INSTALLED_APPS.append(app)
+ INSTALLED_APPS.append(app) # noqa: F405
LOGGING = get_logger_config(
- LOG_DIR,
- logging_env=LOGGING_ENV,
- local_loglevel=LOCAL_LOGLEVEL,
- service_variant=SERVICE_VARIANT,
+ LOG_DIR, # noqa: F405
+ logging_env=LOGGING_ENV, # noqa: F405
+ local_loglevel=LOCAL_LOGLEVEL, # noqa: F405
+ service_variant=SERVICE_VARIANT, # noqa: F405
)
-if ENABLE_CORS_HEADERS or ENABLE_CROSS_DOMAIN_CSRF_COOKIE:
+if ENABLE_CORS_HEADERS or ENABLE_CROSS_DOMAIN_CSRF_COOKIE: # noqa: F405
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = _YAML_TOKENS.get('CORS_ORIGIN_WHITELIST', ())
CORS_ORIGIN_ALLOW_ALL = _YAML_TOKENS.get('CORS_ORIGIN_ALLOW_ALL', False)
@@ -206,9 +206,9 @@ def get_env_setting(setting):
############### Mixed Related(Secure/Not-Secure) Items ##########
LMS_SEGMENT_KEY = _YAML_TOKENS.get('SEGMENT_KEY')
-if AWS_ACCESS_KEY_ID == "":
+if AWS_ACCESS_KEY_ID == "": # noqa: F405
AWS_ACCESS_KEY_ID = None
-if AWS_SECRET_ACCESS_KEY == "":
+if AWS_SECRET_ACCESS_KEY == "": # noqa: F405
AWS_SECRET_ACCESS_KEY = None
# these variable already exists in cms with `private` value. django-storages starting `1.10.1`
@@ -230,18 +230,18 @@ def get_env_setting(setting):
# without overwriting user-defined STORAGES and AWS creds are treated only as a fallback.
if _storages_default_backend_is_missing:
if 'DEFAULT_FILE_STORAGE' in _YAML_TOKENS:
- STORAGES['default']['BACKEND'] = _YAML_TOKENS['DEFAULT_FILE_STORAGE']
+ STORAGES['default']['BACKEND'] = _YAML_TOKENS['DEFAULT_FILE_STORAGE'] # noqa: F405
elif AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY:
- STORAGES['default']['BACKEND'] = 'storages.backends.s3boto3.S3Boto3Storage'
+ STORAGES['default']['BACKEND'] = 'storages.backends.s3boto3.S3Boto3Storage' # noqa: F405
# Apply legacy STATICFILES_STORAGE if no backend is defined for "staticfiles"
if 'STATICFILES_STORAGE' in _YAML_TOKENS and not _yaml_storages.get('staticfiles', {}).get('BACKEND'):
- STORAGES['staticfiles']['BACKEND'] = _YAML_TOKENS['STATICFILES_STORAGE']
+ STORAGES['staticfiles']['BACKEND'] = _YAML_TOKENS['STATICFILES_STORAGE'] # noqa: F405
# The normal database user does not have enough permissions to run migrations.
# Migrations are run with separate credentials, given as DB_MIGRATION_*
# environment variables
-for name, database in DATABASES.items():
+for name, database in DATABASES.items(): # noqa: F405
if name != 'read_replica':
database.update({
'ENGINE': os.environ.get('DB_MIGRATION_ENGINE', database['ENGINE']),
@@ -254,13 +254,13 @@ def get_env_setting(setting):
# Get the MODULESTORE from auth.json, but if it doesn't exist,
# use the one from common.py
-MODULESTORE = convert_module_store_setting_if_needed(MODULESTORE)
+MODULESTORE = convert_module_store_setting_if_needed(MODULESTORE) # noqa: F405
-BROKER_URL = "{}://{}:{}@{}/{}".format(CELERY_BROKER_TRANSPORT,
- CELERY_BROKER_USER,
- CELERY_BROKER_PASSWORD,
- CELERY_BROKER_HOSTNAME,
- CELERY_BROKER_VHOST)
+BROKER_URL = "{}://{}:{}@{}/{}".format(CELERY_BROKER_TRANSPORT, # noqa: F405, UP032
+ CELERY_BROKER_USER, # noqa: F405
+ CELERY_BROKER_PASSWORD, # noqa: F405
+ CELERY_BROKER_HOSTNAME, # noqa: F405
+ CELERY_BROKER_VHOST) # noqa: F405
try:
BROKER_TRANSPORT_OPTIONS = {
'fanout_patterns': True,
@@ -271,15 +271,15 @@ def get_env_setting(setting):
raise ImproperlyConfigured('CELERY_BROKER_TRANSPORT_OPTIONS must be a dict') from exc
# Event tracking
-TRACKING_BACKENDS.update(_YAML_TOKENS.get("TRACKING_BACKENDS", {}))
-EVENT_TRACKING_BACKENDS['tracking_logs']['OPTIONS']['backends'].update(
+TRACKING_BACKENDS.update(_YAML_TOKENS.get("TRACKING_BACKENDS", {})) # noqa: F405
+EVENT_TRACKING_BACKENDS['tracking_logs']['OPTIONS']['backends'].update( # noqa: F405
_YAML_TOKENS.get("EVENT_TRACKING_BACKENDS", {})
)
-EVENT_TRACKING_BACKENDS['segmentio']['OPTIONS']['processors'][0]['OPTIONS']['whitelist'].extend(
- EVENT_TRACKING_SEGMENTIO_EMIT_WHITELIST
+EVENT_TRACKING_BACKENDS['segmentio']['OPTIONS']['processors'][0]['OPTIONS']['whitelist'].extend( # noqa: F405
+ EVENT_TRACKING_SEGMENTIO_EMIT_WHITELIST # noqa: F405
)
-if ENABLE_THIRD_PARTY_AUTH:
+if ENABLE_THIRD_PARTY_AUTH: # noqa: F405
AUTHENTICATION_BACKENDS = _YAML_TOKENS.get('THIRD_PARTY_AUTH_BACKENDS', [
'social_core.backends.google.GoogleOAuth2',
'social_core.backends.linkedin.LinkedinOAuth2',
@@ -289,7 +289,7 @@ def get_env_setting(setting):
'common.djangoapps.third_party_auth.identityserver3.IdentityServer3',
'common.djangoapps.third_party_auth.saml.SAMLAuthBackend',
'common.djangoapps.third_party_auth.lti.LTIAuthBackend',
- ]) + list(AUTHENTICATION_BACKENDS)
+ ]) + list(AUTHENTICATION_BACKENDS) # noqa: F405
# The reduced session expiry time during the third party login pipeline. (Value in seconds)
SOCIAL_AUTH_PIPELINE_TIMEOUT = _YAML_TOKENS.get('SOCIAL_AUTH_PIPELINE_TIMEOUT', 600)
@@ -305,7 +305,7 @@ def get_env_setting(setting):
if hours := _YAML_TOKENS.get('THIRD_PARTY_AUTH_SAML_FETCH_PERIOD_HOURS', 24):
# If we didn't override the value in YAML, OR we overrode it to a truthy value,
# then update CELERYBEAT_SCHEDULE.
- CELERYBEAT_SCHEDULE['refresh-saml-metadata'] = {
+ CELERYBEAT_SCHEDULE['refresh-saml-metadata'] = { # noqa: F405
'task': 'common.djangoapps.third_party_auth.tasks.fetch_saml_metadata',
'schedule': datetime.timedelta(hours=hours),
}
@@ -319,14 +319,14 @@ def get_env_setting(setting):
OAUTH_ENFORCE_SECURE = True
OAUTH_ENFORCE_CLIENT_SECURE = True
# Defaults for the following are defined in lms.envs.common
-OAUTH_EXPIRE_DELTA = datetime.timedelta(days=OAUTH_EXPIRE_CONFIDENTIAL_CLIENT_DAYS)
-OAUTH_EXPIRE_DELTA_PUBLIC = datetime.timedelta(days=OAUTH_EXPIRE_PUBLIC_CLIENT_DAYS)
+OAUTH_EXPIRE_DELTA = datetime.timedelta(days=OAUTH_EXPIRE_CONFIDENTIAL_CLIENT_DAYS) # noqa: F405
+OAUTH_EXPIRE_DELTA_PUBLIC = datetime.timedelta(days=OAUTH_EXPIRE_PUBLIC_CLIENT_DAYS) # noqa: F405
if (
- ENABLE_COURSEWARE_SEARCH or
- ENABLE_DASHBOARD_SEARCH or
- ENABLE_COURSE_DISCOVERY or
- ENABLE_TEAMS
+ ENABLE_COURSEWARE_SEARCH or # noqa: F405
+ ENABLE_DASHBOARD_SEARCH or # noqa: F405
+ ENABLE_COURSE_DISCOVERY or # noqa: F405
+ ENABLE_TEAMS # noqa: F405
):
# Use ElasticSearch as the search engine herein
SEARCH_ENGINE = "search.elastic.ElasticSearchEngine"
@@ -334,20 +334,20 @@ def get_env_setting(setting):
# TODO: Once we have successfully upgraded to ES7, switch this back to ELASTIC_SEARCH_CONFIG.
ELASTIC_SEARCH_CONFIG = _YAML_TOKENS.get('ELASTIC_SEARCH_CONFIG_ES7', [{}])
-XBLOCK_SETTINGS.setdefault("VideoBlock", {})["licensing_enabled"] = FEATURES["LICENSING"]
-XBLOCK_SETTINGS.setdefault("VideoBlock", {})['YOUTUBE_API_KEY'] = YOUTUBE_API_KEY
+XBLOCK_SETTINGS.setdefault("VideoBlock", {})["licensing_enabled"] = FEATURES["LICENSING"] # noqa: F405
+XBLOCK_SETTINGS.setdefault("VideoBlock", {})['YOUTUBE_API_KEY'] = YOUTUBE_API_KEY # noqa: F405
##### Custom Courses for EdX #####
-if CUSTOM_COURSES_EDX:
- INSTALLED_APPS += ['lms.djangoapps.ccx', 'openedx.core.djangoapps.ccxcon.apps.CCXConnectorConfig']
- MODULESTORE_FIELD_OVERRIDE_PROVIDERS += (
+if CUSTOM_COURSES_EDX: # noqa: F405
+ INSTALLED_APPS += ['lms.djangoapps.ccx', 'openedx.core.djangoapps.ccxcon.apps.CCXConnectorConfig'] # noqa: F405
+ MODULESTORE_FIELD_OVERRIDE_PROVIDERS += ( # noqa: F405
'lms.djangoapps.ccx.overrides.CustomCoursesForEdxOverrideProvider',
)
-FIELD_OVERRIDE_PROVIDERS = tuple(FIELD_OVERRIDE_PROVIDERS)
+FIELD_OVERRIDE_PROVIDERS = tuple(FIELD_OVERRIDE_PROVIDERS) # noqa: F405
##### Individual Due Date Extensions #####
-if INDIVIDUAL_DUE_DATES:
+if INDIVIDUAL_DUE_DATES: # noqa: F405
FIELD_OVERRIDE_PROVIDERS += (
'lms.djangoapps.courseware.student_field_overrides.IndividualStudentOverrideProvider',
)
@@ -358,7 +358,7 @@ def get_env_setting(setting):
)
##### Self-Paced Course Due Dates #####
-XBLOCK_FIELD_DATA_WRAPPERS += (
+XBLOCK_FIELD_DATA_WRAPPERS += ( # noqa: F405
'lms.djangoapps.courseware.field_overrides:OverrideModulestoreFieldData.wrap',
)
@@ -372,14 +372,14 @@ def get_env_setting(setting):
##### Credit Provider Integration #####
##################### LTI Provider #####################
-if ENABLE_LTI_PROVIDER:
+if ENABLE_LTI_PROVIDER: # noqa: F405
INSTALLED_APPS.append('lms.djangoapps.lti_provider.apps.LtiProviderConfig')
AUTHENTICATION_BACKENDS.append('lms.djangoapps.lti_provider.users.LtiBackend')
##################### Credit Provider help link ####################
#### JWT configuration ####
-JWT_AUTH.update(_YAML_TOKENS.get('JWT_AUTH', {}))
+JWT_AUTH.update(_YAML_TOKENS.get('JWT_AUTH', {})) # noqa: F405
############## ENTERPRISE SERVICE LMS CONFIGURATION ##################################
@@ -387,14 +387,14 @@ def get_env_setting(setting):
# which are not provided by the Enterprise service. These settings override the
# base values for the parameters as defined in common.py
-ENTERPRISE_EXCLUDED_REGISTRATION_FIELDS = set(ENTERPRISE_EXCLUDED_REGISTRATION_FIELDS)
+ENTERPRISE_EXCLUDED_REGISTRATION_FIELDS = set(ENTERPRISE_EXCLUDED_REGISTRATION_FIELDS) # noqa: F405
########################## Extra middleware classes #######################
# Allow extra middleware classes to be added to the app through configuration.
# TODO: Declare `EXTRA_MIDDLEWARE_CLASSES = []` in lms/envs/common.py so that we can simplify this
# next line. See CMS settings for the example of what we want.
-MIDDLEWARE.extend(_YAML_TOKENS.get('EXTRA_MIDDLEWARE_CLASSES', []))
+MIDDLEWARE.extend(_YAML_TOKENS.get('EXTRA_MIDDLEWARE_CLASSES', [])) # noqa: F405
#######################################################################################################################
@@ -442,69 +442,69 @@ def get_env_setting(setting):
# Defines the task -> alternate worker queue to be used when routing.
EXPLICIT_QUEUES = {
'openedx.core.djangoapps.content.course_overviews.tasks.async_course_overview_update': {
- 'queue': GRADES_DOWNLOAD_ROUTING_KEY},
+ 'queue': GRADES_DOWNLOAD_ROUTING_KEY}, # noqa: F405
'lms.djangoapps.bulk_email.tasks.send_course_email': {
- 'queue': BULK_EMAIL_ROUTING_KEY},
+ 'queue': BULK_EMAIL_ROUTING_KEY}, # noqa: F405
'openedx.core.djangoapps.heartbeat.tasks.sample_task': {
- 'queue': HEARTBEAT_CELERY_ROUTING_KEY},
+ 'queue': HEARTBEAT_CELERY_ROUTING_KEY}, # noqa: F405
'lms.djangoapps.instructor_task.tasks.calculate_grades_csv': {
- 'queue': GRADES_DOWNLOAD_ROUTING_KEY},
+ 'queue': GRADES_DOWNLOAD_ROUTING_KEY}, # noqa: F405
'lms.djangoapps.instructor_task.tasks.calculate_problem_grade_report': {
- 'queue': GRADES_DOWNLOAD_ROUTING_KEY},
+ 'queue': GRADES_DOWNLOAD_ROUTING_KEY}, # noqa: F405
'lms.djangoapps.instructor_task.tasks.generate_certificates': {
- 'queue': GRADES_DOWNLOAD_ROUTING_KEY},
+ 'queue': GRADES_DOWNLOAD_ROUTING_KEY}, # noqa: F405
'lms.djangoapps.verify_student.tasks.send_verification_status_email': {
- 'queue': ACE_ROUTING_KEY},
+ 'queue': ACE_ROUTING_KEY}, # noqa: F405
'lms.djangoapps.verify_student.tasks.send_ace_message': {
- 'queue': ACE_ROUTING_KEY},
+ 'queue': ACE_ROUTING_KEY}, # noqa: F405
'lms.djangoapps.verify_student.tasks.send_request_to_ss_for_user': {
- 'queue': SOFTWARE_SECURE_VERIFICATION_ROUTING_KEY},
+ 'queue': SOFTWARE_SECURE_VERIFICATION_ROUTING_KEY}, # noqa: F405
'openedx.core.djangoapps.schedules.tasks._recurring_nudge_schedule_send': {
- 'queue': ACE_ROUTING_KEY},
+ 'queue': ACE_ROUTING_KEY}, # noqa: F405
'openedx.core.djangoapps.schedules.tasks._upgrade_reminder_schedule_send': {
- 'queue': ACE_ROUTING_KEY},
+ 'queue': ACE_ROUTING_KEY}, # noqa: F405
'openedx.core.djangoapps.schedules.tasks._course_update_schedule_send': {
- 'queue': ACE_ROUTING_KEY},
+ 'queue': ACE_ROUTING_KEY}, # noqa: F405
'openedx.core.djangoapps.schedules.tasks.v1.tasks.send_grade_to_credentials': {
- 'queue': CREDENTIALS_GENERATION_ROUTING_KEY},
+ 'queue': CREDENTIALS_GENERATION_ROUTING_KEY}, # noqa: F405
'common.djangoapps.entitlements.tasks.expire_old_entitlements': {
- 'queue': ENTITLEMENTS_EXPIRATION_ROUTING_KEY},
+ 'queue': ENTITLEMENTS_EXPIRATION_ROUTING_KEY}, # noqa: F405
'lms.djangoapps.grades.tasks.recalculate_course_and_subsection_grades_for_user': {
- 'queue': POLICY_CHANGE_GRADES_ROUTING_KEY},
+ 'queue': POLICY_CHANGE_GRADES_ROUTING_KEY}, # noqa: F405
'lms.djangoapps.grades.tasks.recalculate_subsection_grade_v3': {
- 'queue': SINGLE_LEARNER_COURSE_REGRADE_ROUTING_KEY},
+ 'queue': SINGLE_LEARNER_COURSE_REGRADE_ROUTING_KEY}, # noqa: F405
'openedx.core.djangoapps.programs.tasks.award_program_certificates': {
- 'queue': PROGRAM_CERTIFICATES_ROUTING_KEY},
+ 'queue': PROGRAM_CERTIFICATES_ROUTING_KEY}, # noqa: F405
'openedx.core.djangoapps.programs.tasks.revoke_program_certificates': {
- 'queue': PROGRAM_CERTIFICATES_ROUTING_KEY},
+ 'queue': PROGRAM_CERTIFICATES_ROUTING_KEY}, # noqa: F405
'openedx.core.djangoapps.programs.tasks.update_certificate_available_date_on_course_update': {
- 'queue': PROGRAM_CERTIFICATES_ROUTING_KEY},
+ 'queue': PROGRAM_CERTIFICATES_ROUTING_KEY}, # noqa: F405
'openedx.core.djangoapps.programs.tasks.award_course_certificate': {
- 'queue': PROGRAM_CERTIFICATES_ROUTING_KEY},
+ 'queue': PROGRAM_CERTIFICATES_ROUTING_KEY}, # noqa: F405
'openassessment.workflow.tasks.update_workflows_for_all_blocked_submissions_task': {
- 'queue': ORA_WORKFLOW_UPDATE_ROUTING_KEY},
+ 'queue': ORA_WORKFLOW_UPDATE_ROUTING_KEY}, # noqa: F405
'openassessment.workflow.tasks.update_workflows_for_course_task': {
- 'queue': ORA_WORKFLOW_UPDATE_ROUTING_KEY},
+ 'queue': ORA_WORKFLOW_UPDATE_ROUTING_KEY}, # noqa: F405
'openassessment.workflow.tasks.update_workflows_for_ora_block_task': {
- 'queue': ORA_WORKFLOW_UPDATE_ROUTING_KEY},
+ 'queue': ORA_WORKFLOW_UPDATE_ROUTING_KEY}, # noqa: F405
'openassessment.workflow.tasks.update_workflow_for_submission_task': {
- 'queue': ORA_WORKFLOW_UPDATE_ROUTING_KEY},
+ 'queue': ORA_WORKFLOW_UPDATE_ROUTING_KEY}, # noqa: F405
}
############## XBlock extra mixins ############################
-XBLOCK_MIXINS += tuple(XBLOCK_EXTRA_MIXINS)
+XBLOCK_MIXINS += tuple(XBLOCK_EXTRA_MIXINS) # noqa: F405
############## DRF overrides ##############
-REST_FRAMEWORK.update(_YAML_TOKENS.get('REST_FRAMEWORK', {}))
+REST_FRAMEWORK.update(_YAML_TOKENS.get('REST_FRAMEWORK', {})) # noqa: F405
############################# CELERY ############################
-CELERY_IMPORTS.extend(_YAML_TOKENS.get('CELERY_EXTRA_IMPORTS', []))
+CELERY_IMPORTS.extend(_YAML_TOKENS.get('CELERY_EXTRA_IMPORTS', [])) # noqa: F405
# keys for big blue button live provider
# TODO: This should not be in the core platform. If it has to stay for now, though, then we should move these
# defaults into common.py
-COURSE_LIVE_GLOBAL_CREDENTIALS["BIG_BLUE_BUTTON"] = {
+COURSE_LIVE_GLOBAL_CREDENTIALS["BIG_BLUE_BUTTON"] = { # noqa: F405
"KEY": _YAML_TOKENS.get('BIG_BLUE_BUTTON_GLOBAL_KEY'),
"SECRET": _YAML_TOKENS.get('BIG_BLUE_BUTTON_GLOBAL_SECRET'),
"URL": _YAML_TOKENS.get('BIG_BLUE_BUTTON_GLOBAL_URL'),
@@ -512,7 +512,7 @@ def get_env_setting(setting):
############## Event bus producer ##############
EVENT_BUS_PRODUCER_CONFIG = merge_producer_configs(
- EVENT_BUS_PRODUCER_CONFIG,
+ EVENT_BUS_PRODUCER_CONFIG, # noqa: F405
_YAML_TOKENS.get('EVENT_BUS_PRODUCER_CONFIG', {})
)
diff --git a/lms/envs/test.py b/lms/envs/test.py
index dcf69f978790..bbddd3dcfa38 100644
--- a/lms/envs/test.py
+++ b/lms/envs/test.py
@@ -26,8 +26,8 @@
update_module_store_settings, # lint-amnesty, pylint: disable=wrong-import-order
)
-from .common import *
-from openedx.envs.test import * # must come after .common to override Derived values with literals
+from .common import * # noqa: F403
+from openedx.envs.test import * # must come after .common to override Derived values with literals # noqa: F403
# A proxy for feature flags stored in the settings namespace
FEATURES = FeaturesProxy(globals())
@@ -50,18 +50,18 @@
ENABLE_BULK_USER_RETIREMENT = True
-COMMON_TEST_DATA_ROOT = COMMON_ROOT / "test" / "data"
+COMMON_TEST_DATA_ROOT = COMMON_ROOT / "test" / "data" # noqa: F405
-COMPREHENSIVE_THEME_DIRS = [REPO_ROOT / "themes", REPO_ROOT / "common/test"]
+COMPREHENSIVE_THEME_DIRS = [REPO_ROOT / "themes", REPO_ROOT / "common/test"] # noqa: F405
-WEBPACK_LOADER['DEFAULT']['LOADER_CLASS'] = 'webpack_loader.loader.FakeWebpackLoader'
+WEBPACK_LOADER['DEFAULT']['LOADER_CLASS'] = 'webpack_loader.loader.FakeWebpackLoader' # noqa: F405
-STATUS_MESSAGE_PATH = TEST_ROOT / "status_message.json"
+STATUS_MESSAGE_PATH = TEST_ROOT / "status_message.json" # noqa: F405
-COURSES_ROOT = TEST_ROOT / "data"
+COURSES_ROOT = TEST_ROOT / "data" # noqa: F405
# Where the content data is checked out.
-GITHUB_REPO_ROOT = ENV_ROOT / "data"
+GITHUB_REPO_ROOT = ENV_ROOT / "data" # noqa: F405
USE_I18N = True
LANGUAGE_CODE = 'en' # tests assume they will get English.
@@ -84,7 +84,7 @@
DJFS = {
'type': 'osfs',
- 'directory_root': f'{DATA_DIR}/django-pyfs/static/django-pyfs',
+ 'directory_root': f'{DATA_DIR}/django-pyfs/static/django-pyfs', # noqa: F405
'url_root': '/static/django-pyfs',
}
@@ -96,23 +96,23 @@
# If we don't add these settings, then Django templates that can't
# find pipelined assets will raise a ValueError.
# http://stackoverflow.com/questions/12816941/unit-testing-with-django-pipeline
-STORAGES['staticfiles']['BACKEND'] = 'pipeline.storage.NonPackagingPipelineStorage'
+STORAGES['staticfiles']['BACKEND'] = 'pipeline.storage.NonPackagingPipelineStorage' # noqa: F405
# Don't use compression during tests
-PIPELINE['JS_COMPRESSOR'] = None
+PIPELINE['JS_COMPRESSOR'] = None # noqa: F405
update_module_store_settings(
- MODULESTORE,
+ MODULESTORE, # noqa: F405
module_store_options={
- 'fs_root': TEST_ROOT / "data",
+ 'fs_root': TEST_ROOT / "data", # noqa: F405
},
xml_store_options={
- 'data_dir': mkdtemp_clean(dir=TEST_ROOT), # never inadvertently load all the XML courses
+ 'data_dir': mkdtemp_clean(dir=TEST_ROOT), # never inadvertently load all the XML courses # noqa: F405
},
doc_store_settings={
- 'host': MONGO_HOST,
- 'port': MONGO_PORT_NUM,
- 'db': f'test_xmodule_{THIS_UUID}',
+ 'host': MONGO_HOST, # noqa: F405
+ 'port': MONGO_PORT_NUM, # noqa: F405
+ 'db': f'test_xmodule_{THIS_UUID}', # noqa: F405
'collection': 'test_modulestore',
},
)
@@ -120,9 +120,9 @@
CONTENTSTORE = {
'ENGINE': 'xmodule.contentstore.mongo.MongoContentStore',
'DOC_STORE_CONFIG': {
- 'host': MONGO_HOST,
- 'db': f'test_xcontent_{THIS_UUID}',
- 'port': MONGO_PORT_NUM,
+ 'host': MONGO_HOST, # noqa: F405
+ 'db': f'test_xcontent_{THIS_UUID}', # noqa: F405
+ 'port': MONGO_PORT_NUM, # noqa: F405
}
}
@@ -184,7 +184,7 @@
'common.djangoapps.third_party_auth.dummy.DummyBackend',
'common.djangoapps.third_party_auth.saml.SAMLAuthBackend',
'common.djangoapps.third_party_auth.lti.LTIAuthBackend',
-] + AUTHENTICATION_BACKENDS
+] + AUTHENTICATION_BACKENDS # noqa: F405
THIRD_PARTY_AUTH_CUSTOM_AUTH_FORMS = {
'custom1': {
@@ -240,22 +240,22 @@
CLASS_DASHBOARD = True
# add extra template directory for test-only templates
-MAKO_TEMPLATE_DIRS_BASE.extend([
- COMMON_ROOT / 'test' / 'templates',
- COMMON_ROOT / 'test' / 'test_sites',
- REPO_ROOT / 'openedx' / 'core' / 'djangolib' / 'tests' / 'templates',
+MAKO_TEMPLATE_DIRS_BASE.extend([ # noqa: F405
+ COMMON_ROOT / 'test' / 'templates', # noqa: F405
+ COMMON_ROOT / 'test' / 'test_sites', # noqa: F405
+ REPO_ROOT / 'openedx' / 'core' / 'djangolib' / 'tests' / 'templates', # noqa: F405
])
# Setting for the testing of Software Secure Result Callback
-VERIFY_STUDENT["SOFTWARE_SECURE"] = {
+VERIFY_STUDENT["SOFTWARE_SECURE"] = { # noqa: F405
"API_ACCESS_KEY": "BBBBBBBBBBBBBBBBBBBB",
"API_SECRET_KEY": "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC",
}
######### dashboard git log settings #########
MONGODB_LOG = {
- 'host': MONGO_HOST,
- 'port': MONGO_PORT_NUM,
+ 'host': MONGO_HOST, # noqa: F405
+ 'port': MONGO_PORT_NUM, # noqa: F405
'user': '',
'password': '',
'db': 'xlog',
@@ -274,13 +274,13 @@
FACEBOOK_API_VERSION = "v2.8"
######### custom courses #########
-INSTALLED_APPS += ['lms.djangoapps.ccx', 'openedx.core.djangoapps.ccxcon.apps.CCXConnectorConfig']
+INSTALLED_APPS += ['lms.djangoapps.ccx', 'openedx.core.djangoapps.ccxcon.apps.CCXConnectorConfig'] # noqa: F405
# Set dummy values for profile image settings.
PROFILE_IMAGE_BACKEND = {
'class': 'openedx.core.storage.OverwriteStorage',
'options': {
- 'location': MEDIA_ROOT,
+ 'location': MEDIA_ROOT, # noqa: F405
'base_url': 'http://example-storage.com/profile-images/',
},
}
@@ -306,7 +306,7 @@
COURSE_CATALOG_URL_ROOT = 'https://catalog.example.com'
COURSE_CATALOG_API_URL = f'{COURSE_CATALOG_URL_ROOT}/api/v1'
-COMPREHENSIVE_THEME_LOCALE_PATHS = [REPO_ROOT / "themes/conf/locale", ]
+COMPREHENSIVE_THEME_LOCALE_PATHS = [REPO_ROOT / "themes/conf/locale", ] # noqa: F405
PREPEND_LOCALE_PATHS = []
@@ -330,16 +330,16 @@
ACTIVATION_EMAIL_FROM_ADDRESS = 'test_activate@edx.org'
-TEMPLATES[0]['OPTIONS']['debug'] = True
-TEMPLATES.append(
+TEMPLATES[0]['OPTIONS']['debug'] = True # noqa: F405
+TEMPLATES.append( # noqa: F405
{
# This separate copy of the Mako backend is used to test rendering previews in the 'lms.main' namespace
'NAME': 'preview',
'BACKEND': 'common.djangoapps.edxmako.backend.Mako',
'APP_DIRS': False,
- 'DIRS': MAKO_TEMPLATE_DIRS_BASE,
+ 'DIRS': MAKO_TEMPLATE_DIRS_BASE, # noqa: F405
'OPTIONS': {
- 'context_processors': CONTEXT_PROCESSORS,
+ 'context_processors': CONTEXT_PROCESSORS, # noqa: F405
'debug': False,
'namespace': 'lms.main',
}
@@ -350,7 +350,7 @@
# Most of the JWT_AUTH settings come from lms/envs/common.py (from openedx/envs/common.py),
# but here we update to use JWKS values from openedx/envs/test.py for testing.
-JWT_AUTH.update(jwt_jwks_values)
+JWT_AUTH.update(jwt_jwks_values) # noqa: F405
####################### Plugin Settings ##########################
@@ -361,23 +361,23 @@
derive_settings(__name__)
############################ STATIC FILES #############################
-STATICFILES_DIRS.append(("uploads", MEDIA_ROOT))
+STATICFILES_DIRS.append(("uploads", MEDIA_ROOT)) # noqa: F405
_NEW_STATICFILES_DIRS = []
# Strip out any static files that aren't in the repository root
# so that the tests can run with only the edx-platform directory checked out
-for static_dir in STATICFILES_DIRS: # pylint: disable=not-an-iterable
+for static_dir in STATICFILES_DIRS: # pylint: disable=not-an-iterable # noqa: F405
# Handle both tuples and non-tuple directory definitions
try:
_, data_dir = static_dir
except ValueError:
data_dir = static_dir
- if data_dir.startswith(REPO_ROOT):
+ if data_dir.startswith(REPO_ROOT): # noqa: F405
_NEW_STATICFILES_DIRS.append(static_dir)
STATICFILES_DIRS = _NEW_STATICFILES_DIRS
-FILE_UPLOAD_TEMP_DIR = TEST_ROOT / "uploads"
+FILE_UPLOAD_TEMP_DIR = TEST_ROOT / "uploads" # noqa: F405
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.MemoryFileUploadHandler',
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
@@ -493,7 +493,7 @@
}
### Course Live
-COURSE_LIVE_GLOBAL_CREDENTIALS["BIG_BLUE_BUTTON"] = big_blue_button_credentials
+COURSE_LIVE_GLOBAL_CREDENTIALS["BIG_BLUE_BUTTON"] = big_blue_button_credentials # noqa: F405
### Override default production settings for testing purposes
@@ -503,19 +503,19 @@
CERT_QUEUE = "certificates"
CMS_BASE = "localhost:18010"
COMMENTS_SERVICE_KEY = "password"
-del BROKER_HEARTBEAT
-del BROKER_HEARTBEAT_CHECKRATE
-del BROKER_USE_SSL
-del DEFAULT_ENTERPRISE_API_URL
-del DEFAULT_ENTERPRISE_CONSENT_API_URL
-del EMAIL_FILE_PATH
-del ENABLE_REQUIRE_THIRD_PARTY_AUTH
-del ENTITLEMENTS_EXPIRATION_ROUTING_KEY
-del PYTHON_LIB_FILENAME
-del REGISTRATION_CODE_LENGTH
-del SESSION_INACTIVITY_TIMEOUT_IN_SECONDS
-del SSL_AUTH_DN_FORMAT_STRING
-del SSL_AUTH_EMAIL_DOMAIN
+del BROKER_HEARTBEAT # noqa: F821
+del BROKER_HEARTBEAT_CHECKRATE # noqa: F821
+del BROKER_USE_SSL # noqa: F821
+del DEFAULT_ENTERPRISE_API_URL # noqa: F821
+del DEFAULT_ENTERPRISE_CONSENT_API_URL # noqa: F821
+del EMAIL_FILE_PATH # noqa: F821
+del ENABLE_REQUIRE_THIRD_PARTY_AUTH # noqa: F821
+del ENTITLEMENTS_EXPIRATION_ROUTING_KEY # noqa: F821
+del PYTHON_LIB_FILENAME # noqa: F821
+del REGISTRATION_CODE_LENGTH # noqa: F821
+del SESSION_INACTIVITY_TIMEOUT_IN_SECONDS # noqa: F821
+del SSL_AUTH_DN_FORMAT_STRING # noqa: F821
+del SSL_AUTH_EMAIL_DOMAIN # noqa: F821
EDX_API_KEY = "PUT_YOUR_API_KEY_HERE"
ENTERPRISE_PUBLIC_ENROLLMENT_API_URL = "https://localhost:18000/api/enrollment/v1/"
GOOGLE_ANALYTICS_LINKEDIN = "GOOGLE_ANALYTICS_LINKEDIN_DUMMY"
diff --git a/lms/lib/courseware_search/test/test_lms_result_processor.py b/lms/lib/courseware_search/test/test_lms_result_processor.py
index a50bd9798bfd..8a33868b5ba1 100644
--- a/lms/lib/courseware_search/test/test_lms_result_processor.py
+++ b/lms/lib/courseware_search/test/test_lms_result_processor.py
@@ -72,7 +72,7 @@ def setUp(self):
def test_url_parameter(self):
fake_url = ""
srp = LmsSearchResultProcessor({}, "test")
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
fake_url = srp.url
assert fake_url == ''
@@ -85,7 +85,7 @@ def test_url_parameter(self):
"test"
)
- assert srp.url == '/courses/{}/jump_to/{}'.format(str(self.course.id),
+ assert srp.url == '/courses/{}/jump_to/{}'.format(str(self.course.id), # noqa: UP032
str(self.html.scope_ids.usage_id))
def test_should_remove(self):
diff --git a/lms/tests.py b/lms/tests.py
index 8a447958268b..4f1f47c066b0 100644
--- a/lms/tests.py
+++ b/lms/tests.py
@@ -4,7 +4,7 @@
import logging
import mimetypes
-from django.conf import settings # lint-amnesty, pylint: disable=unused-import
+from django.conf import settings # lint-amnesty, pylint: disable=unused-import # noqa: F401
from django.test import TestCase
log = logging.getLogger(__name__)
diff --git a/lms/urls.py b/lms/urls.py
index 93cc58bc9803..caa95569f3e0 100644
--- a/lms/urls.py
+++ b/lms/urls.py
@@ -273,14 +273,14 @@
urlpatterns += [
# jump_to URLs for direct access to a location in the course
re_path(
- r'^courses/{}/jump_to/(?P.*)$'.format(
+ r'^courses/{}/jump_to/(?P.*)$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.jump_to,
name='jump_to',
),
re_path(
- r'^courses/{}/jump_to_id/(?P.*)$'.format(
+ r'^courses/{}/jump_to_id/(?P.*)$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.jump_to_id,
@@ -289,7 +289,7 @@
# xblock Handler APIs
re_path(
- r'^courses/{course_key}/xblock/{usage_key}/handler/(?P[^/]*)(?:/(?P.*))?$'.format(
+ r'^courses/{course_key}/xblock/{usage_key}/handler/(?P[^/]*)(?:/(?P.*))?$'.format( # noqa: UP032
course_key=settings.COURSE_ID_PATTERN,
usage_key=settings.USAGE_ID_PATTERN,
),
@@ -297,7 +297,7 @@
name='xblock_handler',
),
re_path(
- r'^courses/{course_key}/xblock/{usage_key}/handler_noauth/(?P[^/]*)(?:/(?P.*))?$'.format(
+ r'^courses/{course_key}/xblock/{usage_key}/handler_noauth/(?P[^/]*)(?:/(?P.*))?$'.format( # noqa: UP032
course_key=settings.COURSE_ID_PATTERN,
usage_key=settings.USAGE_ID_PATTERN,
),
@@ -309,7 +309,7 @@
# (unpublished) API that returns JSON with the HTML fragment and related resources
# for the xBlock's requested view.
re_path(
- r'^courses/{course_key}/xblock/{usage_key}/view/(?P[^/]*)$'.format(
+ r'^courses/{course_key}/xblock/{usage_key}/view/(?P[^/]*)$'.format( # noqa: UP032
course_key=settings.COURSE_ID_PATTERN,
usage_key=settings.USAGE_ID_PATTERN,
),
@@ -350,7 +350,7 @@
namespace='xblock_api')),
re_path(
- r'^courses/{}/xqueue/(?P[^/]*)/(?P.*?)/(?P[^/]*)$'.format(
+ r'^courses/{}/xqueue/(?P[^/]*)/(?P.*?)/(?P[^/]*)$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
xqueue_callback,
@@ -358,7 +358,7 @@
),
re_path(
- r'^courses/{}/xqueue/(?P[^/]*)/(?P.*?)/(?P[^/]*)$'.format(
+ r'^courses/{}/xqueue/(?P[^/]*)/(?P.*?)/(?P[^/]*)$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
xqueue_callback,
@@ -378,7 +378,7 @@
# About the course
re_path(
- r'^courses/{}/about$'.format(
+ r'^courses/{}/about$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.course_about,
@@ -390,7 +390,7 @@
name='yt_video_metadata',
),
re_path(
- r'^courses/{}/enroll_staff$'.format(
+ r'^courses/{}/enroll_staff$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
EnrollStaffView.as_view(),
@@ -399,7 +399,7 @@
# Inside the course
re_path(
- r'^courses/{}/$'.format(
+ r'^courses/{}/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.course_about,
@@ -407,7 +407,7 @@
),
# TODO arjun remove when custom tabs in place, see courseware/courses.py
re_path(
- r'^courses/{}/syllabus$'.format(
+ r'^courses/{}/syllabus$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.syllabus,
@@ -416,7 +416,7 @@
# Survey associated with a course
re_path(
- r'^courses/{}/survey$'.format(
+ r'^courses/{}/survey$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.course_survey,
@@ -424,14 +424,14 @@
),
re_path(
- r'^courses/{}/book/(?P\d+)/$'.format(
+ r'^courses/{}/book/(?P\d+)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
staticbook_views.index,
name='book',
),
re_path(
- r'^courses/{}/book/(?P\d+)/(?P\d+)$'.format(
+ r'^courses/{}/book/(?P\d+)/(?P\d+)$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
staticbook_views.index,
@@ -439,14 +439,14 @@
),
re_path(
- r'^courses/{}/pdfbook/(?P\d+)/$'.format(
+ r'^courses/{}/pdfbook/(?P\d+)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
staticbook_views.pdf_index,
name='pdf_book',
),
re_path(
- r'^courses/{}/pdfbook/(?P\d+)/(?P\d+)$'.format(
+ r'^courses/{}/pdfbook/(?P\d+)/(?P\d+)$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
staticbook_views.pdf_index,
@@ -454,14 +454,14 @@
),
re_path(
- r'^courses/{}/pdfbook/(?P\d+)/chapter/(?P\d+)/$'.format(
+ r'^courses/{}/pdfbook/(?P\d+)/chapter/(?P\d+)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
staticbook_views.pdf_index,
name='pdf_book',
),
re_path(
- r'^courses/{}/pdfbook/(?P\d+)/chapter/(?P\d+)/(?P\d+)$'.format(
+ r'^courses/{}/pdfbook/(?P\d+)/chapter/(?P\d+)/(?P\d+)$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
staticbook_views.pdf_index,
@@ -469,14 +469,14 @@
),
re_path(
- r'^courses/{}/htmlbook/(?P\d+)/$'.format(
+ r'^courses/{}/htmlbook/(?P\d+)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
staticbook_views.html_index,
name='html_book',
),
re_path(
- r'^courses/{}/htmlbook/(?P\d+)/chapter/(?P\d+)/$'.format(
+ r'^courses/{}/htmlbook/(?P\d+)/chapter/(?P\d+)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
staticbook_views.html_index,
@@ -484,28 +484,28 @@
),
re_path(
- r'^courses/{}/courseware/?$'.format(
+ r'^courses/{}/courseware/?$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
CoursewareIndex.as_view(),
name='courseware',
),
re_path(
- r'^courses/{}/courseware/(?P[^/]*)/$'.format(
+ r'^courses/{}/courseware/(?P[^/]*)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
CoursewareIndex.as_view(),
name='courseware_section',
),
re_path(
- r'^courses/{}/courseware/(?P[^/]*)/(?P[^/]*)/$'.format(
+ r'^courses/{}/courseware/(?P[^/]*)/(?P[^/]*)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
CoursewareIndex.as_view(),
name='courseware_subsection',
),
re_path(
- r'^courses/{}/courseware/(?P[^/]*)/(?P[^/]*)/(?P[^/]*)/?$'.format(
+ r'^courses/{}/courseware/(?P[^/]*)/(?P[^/]*)/(?P[^/]*)/?$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
CoursewareIndex.as_view(),
@@ -514,7 +514,7 @@
# progress page
re_path(
- r'^courses/{}/progress$'.format(
+ r'^courses/{}/progress$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.progress,
@@ -522,11 +522,11 @@
),
# dates page (no longer functional, just redirects to MFE)
- re_path(r'^courses/{}/dates'.format(settings.COURSE_ID_PATTERN), courseware_views.dates, name='dates'),
+ re_path(r'^courses/{}/dates'.format(settings.COURSE_ID_PATTERN), courseware_views.dates, name='dates'), # noqa: UP032
# Takes optional student_id for instructor use--shows profile as that student sees it.
re_path(
- r'^courses/{}/progress/(?P[^/]*)/$'.format(
+ r'^courses/{}/progress/(?P[^/]*)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.progress,
@@ -543,7 +543,7 @@
# For the instructor
re_path(
- r'^courses/{}/instructor$'.format(
+ r'^courses/{}/instructor$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
instructor_dashboard_views.instructor_dashboard_2,
@@ -551,7 +551,7 @@
),
re_path(
- r'^courses/{}/set_course_mode_price$'.format(
+ r'^courses/{}/set_course_mode_price$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
instructor_dashboard_views.set_course_mode_price,
@@ -560,7 +560,7 @@
# Discussions Management
re_path(
- r'^courses/{}/discussions/settings$'.format(
+ r'^courses/{}/discussions/settings$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
discussion_views.course_discussions_settings_handler,
@@ -574,49 +574,49 @@
# Cohorts management
re_path(
- r'^courses/{}/cohorts/settings$'.format(
+ r'^courses/{}/cohorts/settings$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
course_groups_views.course_cohort_settings_handler,
name='course_cohort_settings',
),
re_path(
- r'^courses/{}/cohorts/(?P[0-9]+)?$'.format(
+ r'^courses/{}/cohorts/(?P[0-9]+)?$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
course_groups_views.cohort_handler,
name='cohorts',
),
re_path(
- r'^courses/{}/cohorts/(?P[0-9]+)$'.format(
+ r'^courses/{}/cohorts/(?P[0-9]+)$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
course_groups_views.users_in_cohort,
name='list_cohort',
),
re_path(
- r'^courses/{}/cohorts/(?P[0-9]+)/add$'.format(
+ r'^courses/{}/cohorts/(?P[0-9]+)/add$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
course_groups_views.add_users_to_cohort,
name='add_to_cohort',
),
re_path(
- r'^courses/{}/cohorts/(?P[0-9]+)/delete$'.format(
+ r'^courses/{}/cohorts/(?P[0-9]+)/delete$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
course_groups_views.remove_user_from_cohort,
name='remove_from_cohort',
),
re_path(
- r'^courses/{}/cohorts/debug$'.format(
+ r'^courses/{}/cohorts/debug$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
course_groups_views.debug_cohort_mgmt,
name='debug_cohort_mgmt',
),
re_path(
- r'^courses/{}/discussion/topics$'.format(
+ r'^courses/{}/discussion/topics$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
discussion_views.discussion_topics,
@@ -625,7 +625,7 @@
# LTI endpoints listing
re_path(
- r'^courses/{}/lti_rest_endpoints/'.format(
+ r'^courses/{}/lti_rest_endpoints/'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.get_course_lti_endpoints,
@@ -634,7 +634,7 @@
# Student Notes
re_path(
- r'^courses/{}/edxnotes/'.format(
+ r'^courses/{}/edxnotes/'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
include('lms.djangoapps.edxnotes.urls'),
@@ -655,7 +655,7 @@
# Course experience
re_path(
- r'^courses/{}/course/'.format(
+ r'^courses/{}/course/'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
include('openedx.features.course_experience.urls'),
@@ -663,7 +663,7 @@
# Course bookmarks UI in LMS
re_path(
- r'^courses/{}/bookmarks/'.format(
+ r'^courses/{}/bookmarks/'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
include('openedx.features.course_bookmarks.urls'),
@@ -677,7 +677,7 @@
# Survey Report
re_path(
- fr'^survey_report/',
+ fr'^survey_report/', # noqa: F541
include('openedx.features.survey_report.urls'),
),
]
@@ -690,7 +690,7 @@
include('lms.djangoapps.teams.api_urls')
),
re_path(
- r'^courses/{}/teams/'.format(
+ r'^courses/{}/teams/'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
include('lms.djangoapps.teams.urls'),
@@ -702,7 +702,7 @@
if settings.FEATURES.get('ENABLE_MASQUERADE'):
urlpatterns += [
re_path(
- r'^courses/{}/masquerade$'.format(
+ r'^courses/{}/masquerade$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
MasqueradeView.as_view(),
@@ -712,7 +712,7 @@
urlpatterns += [
re_path(
- r'^courses/{}/generate_user_cert'.format(
+ r'^courses/{}/generate_user_cert'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.generate_user_cert,
@@ -728,7 +728,7 @@
include('lms.djangoapps.discussion.rest_api.urls')
),
re_path(
- r'^courses/{}/discussion/'.format(
+ r'^courses/{}/discussion/'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
include('lms.djangoapps.discussion.django_comment_client.urls')
@@ -744,7 +744,7 @@
urlpatterns += [
re_path(
- r'^courses/{}/tab/(?P[^/]+)/$'.format(
+ r'^courses/{}/tab/(?P[^/]+)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
CourseTabView.as_view(),
@@ -754,7 +754,7 @@
urlpatterns += [
re_path(
- r'^courses/{}/courseware-search/enabled/$'.format(
+ r'^courses/{}/courseware-search/enabled/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
courseware_views.courseware_mfe_search_enabled,
@@ -769,7 +769,7 @@
urlpatterns += [
re_path(
- r'^courses/{}/lti_tab/(?P[^/]+)/$'.format(
+ r'^courses/{}/lti_tab/(?P[^/]+)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
CourseTabView.as_view(),
@@ -781,7 +781,7 @@
urlpatterns += [
# This MUST be the last view in the courseware--it's a catch-all for custom tabs.
re_path(
- r'^courses/{}/(?P[^/]+)/$'.format(
+ r'^courses/{}/(?P[^/]+)/$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN,
),
StaticCourseTabView.as_view(),
@@ -792,7 +792,7 @@
if settings.FEATURES.get('ENABLE_STUDENT_HISTORY_VIEW'):
urlpatterns += [
re_path(
- r'^courses/{}/submission_history/(?P[^/]*)/(?P.*?)$'.format(
+ r'^courses/{}/submission_history/(?P[^/]*)/(?P.*?)$'.format( # noqa: UP032
settings.COURSE_ID_PATTERN
),
courseware_views.submission_history,
diff --git a/openedx/core/djangoapps/ace_common/templatetags/ace.py b/openedx/core/djangoapps/ace_common/templatetags/ace.py
index 8a7f2b5451ee..085f29def784 100644
--- a/openedx/core/djangoapps/ace_common/templatetags/ace.py
+++ b/openedx/core/djangoapps/ace_common/templatetags/ace.py
@@ -56,7 +56,7 @@ def _get_variables_from_context(context, tag_name):
if request is None:
raise template.VariableDoesNotExist(
- 'The {} template tag requires a "request" to be present in the template context. Consider using '
+ 'The {} template tag requires a "request" to be present in the template context. Consider using ' # noqa: UP032 # pylint: disable=line-too-long
'"emulate_http_request" if you are rendering the template in a celery task.'.format(tag_name)
)
@@ -102,7 +102,7 @@ def _get_google_analytics_tracking_url(context):
campaign_source=message.app_label,
campaign_name=message.name,
campaign_content=message.uuid,
- document_path='/email/{}/{}/{}/{}'.format(
+ document_path='/email/{}/{}/{}/{}'.format( # noqa: UP032
message.app_label,
message.name,
message.send_uuid,
diff --git a/openedx/core/djangoapps/ace_common/tests/mixins.py b/openedx/core/djangoapps/ace_common/tests/mixins.py
index 398470999351..1b16982a1d5f 100644
--- a/openedx/core/djangoapps/ace_common/tests/mixins.py
+++ b/openedx/core/djangoapps/ace_common/tests/mixins.py
@@ -25,7 +25,7 @@ def assert_query_string_equal(self, expected_qs, actual_qs):
Raises:
AssertionError: If the two query strings are not equal.
"""
- self.assertDictEqual(parse_qs(expected_qs), parse_qs(actual_qs))
+ self.assertDictEqual(parse_qs(expected_qs), parse_qs(actual_qs)) # noqa: PT009
def assert_url_components_equal(self, url, **kwargs):
"""
diff --git a/openedx/core/djangoapps/ace_common/tests/test_templatetags.py b/openedx/core/djangoapps/ace_common/tests/test_templatetags.py
index d8513bffd6c8..3280cc9c6232 100644
--- a/openedx/core/djangoapps/ace_common/tests/test_templatetags.py
+++ b/openedx/core/djangoapps/ace_common/tests/test_templatetags.py
@@ -47,7 +47,7 @@ def test_default(self):
scheme='http',
netloc='example.com',
path='/foo',
- query='utm_source=test_app_label&utm_campaign=test_name&utm_medium=email&utm_content={uuid}'.format(
+ query='utm_source=test_app_label&utm_campaign=test_name&utm_medium=email&utm_content={uuid}'.format( # noqa: UP032 # pylint: disable=line-too-long
uuid=self.message.uuid
)
)
@@ -102,7 +102,7 @@ def test_default(self):
cs=self.message.app_label,
cn=self.message.name,
cc=self.message.uuid,
- dp='/email/test_app_label/test_name/{send_uuid}/{uuid}'.format(
+ dp='/email/test_app_label/test_name/{send_uuid}/{uuid}'.format( # noqa: UP032
send_uuid=self.message.send_uuid,
uuid=self.message.uuid,
),
diff --git a/openedx/core/djangoapps/ace_common/tests/test_tracking.py b/openedx/core/djangoapps/ace_common/tests/test_tracking.py
index c93bd2dd9d10..ed8f7ebb39f6 100644
--- a/openedx/core/djangoapps/ace_common/tests/test_tracking.py
+++ b/openedx/core/djangoapps/ace_common/tests/test_tracking.py
@@ -82,7 +82,7 @@ def test_default_parameters(self):
scheme='https',
netloc='www.google-analytics.com',
path='/collect',
- query='v=1&t=event&cs={cs}&cm={cm}&ec=email&ea=edx.bi.email.opened&cid={cid}&tid=UA-123456-1'.format(
+ query='v=1&t=event&cs={cs}&cm={cm}&ec=email&ea=edx.bi.email.opened&cid={cid}&tid=UA-123456-1'.format( # noqa: UP032 # pylint: disable=line-too-long
cs=DEFAULT_CAMPAIGN_SOURCE,
cm=DEFAULT_CAMPAIGN_MEDIUM,
cid=GoogleAnalyticsTrackingPixel.ANONYMOUS_USER_CLIENT_ID,
@@ -138,7 +138,7 @@ def test_custom_dimension(self):
assert pixel.generate_image_url() is not None
self.assert_url_components_equal(
pixel.generate_image_url(),
- query='v=1&t=event&ec=email&ea=edx.bi.email.opened&cid={cid}&tid=UA-123456-1&cd40=10&uid=10'.format(
+ query='v=1&t=event&ec=email&ea=edx.bi.email.opened&cid={cid}&tid=UA-123456-1&cd40=10&uid=10'.format( # noqa: UP032 # pylint: disable=line-too-long
cid=GoogleAnalyticsTrackingPixel.ANONYMOUS_USER_CLIENT_ID,
)
)
@@ -152,7 +152,7 @@ def test_custom_dimension_without_user_id(self):
assert pixel.generate_image_url() is not None
self.assert_url_components_equal(
pixel.generate_image_url(),
- query='v=1&t=event&ec=email&ea=edx.bi.email.opened&cid={cid}&tid=UA-123456-1'.format(
+ query='v=1&t=event&ec=email&ea=edx.bi.email.opened&cid={cid}&tid=UA-123456-1'.format( # noqa: UP032
cid=GoogleAnalyticsTrackingPixel.ANONYMOUS_USER_CLIENT_ID,
)
)
diff --git a/openedx/core/djangoapps/agreements/api.py b/openedx/core/djangoapps/agreements/api.py
index 5aab8f4ef7f4..2b88048a294f 100644
--- a/openedx/core/djangoapps/agreements/api.py
+++ b/openedx/core/djangoapps/agreements/api.py
@@ -4,7 +4,7 @@
import logging
from datetime import datetime
-from typing import Iterator
+from typing import Iterator # noqa: UP035
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
@@ -43,7 +43,7 @@ def create_integrity_signature(username, course_id):
signature, created = IntegritySignature.objects.get_or_create(user=user, course_key=course_key)
if not created:
log.warning(
- 'Integrity signature already exists for user_id={user_id} and '
+ 'Integrity signature already exists for user_id={user_id} and ' # noqa: UP032
'course_id={course_id}'.format(user_id=user.id, course_id=course_id)
)
return signature
diff --git a/openedx/core/djangoapps/agreements/models.py b/openedx/core/djangoapps/agreements/models.py
index be7e9e625753..934e0d795236 100644
--- a/openedx/core/djangoapps/agreements/models.py
+++ b/openedx/core/djangoapps/agreements/models.py
@@ -73,7 +73,7 @@ class Meta:
app_label = 'agreements'
-class UserAgreement(models.Model):
+class UserAgreement(models.Model): # noqa: DJ008
"""
This model stores agreements that the user can accept, which can gate certain
platform features.
@@ -95,12 +95,12 @@ class UserAgreement(models.Model):
"Brief summary of the agreement content. Will be displayed to users in alert to accept the agreement."
),
)
- text = models.TextField(
+ text = models.TextField( # noqa: DJ001
help_text="Full text of the agreement. (Required if url is not provided)",
null=True,
blank=True,
)
- url = models.URLField(
+ url = models.URLField( # noqa: DJ001
help_text=(
"URL where the full agreement can be accessed. "
'Will be used for "Learn More" link in alert to accept the agreement.'
@@ -121,7 +121,7 @@ class UserAgreement(models.Model):
def has_text(self):
return bool(self.text)
- class Meta:
+ class Meta: # noqa: DJ012
app_label = "agreements"
constraints = [
models.CheckConstraint(
@@ -130,7 +130,7 @@ class Meta:
]
-class UserAgreementRecord(models.Model):
+class UserAgreementRecord(models.Model): # noqa: DJ008
"""
This model stores the agreements a user has accepted or acknowledged.
@@ -148,5 +148,5 @@ class UserAgreementRecord(models.Model):
def is_current(self):
return self.agreement.updated < self.timestamp
- class Meta:
+ class Meta: # noqa: DJ012
app_label = "agreements"
diff --git a/openedx/core/djangoapps/agreements/tests/test_api.py b/openedx/core/djangoapps/agreements/tests/test_api.py
index 7a1f203a8684..96d800f5f01f 100644
--- a/openedx/core/djangoapps/agreements/tests/test_api.py
+++ b/openedx/core/djangoapps/agreements/tests/test_api.py
@@ -61,7 +61,7 @@ def test_create_duplicate_integrity_signature(self):
LOGGER_NAME,
'WARNING',
(
- 'Integrity signature already exists for user_id={user_id} and '
+ 'Integrity signature already exists for user_id={user_id} and ' # noqa: UP032
'course_id={course_id}'.format(
user_id=self.user.id, course_id=str(self.course_id)
)
@@ -81,7 +81,7 @@ def test_get_nonexistent_integrity_signature(self):
Test that None is returned if an integrity signature does not exist
"""
signature = get_integrity_signature(self.user.username, self.course_id)
- self.assertIsNone(signature)
+ self.assertIsNone(signature) # noqa: PT009
def test_get_integrity_signatures_for_course(self):
"""
@@ -92,23 +92,23 @@ def test_get_integrity_signatures_for_course(self):
create_integrity_signature(second_user.username, self.course_id)
signatures = get_integrity_signatures_for_course(self.course_id)
self._assert_integrity_signature(signatures[0])
- self.assertEqual(signatures[1].user, second_user)
- self.assertEqual(signatures[1].course_key, self.course.id)
+ self.assertEqual(signatures[1].user, second_user) # noqa: PT009
+ self.assertEqual(signatures[1].course_key, self.course.id) # noqa: PT009
def test_get_integrity_signatures_for_course_empty(self):
"""
Test that a course with no integrity signatures returns an empty queryset
"""
signatures = get_integrity_signatures_for_course(self.course_id)
- self.assertEqual(len(signatures), 0)
+ self.assertEqual(len(signatures), 0) # noqa: PT009
def _assert_integrity_signature(self, signature):
"""
Helper function to assert the returned integrity signature has the correct
user and course key
"""
- self.assertEqual(signature.user, self.user)
- self.assertEqual(signature.course_key, self.course.id)
+ self.assertEqual(signature.user, self.user) # noqa: PT009
+ self.assertEqual(signature.course_key, self.course.id) # noqa: PT009
@skip_unless_lms
@@ -149,15 +149,15 @@ def test_create_multiple_lti_pii_signature(self):
s1 = get_lti_pii_signature(self.user.username, self.course_id) # retrieve the database entry
create_lti_pii_signature(self.user.username, self.course_id, self.lti_tools_2) # signature with updated tools
s2 = get_lti_pii_signature(self.user.username, self.course_id) # retrieve the updated database entry
- self.assertNotEqual(s1, s2) # the signatue retrieved from the database should be the updated version
+ self.assertNotEqual(s1, s2) # the signatue retrieved from the database should be the updated version # noqa: PT009 # pylint: disable=line-too-long
def _assert_lti_pii_signature(self, signature):
"""
Helper function to assert the returned lti pii signature has the correct
user and course key
"""
- self.assertEqual(signature.user, self.user)
- self.assertEqual(signature.course_key, self.course.id)
+ self.assertEqual(signature.user, self.user) # noqa: PT009
+ self.assertEqual(signature.course_key, self.course.id) # noqa: PT009
@skip_unless_lms
@@ -189,7 +189,7 @@ def _assert_ltitools(self, lti_list):
"""
Helper function to assert the returned list has the correct tools
"""
- self.assertEqual(self.lti_tools, lti_list)
+ self.assertEqual(self.lti_tools, lti_list) # noqa: PT009
@skip_unless_lms
diff --git a/openedx/core/djangoapps/agreements/tests/test_models.py b/openedx/core/djangoapps/agreements/tests/test_models.py
index 5aa30d3e4d67..55fe2dad09f9 100644
--- a/openedx/core/djangoapps/agreements/tests/test_models.py
+++ b/openedx/core/djangoapps/agreements/tests/test_models.py
@@ -51,7 +51,7 @@ def test_agreement_must_have_text_or_url(self):
)
assert agreement.pk is not None
- with self.assertRaises(IntegrityError):
+ with self.assertRaises(IntegrityError): # noqa: PT027
UserAgreement.objects.create(
type="type4",
name="Name 4",
diff --git a/openedx/core/djangoapps/agreements/tests/test_views.py b/openedx/core/djangoapps/agreements/tests/test_views.py
index 5d36e1e4845f..95fa3c5dd64c 100644
--- a/openedx/core/djangoapps/agreements/tests/test_views.py
+++ b/openedx/core/djangoapps/agreements/tests/test_views.py
@@ -102,7 +102,7 @@ def test_403_get_if_non_staff(self):
'integrity_signature',
kwargs={'course_id': self.course_id},
)
- + '?username={}'.format(self.other_user.username)
+ + '?username={}'.format(self.other_user.username) # noqa: UP032
)
self._assert_response(response, status.HTTP_403_FORBIDDEN)
@@ -120,7 +120,7 @@ def test_200_get_for_course_staff_request(self):
'integrity_signature',
kwargs={'course_id': self.course_id},
)
- + '?username={}'.format(self.user.username)
+ + '?username={}'.format(self.user.username) # noqa: UP032
)
self._assert_response(response, status.HTTP_200_OK, self.user, self.course_id)
@@ -140,7 +140,7 @@ def test_403_get_for_other_course_instructor(self):
'integrity_signature',
kwargs={'course_id': self.course_id},
)
- + '?username={}'.format(self.user.username)
+ + '?username={}'.format(self.user.username) # noqa: UP032
)
self._assert_response(response, status.HTTP_403_FORBIDDEN)
@@ -157,7 +157,7 @@ def test_200_get_for_admin(self):
'integrity_signature',
kwargs={'course_id': self.course_id},
)
- + '?username={}'.format(self.user.username)
+ + '?username={}'.format(self.user.username) # noqa: UP032
)
self._assert_response(response, status.HTTP_200_OK, self.user, self.course_id)
@@ -180,8 +180,8 @@ def test_post_integrity_signature(self):
# Check that the course has a signature created
signatures = get_integrity_signatures_for_course(self.course_id)
- self.assertEqual(len(signatures), 1)
- self.assertEqual(signatures[0].user.username, self.USERNAME)
+ self.assertEqual(len(signatures), 1) # noqa: PT009
+ self.assertEqual(signatures[0].user.username, self.USERNAME) # noqa: PT009
def test_post_duplicate_integrity_signature(self):
# Create a signature
@@ -190,7 +190,7 @@ def test_post_duplicate_integrity_signature(self):
'integrity_signature',
kwargs={'course_id': self.course_id},
)
- + '?username={}'.format(self.other_user.username)
+ + '?username={}'.format(self.other_user.username) # noqa: UP032
)
# Attempt to create a new signature in the future
@@ -203,15 +203,15 @@ def test_post_duplicate_integrity_signature(self):
)
# The created_at field in the response should equal the original time created
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
original_response.data['created_at'],
new_response.data['created_at'],
)
# The course should not have a second signature
signatures = get_integrity_signatures_for_course(self.course_id)
- self.assertEqual(len(signatures), 1)
- self.assertEqual(signatures[0].user.username, self.USERNAME)
+ self.assertEqual(len(signatures), 1) # noqa: PT009
+ self.assertEqual(signatures[0].user.username, self.USERNAME) # noqa: PT009
@patch.dict(settings.FEATURES, {'ENABLE_INTEGRITY_SIGNATURE': False})
def test_post_integrity_signature_no_waffle_flag(self):
@@ -289,8 +289,8 @@ def test_post_lti_pii_signature(self):
"lti_tools": self.lti_tools, "created_at": self.time_created})
self._assert_response(response, status.HTTP_200_OK, self.user, self.course_id)
signature = get_lti_pii_signature(self.user.username, self.course_id)
- self.assertEqual(signature.user.username, self.user.username)
- self.assertEqual(signature.lti_tools, self.lti_tools)
+ self.assertEqual(signature.user.username, self.user.username) # noqa: PT009
+ self.assertEqual(signature.lti_tools, self.lti_tools) # noqa: PT009
@skip_unless_lms
diff --git a/openedx/core/djangoapps/agreements/urls.py b/openedx/core/djangoapps/agreements/urls.py
index e94f75e26197..36789a8c625d 100644
--- a/openedx/core/djangoapps/agreements/urls.py
+++ b/openedx/core/djangoapps/agreements/urls.py
@@ -17,10 +17,10 @@
router.register(r"agreement", UserAgreementsViewSet, basename="user_agreements")
urlpatterns = [
- re_path(r'^integrity_signature/{course_id}$'.format(
+ re_path(r'^integrity_signature/{course_id}$'.format( # noqa: UP032
course_id=settings.COURSE_ID_PATTERN
), IntegritySignatureView.as_view(), name='integrity_signature'),
- re_path(r'^lti_pii_signature/{course_id}$'.format(
+ re_path(r'^lti_pii_signature/{course_id}$'.format( # noqa: UP032
course_id=settings.COURSE_ID_PATTERN
), LTIPIISignatureView.as_view(), name='lti_pii_signature'),
path('agreement_record/', UserAgreementRecordsView.as_view(), name='user_agreement_record'),
diff --git a/openedx/core/djangoapps/api_admin/management/commands/create_api_access_request.py b/openedx/core/djangoapps/api_admin/management/commands/create_api_access_request.py
index c59e6b438253..24d642b7c862 100644
--- a/openedx/core/djangoapps/api_admin/management/commands/create_api_access_request.py
+++ b/openedx/core/djangoapps/api_admin/management/commands/create_api_access_request.py
@@ -105,7 +105,7 @@ def get_user(self, username):
try:
return User.objects.get(username=username)
except User.DoesNotExist:
- raise CommandError(f'User {username} not found') # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(f'User {username} not found') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def create_api_access_request(self, user, status, reason, website):
"""
@@ -126,14 +126,14 @@ def create_api_access_request(self, user, status, reason, website):
if 'Permission denied' in error_msg and 'mako_lms' in error_msg:
logger.warning(f'Error sending email about access request: {error_msg}')
else:
- raise CommandError(error_msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(error_msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except Exception as e:
- msg = 'Unable to create ApiAccessRequest for {}. Exception is {}: {}'.format(
+ msg = 'Unable to create ApiAccessRequest for {}. Exception is {}: {}'.format( # noqa: UP032
user.username,
type(e).__name__,
e
)
- raise CommandError(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
logger.info(f'Created ApiAccessRequest for user {user.username}')
@@ -145,7 +145,7 @@ def create_api_access_config(self):
_, created = ApiAccessConfig.objects.get_or_create(enabled=True)
except Exception as e:
msg = f'Unable to create ApiAccessConfig. Exception is {type(e).__name__}: {e}'
- raise CommandError(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if created:
logger.info('Created ApiAccessConfig')
diff --git a/openedx/core/djangoapps/api_admin/management/commands/tests/test_create_api_access_request.py b/openedx/core/djangoapps/api_admin/management/commands/tests/test_create_api_access_request.py
index a49d19caa36a..d20c8963b79b 100644
--- a/openedx/core/djangoapps/api_admin/management/commands/tests/test_create_api_access_request.py
+++ b/openedx/core/djangoapps/api_admin/management/commands/tests/test_create_api_access_request.py
@@ -55,7 +55,7 @@ def test_config_already_exists(self):
self.assert_models_exist(True, True)
def test_user_not_found(self):
- with self.assertRaisesRegex(CommandError, r'User .*? not found'):
+ with self.assertRaisesRegex(CommandError, r'User .*? not found'): # noqa: PT027
call_command(self.command, 'not-a-user-notfound-nope')
@patch('openedx.core.djangoapps.api_admin.models.ApiAccessRequest.objects.create')
@@ -64,7 +64,7 @@ def test_api_request_error(self, mocked_method):
self.assert_models_exist(False, False)
- with self.assertRaisesRegex(CommandError, r'Unable to create ApiAccessRequest .*'):
+ with self.assertRaisesRegex(CommandError, r'Unable to create ApiAccessRequest .*'): # noqa: PT027
call_command(self.command, self.user.username)
self.assert_models_exist(False, False)
@@ -92,7 +92,7 @@ def test_api_request_other_oserrors_raise(self, mocked_method):
self.assert_models_exist(False, False)
- with self.assertRaisesRegex(CommandError, 'out of disk space'):
+ with self.assertRaisesRegex(CommandError, 'out of disk space'): # noqa: PT027
call_command(self.command, self.user.username)
self.assert_models_exist(False, False)
@@ -102,7 +102,7 @@ def test_api_config_error(self, mocked_method):
mocked_method.side_effect = Exception()
self.assert_models_exist(False, False)
- with self.assertRaisesRegex(CommandError, r'Unable to create ApiAccessConfig\. .*'):
+ with self.assertRaisesRegex(CommandError, r'Unable to create ApiAccessConfig\. .*'): # noqa: PT027
call_command(self.command, self.user.username, create_config=True)
self.assert_models_exist(False, False)
diff --git a/openedx/core/djangoapps/api_admin/models.py b/openedx/core/djangoapps/api_admin/models.py
index fa6daeebd346..845c6e1bf5ca 100644
--- a/openedx/core/djangoapps/api_admin/models.py
+++ b/openedx/core/djangoapps/api_admin/models.py
@@ -262,5 +262,5 @@ def attributes(self):
'viewers': self.viewers,
}
- def __str__(self):
+ def __str__(self): # noqa: DJ012
return f'Catalog {self.name} [{self.query}]'
diff --git a/openedx/core/djangoapps/api_admin/tests/test_forms.py b/openedx/core/djangoapps/api_admin/tests/test_forms.py
index ceacb23dc023..388249c1d191 100644
--- a/openedx/core/djangoapps/api_admin/tests/test_forms.py
+++ b/openedx/core/djangoapps/api_admin/tests/test_forms.py
@@ -34,7 +34,7 @@ def test_render_value(self):
dummy_string_value = 'staff, verified'
input_field_name = 'viewers'
extra_formating = ''
- expected_widget_html = ''.format( # lint-amnesty, pylint: disable=line-too-long
+ expected_widget_html = ''.format( # lint-amnesty, pylint: disable=line-too-long # noqa: UP032
input_field_name=input_field_name,
serialized_value=dummy_string_value,
extra_formating=extra_formating,
diff --git a/openedx/core/djangoapps/auth_exchange/forms.py b/openedx/core/djangoapps/auth_exchange/forms.py
index 25cad5e36bff..490ec9eb0880 100644
--- a/openedx/core/djangoapps/auth_exchange/forms.py
+++ b/openedx/core/djangoapps/auth_exchange/forms.py
@@ -164,7 +164,7 @@ def clean(self):
try:
client = self.oauth2_adapter.get_client(client_id=client_id)
except Application.DoesNotExist:
- raise OAuthValidationError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise OAuthValidationError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
{
"error": "invalid_client",
"error_description": f"{client_id} is not a valid client_id",
diff --git a/openedx/core/djangoapps/auth_exchange/tests/test_views.py b/openedx/core/djangoapps/auth_exchange/tests/test_views.py
index 6cebc9461aff..de7f9dff0f33 100644
--- a/openedx/core/djangoapps/auth_exchange/tests/test_views.py
+++ b/openedx/core/djangoapps/auth_exchange/tests/test_views.py
@@ -156,7 +156,7 @@ def setUp(self):
def _get_response(self, access_token, token_type='Bearer'):
url = reverse("login_with_access_token")
- return self.client.post(url, HTTP_AUTHORIZATION=f"{token_type} {access_token}".encode('utf-8'))
+ return self.client.post(url, HTTP_AUTHORIZATION=f"{token_type} {access_token}".encode('utf-8')) # noqa: UP012
def _verify_response(self, access_token, expected_status_code, token_type='Bearer', expected_cookie_name=None):
"""
@@ -239,7 +239,7 @@ def test_failure_with_valid_symmetric_jwt(self):
'error_code': 'non_asymmetric_token',
'developer_message': 'Only asymmetric jwt are supported.'
}
- self.assertDictEqual(error_msg, json.loads(response.content))
+ self.assertDictEqual(error_msg, json.loads(response.content)) # noqa: PT009
assert '_auth_user_id' not in self.client.session
assert response.status_code == 401
@@ -253,7 +253,7 @@ def test_failure_with_valid_asymmetric_jwt_and_disabled_user(self):
'error_code': 'account_disabled',
'developer_message': 'User account is disabled.'
}
- self.assertDictEqual(error_msg, json.loads(response.content))
+ self.assertDictEqual(error_msg, json.loads(response.content)) # noqa: PT009
assert '_auth_user_id' not in self.client.session
assert response.status_code == 401
diff --git a/openedx/core/djangoapps/authz/decorators.py b/openedx/core/djangoapps/authz/decorators.py
index b82a2fb69a51..a25b9841fcac 100644
--- a/openedx/core/djangoapps/authz/decorators.py
+++ b/openedx/core/djangoapps/authz/decorators.py
@@ -70,7 +70,7 @@ def user_has_course_permission(
# If AuthZ is enabled for this course, check the permission via AuthZ only.
is_user_allowed = authz_api.is_user_allowed(user.username, authz_permission, str(course_key))
log.info(
- "AuthZ permission granted = {}".format(is_user_allowed),
+ "AuthZ permission granted = {}".format(is_user_allowed), # noqa: UP032
extra={
"user_id": user.id,
"authz_permission": authz_permission,
diff --git a/openedx/core/djangoapps/authz/tests/test_decorators.py b/openedx/core/djangoapps/authz/tests/test_decorators.py
index 014932fbc315..9d9084b11612 100644
--- a/openedx/core/djangoapps/authz/tests/test_decorators.py
+++ b/openedx/core/djangoapps/authz/tests/test_decorators.py
@@ -43,7 +43,7 @@ def test_view_executes_when_permission_granted(self):
result = decorated(self.view_instance, request, str(self.course_key))
- self.assertEqual(result, "success")
+ self.assertEqual(result, "success") # noqa: PT009
mock_view.assert_called_once_with(
self.view_instance,
request,
@@ -73,7 +73,7 @@ def test_view_executes_when_legacy_fallback_read(self):
result = decorated(self.view_instance, request, str(self.course_key))
- self.assertEqual(result, "success")
+ self.assertEqual(result, "success") # noqa: PT009
mock_view.assert_called_once()
def test_view_executes_when_legacy_fallback_write(self):
@@ -99,7 +99,7 @@ def test_view_executes_when_legacy_fallback_write(self):
result = decorated(self.view_instance, request, str(self.course_key))
- self.assertEqual(result, "success")
+ self.assertEqual(result, "success") # noqa: PT009
mock_view.assert_called_once()
def test_access_denied_when_permission_fails(self):
@@ -114,10 +114,10 @@ def test_access_denied_when_permission_fails(self):
):
decorated = authz_permission_required("courses.view")(mock_view)
- with self.assertRaises(DeveloperErrorResponseException) as context:
+ with self.assertRaises(DeveloperErrorResponseException) as context: # noqa: PT027
decorated(self.view_instance, request, str(self.course_key))
- self.assertEqual(context.exception.response.status_code, 403)
+ self.assertEqual(context.exception.response.status_code, 403) # noqa: PT009
mock_view.assert_not_called()
def test_decorator_preserves_function_name(self):
@@ -128,7 +128,7 @@ def sample_view(self, request, course_key):
decorated = authz_permission_required("courses.view")(sample_view)
- self.assertEqual(decorated.__name__, "sample_view")
+ self.assertEqual(decorated.__name__, "sample_view") # noqa: PT009
class GetCourseKeyTests(TestCase):
@@ -141,7 +141,7 @@ def test_course_key_string(self):
"""Valid course key string returns CourseKey."""
result = get_course_key(str(self.course_key))
- self.assertEqual(result, self.course_key)
+ self.assertEqual(result, self.course_key) # noqa: PT009
def test_usage_key_string(self):
"""UsageKey string resolves to course key."""
@@ -153,4 +153,4 @@ def test_usage_key_string(self):
result = get_course_key(str(usage_key))
- self.assertEqual(result, self.course_key)
+ self.assertEqual(result, self.course_key) # noqa: PT009
diff --git a/openedx/core/djangoapps/bookmarks/api.py b/openedx/core/djangoapps/bookmarks/api.py
index c65e21f69b2a..19ccad082c09 100644
--- a/openedx/core/djangoapps/bookmarks/api.py
+++ b/openedx/core/djangoapps/bookmarks/api.py
@@ -4,12 +4,12 @@
# pylint: disable=unused-import
from .api_impl import (
- BookmarksLimitReachedError,
- can_create_more,
- create_bookmark,
- delete_bookmark,
- delete_bookmarks,
- get_bookmark,
- get_bookmarks,
+ BookmarksLimitReachedError, # noqa: F401
+ can_create_more, # noqa: F401
+ create_bookmark, # noqa: F401
+ delete_bookmark, # noqa: F401
+ delete_bookmarks, # noqa: F401
+ get_bookmark, # noqa: F401
+ get_bookmarks, # noqa: F401
)
-from .services import BookmarksService
+from .services import BookmarksService # noqa: F401
diff --git a/openedx/core/djangoapps/bookmarks/apps.py b/openedx/core/djangoapps/bookmarks/apps.py
index 61ff98f6dc60..ea6a4a53166f 100644
--- a/openedx/core/djangoapps/bookmarks/apps.py
+++ b/openedx/core/djangoapps/bookmarks/apps.py
@@ -35,4 +35,4 @@ class BookmarksConfig(AppConfig):
def ready(self):
# Register the signals handled by bookmarks.
- from . import signals # lint-amnesty, pylint: disable=unused-import
+ from . import signals # lint-amnesty, pylint: disable=unused-import # noqa: F401
diff --git a/openedx/core/djangoapps/bookmarks/tasks.py b/openedx/core/djangoapps/bookmarks/tasks.py
index 836335c1289c..a35affb05180 100644
--- a/openedx/core/djangoapps/bookmarks/tasks.py
+++ b/openedx/core/djangoapps/bookmarks/tasks.py
@@ -87,11 +87,11 @@ def paths_equal(paths_1, paths_2):
if len(paths_1) != len(paths_2):
return False
- for path_1, path_2 in zip(paths_1, paths_2):
+ for path_1, path_2 in zip(paths_1, paths_2): # noqa: B905
if len(path_1) != len(path_2):
return False
- for path_item_1, path_item_2 in zip(path_1, path_2):
+ for path_item_1, path_item_2 in zip(path_1, path_2): # noqa: B905
if path_item_1.display_name != path_item_2.display_name:
return False
diff --git a/openedx/core/djangoapps/bookmarks/tests/test_views.py b/openedx/core/djangoapps/bookmarks/tests/test_views.py
index f27fde608ea3..4816ddb26ea8 100644
--- a/openedx/core/djangoapps/bookmarks/tests/test_views.py
+++ b/openedx/core/djangoapps/bookmarks/tests/test_views.py
@@ -91,7 +91,7 @@ def test_get_bookmarks_successfully(self, bookmarks_count, check_all_fields, moc
course, __, bookmarks = self.create_course_with_bookmarks_count(bookmarks_count)
- query_parameters = 'course_id={}&page_size={}'.format(
+ query_parameters = 'course_id={}&page_size={}'.format( # noqa: UP032
quote(str(course.id)), 100)
if check_all_fields:
query_parameters += '&fields=path,display_name'
@@ -133,7 +133,7 @@ def test_get_bookmarks_with_pagination(self, bookmarks_count, mock_tracker):
course, __, bookmarks = self.create_course_with_bookmarks_count(bookmarks_count)
page_size = 5
- query_parameters = 'course_id={}&page_size={}'.format(
+ query_parameters = 'course_id={}&page_size={}'.format( # noqa: UP032
quote(str(course.id)), page_size)
response = self.send_get(
@@ -308,10 +308,10 @@ def test_post_bookmark_when_max_bookmarks_already_exist(self):
)
assert response.data['user_message'] == 'You can create up to {} bookmarks.' \
' You must remove some bookmarks before you can add new ones.'\
- .format(max_bookmarks)
+ .format(max_bookmarks) # noqa: UP032
assert response.data['developer_message'] == 'You can create up to {} bookmarks.' \
' You must remove some bookmarks before you can add new ones.'\
- .format(max_bookmarks)
+ .format(max_bookmarks) # noqa: UP032
def test_unsupported_methods(self):
"""
diff --git a/openedx/core/djangoapps/bookmarks/urls.py b/openedx/core/djangoapps/bookmarks/urls.py
index 9e9d3580fd1d..07af3e22e97c 100644
--- a/openedx/core/djangoapps/bookmarks/urls.py
+++ b/openedx/core/djangoapps/bookmarks/urls.py
@@ -13,7 +13,7 @@
name='bookmarks'
),
re_path(
- r'^v1/bookmarks/{username},{usage_key}/$'.format(
+ r'^v1/bookmarks/{username},{usage_key}/$'.format( # noqa: UP032
username=settings.USERNAME_PATTERN,
usage_key=settings.USAGE_ID_PATTERN
),
diff --git a/openedx/core/djangoapps/cache_toolbox/__init__.py b/openedx/core/djangoapps/cache_toolbox/__init__.py
index f41654ad433f..cb2cdbc3a851 100644
--- a/openedx/core/djangoapps/cache_toolbox/__init__.py
+++ b/openedx/core/djangoapps/cache_toolbox/__init__.py
@@ -25,4 +25,4 @@
https://github.com/playfire/django-cache-toolbox/issues
"""
-from .model import cache_model
+from .model import cache_model # noqa: F401
diff --git a/openedx/core/djangoapps/cache_toolbox/core.py b/openedx/core/djangoapps/cache_toolbox/core.py
index 7fa082ef09a7..c894cad58b0b 100644
--- a/openedx/core/djangoapps/cache_toolbox/core.py
+++ b/openedx/core/djangoapps/cache_toolbox/core.py
@@ -97,7 +97,7 @@ def instance_key(model, instance_or_pk):
"""
Returns the cache key for this (model, instance) pair.
"""
- return '%s.%s:%d' % (
+ return '%s.%s:%d' % ( # noqa: UP031
model._meta.app_label,
model._meta.model_name,
getattr(instance_or_pk, 'pk', instance_or_pk),
diff --git a/openedx/core/djangoapps/cache_toolbox/templatetags/cache_toolbox.py b/openedx/core/djangoapps/cache_toolbox/templatetags/cache_toolbox.py
index c086b5c1292f..83365443fc76 100644
--- a/openedx/core/djangoapps/cache_toolbox/templatetags/cache_toolbox.py
+++ b/openedx/core/djangoapps/cache_toolbox/templatetags/cache_toolbox.py
@@ -56,7 +56,7 @@ def cachedeterministic(parser, token):
parser.delete_first_token()
tokens = token.contents.split()
if len(tokens) != 3:
- raise TemplateSyntaxError("'%r' tag requires 2 arguments." % tokens[0])
+ raise TemplateSyntaxError("'%r' tag requires 2 arguments." % tokens[0]) # noqa: UP031
return CacheNode(nodelist, tokens[1], tokens[2])
@@ -89,5 +89,5 @@ def showifcached(parser, token): # pylint: disable=unused-argument
"""
tokens = token.contents.split()
if len(tokens) != 2:
- raise TemplateSyntaxError("'%r' tag requires 1 argument." % tokens[0])
+ raise TemplateSyntaxError("'%r' tag requires 1 argument." % tokens[0]) # noqa: UP031
return ShowIfCachedNode(tokens[1])
diff --git a/openedx/core/djangoapps/catalog/management/commands/cache_programs.py b/openedx/core/djangoapps/catalog/management/commands/cache_programs.py
index 0d404749a2eb..78509a8d9c8d 100644
--- a/openedx/core/djangoapps/catalog/management/commands/cache_programs.py
+++ b/openedx/core/djangoapps/catalog/management/commands/cache_programs.py
@@ -111,14 +111,14 @@ def handle(self, *args, **options): # lint-amnesty, pylint: disable=too-many-st
programs_by_type_slug.update(self.get_programs_by_type_slug(site, new_programs))
organizations.update(self.get_programs_by_organization(new_programs))
- logger.info('Caching UUIDs for {total} programs for site {site_name}.'.format(
+ logger.info('Caching UUIDs for {total} programs for site {site_name}.'.format( # noqa: UP032
total=len(uuids),
site_name=site.domain,
))
cache.set(SITE_PROGRAM_UUIDS_CACHE_KEY_TPL.format(domain=site.domain), uuids, None)
pathway_ids = list(new_pathways.keys())
- logger.info('Caching ids for {total} pathways for site {site_name}.'.format(
+ logger.info('Caching ids for {total} pathways for site {site_name}.'.format( # noqa: UP032
total=len(pathway_ids),
site_name=site.domain,
))
@@ -166,7 +166,7 @@ def get_site_program_uuids(self, client, site, api_base_url): # lint-amnesty, p
logger.exception(f'Failed to retrieve program UUIDs for site: {site.domain}.')
failure = True
- logger.info('Received {total} UUIDs for site {domain}'.format(
+ logger.info('Received {total} UUIDs for site {domain}'.format( # noqa: UP032
total=len(uuids),
domain=site.domain
))
@@ -214,7 +214,7 @@ def get_pathways(self, client, site, api_base_url):
)
failure = True
- logger.info('Received {total} pathways for site {domain}'.format(
+ logger.info('Received {total} pathways for site {domain}'.format( # noqa: UP032
total=len(pathways),
domain=site.domain
))
diff --git a/openedx/core/djangoapps/catalog/management/commands/create_catalog_integrations.py b/openedx/core/djangoapps/catalog/management/commands/create_catalog_integrations.py
index fa95b0705f11..9e4db73d39a4 100644
--- a/openedx/core/djangoapps/catalog/management/commands/create_catalog_integrations.py
+++ b/openedx/core/djangoapps/catalog/management/commands/create_catalog_integrations.py
@@ -67,7 +67,7 @@ def handle(self, *args, **options):
page_size=page_size
)
except Exception as err:
- raise CommandError(f'Error creating CatalogIntegration: {err}') # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(f'Error creating CatalogIntegration: {err}') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
self.stdout.write(self.style.SUCCESS(
'Successfully created CatalogIntegration enabled={} url={} service_username={}').format(
diff --git a/openedx/core/djangoapps/catalog/management/commands/tests/test_cache_programs.py b/openedx/core/djangoapps/catalog/management/commands/tests/test_cache_programs.py
index 1c81b052da48..b981b3d4f4ac 100644
--- a/openedx/core/djangoapps/catalog/management/commands/tests/test_cache_programs.py
+++ b/openedx/core/djangoapps/catalog/management/commands/tests/test_cache_programs.py
@@ -350,7 +350,7 @@ def test_handle_missing_service_user(self):
Verify that the command raises an exception when run without a service
user, and that program UUIDs are not cached.
"""
- with pytest.raises(Exception):
+ with pytest.raises(Exception): # noqa: B017, PT011
call_command('cache_programs')
cached_uuids = cache.get(SITE_PROGRAM_UUIDS_CACHE_KEY_TPL.format(domain=self.site_domain))
diff --git a/openedx/core/djangoapps/catalog/tests/test_utils.py b/openedx/core/djangoapps/catalog/tests/test_utils.py
index 73bd663299de..eb961951352b 100644
--- a/openedx/core/djangoapps/catalog/tests/test_utils.py
+++ b/openedx/core/djangoapps/catalog/tests/test_utils.py
@@ -169,7 +169,7 @@ def fake_get_many(keys):
key = PROGRAM_CACHE_KEY_TPL.format(uuid=program["uuid"])
assert program == all_programs[key]
- def test_get_one(self, mock_warning, _mock_info):
+ def test_get_one(self, mock_warning, _mock_info): # noqa: PT019
expected_program = ProgramFactory()
expected_uuid = expected_program["uuid"]
@@ -183,7 +183,7 @@ def test_get_one(self, mock_warning, _mock_info):
assert actual_program == expected_program
assert not mock_warning.called
- def test_get_from_course(self, mock_warning, _mock_info):
+ def test_get_from_course(self, mock_warning, _mock_info): # noqa: PT019
expected_program = ProgramFactory()
expected_course = expected_program["courses"][0]["course_runs"][0]["key"]
@@ -196,7 +196,7 @@ def test_get_from_course(self, mock_warning, _mock_info):
assert actual_program == [expected_program]
assert not mock_warning.called
- def test_get_via_uuids(self, mock_warning, _mock_info):
+ def test_get_via_uuids(self, mock_warning, _mock_info): # noqa: PT019
first_program = ProgramFactory()
second_program = ProgramFactory()
@@ -209,7 +209,7 @@ def test_get_via_uuids(self, mock_warning, _mock_info):
assert second_program in results
assert not mock_warning.called
- def test_get_from_catalog_course(self, mock_warning, _mock_info):
+ def test_get_from_catalog_course(self, mock_warning, _mock_info): # noqa: PT019
expected_program = ProgramFactory()
expected_catalog_course = expected_program["courses"][0]
@@ -323,7 +323,7 @@ def fake_get_many(keys):
key = PATHWAY_CACHE_KEY_TPL.format(id=pathway["id"])
assert pathway == all_pathways[key]
- def test_get_one(self, mock_warning, _mock_info):
+ def test_get_one(self, mock_warning, _mock_info): # noqa: PT019
expected_pathway = PathwayFactory()
expected_id = expected_pathway["id"]
@@ -844,8 +844,8 @@ def init_cache(self):
def test_get_masters_programs(self):
expected_programs = [self.masters_program_1, self.masters_program_2]
- self.assertCountEqual(expected_programs, get_programs_by_type(self.site, "masters"))
- self.assertCountEqual(expected_programs, get_programs_by_type_slug(self.site, "masters"))
+ self.assertCountEqual(expected_programs, get_programs_by_type(self.site, "masters")) # noqa: PT009
+ self.assertCountEqual(expected_programs, get_programs_by_type_slug(self.site, "masters")) # noqa: PT009
def test_get_bachelors_programs(self):
expected_programs = [self.bachelors_program]
diff --git a/openedx/core/djangoapps/catalog/utils.py b/openedx/core/djangoapps/catalog/utils.py
index d94fa66a3138..99928500b521 100644
--- a/openedx/core/djangoapps/catalog/utils.py
+++ b/openedx/core/djangoapps/catalog/utils.py
@@ -4,7 +4,7 @@
import datetime
import logging
import uuid
-from typing import TYPE_CHECKING, Any, List, Union
+from typing import TYPE_CHECKING, Any, List, Union # noqa: UP035
from zoneinfo import ZoneInfo
import pycountry
@@ -84,7 +84,7 @@ def check_catalog_integration_and_get_user(error_message_field):
user = catalog_integration.get_service_user()
except ObjectDoesNotExist:
logger.error(
- "Catalog service user with username [{username}] does not exist. "
+ "Catalog service user with username [{username}] does not exist. " # noqa: UP032
"{field} will not be retrieved.".format(
username=catalog_integration.service_username,
field=error_message_field,
@@ -94,7 +94,7 @@ def check_catalog_integration_and_get_user(error_message_field):
return user, catalog_integration
else:
logger.info(
- "Unable to retrieve details about {field} because Catalog Integration is not enabled".format(
+ "Unable to retrieve details about {field} because Catalog Integration is not enabled".format( # noqa: UP032
field=error_message_field,
)
)
@@ -105,11 +105,11 @@ def check_catalog_integration_and_get_user(error_message_field):
def get_programs(
site: "Site" = None,
uuid: str = None,
- uuids: List[str] = None,
+ uuids: List[str] = None, # noqa: UP006
course: str = None,
catalog_course_uuid: str = None,
organization: str = None,
-) -> Union[str, List[str]]:
+) -> Union[str, List[str]]: # noqa: UP006, UP007
"""Read programs from the cache.
The cache is populated by a management command, cache_programs.
@@ -205,7 +205,7 @@ def get_programs_by_type_slug(site, program_type_slug):
return get_programs_by_uuids(uuids)
-def get_programs_by_uuids(uuids: List[Any]) -> List[str]:
+def get_programs_by_uuids(uuids: List[Any]) -> List[str]: # noqa: UP006
"""
Gets a list of programs for the provided uuids
"""
diff --git a/openedx/core/djangoapps/ccxcon/apps.py b/openedx/core/djangoapps/ccxcon/apps.py
index 40aa4a32676d..216890046a4e 100644
--- a/openedx/core/djangoapps/ccxcon/apps.py
+++ b/openedx/core/djangoapps/ccxcon/apps.py
@@ -11,4 +11,4 @@ class CCXConnectorConfig(AppConfig): # lint-amnesty, pylint: disable=missing-cl
verbose_name = "CCX Connector"
def ready(self):
- from . import signals # lint-amnesty, pylint: disable=unused-import
+ from . import signals # lint-amnesty, pylint: disable=unused-import # noqa: F401
diff --git a/openedx/core/djangoapps/ccxcon/tests/test_api.py b/openedx/core/djangoapps/ccxcon/tests/test_api.py
index a49e02d31c31..797778e8084e 100644
--- a/openedx/core/djangoapps/ccxcon/tests/test_api.py
+++ b/openedx/core/djangoapps/ccxcon/tests/test_api.py
@@ -69,7 +69,7 @@ def setUpClass(cls):
# Trying to wrap the whole thing in a bulk operation fails because it
# doesn't find the parents. But we can at least wrap this part...
with cls.store.bulk_operations(course.id, emit_signals=False):
- blocks = flatten([ # pylint: disable=unused-variable
+ blocks = flatten([ # pylint: disable=unused-variable # noqa: F841
[
BlockFactory.create(parent=vertical) for _ in range(2)
] for vertical in cls.verticals
diff --git a/openedx/core/djangoapps/commerce/utils.py b/openedx/core/djangoapps/commerce/utils.py
index 73905dd802ee..1b1a36cf9e67 100644
--- a/openedx/core/djangoapps/commerce/utils.py
+++ b/openedx/core/djangoapps/commerce/utils.py
@@ -66,7 +66,7 @@ def user_agent():
client_name = os.environ.get("EDX_REST_API_CLIENT_NAME") or socket.gethostbyname(socket.gethostname())
except: # pylint: disable=bare-except
pass # using 'unknown_client_name' is good enough. no need to log.
- return "{} edx-rest-api-client/{} {}".format(
+ return "{} edx-rest-api-client/{} {}".format( # noqa: UP032
requests.utils.default_user_agent(), # e.g. "python-requests/2.9.1"
__version__, # version of this client
client_name
@@ -173,7 +173,7 @@ def get_and_cache_oauth_access_token(url, client_id, client_secret, token_type='
"""
oauth_url = _get_oauth_url(url)
- cache_key = 'edx_rest_api_client.access_token.{}.{}.{}.{}'.format(
+ cache_key = 'edx_rest_api_client.access_token.{}.{}.{}.{}'.format( # noqa: UP032
token_type,
grant_type,
client_id,
diff --git a/openedx/core/djangoapps/common_initialization/apps.py b/openedx/core/djangoapps/common_initialization/apps.py
index e7711b3748fa..622a9b709687 100644
--- a/openedx/core/djangoapps/common_initialization/apps.py
+++ b/openedx/core/djangoapps/common_initialization/apps.py
@@ -12,7 +12,7 @@ class CommonInitializationConfig(AppConfig): # lint-amnesty, pylint: disable=mi
def ready(self):
# Common settings validations for the LMS and CMS.
- from . import checks # lint-amnesty, pylint: disable=unused-import
+ from . import checks # lint-amnesty, pylint: disable=unused-import # noqa: F401
self._add_mimetypes()
self._add_required_adapters()
diff --git a/openedx/core/djangoapps/common_views/xblock.py b/openedx/core/djangoapps/common_views/xblock.py
index ec87b07afb47..ef50b75f18dc 100644
--- a/openedx/core/djangoapps/common_views/xblock.py
+++ b/openedx/core/djangoapps/common_views/xblock.py
@@ -23,10 +23,10 @@ def xblock_resource(request, block_type, uri): # pylint: disable=unused-argumen
content = xblock_class.open_local_resource(uri)
except OSError:
log.info('Failed to load xblock resource', exc_info=True)
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except Exception:
log.error('Failed to load xblock resource', exc_info=True)
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
mimetype, _ = mimetypes.guess_type(uri)
return HttpResponse(content, content_type=mimetype)
diff --git a/openedx/core/djangoapps/config_model_utils/models.py b/openedx/core/djangoapps/config_model_utils/models.py
index 11d4d6383a10..17da0ec69056 100644
--- a/openedx/core/djangoapps/config_model_utils/models.py
+++ b/openedx/core/djangoapps/config_model_utils/models.py
@@ -72,7 +72,7 @@ class Meta:
"Configure values for all course runs associated with this site."
),
)
- org = models.CharField(
+ org = models.CharField( # noqa: DJ001
max_length=255,
db_index=True,
null=True,
@@ -82,7 +82,7 @@ class Meta:
"Organization. This is the organization string (i.e. edX, MITx)."
)
)
- org_course = models.CharField(
+ org_course = models.CharField( # noqa: DJ001
max_length=255,
db_index=True,
null=True,
diff --git a/openedx/core/djangoapps/content/block_structure/apps.py b/openedx/core/djangoapps/content/block_structure/apps.py
index bdb77d2bafca..2163160fa789 100644
--- a/openedx/core/djangoapps/content/block_structure/apps.py
+++ b/openedx/core/djangoapps/content/block_structure/apps.py
@@ -21,4 +21,4 @@ def ready(self):
These happen at import time. Hence the unused imports
"""
- from . import signals, tasks # lint-amnesty, pylint: disable=unused-import, unused-variable
+ from . import signals, tasks # lint-amnesty, pylint: disable=unused-import, unused-variable # noqa: F401
diff --git a/openedx/core/djangoapps/content/block_structure/block_structure.py b/openedx/core/djangoapps/content/block_structure/block_structure.py
index fa6fc75dabcd..c898df65de5e 100644
--- a/openedx/core/djangoapps/content/block_structure/block_structure.py
+++ b/openedx/core/djangoapps/content/block_structure/block_structure.py
@@ -302,7 +302,7 @@ def __getattr__(self, field_name):
try:
return self.fields[field_name]
except KeyError:
- raise AttributeError(f"Field {field_name} does not exist") # lint-amnesty, pylint: disable=raise-missing-from
+ raise AttributeError(f"Field {field_name} does not exist") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def __setattr__(self, field_name, field_value):
if self._is_own_field(field_name):
diff --git a/openedx/core/djangoapps/content/block_structure/config/__init__.py b/openedx/core/djangoapps/content/block_structure/config/__init__.py
index 79837df86be6..62e797e9e4c6 100644
--- a/openedx/core/djangoapps/content/block_structure/config/__init__.py
+++ b/openedx/core/djangoapps/content/block_structure/config/__init__.py
@@ -2,8 +2,8 @@
This module contains various configuration settings via
waffle switches for the Block Structure framework.
"""
-from edx_django_utils.cache import RequestCache
-from edx_toggles.toggles import WaffleSwitch
+from edx_django_utils.cache import RequestCache # noqa: F401
+from edx_toggles.toggles import WaffleSwitch # noqa: F401
from openedx.core.lib.cache_utils import request_cached
diff --git a/openedx/core/djangoapps/content/block_structure/config/models.py b/openedx/core/djangoapps/content/block_structure/config/models.py
index 0f540fa0de5d..19979850a616 100644
--- a/openedx/core/djangoapps/content/block_structure/config/models.py
+++ b/openedx/core/djangoapps/content/block_structure/config/models.py
@@ -24,7 +24,7 @@ class Meta:
cache_timeout_in_seconds = IntegerField(blank=True, null=True, default=DEFAULT_CACHE_TIMEOUT_IN_SECONDS)
def __str__(self):
- return "BlockStructureConfiguration: num_versions_to_keep: {}, cache_timeout_in_seconds: {}".format(
+ return "BlockStructureConfiguration: num_versions_to_keep: {}, cache_timeout_in_seconds: {}".format( # noqa: UP032 # pylint: disable=line-too-long
self.num_versions_to_keep,
self.cache_timeout_in_seconds,
)
diff --git a/openedx/core/djangoapps/content/block_structure/models.py b/openedx/core/djangoapps/content/block_structure/models.py
index e7d16b2e977f..1309c81ab3e0 100644
--- a/openedx/core/djangoapps/content/block_structure/models.py
+++ b/openedx/core/djangoapps/content/block_structure/models.py
@@ -46,7 +46,7 @@ def _directory_name(data_usage_key):
# replace any '/' in the usage key so they aren't interpreted
# as folder separators.
encoded_usage_key = str(data_usage_key).replace('/', '_')
- return '{}{}'.format(
+ return '{}{}'.format( # noqa: UP032
directory_prefix,
encoded_usage_key,
)
@@ -144,7 +144,7 @@ def _storage_error_handling(bs_model, operation, is_read_operation=False):
# May have been caused by one of the possible error
# situations listed above. Raise BlockStructureNotFound
# so the block structure can be regenerated and restored.
- raise BlockStructureNotFound(bs_model.data_usage_key) # lint-amnesty, pylint: disable=raise-missing-from
+ raise BlockStructureNotFound(bs_model.data_usage_key) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
else:
raise
@@ -172,7 +172,7 @@ class Meta:
max_length=255,
unique=True,
)
- data_version = models.CharField(
+ data_version = models.CharField( # noqa: DJ001
'Version of the data at the time of collection.',
blank=True,
null=True,
@@ -217,7 +217,7 @@ def get(cls, data_usage_key):
return cls.objects.get(data_usage_key=data_usage_key)
except cls.DoesNotExist:
log.info('BlockStructure: Not found in table; %s.', data_usage_key)
- raise BlockStructureNotFound(data_usage_key) # lint-amnesty, pylint: disable=raise-missing-from
+ raise BlockStructureNotFound(data_usage_key) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
@classmethod
def update_or_create(cls, serialized_data, data_usage_key, **kwargs):
diff --git a/openedx/core/djangoapps/content/block_structure/store.py b/openedx/core/djangoapps/content/block_structure/store.py
index b1db4e1ba120..0eeb3be65973 100644
--- a/openedx/core/djangoapps/content/block_structure/store.py
+++ b/openedx/core/djangoapps/content/block_structure/store.py
@@ -193,7 +193,7 @@ def _deserialize(self, serialized_data, root_block_usage_key):
# Somehow failed to de-serialized the data, assume it's corrupt.
bs_model = self._get_model(root_block_usage_key)
logger.exception("BlockStructure: Failed to load data from cache for %s", bs_model)
- raise BlockStructureNotFound(bs_model.data_usage_key) # lint-amnesty, pylint: disable=raise-missing-from
+ raise BlockStructureNotFound(bs_model.data_usage_key) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return BlockStructureFactory.create_new(
root_block_usage_key,
diff --git a/openedx/core/djangoapps/content/block_structure/tasks.py b/openedx/core/djangoapps/content/block_structure/tasks.py
index df2df80632df..77eafb1ec759 100644
--- a/openedx/core/djangoapps/content/block_structure/tasks.py
+++ b/openedx/core/djangoapps/content/block_structure/tasks.py
@@ -107,7 +107,7 @@ def _call_and_retry_if_needed(self, api_method, **kwargs):
raise
except RETRY_TASKS as exc:
log.exception("%s encountered expected error, retrying.", self.__name__)
- raise self.retry(kwargs=kwargs, exc=exc)
+ raise self.retry(kwargs=kwargs, exc=exc) # noqa: B904
except Exception as exc:
log.exception(
"BlockStructure: %s encountered unknown error in course %s, task_id %s. Retry #%d",
@@ -116,4 +116,4 @@ def _call_and_retry_if_needed(self, api_method, **kwargs):
self.request.id,
self.request.retries,
)
- raise self.retry(kwargs=kwargs, exc=exc)
+ raise self.retry(kwargs=kwargs, exc=exc) # noqa: B904
diff --git a/openedx/core/djangoapps/content/block_structure/tests/helpers.py b/openedx/core/djangoapps/content/block_structure/tests/helpers.py
index a2bf6216fb13..ac4eecf5066e 100644
--- a/openedx/core/djangoapps/content/block_structure/tests/helpers.py
+++ b/openedx/core/djangoapps/content/block_structure/tests/helpers.py
@@ -62,7 +62,7 @@ def __getattr__(self, attr):
try:
return self.field_map[attr]
except KeyError:
- raise AttributeError # lint-amnesty, pylint: disable=raise-missing-from
+ raise AttributeError # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def get_children(self):
"""
@@ -316,7 +316,7 @@ def assert_block_structure(self, block_structure, children_map, missing_blocks=N
# Verify presence
assert (self.block_key_factory(block_key) in block_structure) == (block_key not in missing_blocks),\
'Expected presence in block_structure for block_key {} to match absence in missing_blocks.'\
- .format(str(block_key))
+ .format(str(block_key)) # noqa: UP032
# Verify children
if block_key not in missing_blocks:
diff --git a/openedx/core/djangoapps/content/block_structure/tests/test_block_structure.py b/openedx/core/djangoapps/content/block_structure/tests/test_block_structure.py
index fda52320b76c..02acf78c3a05 100644
--- a/openedx/core/djangoapps/content/block_structure/tests/test_block_structure.py
+++ b/openedx/core/djangoapps/content/block_structure/tests/test_block_structure.py
@@ -37,11 +37,11 @@ def test_relations(self, children_map):
# get_children
for parent, children in enumerate(children_map):
- self.assertSetEqual(set(block_structure.get_children(parent)), set(children))
+ self.assertSetEqual(set(block_structure.get_children(parent)), set(children)) # noqa: PT009
# get_parents
for child, parents in enumerate(self.get_parents_map(children_map)):
- self.assertSetEqual(set(block_structure.get_parents(child)), set(parents))
+ self.assertSetEqual(set(block_structure.get_parents(child)), set(parents)) # noqa: PT009
# __contains__
for node in range(len(children_map)):
@@ -65,7 +65,7 @@ class TestNonVersionedTransformer(MockTransformer):
block_structure = BlockStructureModulestoreData(root_block_usage_key=0)
- with self.assertRaisesRegex(TransformerException, "Version attributes are not set"):
+ with self.assertRaisesRegex(TransformerException, "Version attributes are not set"): # noqa: PT027
block_structure._add_transformer(TestNonVersionedTransformer())
def test_transformer_data(self):
diff --git a/openedx/core/djangoapps/content/block_structure/tests/test_factory.py b/openedx/core/djangoapps/content/block_structure/tests/test_factory.py
index 3fb6db28e7b9..e762d559af89 100644
--- a/openedx/core/djangoapps/content/block_structure/tests/test_factory.py
+++ b/openedx/core/djangoapps/content/block_structure/tests/test_factory.py
@@ -141,7 +141,7 @@ def test_from_modulestore_normalizes_locations_with_branch_info(self):
for block_key in block_structure:
# The block_key should equal its normalized version
normalized_key = block_key.for_branch(None)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
block_key,
normalized_key,
f"Block key {block_key} should be normalized (without branch info). "
@@ -149,7 +149,7 @@ def test_from_modulestore_normalizes_locations_with_branch_info(self):
)
# Verify it doesn't have branch information in the course_key
if hasattr(block_key.course_key, 'branch'):
- self.assertIsNone(
+ self.assertIsNone( # noqa: PT009
block_key.course_key.branch,
f"Block key {block_key} should not have branch information"
)
diff --git a/openedx/core/djangoapps/content/block_structure/tests/test_manager.py b/openedx/core/djangoapps/content/block_structure/tests/test_manager.py
index 2e50214456f2..04a08accf6b3 100644
--- a/openedx/core/djangoapps/content/block_structure/tests/test_manager.py
+++ b/openedx/core/djangoapps/content/block_structure/tests/test_manager.py
@@ -243,10 +243,10 @@ def mock_branch_setting(branch, course_key):
self.bs_manager.get_collected()
# Verify branch_setting was called with the correct parameters
- self.assertEqual(len(branch_setting_calls), 1)
+ self.assertEqual(len(branch_setting_calls), 1) # noqa: PT009
branch, course_key = branch_setting_calls[0]
- self.assertEqual(branch, ModuleStoreEnum.Branch.published_only)
- self.assertEqual(course_key, self.block_key_factory(0).course_key)
+ self.assertEqual(branch, ModuleStoreEnum.Branch.published_only) # noqa: PT009
+ self.assertEqual(course_key, self.block_key_factory(0).course_key) # noqa: PT009
finally:
# Restore original method if it existed
diff --git a/openedx/core/djangoapps/content/block_structure/tests/test_models.py b/openedx/core/djangoapps/content/block_structure/tests/test_models.py
index bea7d561d27a..43d909e42eb1 100644
--- a/openedx/core/djangoapps/content/block_structure/tests/test_models.py
+++ b/openedx/core/djangoapps/content/block_structure/tests/test_models.py
@@ -83,7 +83,7 @@ def test_update_or_create(self, mock_log):
serialized_data = 'initial data'
# shouldn't already exist
- with pytest.raises(BlockStructureNotFound):
+ with pytest.raises(BlockStructureNotFound): # noqa: PT012
BlockStructureModel.get(self.usage_key)
assert 'BlockStructure: Not found in table;' in mock_log.info.call_args[0][0]
@@ -154,7 +154,7 @@ def test_prune_keep_count(self, prune_keep_count, num_prior_edits):
def test_error_handling(self, error_raised_in_operation, errno_raised, message_raised,
expected_error_raised, is_read_operation):
bs_model, _ = BlockStructureModel.update_or_create('test data', **self.params)
- with pytest.raises(expected_error_raised):
+ with pytest.raises(expected_error_raised): # noqa: PT012
with _storage_error_handling(bs_model, 'operation', is_read_operation):
if errno_raised is not None: # lint-amnesty, pylint: disable=no-else-raise
raise error_raised_in_operation(errno_raised, message_raised)
diff --git a/openedx/core/djangoapps/content/block_structure/tests/test_transformer_registry.py b/openedx/core/djangoapps/content/block_structure/tests/test_transformer_registry.py
index 5e71e1da4406..c0dd72c1b62e 100644
--- a/openedx/core/djangoapps/content/block_structure/tests/test_transformer_registry.py
+++ b/openedx/core/djangoapps/content/block_structure/tests/test_transformer_registry.py
@@ -62,7 +62,7 @@ def tearDown(self):
def test_find_unregistered(self, transformers, expected_unregistered):
with mock_registered_transformers([TestTransformer1, TestTransformer2]):
- self.assertSetEqual(
+ self.assertSetEqual( # noqa: PT009
TransformerRegistry.find_unregistered(transformers),
set(expected_unregistered),
)
diff --git a/openedx/core/djangoapps/content/course_overviews/apps.py b/openedx/core/djangoapps/content/course_overviews/apps.py
index d7976cf219ba..be99458bc064 100644
--- a/openedx/core/djangoapps/content/course_overviews/apps.py
+++ b/openedx/core/djangoapps/content/course_overviews/apps.py
@@ -16,4 +16,4 @@ class CourseOverviewsConfig(AppConfig):
def ready(self):
# Import signals to activate signal handler which invalidates
# the CourseOverview cache every time a course is published.
- from . import signals # lint-amnesty, pylint: disable=unused-import, unused-variable
+ from . import signals # lint-amnesty, pylint: disable=unused-import, unused-variable # noqa: F401
diff --git a/openedx/core/djangoapps/content/course_overviews/management/commands/backfill_history.py b/openedx/core/djangoapps/content/course_overviews/management/commands/backfill_history.py
index 053932811ac6..fe94e38b968f 100644
--- a/openedx/core/djangoapps/content/course_overviews/management/commands/backfill_history.py
+++ b/openedx/core/djangoapps/content/course_overviews/management/commands/backfill_history.py
@@ -90,7 +90,7 @@ def handle(self, *args, **options):
FROM information_schema.columns
WHERE table_name='{}'
ORDER BY ordinal_position
- """.format(table)
+ """.format(table) # noqa: UP032
cursor.execute(query)
columns = [column[0] for column in cursor.fetchall()]
if exclude_column in columns:
@@ -114,7 +114,7 @@ def handle(self, *args, **options):
FROM {historical_table}
WHERE ID in ({ids})
AND history_type='+'
- """.format(
+ """.format( # noqa: UP032
historical_table=historical_table,
ids=ids
) # noqa
diff --git a/openedx/core/djangoapps/content/course_overviews/management/commands/generate_course_overview.py b/openedx/core/djangoapps/content/course_overviews/management/commands/generate_course_overview.py
index a3c2b1ea4694..ed7fd7935c93 100644
--- a/openedx/core/djangoapps/content/course_overviews/management/commands/generate_course_overview.py
+++ b/openedx/core/djangoapps/content/course_overviews/management/commands/generate_course_overview.py
@@ -72,4 +72,4 @@ def handle(self, *args, **options):
**kwargs
)
except InvalidKeyError as exc:
- raise CommandError('Invalid Course Key: ' + str(exc)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError('Invalid Course Key: ' + str(exc)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
diff --git a/openedx/core/djangoapps/content/course_overviews/management/commands/tests/test_simulate_publish.py b/openedx/core/djangoapps/content/course_overviews/management/commands/tests/test_simulate_publish.py
index f41573fcae97..3107e49c7a68 100644
--- a/openedx/core/djangoapps/content/course_overviews/management/commands/tests/test_simulate_publish.py
+++ b/openedx/core/djangoapps/content/course_overviews/management/commands/tests/test_simulate_publish.py
@@ -152,7 +152,7 @@ def sample_receiver_2(self, sender, course_key, **kwargs): # pylint: disable=un
def test_args_from_database(self):
"""Test management command arguments injected from config model."""
# Nothing in the database, should default to disabled
- with self.assertRaisesRegex(CommandError, 'SimulateCourseConfigPublish is disabled.*'):
+ with self.assertRaisesRegex(CommandError, 'SimulateCourseConfigPublish is disabled.*'): # noqa: PT027
call_command('simulate_publish', '--args-from-database')
# Add a config
diff --git a/openedx/core/djangoapps/content/course_overviews/models.py b/openedx/core/djangoapps/content/course_overviews/models.py
index 190fc1a3ee0b..25d146bb3fc8 100644
--- a/openedx/core/djangoapps/content/course_overviews/models.py
+++ b/openedx/core/djangoapps/content/course_overviews/models.py
@@ -72,7 +72,7 @@ class Meta:
id = CourseKeyField(db_index=True, primary_key=True, max_length=255)
_location = UsageKeyField(max_length=255)
org = models.TextField(max_length=255, default='outdated_entry')
- display_name = models.TextField(null=True)
+ display_name = models.TextField(null=True) # noqa: DJ001
display_number_with_default = models.TextField()
display_org_with_default = models.TextField()
@@ -85,18 +85,18 @@ class Meta:
start_date = models.DateTimeField(null=True)
end_date = models.DateTimeField(null=True)
- advertised_start = models.TextField(null=True)
+ advertised_start = models.TextField(null=True) # noqa: DJ001
announcement = models.DateTimeField(null=True)
# URLs
# Not allowing null per django convention; not sure why many TextFields in this model do allow null
banner_image_url = models.TextField()
course_image_url = models.TextField()
- social_sharing_url = models.TextField(null=True)
- end_of_course_survey_url = models.TextField(null=True)
+ social_sharing_url = models.TextField(null=True) # noqa: DJ001
+ end_of_course_survey_url = models.TextField(null=True) # noqa: DJ001
# Certification data
- certificates_display_behavior = models.TextField(null=True)
+ certificates_display_behavior = models.TextField(null=True) # noqa: DJ001
certificates_show_before_end = models.BooleanField(default=False)
cert_html_view_enabled = models.BooleanField(default=False)
has_any_active_web_certificate = models.BooleanField(default=False)
@@ -116,17 +116,17 @@ class Meta:
# Enrollment details
enrollment_start = models.DateTimeField(null=True)
enrollment_end = models.DateTimeField(null=True)
- enrollment_domain = models.TextField(null=True)
+ enrollment_domain = models.TextField(null=True) # noqa: DJ001
invitation_only = models.BooleanField(default=False)
max_student_enrollments_allowed = models.IntegerField(null=True)
# Catalog information
- catalog_visibility = models.TextField(null=True)
- short_description = models.TextField(null=True)
- course_video_url = models.TextField(null=True)
- effort = models.TextField(null=True)
+ catalog_visibility = models.TextField(null=True) # noqa: DJ001
+ short_description = models.TextField(null=True) # noqa: DJ001
+ course_video_url = models.TextField(null=True) # noqa: DJ001
+ effort = models.TextField(null=True) # noqa: DJ001
self_paced = models.BooleanField(default=False)
- marketing_url = models.TextField(null=True)
+ marketing_url = models.TextField(null=True) # noqa: DJ001
eligible_for_financial_aid = models.BooleanField(default=True)
# Course highlight info, used to guide course update emails
@@ -134,8 +134,8 @@ class Meta:
# Proctoring
enable_proctored_exams = models.BooleanField(default=False)
- proctoring_provider = models.TextField(null=True)
- proctoring_escalation_email = models.TextField(null=True)
+ proctoring_provider = models.TextField(null=True) # noqa: DJ001
+ proctoring_escalation_email = models.TextField(null=True) # noqa: DJ001
allow_proctoring_opt_out = models.BooleanField(default=False)
# Entrance Exam information
@@ -146,9 +146,9 @@ class Meta:
# Open Response Assessment configuration
force_on_flexible_peer_openassessments = models.BooleanField(default=False)
- external_id = models.CharField(max_length=128, null=True, blank=True)
+ external_id = models.CharField(max_length=128, null=True, blank=True) # noqa: DJ001
- language = models.TextField(null=True)
+ language = models.TextField(null=True) # noqa: DJ001
history = HistoricalRecords()
@@ -1004,11 +1004,11 @@ class CourseOverviewTab(models.Model):
"""
tab_id = models.CharField(max_length=50)
course_overview = models.ForeignKey(CourseOverview, db_index=True, related_name="tab_set", on_delete=models.CASCADE)
- type = models.CharField(max_length=50, null=True)
- name = models.TextField(null=True)
+ type = models.CharField(max_length=50, null=True) # noqa: DJ001
+ name = models.TextField(null=True) # noqa: DJ001
course_staff_only = models.BooleanField(default=False)
- url_slug = models.TextField(null=True)
- link = models.TextField(null=True)
+ url_slug = models.TextField(null=True) # noqa: DJ001
+ link = models.TextField(null=True) # noqa: DJ001
is_hidden = models.BooleanField(default=False)
def __str__(self):
@@ -1152,7 +1152,7 @@ def create(cls, course_overview, course=None):
pass
def __str__(self):
- return "CourseOverviewImageSet({}, small_url={}, large_url={})".format(
+ return "CourseOverviewImageSet({}, small_url={}, large_url={})".format( # noqa: UP032
self.course_overview_id, self.small_url, self.large_url
)
@@ -1187,7 +1187,7 @@ def large(self):
return (self.large_width, self.large_height)
def __str__(self):
- return "CourseOverviewImageConfig(enabled={}, small={}, large={})".format(
+ return "CourseOverviewImageConfig(enabled={}, small={}, large={})".format( # noqa: UP032
self.enabled, self.small, self.large
)
diff --git a/openedx/core/djangoapps/content/course_overviews/tests/test_api.py b/openedx/core/djangoapps/content/course_overviews/tests/test_api.py
index 2a518fa1d7de..c3e07fc87691 100644
--- a/openedx/core/djangoapps/content/course_overviews/tests/test_api.py
+++ b/openedx/core/djangoapps/content/course_overviews/tests/test_api.py
@@ -70,7 +70,7 @@ def test_get_course_overview_or_404_missing(self):
Test for `test_get_course_overview_or_404` function when the overview does not exist.
"""
course_run_key = CourseKey.from_string('course-v1:coping+with+deletions')
- with self.assertRaises(Http404):
+ with self.assertRaises(Http404): # noqa: PT027
get_course_overview_or_404(course_run_key)
def test_get_course_overview_from_ids(self):
diff --git a/openedx/core/djangoapps/content/course_overviews/tests/test_course_overviews.py b/openedx/core/djangoapps/content/course_overviews/tests/test_course_overviews.py
index 86c97c553cfd..84ce5a6fd3ca 100644
--- a/openedx/core/djangoapps/content/course_overviews/tests/test_course_overviews.py
+++ b/openedx/core/djangoapps/content/course_overviews/tests/test_course_overviews.py
@@ -362,7 +362,7 @@ def test_get_errored_course(self):
# This mock makes it so when the module store tries to load course data,
# an exception is thrown, which causes get_course to return an ErrorBlock,
# which causes get_from_id to raise an IOError.
- with pytest.raises(IOError):
+ with pytest.raises(IOError): # noqa: PT011
CourseOverview.load_from_module_store(self.store.make_course_key('Non', 'Existent', 'Course'))
def test_malformed_grading_policy(self):
@@ -375,7 +375,7 @@ def test_malformed_grading_policy(self):
"""
course = CourseFactory.create()
course._grading_policy['GRADE_CUTOFFS'] = {} # pylint: disable=protected-access
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
__ = course.lowest_passing_grade
course_overview = CourseOverview._create_or_update(course) # pylint: disable=protected-access
assert course_overview.lowest_passing_grade is None
diff --git a/openedx/core/djangoapps/content/course_overviews/tests/test_signals.py b/openedx/core/djangoapps/content/course_overviews/tests/test_signals.py
index a452009d32f0..ba9eb3ecc3aa 100644
--- a/openedx/core/djangoapps/content/course_overviews/tests/test_signals.py
+++ b/openedx/core/djangoapps/content/course_overviews/tests/test_signals.py
@@ -89,7 +89,7 @@ def test_cache_invalidation(self):
assert not course_overview_2.mobile_available
# Verify that when the course is deleted, the corresponding CourseOverview is deleted as well.
- with pytest.raises(CourseOverview.DoesNotExist):
+ with pytest.raises(CourseOverview.DoesNotExist): # noqa: PT012
self.store.delete_course(course.id, ModuleStoreEnum.UserID.test)
CourseOverview.get_from_id(course.id)
diff --git a/openedx/core/djangoapps/content/learning_sequences/api/__init__.py b/openedx/core/djangoapps/content/learning_sequences/api/__init__.py
index 2ab8283a6e1f..e50ae2c3aca5 100644
--- a/openedx/core/djangoapps/content/learning_sequences/api/__init__.py
+++ b/openedx/core/djangoapps/content/learning_sequences/api/__init__.py
@@ -1,10 +1,10 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from .outlines import (
- get_content_errors,
- get_course_keys_with_outlines,
- get_course_outline,
- get_user_course_outline,
- get_user_course_outline_details,
- key_supports_outlines,
- replace_course_outline,
+ get_content_errors, # noqa: F401
+ get_course_keys_with_outlines, # noqa: F401
+ get_course_outline, # noqa: F401
+ get_user_course_outline, # noqa: F401
+ get_user_course_outline_details, # noqa: F401
+ key_supports_outlines, # noqa: F401
+ replace_course_outline, # noqa: F401
)
diff --git a/openedx/core/djangoapps/content/learning_sequences/api/outlines.py b/openedx/core/djangoapps/content/learning_sequences/api/outlines.py
index 429927c61ab1..297726e42bf0 100644
--- a/openedx/core/djangoapps/content/learning_sequences/api/outlines.py
+++ b/openedx/core/djangoapps/content/learning_sequences/api/outlines.py
@@ -6,7 +6,7 @@
import logging
from collections import defaultdict
from datetime import datetime
-from typing import Dict, FrozenSet, List, Optional, Union
+from typing import Dict, FrozenSet, List, Optional, Union # noqa: UP035
from django.db import transaction
from django.db.models.query import QuerySet
@@ -117,7 +117,7 @@ def get_course_outline(course_key: CourseKey) -> CourseOutlineData:
course_context = _get_course_context_for_outline(course_key)
# Check to see if it's in the cache.
- cache_key = "learning_sequences.api.get_course_outline.v2.{}.{}".format(
+ cache_key = "learning_sequences.api.get_course_outline.v2.{}.{}".format( # noqa: UP032
course_context.learning_context.context_key, course_context.learning_context.published_version
)
outline_cache_result = TieredCache.get_cached_response(cache_key)
@@ -199,7 +199,7 @@ def get_course_outline(course_key: CourseKey) -> CourseOutlineData:
return outline_data
-def _get_user_partition_groups_from_qset(upg_qset) -> Dict[int, FrozenSet[int]]:
+def _get_user_partition_groups_from_qset(upg_qset) -> Dict[int, FrozenSet[int]]: # noqa: UP006
"""
Given a QuerySet of UserPartitionGroup, return a mapping of UserPartition
IDs to the set of Group IDs for each UserPartition.
@@ -220,7 +220,7 @@ def _get_course_context_for_outline(course_key: CourseKey) -> CourseContext:
"""
if course_key.deprecated:
raise ValueError(
- "Learning Sequence API does not support Old Mongo courses: {}"
+ "Learning Sequence API does not support Old Mongo courses: {}" # noqa: UP032
.format(course_key),
)
try:
@@ -232,13 +232,13 @@ def _get_course_context_for_outline(course_key: CourseKey) -> CourseContext:
)
except LearningContext.DoesNotExist:
# Could happen if it hasn't been published.
- raise CourseOutlineData.DoesNotExist( # lint-amnesty, pylint: disable=raise-missing-from
+ raise CourseOutlineData.DoesNotExist( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
f"No CourseOutlineData for {course_key}"
)
return course_context
-def get_content_errors(course_key: CourseKey) -> List[ContentErrorData]:
+def get_content_errors(course_key: CourseKey) -> List[ContentErrorData]: # noqa: UP006
"""
Get ContentErrors created in the most recent publish of this Course run.
"""
@@ -386,7 +386,7 @@ def _get_user_course_outline_and_processors(course_key: CourseKey, # lint-amnes
@function_trace('learning_sequences.api.replace_course_outline')
def replace_course_outline(course_outline: CourseOutlineData,
- content_errors: Optional[List[ContentErrorData]] = None):
+ content_errors: Optional[List[ContentErrorData]] = None): # noqa: UP006, UP045
"""
Replace the model data stored for the Course Outline with the contents of
course_outline (a CourseOutlineData). Record any content errors.
@@ -538,8 +538,8 @@ def _update_course_section_sequences(course_outline: CourseOutlineData, course_c
_update_user_partition_groups(sequence_data.user_partition_groups, course_section_sequence)
-def _update_user_partition_groups(upg_data: Dict[int, FrozenSet[int]],
- model_obj: Union[CourseSection, CourseSectionSequence]):
+def _update_user_partition_groups(upg_data: Dict[int, FrozenSet[int]], # noqa: UP006
+ model_obj: Union[CourseSection, CourseSectionSequence]): # noqa: UP007
"""
Replace UserPartitionGroups associated with this content with `upg_data`.
"""
@@ -554,7 +554,7 @@ def _update_user_partition_groups(upg_data: Dict[int, FrozenSet[int]],
def _update_publish_report(course_outline: CourseOutlineData,
- content_errors: List[ContentErrorData],
+ content_errors: List[ContentErrorData], # noqa: UP006
course_context: CourseContext):
"""
Record ContentErrors for this course publish. Deletes previous errors.
diff --git a/openedx/core/djangoapps/content/learning_sequences/api/processors/cohort_partition_groups.py b/openedx/core/djangoapps/content/learning_sequences/api/processors/cohort_partition_groups.py
index fa921902c833..1e19debf01d6 100644
--- a/openedx/core/djangoapps/content/learning_sequences/api/processors/cohort_partition_groups.py
+++ b/openedx/core/djangoapps/content/learning_sequences/api/processors/cohort_partition_groups.py
@@ -24,8 +24,8 @@ class CohortPartitionGroupsOutlineProcessor(OutlineProcessor):
"""
def __init__(self, course_key: CourseKey, user: types.User, at_time: datetime):
super().__init__(course_key, user, at_time)
- self.user_cohort_group_id: Union[int, None] = None
- self.cohorted_partition_id: Union[int, None] = None
+ self.user_cohort_group_id: Union[int, None] = None # noqa: UP007
+ self.cohorted_partition_id: Union[int, None] = None # noqa: UP007
def load_data(self, full_course_outline) -> None:
"""
diff --git a/openedx/core/djangoapps/content/learning_sequences/api/processors/enrollment_track_partition_groups.py b/openedx/core/djangoapps/content/learning_sequences/api/processors/enrollment_track_partition_groups.py
index 88290c5a71bd..c77107b03e1a 100644
--- a/openedx/core/djangoapps/content/learning_sequences/api/processors/enrollment_track_partition_groups.py
+++ b/openedx/core/djangoapps/content/learning_sequences/api/processors/enrollment_track_partition_groups.py
@@ -1,7 +1,7 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import logging
from datetime import datetime
-from typing import Dict
+from typing import Dict # noqa: UP035
from opaque_keys.edx.keys import CourseKey
@@ -32,7 +32,7 @@ class EnrollmentTrackPartitionGroupsOutlineProcessor(OutlineProcessor):
"""
def __init__(self, course_key: CourseKey, user: types.User, at_time: datetime):
super().__init__(course_key, user, at_time)
- self.enrollment_track_groups: Dict[str, Group] = {}
+ self.enrollment_track_groups: Dict[str, Group] = {} # noqa: UP006
self.user_group = None
def load_data(self, full_course_outline) -> None:
diff --git a/openedx/core/djangoapps/content/learning_sequences/api/processors/schedule.py b/openedx/core/djangoapps/content/learning_sequences/api/processors/schedule.py
index c75eef7028d3..2c03a218fc37 100644
--- a/openedx/core/djangoapps/content/learning_sequences/api/processors/schedule.py
+++ b/openedx/core/djangoapps/content/learning_sequences/api/processors/schedule.py
@@ -127,7 +127,7 @@ def _effective_start(*dates):
specified_dates = [date for date in dates if date is not None]
return max(specified_dates) if specified_dates else None
- pruned_section_keys = {section.usage_key for section in pruned_course_outline.sections} # lint-amnesty, pylint: disable=unused-variable
+ pruned_section_keys = {section.usage_key for section in pruned_course_outline.sections} # lint-amnesty, pylint: disable=unused-variable # noqa: F841
course_usage_key = self.course_key.make_usage_key('course', 'course')
course_start = self.keys_to_schedule_fields[course_usage_key].get('start')
course_end = self.keys_to_schedule_fields[course_usage_key].get('end')
diff --git a/openedx/core/djangoapps/content/learning_sequences/api/processors/team_partition_groups.py b/openedx/core/djangoapps/content/learning_sequences/api/processors/team_partition_groups.py
index 1dbc5d0bce8b..a0f4a7afbcd4 100644
--- a/openedx/core/djangoapps/content/learning_sequences/api/processors/team_partition_groups.py
+++ b/openedx/core/djangoapps/content/learning_sequences/api/processors/team_partition_groups.py
@@ -3,7 +3,7 @@
"""
import logging
from datetime import datetime
-from typing import Dict
+from typing import Dict # noqa: UP035
from opaque_keys.edx.keys import CourseKey
@@ -31,7 +31,7 @@ def __init__(self, course_key: CourseKey, user: types.User, at_time: datetime):
belongs in each partition.
"""
super().__init__(course_key, user, at_time)
- self.current_user_groups: Dict[str, Group] = {}
+ self.current_user_groups: Dict[str, Group] = {} # noqa: UP006
def load_data(self, _) -> None:
"""
diff --git a/openedx/core/djangoapps/content/learning_sequences/api/tests/test_data.py b/openedx/core/djangoapps/content/learning_sequences/api/tests/test_data.py
index e8910fd87d35..48e3a5e65f0d 100644
--- a/openedx/core/djangoapps/content/learning_sequences/api/tests/test_data.py
+++ b/openedx/core/djangoapps/content/learning_sequences/api/tests/test_data.py
@@ -21,7 +21,7 @@ def setUpClass(cls):
test as needed.
"""
super().setUpClass()
- normal_visibility = VisibilityData( # lint-amnesty, pylint: disable=unused-variable
+ normal_visibility = VisibilityData( # lint-amnesty, pylint: disable=unused-variable # noqa: F841
hide_from_toc=False,
visible_to_staff_only=False
)
@@ -29,7 +29,7 @@ def setUpClass(cls):
cls.course_outline = CourseOutlineData(
course_key=cls.course_key,
title="Exciting Test Course!",
- published_at=datetime(2020, 5, 19, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 19, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2014",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -41,7 +41,7 @@ def setUpClass(cls):
def test_deprecated_course_key(self):
"""Old-Mongo style, "Org/Course/Run" keys are not supported."""
old_course_key = CourseKey.from_string("OpenEdX/TestCourse/TestRun")
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
attr.evolve(self.course_outline, course_key=old_course_key)
def test_sequence_building(self):
@@ -58,7 +58,7 @@ def test_duplicate_sequence(self):
section_with_dupe_seq = attr.evolve(
self.course_outline.sections[1], title="Chapter 2 dupe",
)
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
attr.evolve(
self.course_outline,
sections=self.course_outline.sections + [section_with_dupe_seq]
@@ -66,7 +66,7 @@ def test_duplicate_sequence(self):
def test_size(self):
"""Limit how large a CourseOutline is allowed to be."""
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
attr.evolve(
self.course_outline,
sections=generate_sections(self.course_key, [1001])
@@ -116,7 +116,7 @@ def test_days_early_for_beta(self):
assert new_outline != self.course_outline
assert new_outline.days_early_for_beta == 5
- with pytest.raises(ValueError) as error:
+ with pytest.raises(ValueError) as error: # noqa: PT011
attr.evolve(self.course_outline, days_early_for_beta=-1)
assert error.match(
"Provided value -1 for days_early_for_beta is invalid. The value must be positive or zero. "
@@ -139,7 +139,7 @@ def test_empty_user_partition_groups(self):
51: frozenset([1]),
}
)
- with self.assertRaises(ValueError):
+ with self.assertRaises(ValueError): # noqa: PT027
attr.evolve(
valid_section,
user_partition_groups={
diff --git a/openedx/core/djangoapps/content/learning_sequences/api/tests/test_outlines.py b/openedx/core/djangoapps/content/learning_sequences/api/tests/test_outlines.py
index ade5b32c4de3..da0a2ea4c2cf 100644
--- a/openedx/core/djangoapps/content/learning_sequences/api/tests/test_outlines.py
+++ b/openedx/core/djangoapps/content/learning_sequences/api/tests/test_outlines.py
@@ -77,14 +77,14 @@ class CourseOutlineTestCase(CacheIsolationTestCase):
@classmethod
def setUpTestData(cls): # lint-amnesty, pylint: disable=super-method-not-called
cls.course_key = CourseKey.from_string("course-v1:OpenEdX+Learn+Roundtrip")
- normal_visibility = VisibilityData( # lint-amnesty, pylint: disable=unused-variable
+ normal_visibility = VisibilityData( # lint-amnesty, pylint: disable=unused-variable # noqa: F841
hide_from_toc=False,
visible_to_staff_only=False
)
cls.course_outline = CourseOutlineData(
course_key=cls.course_key,
title="Roundtrip Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2015",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -96,13 +96,13 @@ def setUpTestData(cls): # lint-amnesty, pylint: disable=super-method-not-called
def test_deprecated_course_key(self):
"""Don't allow Old Mongo Courses at all."""
old_course_key = CourseKey.from_string("Org/Course/Run")
- with pytest.raises(ValueError):
- outline = get_course_outline(old_course_key) # lint-amnesty, pylint: disable=unused-variable
+ with pytest.raises(ValueError): # noqa: PT011
+ outline = get_course_outline(old_course_key) # lint-amnesty, pylint: disable=unused-variable # noqa: F841
def test_simple_roundtrip(self):
"""Happy path for writing/reading-back a course outline."""
with pytest.raises(CourseOutlineData.DoesNotExist):
- course_outline = get_course_outline(self.course_key) # lint-amnesty, pylint: disable=unused-variable
+ course_outline = get_course_outline(self.course_key) # lint-amnesty, pylint: disable=unused-variable # noqa: F841
replace_course_outline(self.course_outline)
outline = get_course_outline(self.course_key)
@@ -153,7 +153,7 @@ def test_cached_response(self):
# Make sure this new outline is returned instead of the previously
# cached one.
with self.assertNumQueries(5):
- uncached_new_version_outline = get_course_outline(self.course_key) # lint-amnesty, pylint: disable=unused-variable
+ uncached_new_version_outline = get_course_outline(self.course_key) # lint-amnesty, pylint: disable=unused-variable # noqa: F841
assert new_version_outline == new_version_outline # lint-amnesty, pylint: disable=comparison-with-itself
@@ -180,7 +180,7 @@ def setUpTestData(cls): # lint-amnesty, pylint: disable=super-method-not-called
cls.simple_outline = CourseOutlineData(
course_key=cls.course_key,
title="User Outline Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -197,7 +197,7 @@ def setUpTestData(cls): # lint-amnesty, pylint: disable=super-method-not-called
def test_simple_outline(self):
"""This outline is the same for everyone."""
- at_time = datetime(2020, 5, 21, tzinfo=timezone.utc)
+ at_time = datetime(2020, 5, 21, tzinfo=timezone.utc) # noqa: UP017
beta_tester_outline = get_user_course_outline(
self.course_key, self.beta_tester, at_time
)
@@ -290,31 +290,31 @@ def setUpTestData(cls):
[
(
cls.course_key.make_usage_key('course', 'course'),
- {'start': datetime(2020, 5, 10, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 10, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.entrance_exam_section_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.entrance_exam_seq_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.open_section_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.open_seq_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.gated_section_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.gated_seq_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
]
)
@@ -326,7 +326,7 @@ def setUpTestData(cls):
cls.outline = CourseOutlineData(
course_key=cls.course_key,
title="User Outline Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=str(cls.entrance_exam_section_key),
days_early_for_beta=None,
@@ -388,7 +388,7 @@ def test_user_can_skip_entrance_exam(self, required_content_mock, user_can_skip_
required_content_mock.return_value = [str(self.entrance_exam_section_key)]
user_can_skip_entrance_exam_mock.return_value = True
staff_details, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
@@ -403,7 +403,7 @@ def test_user_can_not_skip_entrance_exam(self, required_content_mock, user_can_s
required_content_mock.return_value = [str(self.entrance_exam_section_key)]
user_can_skip_entrance_exam_mock.return_value = False
staff_details, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
assert len(staff_details.outline.accessible_sequences) == 3
@@ -439,19 +439,19 @@ def setUpTestData(cls):
[
(
cls.course_key.make_usage_key('course', 'course'),
- {'start': datetime(2020, 5, 10, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 10, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.section_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.open_seq_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.milestone_required_seq_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
]
)
@@ -463,7 +463,7 @@ def setUpTestData(cls):
cls.outline = CourseOutlineData(
course_key=cls.course_key,
title="User Outline Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -504,7 +504,7 @@ def get_milestones_side_effect(_course_key, usage_key, _milestone_type, _user_id
get_course_content_milestones_mock.side_effect = get_milestones_side_effect
staff_details, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
@@ -553,26 +553,26 @@ def setUpTestData(cls):
[
(
cls.course_key.make_usage_key('course', 'course'),
- {'start': datetime(2020, 5, 10, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 10, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.section_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
# Sequence that starts before containing Section.
(
cls.seq_before_key,
- {'start': datetime(2020, 5, 14, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 14, tzinfo=timezone.utc)} # noqa: UP017
),
# Sequence starts at same time as containing Section.
(
cls.seq_same_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
# Sequence starts after containing Section.
(
cls.seq_after_key,
- {'start': datetime(2020, 5, 16, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 16, tzinfo=timezone.utc)} # noqa: UP017
),
# Sequence should inherit start information from Section.
(
@@ -584,7 +584,7 @@ def setUpTestData(cls):
cls.seq_due_key,
{
'start': None,
- 'due': datetime(2020, 5, 20, tzinfo=timezone.utc)
+ 'due': datetime(2020, 5, 20, tzinfo=timezone.utc) # noqa: UP017
}
),
]
@@ -596,7 +596,7 @@ def setUpTestData(cls):
cls.outline = CourseOutlineData(
course_key=cls.course_key,
title="User Outline Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -648,7 +648,7 @@ def setUpTestData(cls):
def test_before_course_starts(self):
staff_details, student_details, beta_tester_details = self.get_details(
- datetime(2020, 5, 9, tzinfo=timezone.utc)
+ datetime(2020, 5, 9, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
assert len(staff_details.outline.accessible_sequences) == 5
@@ -668,7 +668,7 @@ def test_course_beta_access(self):
replace_course_outline(course_outline)
staff_details, student_details, beta_tester_details = self.get_details(
- datetime(2020, 5, 9, tzinfo=timezone.utc)
+ datetime(2020, 5, 9, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
assert len(staff_details.outline.accessible_sequences) == 5
@@ -684,7 +684,7 @@ def test_course_beta_access(self):
def test_before_section_starts(self):
staff_details, student_details, beta_tester_details = self.get_details(
- datetime(2020, 5, 14, tzinfo=timezone.utc)
+ datetime(2020, 5, 14, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
assert len(staff_details.outline.accessible_sequences) == 5
@@ -694,8 +694,8 @@ def test_before_section_starts(self):
# started yet.
assert len(student_details.outline.accessible_sequences) == 0
before_seq_sched_item_data = student_details.schedule.sequences[self.seq_before_key]
- assert before_seq_sched_item_data.start == datetime(2020, 5, 14, tzinfo=timezone.utc)
- assert before_seq_sched_item_data.effective_start == datetime(2020, 5, 15, tzinfo=timezone.utc)
+ assert before_seq_sched_item_data.start == datetime(2020, 5, 14, tzinfo=timezone.utc) # noqa: UP017
+ assert before_seq_sched_item_data.effective_start == datetime(2020, 5, 15, tzinfo=timezone.utc) # noqa: UP017
# Beta tester can access nothing
assert len(beta_tester_details.outline.accessible_sequences) == 0
@@ -706,7 +706,7 @@ def test_section_beta_access(self):
replace_course_outline(course_outline)
staff_details, student_details, beta_tester_details = self.get_details(
- datetime(2020, 5, 14, tzinfo=timezone.utc)
+ datetime(2020, 5, 14, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
assert len(staff_details.outline.accessible_sequences) == 5
@@ -716,15 +716,15 @@ def test_section_beta_access(self):
# started yet.
assert len(student_details.outline.accessible_sequences) == 0
before_seq_sched_item_data = student_details.schedule.sequences[self.seq_before_key]
- assert before_seq_sched_item_data.start == datetime(2020, 5, 14, tzinfo=timezone.utc)
- assert before_seq_sched_item_data.effective_start == datetime(2020, 5, 15, tzinfo=timezone.utc)
+ assert before_seq_sched_item_data.start == datetime(2020, 5, 14, tzinfo=timezone.utc) # noqa: UP017
+ assert before_seq_sched_item_data.effective_start == datetime(2020, 5, 15, tzinfo=timezone.utc) # noqa: UP017
# Beta tester can access some
assert len(beta_tester_details.outline.accessible_sequences) == 4
def test_at_section_start(self):
staff_details, student_details, beta_tester_details = self.get_details(
- datetime(2020, 5, 15, tzinfo=timezone.utc)
+ datetime(2020, 5, 15, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
assert len(staff_details.outline.accessible_sequences) == 5
@@ -745,7 +745,7 @@ def test_at_beta_section_start(self):
replace_course_outline(course_outline)
staff_details, student_details, beta_tester_details = self.get_details(
- datetime(2020, 5, 15, tzinfo=timezone.utc)
+ datetime(2020, 5, 15, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
assert len(staff_details.outline.accessible_sequences) == 5
@@ -762,7 +762,7 @@ def test_at_beta_section_start(self):
def test_is_due_and_before_due(self):
staff_details, student_details, beta_tester_details = self.get_details(
- datetime(2020, 5, 16, tzinfo=timezone.utc)
+ datetime(2020, 5, 16, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
assert len(staff_details.outline.accessible_sequences) == 5
@@ -773,14 +773,14 @@ def test_is_due_and_before_due(self):
assert self.seq_due_key in student_details.outline.accessible_sequences
seq_due_sched_item_data = student_details.schedule.sequences[self.seq_due_key]
- assert seq_due_sched_item_data.due == datetime(2020, 5, 20, tzinfo=timezone.utc)
+ assert seq_due_sched_item_data.due == datetime(2020, 5, 20, tzinfo=timezone.utc) # noqa: UP017
# Beta tester can access some
assert len(beta_tester_details.outline.accessible_sequences) == 5
def test_is_due_and_after_due(self):
staff_details, student_details, beta_tester_details = self.get_details(
- datetime(2020, 5, 21, tzinfo=timezone.utc)
+ datetime(2020, 5, 21, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
assert len(staff_details.outline.accessible_sequences) == 5
@@ -821,20 +821,20 @@ def setUpTestData(cls):
(
cls.course_key.make_usage_key('course', 'course'),
{
- 'start': datetime(2020, 5, 10, tzinfo=timezone.utc),
+ 'start': datetime(2020, 5, 10, tzinfo=timezone.utc), # noqa: UP017
}
),
(
cls.section_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.seq_one_key,
- {'due': datetime(2020, 5, 21, tzinfo=timezone.utc)}
+ {'due': datetime(2020, 5, 21, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.seq_two_key,
- {'due': datetime(2020, 5, 21, tzinfo=timezone.utc)}
+ {'due': datetime(2020, 5, 21, tzinfo=timezone.utc)} # noqa: UP017
),
]
)
@@ -845,7 +845,7 @@ def setUpTestData(cls):
cls.outline = CourseOutlineData(
course_key=cls.course_key,
title="User Outline Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -878,10 +878,10 @@ def setUpTestData(cls):
cls.student.courseenrollment_set.create(course_id=cls.course_key, is_active=True, mode="audit")
def test_sequences_accessible_after_due(self):
- at_time = datetime(2020, 5, 22, tzinfo=timezone.utc) # lint-amnesty, pylint: disable=unused-variable
+ at_time = datetime(2020, 5, 22, tzinfo=timezone.utc) # lint-amnesty, pylint: disable=unused-variable # noqa: F841, UP017
staff_details, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
@@ -920,27 +920,27 @@ def setUpTestData(cls):
[
(
cls.course_key.make_usage_key('course', 'course'),
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.section_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.seq_practice_exam_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.seq_proctored_exam_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.seq_timed_exam_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
(
cls.seq_normal_key,
- {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)}
+ {'start': datetime(2020, 5, 15, tzinfo=timezone.utc)} # noqa: UP017
),
]
)
@@ -951,7 +951,7 @@ def setUpTestData(cls):
cls.outline = CourseOutlineData(
course_key=cls.course_key,
title="User Outline Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -998,10 +998,10 @@ def setUpTestData(cls):
@patch.dict(settings.FEATURES, {'ENABLE_SPECIAL_EXAMS': True})
def test_special_exams_enabled_all_sequences_visible(self):
- at_time = datetime(2020, 5, 22, tzinfo=timezone.utc) # lint-amnesty, pylint: disable=unused-variable
+ at_time = datetime(2020, 5, 22, tzinfo=timezone.utc) # lint-amnesty, pylint: disable=unused-variable # noqa: F841, UP017
staff_details, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
@@ -1014,10 +1014,10 @@ def test_special_exams_enabled_all_sequences_visible(self):
@patch.dict(settings.FEATURES, {'ENABLE_SPECIAL_EXAMS': False})
def test_special_exams_disabled_preserves_exam_sequences(self):
- at_time = datetime(2020, 5, 22, tzinfo=timezone.utc) # lint-amnesty, pylint: disable=unused-variable
+ at_time = datetime(2020, 5, 22, tzinfo=timezone.utc) # lint-amnesty, pylint: disable=unused-variable # noqa: F841, UP017
staff_details, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
# Staff can always access all sequences
@@ -1034,7 +1034,7 @@ def test_special_exams_disabled_preserves_exam_sequences(self):
@patch.dict(settings.FEATURES, {'ENABLE_SPECIAL_EXAMS': True})
@patch('openedx.core.djangoapps.content.learning_sequences.api.processors.special_exams.get_attempt_status_summary')
def test_special_exam_attempt_data_in_details(self, mock_get_attempt_status_summary):
- at_time = datetime(2020, 5, 22, tzinfo=timezone.utc) # lint-amnesty, pylint: disable=unused-variable
+ at_time = datetime(2020, 5, 22, tzinfo=timezone.utc) # lint-amnesty, pylint: disable=unused-variable # noqa: F841, UP017
def get_attempt_status_side_effect(user_id, _course_key, usage_key):
"""
@@ -1045,7 +1045,7 @@ def get_attempt_status_side_effect(user_id, _course_key, usage_key):
for sequence_key in self.get_sequence_keys(exclude=[self.seq_normal_key]):
if usage_key == str(sequence_key):
- num_fake_attempts = mock_get_attempt_status_summary.call_count % len(self.all_seq_keys) # lint-amnesty, pylint: disable=unused-variable
+ num_fake_attempts = mock_get_attempt_status_summary.call_count % len(self.all_seq_keys) # lint-amnesty, pylint: disable=unused-variable # noqa: F841
return {
"summary": {
"usage_key": usage_key
@@ -1055,7 +1055,7 @@ def get_attempt_status_side_effect(user_id, _course_key, usage_key):
mock_get_attempt_status_summary.side_effect = get_attempt_status_side_effect
_, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
assert len(student_details.special_exam_attempts.sequences) == 3
@@ -1068,10 +1068,10 @@ def get_attempt_status_side_effect(user_id, _course_key, usage_key):
@patch.dict(settings.FEATURES, {'ENABLE_SPECIAL_EXAMS': False})
@patch('openedx.core.djangoapps.content.learning_sequences.api.processors.special_exams.get_attempt_status_summary')
def test_special_exam_attempt_data_empty_when_disabled(self, mock_get_attempt_status_summary):
- at_time = datetime(2020, 5, 22, tzinfo=timezone.utc) # lint-amnesty, pylint: disable=unused-variable
+ at_time = datetime(2020, 5, 22, tzinfo=timezone.utc) # lint-amnesty, pylint: disable=unused-variable # noqa: F841, UP017
_, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
# Ensure that no calls are made to get_attempt_status_summary and no data in special_exam_attempts
@@ -1083,7 +1083,7 @@ def test_special_exam_attempt_data_empty_when_disabled(self, mock_get_attempt_st
@patch('openedx.core.djangoapps.content.learning_sequences.api.processors.special_exams.get_attempt_status_summary')
def test_special_exam_attempt_data_exams_ida_flag_on(self, mock_get_attempt_status_summary):
_, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
# Ensure that no calls are made to get_attempt_status_summary
@@ -1093,7 +1093,7 @@ def test_special_exam_attempt_data_exams_ida_flag_on(self, mock_get_attempt_stat
@patch.dict(settings.FEATURES, {'ENABLE_SPECIAL_EXAMS': True})
def test_special_exam_attempt_data_exam_type(self):
_, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
# Ensure that exam type is correct for proctored exam
@@ -1146,7 +1146,7 @@ def setUpTestData(cls):
cls.outline = CourseOutlineData(
course_key=cls.course_key,
title="User Outline Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -1188,10 +1188,10 @@ def setUpTestData(cls):
cls.student.courseenrollment_set.create(course_id=cls.course_key, is_active=True, mode="audit")
def test_visibility(self):
- at_time = datetime(2020, 5, 21, tzinfo=timezone.utc) # Exact value doesn't matter # lint-amnesty, pylint: disable=unused-variable
+ at_time = datetime(2020, 5, 21, tzinfo=timezone.utc) # Exact value doesn't matter # lint-amnesty, pylint: disable=unused-variable # noqa: F841, UP017
staff_details, student_details, _ = self.get_details(
- datetime(2020, 5, 25, tzinfo=timezone.utc)
+ datetime(2020, 5, 25, tzinfo=timezone.utc) # noqa: UP017
)
# Sections visible
@@ -1224,7 +1224,7 @@ def setUpTestData(cls):
# Handy variable as we almost always need to test with all types of users
cls.all_users = [cls.global_staff, cls.student, cls.unenrolled_student, cls.anonymous_user]
- cls.course_access_time = datetime(2020, 5, 21, tzinfo=timezone.utc) # Some random time in past
+ cls.course_access_time = datetime(2020, 5, 21, tzinfo=timezone.utc) # Some random time in past # noqa: UP017
# Create course, set it start date to some time in past and attach outline to it
cls.course_key = CourseKey.from_string("course-v1:OpenEdX+Outline+T0")
@@ -1234,7 +1234,7 @@ def setUpTestData(cls):
cls.course_outline = CourseOutlineData(
course_key=cls.course_key,
title="User Outline Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -1366,7 +1366,7 @@ def _create_and_enroll_learner(self, username, mode, is_staff=False):
Returns created learner
"""
learner = UserFactory.create(
- username=username, email='{}@example.com'.format(username), is_staff=is_staff
+ username=username, email='{}@example.com'.format(username), is_staff=is_staff # noqa: UP032
)
learner.courseenrollment_set.create(course_id=self.course_key, is_active=True, mode=mode)
return learner
@@ -1374,7 +1374,7 @@ def _create_and_enroll_learner(self, username, mode, is_staff=False):
def _setup_course_outline_with_sections(
self,
course_sections,
- course_start_date=datetime(2021, 3, 26, tzinfo=timezone.utc)
+ course_start_date=datetime(2021, 3, 26, tzinfo=timezone.utc) # noqa: UP017
):
"""
Helper function to update the course outline under test with
@@ -1565,7 +1565,7 @@ def test_enrollment_track_partition_on_section(
self._create_and_enroll_learner(username, mode)
)
- check_date = datetime(2021, 3, 27, tzinfo=timezone.utc)
+ check_date = datetime(2021, 3, 27, tzinfo=timezone.utc) # noqa: UP017
# Get details
staff_details, _, beta_tester_details = self.get_details(check_date)
@@ -1712,7 +1712,7 @@ def test_processor_only(
self._create_and_enroll_learner(username, mode)
)
- check_date = datetime(2021, 3, 27, tzinfo=timezone.utc)
+ check_date = datetime(2021, 3, 27, tzinfo=timezone.utc) # noqa: UP017
for learner_to_verify in learners_to_verify:
processor = EnrollmentTrackPartitionGroupsOutlineProcessor(
self.course_key, learner_to_verify, check_date
@@ -1742,7 +1742,7 @@ def _create_and_enroll_learner(self, username, is_staff=False):
Returns the created learner
"""
learner = UserFactory.create(
- username=username, email='{}@example.com'.format(username), is_staff=is_staff
+ username=username, email='{}@example.com'.format(username), is_staff=is_staff # noqa: UP032
)
learner.courseenrollment_set.create(course_id=self.course_key, is_active=True, mode=CourseMode.VERIFIED)
return learner
@@ -1750,7 +1750,7 @@ def _create_and_enroll_learner(self, username, is_staff=False):
def _setup_course_outline_with_sections(
self,
course_sections,
- course_start_date=datetime(2021, 3, 26, tzinfo=timezone.utc)
+ course_start_date=datetime(2021, 3, 26, tzinfo=timezone.utc) # noqa: UP017
):
"""
Helper function to update the course outline under test with
@@ -1899,7 +1899,7 @@ def test_cohort_partition_on_outline(
]
)
- check_date = datetime(2021, 3, 27, tzinfo=timezone.utc)
+ check_date = datetime(2021, 3, 27, tzinfo=timezone.utc) # noqa: UP017
for learner_to_verify in learners_to_verify:
learner_details = get_user_course_outline_details(self.course_key, learner_to_verify, check_date)
@@ -1917,7 +1917,7 @@ def test_errors(self):
outline = CourseOutlineData(
course_key=course_key,
title="Outline Errors Test Course!",
- published_at=datetime(2021, 3, 21, tzinfo=timezone.utc),
+ published_at=datetime(2021, 3, 21, tzinfo=timezone.utc), # noqa: UP017
published_version="8ebece4b69dd593d82fe2020",
sections=[],
self_paced=False,
@@ -1984,7 +1984,7 @@ def _create_and_enroll_learner(cls, username, is_staff=False):
Returns the created learner
"""
learner = UserFactory.create(
- username=username, email='{}@example.com'.format(username), is_staff=is_staff
+ username=username, email='{}@example.com'.format(username), is_staff=is_staff # noqa: UP032
)
learner.courseenrollment_set.create(course_id=cls.course_key, is_active=True)
return learner
@@ -1993,7 +1993,7 @@ def _create_and_enroll_learner(cls, username, is_staff=False):
def _setup_course_outline_with_sections(
cls,
course_sections,
- course_start_date=datetime(2021, 3, 26, tzinfo=timezone.utc)
+ course_start_date=datetime(2021, 3, 26, tzinfo=timezone.utc) # noqa: UP017
):
"""
Helper function to update the course outline under test with
diff --git a/openedx/core/djangoapps/content/learning_sequences/data.py b/openedx/core/djangoapps/content/learning_sequences/data.py
index 78d37707862b..6c1beb33376f 100644
--- a/openedx/core/djangoapps/content/learning_sequences/data.py
+++ b/openedx/core/djangoapps/content/learning_sequences/data.py
@@ -23,7 +23,7 @@
import logging
from datetime import datetime
from enum import Enum
-from typing import Dict, FrozenSet, List, Optional
+from typing import Dict, FrozenSet, List, Optional # noqa: UP035
import attr
from opaque_keys.edx.keys import CourseKey, UsageKey
@@ -59,7 +59,7 @@ class ContentErrorData:
the outline (unknown tag types, sequences where we expect sections, etc.)
"""
message: str
- usage_key: Optional[UsageKey] = None
+ usage_key: Optional[UsageKey] = None # noqa: UP045
@attr.s(frozen=True, auto_attribs=True)
@@ -136,7 +136,7 @@ class CourseLearningSequenceData:
# associated with this piece of content. See models.UserPartitionGroup
# for more details.
user_partition_groups = attr.ib(
- type=Dict[int, FrozenSet[int]],
+ type=Dict[int, FrozenSet[int]], # noqa: UP006
factory=dict,
validator=[user_partition_groups_not_empty],
)
@@ -150,13 +150,13 @@ class CourseSectionData:
usage_key = attr.ib(type=UsageKey)
title = attr.ib(type=str)
visibility = attr.ib(type=VisibilityData, default=VisibilityData())
- sequences = attr.ib(type=List[CourseLearningSequenceData], factory=list)
+ sequences = attr.ib(type=List[CourseLearningSequenceData], factory=list) # noqa: UP006
# Mapping of UserPartition IDs to list of UserPartition Groups that are
# associated with this piece of content. See models.UserPartitionGroup
# for more details.
user_partition_groups = attr.ib(
- type=Dict[int, FrozenSet[int]],
+ type=Dict[int, FrozenSet[int]], # noqa: UP006
factory=dict,
validator=[user_partition_groups_not_empty],
)
@@ -200,21 +200,21 @@ def not_deprecated(self, _attribute, value):
# The time period (in days) before the official start of the course during which
# beta testers have access to the course.
- days_early_for_beta = attr.ib(type=Optional[int])
+ days_early_for_beta = attr.ib(type=Optional[int]) # noqa: UP045
- sections = attr.ib(type=List[CourseSectionData])
+ sections = attr.ib(type=List[CourseSectionData]) # noqa: UP006
# Defines if course self-paced or instructor-paced.
self_paced = attr.ib(type=bool)
# To make sure that our data structure is consistent, this field is
# derived from what you pass into `sections`. Do not set this directly.
- sequences = attr.ib(type=Dict[UsageKey, CourseLearningSequenceData], init=False)
+ sequences = attr.ib(type=Dict[UsageKey, CourseLearningSequenceData], init=False) # noqa: UP006
course_visibility: CourseVisibility = attr.ib(validator=attr.validators.in_(CourseVisibility))
# Entrance Exam ID
- entrance_exam_id = attr.ib(type=Optional[str])
+ entrance_exam_id = attr.ib(type=Optional[str]) # noqa: UP045
def __attrs_post_init__(self):
"""Post-init hook that validates and inits the `sequences` field."""
@@ -223,7 +223,7 @@ def __attrs_post_init__(self):
for seq in section.sequences:
if seq.usage_key in sequences: # lint-amnesty, pylint: disable=no-else-raise
raise ValueError(
- "Sequence {} appears in more than one Section."
+ "Sequence {} appears in more than one Section." # noqa: UP032
.format(seq.usage_key)
)
else:
@@ -237,7 +237,7 @@ def __attrs_post_init__(self):
# sequences manually here, instead of in a @sequences.validator
if len(sequences) > self.MAX_SEQUENCE_COUNT:
raise ValueError(
- "sequences cannot have more than {} entries ({} attempted)"
+ "sequences cannot have more than {} entries ({} attempted)" # noqa: UP032
.format(self.MAX_SEQUENCE_COUNT, len(sequences))
)
@@ -285,7 +285,7 @@ def validate_days_early_for_beta(self, attribute, value): # lint-amnesty, pylin
"""
if value is not None and value < 0:
raise ValueError(
- "Provided value {} for days_early_for_beta is invalid. The value must be positive or zero. "
+ "Provided value {} for days_early_for_beta is invalid. The value must be positive or zero. " # noqa: UP032 # pylint: disable=line-too-long
"A positive value will shift back the starting date for Beta users by that many days.".format(value)
)
@@ -298,11 +298,11 @@ class ScheduleItemData:
usage_key: UsageKey
# Start date that is specified for this item
- start: Optional[datetime]
+ start: Optional[datetime] # noqa: UP045
# Effective release date that it's available (may be affected by parents)
- effective_start: Optional[datetime]
- due: Optional[datetime]
+ effective_start: Optional[datetime] # noqa: UP045
+ due: Optional[datetime] # noqa: UP045
@attr.s(frozen=True, auto_attribs=True)
@@ -310,10 +310,10 @@ class ScheduleData:
"""
Overall course schedule data.
"""
- course_start: Optional[datetime]
- course_end: Optional[datetime]
- sections: Dict[UsageKey, ScheduleItemData]
- sequences: Dict[UsageKey, ScheduleItemData]
+ course_start: Optional[datetime] # noqa: UP045
+ course_end: Optional[datetime] # noqa: UP045
+ sections: Dict[UsageKey, ScheduleItemData] # noqa: UP006
+ sequences: Dict[UsageKey, ScheduleItemData] # noqa: UP006
@attr.s(frozen=True, auto_attribs=True)
@@ -321,7 +321,7 @@ class SpecialExamAttemptData:
"""
Overall special exam attempt data.
"""
- sequences: Dict[UsageKey, Dict]
+ sequences: Dict[UsageKey, Dict] # noqa: UP006
@attr.s(frozen=True, auto_attribs=True)
@@ -360,7 +360,7 @@ class is a pretty dumb container that doesn't understand anything about how
# * If anonymous course access is enabled in "public_outline" mode,
# unauthenticated users (AnonymousUser) will see the course outline but
# not be able to access anything inside.
- accessible_sequences: FrozenSet[UsageKey]
+ accessible_sequences: FrozenSet[UsageKey] # noqa: UP006
@attr.s(frozen=True, auto_attribs=True)
diff --git a/openedx/core/djangoapps/content/learning_sequences/models.py b/openedx/core/djangoapps/content/learning_sequences/models.py
index c03074b91bf5..e74e6abf873b 100644
--- a/openedx/core/djangoapps/content/learning_sequences/models.py
+++ b/openedx/core/djangoapps/content/learning_sequences/models.py
@@ -92,7 +92,7 @@ class CourseContext(TimeStampedModel):
)
days_early_for_beta = models.IntegerField(null=True, blank=True)
self_paced = models.BooleanField(default=False)
- entrance_exam_id = models.CharField(max_length=255, null=True)
+ entrance_exam_id = models.CharField(max_length=255, null=True) # noqa: DJ001
class Meta:
verbose_name = 'Course'
@@ -159,7 +159,7 @@ class Meta:
abstract = True
-class UserPartitionGroup(models.Model):
+class UserPartitionGroup(models.Model): # noqa: DJ008
"""
Each row represents a Group in a UserPartition.
@@ -201,7 +201,7 @@ class Meta:
]
-class CourseSection(CourseContentVisibilityMixin, TimeStampedModel):
+class CourseSection(CourseContentVisibilityMixin, TimeStampedModel): # noqa: DJ008
"""
Course Section data, mapping to the 'chapter' block type.
@@ -234,7 +234,7 @@ class Meta:
]
-class SectionPartitionGroup(models.Model):
+class SectionPartitionGroup(models.Model): # noqa: DJ008
"""
Model which maps user partition groups to course sections.
Used for the user_partition_groups ManyToManyField field in the CourseSection model above.
@@ -248,7 +248,7 @@ class Meta:
['user_partition_group', 'course_section'],
]
- user_partition_group = models.ForeignKey(UserPartitionGroup, on_delete=models.CASCADE)
+ user_partition_group = models.ForeignKey(UserPartitionGroup, on_delete=models.CASCADE) # noqa: DJ012
course_section = models.ForeignKey(CourseSection, on_delete=models.CASCADE)
@@ -302,7 +302,7 @@ def __str__(self):
return f"{self.section.title} > {self.sequence.title}"
-class SectionSequencePartitionGroup(models.Model):
+class SectionSequencePartitionGroup(models.Model): # noqa: DJ008
"""
Model which maps user partition groups to course section sequences.
Used for the user_partition_groups ManyToManyField field in the CourseSectionSequence model above.
@@ -316,7 +316,7 @@ class Meta:
['user_partition_group', 'course_section_sequence'],
]
- user_partition_group = models.ForeignKey(UserPartitionGroup, on_delete=models.CASCADE)
+ user_partition_group = models.ForeignKey(UserPartitionGroup, on_delete=models.CASCADE) # noqa: DJ012
course_section_sequence = models.ForeignKey(CourseSectionSequence, on_delete=models.CASCADE)
@@ -334,7 +334,7 @@ class CourseSequenceExam(TimeStampedModel):
is_time_limited = models.BooleanField(default=False)
-class PublishReport(models.Model):
+class PublishReport(models.Model): # noqa: DJ008
"""
A report about the content that generated this LearningContext publish.
@@ -352,7 +352,7 @@ class PublishReport(models.Model):
num_sequences = models.PositiveIntegerField(null=False, db_index=True)
-class ContentError(models.Model):
+class ContentError(models.Model): # noqa: DJ008
"""
Human readable content errors.
diff --git a/openedx/core/djangoapps/content/learning_sequences/tests/test_views.py b/openedx/core/djangoapps/content/learning_sequences/tests/test_views.py
index c56bb0474903..a971556375ba 100644
--- a/openedx/core/djangoapps/content/learning_sequences/tests/test_views.py
+++ b/openedx/core/djangoapps/content/learning_sequences/tests/test_views.py
@@ -50,7 +50,7 @@ def setUpTestData(cls): # lint-amnesty, pylint: disable=super-method-not-called
cls.outline = CourseOutlineData(
course_key=cls.course_key,
title="Views Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -110,7 +110,7 @@ def test_outline_as_staff(self):
# the raw form for max compatibility (i.e. guard against serialization
# of dates changing), or do the parsing for conveninece? Convenience for
# now.
- assert data['published_at'] == datetime(2020, 5, 20, tzinfo=timezone.utc)
+ assert data['published_at'] == datetime(2020, 5, 20, tzinfo=timezone.utc) # noqa: UP017
assert data['published_version'] == "5ebece4b69dd593d82fe2020"
# Basic outline structure checks
@@ -139,7 +139,7 @@ def setUpTestData(cls): # lint-amnesty, pylint: disable=super-method-not-called
outline = CourseOutlineData(
course_key=course_key,
title="Views Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=None,
days_early_for_beta=None,
@@ -260,7 +260,7 @@ def setUpTestData(cls):
outline = CourseOutlineData(
course_key=cls.course_key,
title="Views Test Course!",
- published_at=datetime(2020, 5, 20, tzinfo=timezone.utc),
+ published_at=datetime(2020, 5, 20, tzinfo=timezone.utc), # noqa: UP017
published_version="5ebece4b69dd593d82fe2020",
entrance_exam_id=None,
days_early_for_beta=None,
diff --git a/openedx/core/djangoapps/content/learning_sequences/views.py b/openedx/core/djangoapps/content/learning_sequences/views.py
index 7bd453ca1d42..816edd63b053 100644
--- a/openedx/core/djangoapps/content/learning_sequences/views.py
+++ b/openedx/core/djangoapps/content/learning_sequences/views.py
@@ -161,7 +161,7 @@ def get(self, request, course_key_str, format=None): # lint-amnesty, pylint: di
# Translate input params and do course key validation (will cause HTTP
# 400 error if an invalid CourseKey was entered, instead of 404).
course_key = validate_course_key(course_key_str)
- at_time = datetime.now(timezone.utc)
+ at_time = datetime.now(timezone.utc) # noqa: UP017
# Get target user (and override request user for the benefit of any waffle checks)
request.user = self._determine_user(request, course_key)
diff --git a/openedx/core/djangoapps/content/search/api.py b/openedx/core/djangoapps/content/search/api.py
index 1d7b01c30d39..e32b785baa85 100644
--- a/openedx/core/djangoapps/content/search/api.py
+++ b/openedx/core/djangoapps/content/search/api.py
@@ -9,7 +9,7 @@
from contextlib import contextmanager, nullcontext
from datetime import datetime, timedelta, timezone
from functools import wraps
-from typing import Callable, Generator, cast
+from typing import Callable, Generator, cast # noqa: UP035
from django.conf import settings
from django.contrib.auth import get_user_model
@@ -964,7 +964,7 @@ def generate_user_token_for_studio_search(request):
"""
Returns a Meilisearch API key that only allows the user to search content that they have permission to view
"""
- expires_at = datetime.now(tz=timezone.utc) + timedelta(days=7)
+ expires_at = datetime.now(tz=timezone.utc) + timedelta(days=7) # noqa: UP017
search_rules = {
STUDIO_INDEX_NAME: _get_meili_access_filter(request),
diff --git a/openedx/core/djangoapps/content/search/apps.py b/openedx/core/djangoapps/content/search/apps.py
index 13a83a11a6a6..4a377f0a92a1 100644
--- a/openedx/core/djangoapps/content/search/apps.py
+++ b/openedx/core/djangoapps/content/search/apps.py
@@ -13,4 +13,4 @@ class ContentSearchConfig(AppConfig):
def ready(self):
# Connect signal handlers
- from . import handlers # pylint: disable=unused-import
+ from . import handlers # pylint: disable=unused-import # noqa: F401
diff --git a/openedx/core/djangoapps/content/search/models.py b/openedx/core/djangoapps/content/search/models.py
index 6fa53ef17b34..f349dac957c9 100644
--- a/openedx/core/djangoapps/content/search/models.py
+++ b/openedx/core/djangoapps/content/search/models.py
@@ -12,7 +12,7 @@
from openedx.core.djangoapps.content_libraries.api import get_libraries_for_user
-class SearchAccess(models.Model):
+class SearchAccess(models.Model): # noqa: DJ008
"""
Stores a numeric ID for each ContextKey.
@@ -67,7 +67,7 @@ def get_access_ids_for_request(request: Request, omit_orgs: list[str] = None) ->
)
-class IncrementalIndexCompleted(models.Model):
+class IncrementalIndexCompleted(models.Model): # noqa: DJ008
"""
Stores the contex keys of aleady indexed courses and libraries for incremental indexing.
"""
diff --git a/openedx/core/djangoapps/content/search/plain_text_math.py b/openedx/core/djangoapps/content/search/plain_text_math.py
index 70f6c3fd2cf0..e1f550e3b554 100644
--- a/openedx/core/djangoapps/content/search/plain_text_math.py
+++ b/openedx/core/djangoapps/content/search/plain_text_math.py
@@ -65,7 +65,7 @@ def _nested_bracket_matcher(equation: str, opening_pattern: str) -> str:
raise EqnPatternNotFound()
open_count = 0
inner_start = start + len(opening_pattern)
- for i, char in enumerate(equation[inner_start:]):
+ for i, char in enumerate(equation[inner_start:]): # noqa: B007
if char == "{":
open_count += 1
if char == "}":
diff --git a/openedx/core/djangoapps/content/search/tests/test_api.py b/openedx/core/djangoapps/content/search/tests/test_api.py
index e8f345f9c410..356125febf19 100644
--- a/openedx/core/djangoapps/content/search/tests/test_api.py
+++ b/openedx/core/djangoapps/content/search/tests/test_api.py
@@ -61,7 +61,7 @@ def setUp(self) -> None:
# Clear the Meilisearch client to avoid side effects from other tests
api.clear_meilisearch_client()
- modified_date = datetime(2024, 5, 6, 7, 8, 9, tzinfo=timezone.utc)
+ modified_date = datetime(2024, 5, 6, 7, 8, 9, tzinfo=timezone.utc) # noqa: UP017
# Create course
with freeze_time(modified_date):
self.course = self.store.create_course(
@@ -134,7 +134,7 @@ def setUp(self) -> None:
lib_access, _ = SearchAccess.objects.get_or_create(context_key=self.library.key)
# Populate it with 2 problems, freezing the date so we can verify created date serializes correctly.
- self.created_date = datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc)
+ self.created_date = datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(self.created_date):
self.problem1 = library_api.create_library_block(self.library.key, "problem", "p1")
self.problem2 = library_api.create_library_block(self.library.key, "problem", "p2")
@@ -332,7 +332,7 @@ def tearDown(self):
@override_settings(MEILISEARCH_ENABLED=False)
def test_reindex_meilisearch_disabled(self, mock_meilisearch) -> None:
- with self.assertRaises(RuntimeError):
+ with self.assertRaises(RuntimeError): # noqa: PT027
api.rebuild_index()
mock_meilisearch.return_value.swap_indexes.assert_not_called()
@@ -683,7 +683,7 @@ def test_index_library_block_and_collections(self, mock_meilisearch) -> None:
Test indexing an Library Block and the Collections it's in.
"""
# Create collections (these internally call `upsert_library_collection_index_doc`)
- created_date = datetime(2023, 5, 6, 7, 8, 9, tzinfo=timezone.utc)
+ created_date = datetime(2023, 5, 6, 7, 8, 9, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(created_date):
collection1 = library_api.create_library_collection(
self.library.key,
@@ -704,7 +704,7 @@ def test_index_library_block_and_collections(self, mock_meilisearch) -> None:
# Add Problem1 to both Collections (these internally call `upsert_item_collections_index_docs` and
# `upsert_library_collection_index_doc`)
# (adding in reverse order to test sorting of collection tag)
- updated_date = datetime(2023, 6, 7, 8, 9, 10, tzinfo=timezone.utc)
+ updated_date = datetime(2023, 6, 7, 8, 9, 10, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(updated_date):
for collection in (collection2, collection1):
library_api.update_library_collection_items(
@@ -887,7 +887,7 @@ def test_delete_collection(self, mock_meilisearch) -> None:
Test soft-deleting, restoring, and hard-deleting a collection.
"""
# Add a component to the collection
- updated_date = datetime(2023, 6, 7, 8, 9, 10, tzinfo=timezone.utc)
+ updated_date = datetime(2023, 6, 7, 8, 9, 10, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(updated_date):
library_api.update_library_collection_items(
self.library.key,
@@ -962,7 +962,7 @@ def test_delete_collection(self, mock_meilisearch) -> None:
mock_meilisearch.return_value.get_index.return_value.get_document.return_value = None
# Restore the collection
- restored_date = datetime(2023, 8, 9, 10, 11, 12, tzinfo=timezone.utc)
+ restored_date = datetime(2023, 8, 9, 10, 11, 12, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(restored_date):
content_api.restore_collection(
self.collection.learning_package_id,
diff --git a/openedx/core/djangoapps/content/search/tests/test_documents.py b/openedx/core/djangoapps/content/search/tests/test_documents.py
index a580adf8ec01..a9aea3ab3cfb 100644
--- a/openedx/core/djangoapps/content/search/tests/test_documents.py
+++ b/openedx/core/djangoapps/content/search/tests/test_documents.py
@@ -54,7 +54,7 @@ def setUpClass(cls):
super().setUpClass()
cls.store = modulestore()
# Create a library and collection with a block
- cls.created_date = datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc)
+ cls.created_date = datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(cls.created_date):
# Get references to some blocks in the toy course
cls.org = Organization.objects.create(name="edX", short_name="edX")
@@ -478,8 +478,8 @@ def test_html_published_library_block(self):
# Verify publish status is set to modified
library_block_modified = replace(
self.library_block,
- modified=datetime(2024, 4, 5, 6, 7, 8, tzinfo=timezone.utc),
- last_published=datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc),
+ modified=datetime(2024, 4, 5, 6, 7, 8, tzinfo=timezone.utc), # noqa: UP017
+ last_published=datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc), # noqa: UP017
)
doc = searchable_doc_for_library_block(library_block_modified)
doc.update(searchable_doc_tags(library_block_modified.usage_key))
diff --git a/openedx/core/djangoapps/content/search/tests/test_handlers.py b/openedx/core/djangoapps/content/search/tests/test_handlers.py
index 462d4770cd2f..bb3654942b64 100644
--- a/openedx/core/djangoapps/content/search/tests/test_handlers.py
+++ b/openedx/core/djangoapps/content/search/tests/test_handlers.py
@@ -62,7 +62,7 @@ def test_create_delete_xblock(self, meilisearch_client):
course_access, _ = SearchAccess.objects.get_or_create(context_key=course.id)
# Create XBlocks
- created_date = datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc)
+ created_date = datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(created_date):
sequential = self.store.create_child(self.user_id, course.location, "sequential", "test_sequential")
doc_sequential = {
@@ -116,7 +116,7 @@ def test_create_delete_xblock(self, meilisearch_client):
# Update the XBlock
sequential = self.store.get_item(sequential.location, self.user_id) # Refresh the XBlock
sequential.display_name = "Updated Sequential"
- modified_date = datetime(2024, 5, 6, 7, 8, 9, tzinfo=timezone.utc)
+ modified_date = datetime(2024, 5, 6, 7, 8, 9, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(modified_date):
self.store.update_item(sequential, self.user_id)
@@ -165,7 +165,7 @@ def test_create_delete_library_block(self, meilisearch_client):
lib_access = SearchAccess.objects.get(context_key=library.key)
# Populate it with a problem, freezing the date so we can verify created date serializes correctly.
- created_date = datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc)
+ created_date = datetime(2023, 4, 5, 6, 7, 8, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(created_date):
problem = library_api.create_library_block(library.key, "problem", "Problem1")
doc_problem = {
@@ -196,14 +196,14 @@ def test_create_delete_library_block(self, meilisearch_client):
meilisearch_client.return_value.index.return_value.update_documents.assert_called_with([doc_problem])
# Edit the problem block, freezing the date so we can verify modified date serializes correctly
- modified_date = datetime(2024, 5, 6, 7, 8, 9, tzinfo=timezone.utc)
+ modified_date = datetime(2024, 5, 6, 7, 8, 9, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(modified_date):
library_api.set_library_block_olx(problem.usage_key, "")
doc_problem["modified"] = modified_date.timestamp()
meilisearch_client.return_value.index.return_value.update_documents.assert_called_with([doc_problem])
# Publish the content library, freezing the date so we can verify last_published date serializes correctly
- published_date = datetime(2024, 6, 7, 8, 9, 10, tzinfo=timezone.utc)
+ published_date = datetime(2024, 6, 7, 8, 9, 10, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(published_date):
library_api.publish_changes(library.key)
doc_problem["last_published"] = published_date.timestamp()
diff --git a/openedx/core/djangoapps/content/search/tests/test_views.py b/openedx/core/djangoapps/content/search/tests/test_views.py
index 7c1b8e99850a..3d056b2b4327 100644
--- a/openedx/core/djangoapps/content/search/tests/test_views.py
+++ b/openedx/core/djangoapps/content/search/tests/test_views.py
@@ -110,12 +110,12 @@ def test_studio_search_enabled(self, mock_search_client):
so any logged-in user can get a restricted API key for Meilisearch using the REST API.
"""
self.client.login(username='student', password='student_pass')
- mock_generate_tenant_token = self._mock_generate_tenant_token(mock_search_client)
+ mock_generate_tenant_token = self._mock_generate_tenant_token(mock_search_client) # noqa: F841
result = self.client.get(STUDIO_SEARCH_ENDPOINT_URL)
assert result.status_code == 200
assert result.data["index_name"] == "studio_content"
assert result.data["url"] == "http://meilisearch.url"
- assert result.data["api_key"] and isinstance(result.data["api_key"], str)
+ assert result.data["api_key"] and isinstance(result.data["api_key"], str) # noqa: PT018
@mock_meilisearch(enabled=True)
@patch('openedx.core.djangoapps.content.search.api.MeilisearchClient')
diff --git a/openedx/core/djangoapps/content_libraries/api/__init__.py b/openedx/core/djangoapps/content_libraries/api/__init__.py
index 377cb038a4b6..a77a4dfa7489 100644
--- a/openedx/core/djangoapps/content_libraries/api/__init__.py
+++ b/openedx/core/djangoapps/content_libraries/api/__init__.py
@@ -1,11 +1,11 @@
"""
Python API for working with content libraries
"""
-from . import permissions
-from .block_metadata import *
-from .blocks import *
-from .collections import *
-from .container_metadata import *
-from .containers import *
-from .exceptions import *
-from .libraries import *
+from . import permissions # noqa: F401
+from .block_metadata import * # noqa: F403
+from .blocks import * # noqa: F403
+from .collections import * # noqa: F403
+from .container_metadata import * # noqa: F403
+from .containers import * # noqa: F403
+from .exceptions import * # noqa: F403
+from .libraries import * # noqa: F403
diff --git a/openedx/core/djangoapps/content_libraries/api/block_metadata.py b/openedx/core/djangoapps/content_libraries/api/block_metadata.py
index 2595830beeaf..fb1d2235219f 100644
--- a/openedx/core/djangoapps/content_libraries/api/block_metadata.py
+++ b/openedx/core/djangoapps/content_libraries/api/block_metadata.py
@@ -5,7 +5,7 @@
from dataclasses import dataclass
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext as _ # noqa: F401
from opaque_keys.edx.locator import LibraryUsageLocatorV2
from .libraries import PublishableItem, library_component_usage_key
diff --git a/openedx/core/djangoapps/content_libraries/api/blocks.py b/openedx/core/djangoapps/content_libraries/api/blocks.py
index 8ee865f8f45b..3678ea9f42d6 100644
--- a/openedx/core/djangoapps/content_libraries/api/blocks.py
+++ b/openedx/core/djangoapps/content_libraries/api/blocks.py
@@ -233,7 +233,7 @@ def set_library_block_olx(usage_key: LibraryUsageLocatorV2, new_olx_str: str) ->
del node.attrib["url_name"]
new_olx_str = etree.tostring(node, encoding='unicode')
- now = datetime.now(tz=timezone.utc)
+ now = datetime.now(tz=timezone.utc) # noqa: UP017
with transaction.atomic():
new_content = content_api.get_or_create_text_media(
@@ -421,7 +421,7 @@ def _import_staged_block(
component_type = content_api.get_or_create_component_type(
"xblock.v1", usage_key.block_type
)
- component = content_api.create_component(
+ component = content_api.create_component( # noqa: F841
learning_package.id,
component_type=component_type,
local_key=usage_key.block_id,
@@ -654,7 +654,7 @@ def import_staged_content_from_user_clipboard(library_key: LibraryLocatorV2, use
if olx_str is None:
raise RuntimeError("olx_str missing") # Shouldn't happen - mostly here for type checker
- now = datetime.now(tz=timezone.utc)
+ now = datetime.now(tz=timezone.utc) # noqa: UP017
if _is_container(user_clipboard.content.block_type):
# This is a container and we can import it as such.
@@ -911,7 +911,7 @@ def add_library_block_static_asset_file(
component_version = content_api.create_next_component_version(
component.pk,
media_to_replace={file_path: file_content},
- created=datetime.now(tz=timezone.utc),
+ created=datetime.now(tz=timezone.utc), # noqa: UP017
created_by=user.id if user else None,
)
transaction.on_commit(
@@ -953,10 +953,10 @@ def delete_library_block_static_asset_file(usage_key, file_path, user=None):
delete_library_block_static_asset_file(video_block, "subtitles-en.srt")
"""
component = get_component_from_usage_key(usage_key)
- now = datetime.now(tz=timezone.utc)
+ now = datetime.now(tz=timezone.utc) # noqa: UP017
with transaction.atomic():
- component_version = content_api.create_next_component_version(
+ component_version = content_api.create_next_component_version( # noqa: F841
component.pk,
media_to_replace={file_path: None},
created=now,
@@ -1032,7 +1032,7 @@ def _create_component_for_block(
text data like X" goes in xblock.api.
"""
display_name = xblock_type_display_name(usage_key.block_type)
- now = datetime.now(tz=timezone.utc)
+ now = datetime.now(tz=timezone.utc) # noqa: UP017
xml_text = f'<{usage_key.block_type} />'
learning_package = content_lib.learning_package
diff --git a/openedx/core/djangoapps/content_libraries/api/containers.py b/openedx/core/djangoapps/content_libraries/api/containers.py
index c1618e485d8c..15d8d19833a5 100644
--- a/openedx/core/djangoapps/content_libraries/api/containers.py
+++ b/openedx/core/djangoapps/content_libraries/api/containers.py
@@ -116,7 +116,7 @@ def create_container(
)
if not created:
- created = datetime.now(tz=timezone.utc)
+ created = datetime.now(tz=timezone.utc) # noqa: UP017
# Then try creating the actual container:
container, _initial_version = content_api.create_container_and_version(
@@ -150,7 +150,7 @@ def update_container(
"""
container = get_container_from_key(container_key)
library_key = container_key.lib_key
- created = datetime.now(tz=timezone.utc)
+ created = datetime.now(tz=timezone.utc) # noqa: UP017
# Get children containers or components to update their index data
children = get_container_children(container_key, published=False)
@@ -406,7 +406,7 @@ def update_container_children(
[ 🛑 UNSTABLE ] Adds children components or containers to given container.
"""
container = get_container_from_key(container_key)
- created = datetime.now(tz=timezone.utc)
+ created = datetime.now(tz=timezone.utc) # noqa: UP017
new_version = content_api.create_next_container_version(
container,
diff --git a/openedx/core/djangoapps/content_libraries/api/libraries.py b/openedx/core/djangoapps/content_libraries/api/libraries.py
index 827db78406e7..4fdbcb95d5f4 100644
--- a/openedx/core/djangoapps/content_libraries/api/libraries.py
+++ b/openedx/core/djangoapps/content_libraries/api/libraries.py
@@ -445,7 +445,7 @@ def create_library(
"""
assert isinstance(org, Organization)
validate_unicode_slug(slug)
- is_learning_package_loaded = learning_package is not None
+ is_learning_package_loaded = learning_package is not None # noqa: F841
try:
with transaction.atomic():
ref = ContentLibrary.objects.create(
@@ -475,7 +475,7 @@ def create_library(
ref.learning_package = learning_package
ref.save()
except IntegrityError:
- raise LibraryAlreadyExists(slug) # lint-amnesty, pylint: disable=raise-missing-from
+ raise LibraryAlreadyExists(slug) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
# .. event_implemented_name: CONTENT_LIBRARY_CREATED
# .. event_type: org.openedx.content_authoring.content_library.created.v1
diff --git a/openedx/core/djangoapps/content_libraries/apps.py b/openedx/core/djangoapps/content_libraries/apps.py
index 336422705473..cd4ac24e4c93 100644
--- a/openedx/core/djangoapps/content_libraries/apps.py
+++ b/openedx/core/djangoapps/content_libraries/apps.py
@@ -36,4 +36,4 @@ def ready(self):
"""
Import signal handler's module to ensure they are registered.
"""
- from . import signal_handlers # pylint: disable=unused-import
+ from . import signal_handlers # pylint: disable=unused-import # noqa: F401
diff --git a/openedx/core/djangoapps/content_libraries/models.py b/openedx/core/djangoapps/content_libraries/models.py
index e0185061eda9..9af747d8eb60 100644
--- a/openedx/core/djangoapps/content_libraries/models.py
+++ b/openedx/core/djangoapps/content_libraries/models.py
@@ -25,7 +25,7 @@
log = logging.getLogger(__name__)
-warnings.warn(
+warnings.warn( # noqa: B028
(
"ContentLibraryPermission model and related content library authorization "
"APIs are deprecated. See https://github.com/openedx/openedx-platform/issues/37409."
@@ -40,7 +40,7 @@ class ContentLibraryManager(models.Manager["ContentLibrary"]):
"""
Custom manager for ContentLibrary class.
"""
- def get_by_key(self, library_key) -> "ContentLibrary":
+ def get_by_key(self, library_key) -> "ContentLibrary": # noqa: UP037
"""
Get the ContentLibrary for the given LibraryLocatorV2 key.
"""
@@ -115,7 +115,7 @@ def library_key(self):
"""
return LibraryLocatorV2(org=self.org.short_name, slug=self.slug)
- def __str__(self):
+ def __str__(self): # noqa: DJ012
return f"ContentLibrary ({str(self.library_key)})"
@@ -161,6 +161,6 @@ def save(self, *args, **kwargs): # lint-amnesty, pylint: disable=arguments-diff
raise ValidationError(_("One and only one of 'user' and 'group' must be set."))
return super().save(*args, **kwargs)
- def __str__(self):
+ def __str__(self): # noqa: DJ012
who = self.user.username if self.user else self.group.name
return f"ContentLibraryPermission ({self.access_level} for {who})"
diff --git a/openedx/core/djangoapps/content_libraries/rest_api/blocks.py b/openedx/core/djangoapps/content_libraries/rest_api/blocks.py
index 27ae788e3fbd..518ac5b31fe3 100644
--- a/openedx/core/djangoapps/content_libraries/rest_api/blocks.py
+++ b/openedx/core/djangoapps/content_libraries/rest_api/blocks.py
@@ -90,7 +90,7 @@ def post(self, request, lib_key_str):
try:
result = api.create_library_block(library_key, user_id=request.user.id, **serializer.validated_data)
except api.IncompatibleTypesError as err:
- raise ValidationError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
detail={'block_type': str(err)},
)
@@ -205,7 +205,7 @@ def put(self, request, usage_key_str, file_path):
try:
result = api.add_library_block_static_asset_file(usage_key, file_path, file_content, request.user)
except ValueError:
- raise ValidationError("Invalid file path") # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError("Invalid file path") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return Response(self.serializer_class(result).data)
@convert_exceptions
@@ -220,7 +220,7 @@ def delete(self, request, usage_key_str, file_path):
try:
api.delete_library_block_static_asset_file(usage_key, file_path, request.user)
except ValueError:
- raise ValidationError("Invalid file path") # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError("Invalid file path") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return Response(status=status.HTTP_204_NO_CONTENT)
@@ -318,7 +318,7 @@ def post(self, request, usage_key_str):
try:
version_num = api.set_library_block_olx(key, new_olx_str).version_num
except ValueError as err:
- raise ValidationError(detail=str(err)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(detail=str(err)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return Response(self.serializer_class({"olx": new_olx_str, "version_num": version_num}).data)
diff --git a/openedx/core/djangoapps/content_libraries/rest_api/libraries.py b/openedx/core/djangoapps/content_libraries/rest_api/libraries.py
index 33156ee79be5..fe5f59d5c365 100644
--- a/openedx/core/djangoapps/content_libraries/rest_api/libraries.py
+++ b/openedx/core/djangoapps/content_libraries/rest_api/libraries.py
@@ -118,7 +118,7 @@
log = logging.getLogger(__name__)
-warnings.warn(
+warnings.warn( # noqa: B028
(
"Content library team authorization REST APIs are deprecated. "
"See https://github.com/openedx/openedx-platform/issues/37409."
@@ -227,7 +227,7 @@ def post(self, request):
try:
ensure_organization(org_name)
except InvalidOrganizationException:
- raise ValidationError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
detail={"org": f"No such organization '{org_name}' found."}
)
# Ensure the user is allowed to create libraries under this org
@@ -252,7 +252,7 @@ def post(self, request):
# users can then manage roles for others.
api.assign_library_role_to_user(result.key, request.user, api.AccessLevel.ADMIN_LEVEL)
except api.LibraryAlreadyExists:
- raise ValidationError(detail={"slug": "A library with that ID already exists."}) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(detail={"slug": "A library with that ID already exists."}) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return Response(ContentLibraryMetadataSerializer(result).data)
@@ -290,7 +290,7 @@ def patch(self, request, lib_key_str):
try:
api.update_library(key, **data)
except api.IncompatibleTypesError as err:
- raise ValidationError({'type': str(err)}) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError({'type': str(err)}) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
result = api.get_library(key)
return Response(ContentLibraryMetadataSerializer(result).data)
@@ -336,7 +336,7 @@ def post(self, request, lib_key_str):
try:
user = User.objects.get(email=serializer.validated_data.get('email'))
except User.DoesNotExist:
- raise ValidationError({'email': _('We could not find a user with that email address.')}) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError({'email': _('We could not find a user with that email address.')}) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
grant = api.get_library_user_permissions(key, user)
if grant:
return Response(
@@ -346,7 +346,7 @@ def post(self, request, lib_key_str):
try:
api.set_library_user_permissions(key, user, access_level=serializer.validated_data["access_level"])
except api.LibraryPermissionIntegrityError as err:
- raise ValidationError(detail=str(err)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(detail=str(err)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
grant = api.get_library_user_permissions(key, user)
return Response(ContentLibraryPermissionSerializer(grant).data)
@@ -397,7 +397,7 @@ def put(self, request, lib_key_str, username):
try:
api.set_library_user_permissions(key, user, access_level=serializer.validated_data["access_level"])
except api.LibraryPermissionIntegrityError as err:
- raise ValidationError(detail=str(err)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(detail=str(err)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
grant = api.get_library_user_permissions(key, user)
return Response(ContentLibraryPermissionSerializer(grant).data)
@@ -438,7 +438,7 @@ def delete(self, request, lib_key_str, username):
try:
api.set_library_user_permissions(key, user, access_level=None)
except api.LibraryPermissionIntegrityError as err:
- raise ValidationError(detail=str(err)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(detail=str(err)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return Response({})
@@ -627,7 +627,7 @@ def post(self, request, lib_key_str):
try:
result = api.create_library_block(library_key, user_id=request.user.id, **serializer.validated_data)
except api.IncompatibleTypesError as err:
- raise ValidationError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
detail={'block_type': str(err)},
)
diff --git a/openedx/core/djangoapps/content_libraries/rest_api/utils.py b/openedx/core/djangoapps/content_libraries/rest_api/utils.py
index 90ba99c0f7f0..97d3bf23e712 100644
--- a/openedx/core/djangoapps/content_libraries/rest_api/utils.py
+++ b/openedx/core/djangoapps/content_libraries/rest_api/utils.py
@@ -24,29 +24,29 @@ def wrapped_fn(*args, **kwargs):
return fn(*args, **kwargs)
except InvalidKeyError as exc:
log.exception(str(exc))
- raise NotFound # lint-amnesty, pylint: disable=raise-missing-from
+ raise NotFound # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except api.ContentLibraryNotFound:
log.exception("Content library not found")
- raise NotFound # lint-amnesty, pylint: disable=raise-missing-from
+ raise NotFound # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except api.ContentLibraryBlockNotFound:
log.exception("XBlock not found in content library")
- raise NotFound # lint-amnesty, pylint: disable=raise-missing-from
+ raise NotFound # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except api.ContentLibraryCollectionNotFound:
log.exception("Collection not found in content library")
- raise NotFound # lint-amnesty, pylint: disable=raise-missing-from
+ raise NotFound # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except api.ContentLibraryContainerNotFound:
log.exception("Container not found in content library")
- raise NotFound # lint-amnesty, pylint: disable=raise-missing-from
+ raise NotFound # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except api.LibraryCollectionAlreadyExists as exc:
log.exception(str(exc))
- raise ValidationError(str(exc)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(str(exc)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except api.LibraryBlockAlreadyExists as exc:
log.exception(str(exc))
- raise ValidationError(str(exc)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(str(exc)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except api.InvalidNameError as exc:
log.exception(str(exc))
- raise ValidationError(str(exc)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(str(exc)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except api.BlockLimitReachedError as exc:
log.exception(str(exc))
- raise ValidationError(str(exc)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(str(exc)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return wrapped_fn
diff --git a/openedx/core/djangoapps/content_libraries/tasks.py b/openedx/core/djangoapps/content_libraries/tasks.py
index a8fd398ad04b..bb5db0a397c1 100644
--- a/openedx/core/djangoapps/content_libraries/tasks.py
+++ b/openedx/core/djangoapps/content_libraries/tasks.py
@@ -478,7 +478,7 @@ def _copy_overrides(
if field.scope == Scope.settings and field.is_set_on(source_block):
setattr(dest_block, field.name, field.read_from(source_block))
if source_block.has_children:
- for source_child_key, dest_child_key in zip(source_block.children, dest_block.children):
+ for source_child_key, dest_child_key in zip(source_block.children, dest_block.children): # noqa: B905
_copy_overrides(
store=store,
user_id=user_id,
diff --git a/openedx/core/djangoapps/content_libraries/tests/__init__.py b/openedx/core/djangoapps/content_libraries/tests/__init__.py
index 18083ab3e0ac..880199a78ea5 100644
--- a/openedx/core/djangoapps/content_libraries/tests/__init__.py
+++ b/openedx/core/djangoapps/content_libraries/tests/__init__.py
@@ -1,4 +1,4 @@
"""
Python API for testing content libraries
"""
-from .base import *
+from .base import * # noqa: F403
diff --git a/openedx/core/djangoapps/content_libraries/tests/base.py b/openedx/core/djangoapps/content_libraries/tests/base.py
index dce317c3ec71..1ccd076ad3c1 100644
--- a/openedx/core/djangoapps/content_libraries/tests/base.py
+++ b/openedx/core/djangoapps/content_libraries/tests/base.py
@@ -380,7 +380,7 @@ def _embed_block(
if version is not None:
url += f"?version={version}"
response = self.client.get(url)
- assert response.status_code == expect_response, 'Unexpected response code {}:'.format(response.status_code)
+ assert response.status_code == expect_response, 'Unexpected response code {}:'.format(response.status_code) # noqa: UP032 # pylint: disable=line-too-long
return response.content.decode()
def _get_block_handler_url(self, block_key, handler_name):
diff --git a/openedx/core/djangoapps/content_libraries/tests/test_api.py b/openedx/core/djangoapps/content_libraries/tests/test_api.py
index bfd0657f8364..a6528c089bd0 100644
--- a/openedx/core/djangoapps/content_libraries/tests/test_api.py
+++ b/openedx/core/djangoapps/content_libraries/tests/test_api.py
@@ -139,7 +139,7 @@ def test_create_library_collection(self) -> None:
def test_create_library_collection_invalid_library(self) -> None:
library_key = LibraryLocatorV2.from_string("lib:INVALID:test-lib-does-not-exist")
- with self.assertRaises(api.ContentLibraryNotFound) as exc:
+ with self.assertRaises(api.ContentLibraryNotFound) as exc: # noqa: F841, PT027
api.create_library_collection(
library_key,
collection_key="COL4",
@@ -176,7 +176,7 @@ def test_update_library_collection(self) -> None:
)
def test_update_library_collection_wrong_library(self) -> None:
- with self.assertRaises(api.ContentLibraryCollectionNotFound) as exc:
+ with self.assertRaises(api.ContentLibraryCollectionNotFound) as exc: # noqa: F841, PT027
api.update_library_collection(
self.lib1.library_key,
self.col2.key,
@@ -299,7 +299,7 @@ def test_update_library_collection_components_event(self) -> None:
)
def test_update_collection_components_from_wrong_library(self) -> None:
- with self.assertRaises(api.ContentLibraryBlockNotFound) as exc:
+ with self.assertRaises(api.ContentLibraryBlockNotFound) as exc: # noqa: PT027
api.update_library_collection_items(
self.lib2.library_key,
self.col2.key,
@@ -451,7 +451,7 @@ def test_delete_container_when_container_does_not_exist(self) -> None:
"openedx.core.djangoapps.content_libraries.api.containers.get_container_from_key",
side_effect=Container.DoesNotExist,
), mock.patch("openedx_content.api.soft_delete_draft") as mock_soft_delete:
- with self.assertRaises(Container.DoesNotExist):
+ with self.assertRaises(Container.DoesNotExist): # noqa: PT027
api.delete_container(container_key)
mock_soft_delete.assert_not_called()
@@ -482,7 +482,7 @@ def test_delete_library_block_when_component_does_not_exist(self) -> None:
"openedx.core.djangoapps.content_libraries.api.blocks.get_component_from_usage_key",
side_effect=Component.DoesNotExist,
), mock.patch("openedx_content.api.soft_delete_draft") as mock_soft_delete:
- with self.assertRaises(Component.DoesNotExist):
+ with self.assertRaises(Component.DoesNotExist): # noqa: PT027
api.delete_library_block(usage_key)
mock_soft_delete.assert_not_called()
@@ -1294,7 +1294,7 @@ def test_import_container_no_signals_on_failure(self) -> None:
with mock.patch(
"openedx.core.djangoapps.content_libraries.api.blocks.update_container_children",
side_effect=RuntimeError("Simulated failure"),
- ), self.assertRaises(RuntimeError):
+ ), self.assertRaises(RuntimeError): # noqa: PT027
api.import_staged_content_from_user_clipboard(self.lib1.library_key, self.user)
assert event_receiver.call_count == 0
@@ -1534,7 +1534,7 @@ def test_library_creation_handles_authz_exception(
# Library creation should still succeed (the exception should be caught/handled)
# Note: Currently, the code doesn't catch this exception, so we expect it to propagate.
# This test documents the current behavior and can be updated if error handling is added.
- with self.assertRaises(Exception) as context:
+ with self.assertRaises(Exception) as context: # noqa: PT027
self._create_library("test-lib-role-4", "Test Library Role 4")
assert "AuthZ unavailable" in str(context.exception)
diff --git a/openedx/core/djangoapps/content_libraries/tests/test_containers.py b/openedx/core/djangoapps/content_libraries/tests/test_containers.py
index ef9ecf226255..37ad621d26e6 100644
--- a/openedx/core/djangoapps/content_libraries/tests/test_containers.py
+++ b/openedx/core/djangoapps/content_libraries/tests/test_containers.py
@@ -38,8 +38,8 @@ class ContainersTestCase(ContentLibrariesRestApiTest):
def setUp(self) -> None:
super().setUp()
- self.create_date = datetime(2024, 9, 8, 7, 6, 5, tzinfo=timezone.utc)
- self.modified_date = datetime(2024, 10, 9, 8, 7, 6, tzinfo=timezone.utc)
+ self.create_date = datetime(2024, 9, 8, 7, 6, 5, tzinfo=timezone.utc) # noqa: UP017
+ self.modified_date = datetime(2024, 10, 9, 8, 7, 6, tzinfo=timezone.utc) # noqa: UP017
self.lib = self._create_library(
slug="containers",
title="Container Test Library",
@@ -159,7 +159,7 @@ def test_container_crud(self, container_type, slug, display_name) -> None:
Test Create, Read, Update, and Delete of a Containers
"""
# Create container:
- create_date = datetime(2024, 9, 8, 7, 6, 5, tzinfo=timezone.utc)
+ create_date = datetime(2024, 9, 8, 7, 6, 5, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(create_date):
container_data = self._create_container(
self.lib["id"],
@@ -190,7 +190,7 @@ def test_container_crud(self, container_type, slug, display_name) -> None:
self.assertDictContainsEntries(container_as_read, expected_data)
# Update the container:
- modified_date = datetime(2024, 10, 9, 8, 7, 6, tzinfo=timezone.utc)
+ modified_date = datetime(2024, 10, 9, 8, 7, 6, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(modified_date):
container_data = self._update_container(container_id, display_name=f"New Display Name for {container_type}")
expected_data["last_draft_created"] = expected_data["modified"] = "2024-10-09T08:07:06Z"
diff --git a/openedx/core/djangoapps/content_libraries/tests/test_content_libraries.py b/openedx/core/djangoapps/content_libraries/tests/test_content_libraries.py
index a4f387f161d0..4cdb630ab410 100644
--- a/openedx/core/djangoapps/content_libraries/tests/test_content_libraries.py
+++ b/openedx/core/djangoapps/content_libraries/tests/test_content_libraries.py
@@ -308,7 +308,7 @@ def test_library_blocks(self): # pylint: disable=too-many-statements
Tests with some non-ASCII chars in slugs, titles, descriptions.
"""
- admin = UserFactory.create(username="Admin", email="admin@example.com", is_staff=True)
+ admin = UserFactory.create(username="Admin", email="admin@example.com", is_staff=True) # noqa: F841
lib = self._create_library(slug="téstlꜟط", title="A Tést Lꜟطrary", description="Tésting XBlocks")
lib_id = lib["id"]
@@ -318,7 +318,7 @@ def test_library_blocks(self): # pylint: disable=too-many-statements
assert self._get_library_blocks(lib_id)['results'] == []
# Add a 'problem' XBlock to the library:
- create_date = datetime(2024, 6, 6, 6, 6, 6, tzinfo=timezone.utc)
+ create_date = datetime(2024, 6, 6, 6, 6, 6, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(create_date):
block_data = self._add_block_to_library(lib_id, "problem", "ࠒröblæm1")
self.assertDictContainsEntries(block_data, {
@@ -338,7 +338,7 @@ def test_library_blocks(self): # pylint: disable=too-many-statements
assert self._get_library(lib_id)['has_unpublished_changes'] is True
# Publish the changes:
- publish_date = datetime(2024, 7, 7, 7, 7, 7, tzinfo=timezone.utc)
+ publish_date = datetime(2024, 7, 7, 7, 7, 7, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(publish_date):
self._commit_library_changes(lib_id)
assert self._get_library(lib_id)['has_unpublished_changes'] is False
@@ -367,7 +367,7 @@ def test_library_blocks(self): # pylint: disable=too-many-statements
""".strip()
- update_date = datetime(2024, 8, 8, 8, 8, 8, tzinfo=timezone.utc)
+ update_date = datetime(2024, 8, 8, 8, 8, 8, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(update_date):
self._set_library_block_olx(block_id, new_olx)
# now reading it back, we should get that exact OLX (no change to whitespace etc.):
@@ -409,7 +409,7 @@ def test_library_blocks(self): # pylint: disable=too-many-statements
assert self._get_library_block_olx(block_id) == new_olx
unpublished_block_data = self._get_library_block(block_id)
assert unpublished_block_data['has_unpublished_changes'] is True
- block_update_date = datetime(2024, 8, 8, 8, 8, 9, tzinfo=timezone.utc)
+ block_update_date = datetime(2024, 8, 8, 8, 8, 9, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(block_update_date):
self._publish_library_block(block_id)
# Confirm the block is now published:
@@ -432,7 +432,7 @@ def test_library_blocks_studio_view(self):
assert self._get_library_blocks(lib_id)['results'] == []
# Add a 'html' XBlock to the library:
- create_date = datetime(2024, 6, 6, 6, 6, 6, tzinfo=timezone.utc)
+ create_date = datetime(2024, 6, 6, 6, 6, 6, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(create_date):
block_data = self._add_block_to_library(lib_id, "problem", "problem1")
self.assertDictContainsEntries(block_data, {
@@ -452,7 +452,7 @@ def test_library_blocks_studio_view(self):
assert self._get_library(lib_id)['has_unpublished_changes'] is True
# Publish the changes:
- publish_date = datetime(2024, 7, 7, 7, 7, 7, tzinfo=timezone.utc)
+ publish_date = datetime(2024, 7, 7, 7, 7, 7, tzinfo=timezone.utc) # noqa: UP017
with freeze_time(publish_date):
self._commit_library_changes(lib_id)
assert self._get_library(lib_id)['has_unpublished_changes'] is False
@@ -469,7 +469,7 @@ def test_library_blocks_studio_view(self):
assert ' str:
""" Get a filename that can be used for the OLX content of this staged content """
return f"{self.suggested_url_name}.xml"
- def __str__(self):
+ def __str__(self): # noqa: DJ012
""" String representation of this instance """
return f'Staged {self.block_type} block "{self.display_name}" ({self.status})'
-class StagedContentFile(models.Model):
+class StagedContentFile(models.Model): # noqa: DJ008
"""
A data file ("Static Asset") associated with some StagedContent.
@@ -101,7 +101,7 @@ class StagedContentFile(models.Model):
md5_hash = models.CharField(max_length=32, blank=True)
-class UserClipboard(models.Model):
+class UserClipboard(models.Model): # noqa: DJ008
"""
Each user has a clipboard that can hold one item at a time, where an item
is some OLX content that can be used in a course, such as an XBlock, a Unit,
@@ -157,7 +157,7 @@ def clean(self):
f"StagedContent.purpose must be '{CLIPBOARD_PURPOSE}' to use it as clipboard content."
)
- def save(self, *args, **kwargs):
+ def save(self, *args, **kwargs): # noqa: DJ012
""" Save this model instance """
# Enforce checks on save:
self.full_clean()
diff --git a/openedx/core/djangoapps/content_staging/views.py b/openedx/core/djangoapps/content_staging/views.py
index fda65091516d..b7cf60b38c51 100644
--- a/openedx/core/djangoapps/content_staging/views.py
+++ b/openedx/core/djangoapps/content_staging/views.py
@@ -93,7 +93,7 @@ def post(self, request):
try:
usage_key = UsageKey.from_string(request.data["usage_key"])
except (ValueError, InvalidKeyError):
- raise ValidationError('Invalid usage key') # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError('Invalid usage key') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if usage_key.block_type in ('course', 'chapter', 'sequential'):
raise ValidationError('Requested XBlock tree is too large')
course_key = usage_key.context_key
diff --git a/openedx/core/djangoapps/content_tagging/api.py b/openedx/core/djangoapps/content_tagging/api.py
index 9d4fd85a753d..ed77d9516ee5 100644
--- a/openedx/core/djangoapps/content_tagging/api.py
+++ b/openedx/core/djangoapps/content_tagging/api.py
@@ -6,7 +6,7 @@
import csv
import io
from itertools import groupby
-from typing import Iterator
+from typing import Iterator # noqa: UP035
import openedx_tagging.api as oel_tagging
from django.db.models import Exists, OuterRef, Q, QuerySet
@@ -323,7 +323,7 @@ def import_course_tags_from_csv(csv_path, course_id) -> None:
Import tags from a csv file generated on export.
"""
# Open csv file and extract the tags
- with open(csv_path, 'r') as csv_file:
+ with open(csv_path, 'r') as csv_file: # noqa: UP015
csv_reader = csv.DictReader(csv_file)
tags_in_blocks = list(csv_reader)
diff --git a/openedx/core/djangoapps/content_tagging/apps.py b/openedx/core/djangoapps/content_tagging/apps.py
index de52da36780b..92fef25069b1 100644
--- a/openedx/core/djangoapps/content_tagging/apps.py
+++ b/openedx/core/djangoapps/content_tagging/apps.py
@@ -13,4 +13,4 @@ class ContentTaggingConfig(AppConfig):
def ready(self):
# Connect signal handlers
- from . import handlers # pylint: disable=unused-import
+ from . import handlers # pylint: disable=unused-import # noqa: F401
diff --git a/openedx/core/djangoapps/content_tagging/helpers/objecttag_export_helpers.py b/openedx/core/djangoapps/content_tagging/helpers/objecttag_export_helpers.py
index cb7865e136c6..0c3a6d994eba 100644
--- a/openedx/core/djangoapps/content_tagging/helpers/objecttag_export_helpers.py
+++ b/openedx/core/djangoapps/content_tagging/helpers/objecttag_export_helpers.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-from typing import Any, Callable, Iterator, Union
+from typing import Any, Callable, Iterator, Union # noqa: UP035
from attrs import define
from opaque_keys.edx.keys import CourseKey, UsageKey
@@ -141,7 +141,7 @@ def build_object_tree_with_objecttags(
"""
Returns the object with the tags associated with it.
"""
- get_tagged_children: Union[
+ get_tagged_children: Union[ # noqa: UP007
# _get_course_tagged_object_and_children type
Callable[[library_api.LibraryXBlockMetadata, dict[str, dict[int, list[Any]]]], tuple[TaggedContent, None]],
# _get_library_block_tagged_object type
diff --git a/openedx/core/djangoapps/content_tagging/models/__init__.py b/openedx/core/djangoapps/content_tagging/models/__init__.py
index 4f0729e12e52..6ddfa23fefbe 100644
--- a/openedx/core/djangoapps/content_tagging/models/__init__.py
+++ b/openedx/core/djangoapps/content_tagging/models/__init__.py
@@ -1,4 +1,4 @@
"""
Content Tagging and System defined models
"""
-from .base import TaxonomyOrg
+from .base import TaxonomyOrg # noqa: F401
diff --git a/openedx/core/djangoapps/content_tagging/models/base.py b/openedx/core/djangoapps/content_tagging/models/base.py
index dcdf5bc6844a..6779a6008e16 100644
--- a/openedx/core/djangoapps/content_tagging/models/base.py
+++ b/openedx/core/djangoapps/content_tagging/models/base.py
@@ -10,7 +10,7 @@
from organizations.models import Organization
-class TaxonomyOrg(models.Model):
+class TaxonomyOrg(models.Model): # noqa: DJ008
"""
Represents the many-to-many relationship between Taxonomies and Organizations.
diff --git a/openedx/core/djangoapps/content_tagging/rest_api/v1/tests/test_views.py b/openedx/core/djangoapps/content_tagging/rest_api/v1/tests/test_views.py
index 46a0b78e73f6..35f209f8a7e1 100644
--- a/openedx/core/djangoapps/content_tagging/rest_api/v1/tests/test_views.py
+++ b/openedx/core/djangoapps/content_tagging/rest_api/v1/tests/test_views.py
@@ -338,7 +338,7 @@ def _test_list_taxonomy(
response = self.client.get(url, query_params, format="json")
assert response.status_code == status.HTTP_200_OK
- self.assertEqual(set(t["name"] for t in response.data["results"]), set(expected_taxonomies))
+ self.assertEqual(set(t["name"] for t in response.data["results"]), set(expected_taxonomies)) # noqa: PT009
def test_list_taxonomy_staff(self) -> None:
"""
@@ -452,7 +452,7 @@ def test_list_taxonomy_pagination(
assert response.status_code == status.HTTP_200_OK if len(expected_taxonomies) > 0 else status.HTTP_404_NOT_FOUND
if status.is_success(response.status_code):
- self.assertEqual(set(t["name"] for t in response.data["results"]), set(expected_taxonomies))
+ self.assertEqual(set(t["name"] for t in response.data["results"]), set(expected_taxonomies)) # noqa: PT009
parsed_url = urlparse(response.data["next"])
next_page = parse_qs(parsed_url.query).get("page", [None])[0]
@@ -1651,7 +1651,7 @@ def test_tag_library_objects_with_manage_library_tags_permission(
self.client.force_authenticate(user=self.library_userA)
response = self._call_put_request(object_id, self.tA1.pk, ["Tag 1"])
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
mock_is_user_allowed.assert_called_with(
self.library_userA.username,
authz_permissions.MANAGE_LIBRARY_TAGS.identifier,
@@ -1999,7 +1999,7 @@ def test_object_tags_query_count(
user_attr: str,
object_attr: str,
expected_queries: int,
- expected_perm: bool = True):
+ expected_perm: bool = True): # noqa: PT028
"""
Test how many queries are used when retrieving object tags and permissions
"""
@@ -2108,25 +2108,25 @@ def get_url(self, course_key):
def test_authorized_user_can_access(self):
"""User with COURSE_STAFF role can access."""
resp = self.authorized_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_unauthorized_user_cannot_access(self):
"""User without role cannot access."""
resp = self.unauthorized_client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_role_scoped_to_course(self):
"""Authorization should only apply to the assigned course."""
other_course = self.store.create_course("OtherOrg", "OtherCourse", "Run", self.staff.id)
resp = self.authorized_client.get(self.get_url(other_course.id))
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_staff_user_allowed_via_legacy(self):
"""Staff users should still pass through legacy fallback."""
self.client.force_authenticate(user=self.staff)
resp = self.client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
def test_superuser_allowed(self):
"""Superusers should always be allowed."""
@@ -2134,7 +2134,7 @@ def test_superuser_allowed(self):
client = APIClient()
client.force_authenticate(user=superuser)
resp = client.get(self.get_url(self.course_key))
- self.assertEqual(resp.status_code, status.HTTP_200_OK)
+ self.assertEqual(resp.status_code, status.HTTP_200_OK) # noqa: PT009
@skip_unless_cms
@ddt.ddt
diff --git a/openedx/core/djangoapps/content_tagging/rest_api/v1/views.py b/openedx/core/djangoapps/content_tagging/rest_api/v1/views.py
index 854183eef491..a52a8810b547 100644
--- a/openedx/core/djangoapps/content_tagging/rest_api/v1/views.py
+++ b/openedx/core/djangoapps/content_tagging/rest_api/v1/views.py
@@ -190,7 +190,7 @@ def get(self, request: RestRequest, **kwargs) -> StreamingHttpResponse:
Export a CSV with all children and tags for a given course/context.
"""
- class Echo(object):
+ class Echo(object): # noqa: UP004
"""
Class that implements just the write method of the file-like interface,
used for the streaming response.
diff --git a/openedx/core/djangoapps/content_tagging/rules.py b/openedx/core/djangoapps/content_tagging/rules.py
index e20cb401c688..3b70076189ef 100644
--- a/openedx/core/djangoapps/content_tagging/rules.py
+++ b/openedx/core/djangoapps/content_tagging/rules.py
@@ -26,7 +26,7 @@
from .models import TaxonomyOrg
from .utils import check_taxonomy_context_key_org, get_context_key_from_key_string, rules_cache
-UserType = Union[django.contrib.auth.models.User, django.contrib.auth.models.AnonymousUser]
+UserType = Union[django.contrib.auth.models.User, django.contrib.auth.models.AnonymousUser] # noqa: UP007
def is_org_admin(user: UserType, orgs: list[Organization] | None = None) -> bool:
diff --git a/openedx/core/djangoapps/content_tagging/tests/test_api.py b/openedx/core/djangoapps/content_tagging/tests/test_api.py
index 1561bdf695b4..a3d965cef1c7 100644
--- a/openedx/core/djangoapps/content_tagging/tests/test_api.py
+++ b/openedx/core/djangoapps/content_tagging/tests/test_api.py
@@ -447,18 +447,18 @@ def test_export_tags_in_csv_file(self) -> None:
file_path = os.path.join(file_dir_name, file_name)
- self.assertTrue(os.path.exists(file_path))
+ self.assertTrue(os.path.exists(file_path)) # noqa: PT009
- with open(file_path, 'r') as f:
+ with open(file_path, 'r') as f: # noqa: UP015
content = f.read()
cleaned_content = content.replace('\r\n', '\n')
cleaned_expected_csv = self.expected_csv.replace('\r\n', '\n')
- self.assertEqual(cleaned_content, cleaned_expected_csv)
+ self.assertEqual(cleaned_content, cleaned_expected_csv) # noqa: PT009
def test_import_tags_invalid_format(self) -> None:
csv_path = self._create_csv_file('invalid format, Invalid\r\ntest1, test2')
- with self.assertRaises(ValueError) as exc:
+ with self.assertRaises(ValueError) as exc: # noqa: PT027
api.import_course_tags_from_csv(csv_path, self.course.id)
assert "Invalid format of csv in" in str(exc.exception)
diff --git a/openedx/core/djangoapps/content_tagging/tests/test_objecttag_export_helpers.py b/openedx/core/djangoapps/content_tagging/tests/test_objecttag_export_helpers.py
index 11eaa9389e2f..f5525f530628 100644
--- a/openedx/core/djangoapps/content_tagging/tests/test_objecttag_export_helpers.py
+++ b/openedx/core/djangoapps/content_tagging/tests/test_objecttag_export_helpers.py
@@ -279,7 +279,7 @@ def setUp(self):
untagged_sequential.children.append(untagged_vertical)
# /Untagged blocks
- vertical = BlockFactory.create(
+ vertical = BlockFactory.create( # noqa: F841
parent=self.sequential,
category="vertical",
display_name="test vertical1",
diff --git a/openedx/core/djangoapps/content_tagging/tests/test_rules.py b/openedx/core/djangoapps/content_tagging/tests/test_rules.py
index 019310ef46dc..4432310147c7 100644
--- a/openedx/core/djangoapps/content_tagging/tests/test_rules.py
+++ b/openedx/core/djangoapps/content_tagging/tests/test_rules.py
@@ -656,7 +656,7 @@ def test_change_objecttag_objectid_with_manage_library_tags_permission(self, moc
result = can_change_object_tag_objectid(self.library_user, str(self.library_key))
- self.assertTrue(result)
+ self.assertTrue(result) # noqa: PT009
mock_is_user_allowed.assert_called_once_with(
self.library_user.username,
authz_permissions.MANAGE_LIBRARY_TAGS.identifier,
@@ -673,7 +673,7 @@ def test_change_objecttag_objectid_without_manage_library_tags_but_org_admin(sel
result = can_change_object_tag_objectid(self.org_admin, str(self.library_key))
- self.assertTrue(result)
+ self.assertTrue(result) # noqa: PT009
@patch("openedx_authz.api.is_user_allowed")
def test_change_objecttag_objectid_without_permissions(self, mock_is_user_allowed):
@@ -685,7 +685,7 @@ def test_change_objecttag_objectid_without_permissions(self, mock_is_user_allowe
result = can_change_object_tag_objectid(self.regular_user, str(self.library_key))
- self.assertFalse(result)
+ self.assertFalse(result) # noqa: PT009
@patch("openedx_authz.api.is_user_allowed")
def test_remove_objecttag_objectid_with_manage_library_tags_permission(self, mock_is_user_allowed):
@@ -697,7 +697,7 @@ def test_remove_objecttag_objectid_with_manage_library_tags_permission(self, moc
result = can_remove_object_tag_objectid(self.library_user, str(self.library_key))
- self.assertTrue(result)
+ self.assertTrue(result) # noqa: PT009
mock_is_user_allowed.assert_called_once_with(
self.library_user.username,
authz_permissions.MANAGE_LIBRARY_TAGS.identifier,
@@ -714,7 +714,7 @@ def test_remove_objecttag_objectid_without_manage_library_tags_but_org_admin(sel
result = can_remove_object_tag_objectid(self.org_admin, str(self.library_key))
- self.assertTrue(result)
+ self.assertTrue(result) # noqa: PT009
@patch("openedx_authz.api.is_user_allowed")
def test_remove_objecttag_objectid_without_permissions(self, mock_is_user_allowed):
@@ -726,20 +726,20 @@ def test_remove_objecttag_objectid_without_permissions(self, mock_is_user_allowe
result = can_remove_object_tag_objectid(self.regular_user, str(self.library_key))
- self.assertFalse(result)
+ self.assertFalse(result) # noqa: PT009
def test_invalid_library_key(self):
"""
Test that invalid library keys return False.
"""
- self.assertFalse(can_change_object_tag_objectid(self.library_user, "invalid_key"))
- self.assertFalse(can_remove_object_tag_objectid(self.library_user, "invalid_key"))
+ self.assertFalse(can_change_object_tag_objectid(self.library_user, "invalid_key")) # noqa: PT009
+ self.assertFalse(can_remove_object_tag_objectid(self.library_user, "invalid_key")) # noqa: PT009
def test_empty_object_id(self):
"""
Test behavior with empty object_id.
"""
- self.assertTrue(can_change_object_tag_objectid(self.library_user, ""))
+ self.assertTrue(can_change_object_tag_objectid(self.library_user, "")) # noqa: PT009
- with self.assertRaises(ValueError):
+ with self.assertRaises(ValueError): # noqa: PT027
can_remove_object_tag_objectid(self.library_user, "")
diff --git a/openedx/core/djangoapps/content_tagging/types.py b/openedx/core/djangoapps/content_tagging/types.py
index ab2f56c53a75..2c4aac1690cb 100644
--- a/openedx/core/djangoapps/content_tagging/types.py
+++ b/openedx/core/djangoapps/content_tagging/types.py
@@ -3,15 +3,15 @@
"""
from __future__ import annotations
-from typing import Dict, List, Union
+from typing import Dict, List, Union # noqa: UP035
from opaque_keys.edx.keys import CollectionKey, ContainerKey, CourseKey, UsageKey
from opaque_keys.edx.locator import LibraryLocatorV2
from openedx_tagging.models import Taxonomy
-ContentKey = Union[LibraryLocatorV2, CourseKey, UsageKey, CollectionKey, ContainerKey]
-ContextKey = Union[LibraryLocatorV2, CourseKey]
+ContentKey = Union[LibraryLocatorV2, CourseKey, UsageKey, CollectionKey, ContainerKey] # noqa: UP007
+ContextKey = Union[LibraryLocatorV2, CourseKey] # noqa: UP007
-TagValuesByTaxonomyIdDict = Dict[int, List[str]]
-TagValuesByObjectIdDict = Dict[str, TagValuesByTaxonomyIdDict]
-TaxonomyDict = Dict[int, Taxonomy]
+TagValuesByTaxonomyIdDict = Dict[int, List[str]] # noqa: UP006
+TagValuesByObjectIdDict = Dict[str, TagValuesByTaxonomyIdDict] # noqa: UP006
+TaxonomyDict = Dict[int, Taxonomy] # noqa: UP006
diff --git a/openedx/core/djangoapps/contentserver/test/test_contentserver.py b/openedx/core/djangoapps/contentserver/test/test_contentserver.py
index df29b64d2781..63f79a748967 100644
--- a/openedx/core/djangoapps/contentserver/test/test_contentserver.py
+++ b/openedx/core/djangoapps/contentserver/test/test_contentserver.py
@@ -32,7 +32,7 @@
log = logging.getLogger(__name__)
TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
-TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex
+TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex # noqa: UP031
TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT
FAKE_MD5_HASH = 'ffffffffffffffffffffffffffffffff'
@@ -300,7 +300,7 @@ def test_range_request_full_file(self):
assert resp.status_code == 206
# HTTP_206_PARTIAL_CONTENT
assert resp['Content-Range'] ==\
- 'bytes {first}-{last}/{length}'.format(first=0, last=(self.length_unlocked - 1),
+ 'bytes {first}-{last}/{length}'.format(first=0, last=(self.length_unlocked - 1), # noqa: UP032
length=self.length_unlocked)
assert resp['Content-Length'] == str(self.length_unlocked)
@@ -312,12 +312,12 @@ def test_range_request_partial_file(self):
"""
first_byte = self.length_unlocked // 4
last_byte = self.length_unlocked // 2
- resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes={first}-{last}'.format(
+ resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes={first}-{last}'.format( # noqa: UP032
first=first_byte, last=last_byte))
assert resp.status_code == 206
# HTTP_206_PARTIAL_CONTENT
- assert resp['Content-Range'] == 'bytes {first}-{last}/{length}'.format(first=first_byte,
+ assert resp['Content-Range'] == 'bytes {first}-{last}/{length}'.format(first=first_byte, # noqa: UP032
last=last_byte,
length=self.length_unlocked)
assert resp['Content-Length'] == str((last_byte - first_byte) + 1)
@@ -328,7 +328,7 @@ def test_range_request_multiple_ranges(self):
"""
first_byte = self.length_unlocked / 4
last_byte = self.length_unlocked / 2
- resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes={first}-{last}, -100'.format(
+ resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes={first}-{last}, -100'.format( # noqa: UP032
first=first_byte, last=last_byte))
assert resp.status_code == 200
@@ -354,7 +354,7 @@ def test_range_request_malformed_invalid_range(self):
Test that a range request with malformed Range (first_byte > last_byte) outputs
416 Requested Range Not Satisfiable.
"""
- resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes={first}-{last}'.format(
+ resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes={first}-{last}'.format( # noqa: UP032
first=(self.length_unlocked // 2), last=(self.length_unlocked // 4)))
assert resp.status_code == 416
@@ -363,7 +363,7 @@ def test_range_request_malformed_out_of_bounds(self):
Test that a range request with malformed Range (first_byte, last_byte == totalLength, offset by 1 error)
outputs 416 Requested Range Not Satisfiable.
"""
- resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes={first}-{last}'.format(
+ resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes={first}-{last}'.format( # noqa: UP032
first=(self.length_unlocked), last=(self.length_unlocked)))
assert resp.status_code == 416
@@ -526,6 +526,6 @@ def test_valid_syntax(self, header_value, excepted_ranges_length, expected_range
)
@ddt.unpack
def test_invalid_syntax(self, header_value, exception_class, exception_message_regex):
- self.assertRaisesRegex(
+ self.assertRaisesRegex( # noqa: PT027
exception_class, exception_message_regex, views.parse_range_header, header_value, self.content_length
)
diff --git a/openedx/core/djangoapps/contentserver/views.py b/openedx/core/djangoapps/contentserver/views.py
index 7225c256b024..8cd3e9ccd770 100644
--- a/openedx/core/djangoapps/contentserver/views.py
+++ b/openedx/core/djangoapps/contentserver/views.py
@@ -169,7 +169,7 @@ def process_request(request):
if 0 <= first <= last < content.length:
# If the byte range is satisfiable
response = HttpResponse(content.stream_data_in_range(first, last))
- response['Content-Range'] = 'bytes {first}-{last}/{length}'.format(
+ response['Content-Range'] = 'bytes {first}-{last}/{length}'.format( # noqa: UP032
first=first, last=last, length=content.length
)
response['Content-Length'] = str(last - first + 1)
@@ -226,7 +226,7 @@ def set_caching_headers(content, location, response):
set_custom_attribute('contentserver.cacheable', True)
response['Expires'] = get_expiration_value(datetime.datetime.utcnow(), cache_ttl)
- response['Cache-Control'] = "public, max-age={ttl}, s-maxage={ttl}".format(ttl=cache_ttl)
+ response['Cache-Control'] = "public, max-age={ttl}, s-maxage={ttl}".format(ttl=cache_ttl) # noqa: UP032
elif is_restricted:
set_custom_attribute('contentserver.cacheable', False)
diff --git a/openedx/core/djangoapps/cors_csrf/tests/test_authentication.py b/openedx/core/djangoapps/cors_csrf/tests/test_authentication.py
index 3baa9b710f50..237e341bcd8d 100644
--- a/openedx/core/djangoapps/cors_csrf/tests/test_authentication.py
+++ b/openedx/core/djangoapps/cors_csrf/tests/test_authentication.py
@@ -31,7 +31,7 @@ def setUp(self):
def test_perform_csrf_referer_check(self):
request = self._fake_request()
- with self.assertRaisesRegex(PermissionDenied, 'CSRF'):
+ with self.assertRaisesRegex(PermissionDenied, 'CSRF'): # noqa: PT027
self.auth.enforce_csrf(request)
@patch.dict(settings.FEATURES, {
diff --git a/openedx/core/djangoapps/cors_csrf/tests/test_middleware.py b/openedx/core/djangoapps/cors_csrf/tests/test_middleware.py
index 7f7e7869596c..9262dcec7f53 100644
--- a/openedx/core/djangoapps/cors_csrf/tests/test_middleware.py
+++ b/openedx/core/djangoapps/cors_csrf/tests/test_middleware.py
@@ -271,7 +271,7 @@ def _assert_cookie_sent(self, response, is_set):
assert self.COOKIE_NAME in response.cookies
cookie_header = str(response.cookies[self.COOKIE_NAME])
- expected = 'Set-Cookie: {name}={value}; Domain={domain};'.format(
+ expected = 'Set-Cookie: {name}={value}; Domain={domain};'.format( # noqa: UP032
name=self.COOKIE_NAME,
value=self.COOKIE_VALUE,
domain=self.COOKIE_DOMAIN
diff --git a/openedx/core/djangoapps/course_apps/apps.py b/openedx/core/djangoapps/course_apps/apps.py
index 87c1bde6ad47..32f9646af9f5 100644
--- a/openedx/core/djangoapps/course_apps/apps.py
+++ b/openedx/core/djangoapps/course_apps/apps.py
@@ -25,4 +25,4 @@ class CourseAppsConfig(AppConfig):
def ready(self):
# Connect signal handlers
- from . import handlers # pylint: disable=unused-import
+ from . import handlers # pylint: disable=unused-import # noqa: F401
diff --git a/openedx/core/djangoapps/course_apps/models.py b/openedx/core/djangoapps/course_apps/models.py
index f23c9b606f0e..d1100bf365ec 100644
--- a/openedx/core/djangoapps/course_apps/models.py
+++ b/openedx/core/djangoapps/course_apps/models.py
@@ -1,7 +1,7 @@
"""
Models to store course apps data.
"""
-from typing import Dict
+from typing import Dict # noqa: UP035
from django.db import models
from model_utils.models import TimeStampedModel
@@ -27,7 +27,7 @@ def __str__(self):
return f'CourseAppStatus(course_key="{self.course_key}", app_id="{self.app_id}", enabled="{self.enabled})"'
@classmethod
- def get_all_app_status_data_for_course(cls, course_key: CourseKey) -> Dict[str, bool]:
+ def get_all_app_status_data_for_course(cls, course_key: CourseKey) -> Dict[str, bool]: # noqa: UP006
"""
Get a dictionary containing the status of all apps linked to the course.
diff --git a/openedx/core/djangoapps/course_apps/plugins.py b/openedx/core/djangoapps/course_apps/plugins.py
index 0249dacb74ad..0a416310853f 100644
--- a/openedx/core/djangoapps/course_apps/plugins.py
+++ b/openedx/core/djangoapps/course_apps/plugins.py
@@ -2,7 +2,7 @@
Course Apps plugin base class and plugin manager.
"""
from abc import ABC, abstractmethod
-from typing import Dict, Iterator, Optional
+from typing import Dict, Iterator, Optional # noqa: UP035
from edx_django_utils.plugins import PluginManager
from opaque_keys.edx.keys import CourseKey
@@ -23,7 +23,7 @@ class CourseApp(ABC):
# A description for the app.
description: str = ""
# A map of documentation links for the app
- documentation_links: Dict = {
+ documentation_links: Dict = { # noqa: UP006
# eg:
# "learn_more_configuration": "https://..."
}
@@ -60,7 +60,7 @@ def is_enabled(cls, course_key: CourseKey) -> bool:
@classmethod
@abstractmethod
- def set_enabled(cls, course_key: CourseKey, enabled: bool, user: 'User') -> bool:
+ def set_enabled(cls, course_key: CourseKey, enabled: bool, user: 'User') -> bool: # noqa: F821
"""
Update the status of this app for the provided course and return the new status.
@@ -75,7 +75,7 @@ def set_enabled(cls, course_key: CourseKey, enabled: bool, user: 'User') -> bool
@classmethod
@abstractmethod
- def get_allowed_operations(cls, course_key: CourseKey, user: Optional['User'] = None) -> Dict[str, bool]:
+ def get_allowed_operations(cls, course_key: CourseKey, user: Optional['User'] = None) -> Dict[str, bool]: # noqa: F821, UP006 # pylint: disable=line-too-long
"""
Returns a dictionary of available operations for this app.
diff --git a/openedx/core/djangoapps/course_apps/rest_api/v1/views.py b/openedx/core/djangoapps/course_apps/rest_api/v1/views.py
index cef3790ca319..6c34376cdcaf 100644
--- a/openedx/core/djangoapps/course_apps/rest_api/v1/views.py
+++ b/openedx/core/djangoapps/course_apps/rest_api/v1/views.py
@@ -1,6 +1,6 @@
# pylint: disable=missing-module-docstring
import logging
-from typing import Dict
+from typing import Dict # noqa: UP035
from django.contrib.auth import get_user_model
from edx_api_doc_tools import path_parameter, schema
@@ -70,7 +70,7 @@ class CourseAppSerializer(serializers.Serializer): # pylint: disable=abstract-m
help_text="What all operations are supported by the app.",
)
- def to_representation(self, instance: CourseApp) -> Dict:
+ def to_representation(self, instance: CourseApp) -> Dict: # noqa: UP006
course_key = self.context.get("course_key")
request = self.context.get("request")
app_status = self.context.get("app_status")
diff --git a/openedx/core/djangoapps/course_apps/tests/test_proctoring_app.py b/openedx/core/djangoapps/course_apps/tests/test_proctoring_app.py
index 08ee2bef7107..b00356e432a5 100644
--- a/openedx/core/djangoapps/course_apps/tests/test_proctoring_app.py
+++ b/openedx/core/djangoapps/course_apps/tests/test_proctoring_app.py
@@ -59,7 +59,7 @@ def test_proctoring_app_set_enabled(self):
"""
Test that setting enable status on proctoring app should raise exception.
"""
- with self.assertRaisesRegex(ValueError, "Proctoring cannot be enabled/disabled via this API."):
+ with self.assertRaisesRegex(ValueError, "Proctoring cannot be enabled/disabled via this API."): # noqa: PT027
ProctoringCourseApp().set_enabled(
course_key=self.course.id,
enabled=True,
diff --git a/openedx/core/djangoapps/course_apps/tests/utils.py b/openedx/core/djangoapps/course_apps/tests/utils.py
index 962593ee425c..7a5e7ed16f73 100644
--- a/openedx/core/djangoapps/course_apps/tests/utils.py
+++ b/openedx/core/djangoapps/course_apps/tests/utils.py
@@ -1,7 +1,7 @@
"""
Test utilities for course apps.
"""
-from typing import Type
+from typing import Type # noqa: UP035
from opaque_keys.edx.keys import CourseKey
@@ -17,7 +17,7 @@ def make_test_course_app(
name: str = "Test Course App",
description: str = "Test Course App Description",
is_available: bool = True,
-) -> Type[CourseApp]:
+) -> Type[CourseApp]: # noqa: UP006
"""
Creates a test plugin entrypoint based on provided parameters."""
@@ -47,7 +47,7 @@ def get_allowed_operations(cls, course_key, user=None): # pylint=disable=unused
}
@classmethod
- def set_enabled(cls, course_key: CourseKey, enabled: bool, user: 'User') -> bool:
+ def set_enabled(cls, course_key: CourseKey, enabled: bool, user: 'User') -> bool: # noqa: F821
cls._enabled[course_key] = enabled
return enabled
diff --git a/openedx/core/djangoapps/course_date_signals/apps.py b/openedx/core/djangoapps/course_date_signals/apps.py
index 97a6580eee0c..9de060de0056 100644
--- a/openedx/core/djangoapps/course_date_signals/apps.py
+++ b/openedx/core/djangoapps/course_date_signals/apps.py
@@ -12,4 +12,4 @@ def ready(self):
"""
Connect handlers to signals.
"""
- from . import handlers # lint-amnesty, pylint: disable=unused-import, unused-variable
+ from . import handlers # lint-amnesty, pylint: disable=unused-import, unused-variable # noqa: F401
diff --git a/openedx/core/djangoapps/course_date_signals/handlers.py b/openedx/core/djangoapps/course_date_signals/handlers.py
index 50001cc82f0f..435a446edf7e 100644
--- a/openedx/core/djangoapps/course_date_signals/handlers.py
+++ b/openedx/core/djangoapps/course_date_signals/handlers.py
@@ -33,12 +33,12 @@ def _field_values(fields, xblock):
try:
result[field.name] = field.read_from(xblock)
except TypeError as exception:
- exception_message = "{message}, Block-location:{location}, Field-name:{field_name}".format(
+ exception_message = "{message}, Block-location:{location}, Field-name:{field_name}".format( # noqa: UP032 # pylint: disable=line-too-long
message=str(exception),
location=str(xblock.location),
field_name=field.name
)
- raise TypeError(exception_message) # lint-amnesty, pylint: disable=raise-missing-from
+ raise TypeError(exception_message) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return result
diff --git a/openedx/core/djangoapps/course_date_signals/tests.py b/openedx/core/djangoapps/course_date_signals/tests.py
index d9e8801923ec..8478f69faee1 100644
--- a/openedx/core/djangoapps/course_date_signals/tests.py
+++ b/openedx/core/djangoapps/course_date_signals/tests.py
@@ -128,7 +128,7 @@ def test_sequence_with_graded_and_ungraded_assignments(self):
(graded_problem_1.location, {'due': 5}),
]
sequence = self.store.get_item(sequence.location)
- self.assertCountEqual(_gather_graded_items(sequence, 5), expected_graded_items)
+ self.assertCountEqual(_gather_graded_items(sequence, 5), expected_graded_items) # noqa: PT009
def test_sequence_with_ora_and_non_ora_assignments(self):
"""
@@ -159,7 +159,7 @@ def test_sequence_with_ora_and_non_ora_assignments(self):
(graded_problem_1.location, {'due': 5}),
]
sequence = self.store.get_item(sequence.location)
- self.assertCountEqual(_gather_graded_items(sequence, 5), expected_graded_items)
+ self.assertCountEqual(_gather_graded_items(sequence, 5), expected_graded_items) # noqa: PT009
def test_get_custom_pacing_children(self):
"""
@@ -179,7 +179,7 @@ def test_get_custom_pacing_children(self):
(vertical3.location, {'due': timedelta(weeks=2)})
]
sequence = self.store.get_item(sequence.location)
- self.assertCountEqual(_get_custom_pacing_children(sequence, 2), expected_dates)
+ self.assertCountEqual(_get_custom_pacing_children(sequence, 2), expected_dates) # noqa: PT009
with self.store.bulk_operations(self.course.id):
# A subsection with multiple units, each of which has a problem.
@@ -191,19 +191,19 @@ def test_get_custom_pacing_children(self):
(problem2.location, {'due': timedelta(weeks=2)})
])
sequence = self.store.get_item(sequence.location)
- self.assertCountEqual(_get_custom_pacing_children(sequence, 2), expected_dates)
+ self.assertCountEqual(_get_custom_pacing_children(sequence, 2), expected_dates) # noqa: PT009
# A subsection that has ORA as a problem. ORA should not inherit due date.
BlockFactory.create(parent=vertical3, category='openassessment')
sequence = self.store.get_item(sequence.location)
- self.assertCountEqual(_get_custom_pacing_children(sequence, 2), expected_dates)
+ self.assertCountEqual(_get_custom_pacing_children(sequence, 2), expected_dates) # noqa: PT009
# A subsection that has an ORA problem and a non ORA problem. ORA should
# not inherit due date, but non ORA problems should.
problem3 = BlockFactory(parent=vertical3, category='problem')
expected_dates.append((problem3.location, {'due': timedelta(weeks=2)}))
sequence = self.store.get_item(sequence.location)
- self.assertCountEqual(_get_custom_pacing_children(sequence, 2), expected_dates)
+ self.assertCountEqual(_get_custom_pacing_children(sequence, 2), expected_dates) # noqa: PT009
class SelfPacedCustomDueDateTests(ModuleStoreTestCase):
@@ -239,7 +239,7 @@ def test_extract_dates_from_course_inheritance(self):
(problem.location, {'due': timedelta(days=21)})
]
course = self.store.get_item(self.course.location)
- self.assertCountEqual(extract_dates_from_course(course), expected_dates)
+ self.assertCountEqual(extract_dates_from_course(course), expected_dates) # noqa: PT009
@override_waffle_flag(CUSTOM_RELATIVE_DATES, active=True)
def test_extract_dates_from_course_custom_and_default_pls_one_subsection(self):
@@ -260,7 +260,7 @@ def test_extract_dates_from_course_custom_and_default_pls_one_subsection(self):
(sequential.location, {'due': timedelta(days=21)})
]
course = self.store.get_item(self.course.location)
- self.assertCountEqual(extract_dates_from_course(course), expected_dates)
+ self.assertCountEqual(extract_dates_from_course(course), expected_dates) # noqa: PT009
@override_waffle_flag(CUSTOM_RELATIVE_DATES, active=True)
def test_extract_dates_from_course_custom_and_default_pls_one_subsection_graded(self):
@@ -294,7 +294,7 @@ def test_extract_dates_from_course_custom_and_default_pls_one_subsection_graded(
]
course = self.store.get_item(self.course.location)
with patch.object(utils, 'get_expected_duration', return_value=timedelta(weeks=6)):
- self.assertCountEqual(extract_dates_from_course(course), expected_dates)
+ self.assertCountEqual(extract_dates_from_course(course), expected_dates) # noqa: PT009
@override_waffle_flag(CUSTOM_RELATIVE_DATES, active=True)
def test_extract_dates_from_course_custom_and_default_pls_multiple_subsections_graded(self):
@@ -335,7 +335,7 @@ def test_extract_dates_from_course_custom_and_default_pls_multiple_subsections_g
course = self.store.get_item(self.course.location)
with patch.object(utils, 'get_expected_duration', return_value=timedelta(weeks=8)):
- self.assertCountEqual(extract_dates_from_course(course), expected_dates)
+ self.assertCountEqual(extract_dates_from_course(course), expected_dates) # noqa: PT009
@override_waffle_flag(CUSTOM_RELATIVE_DATES, active=True)
def test_extract_dates_from_course_all_subsections(self):
@@ -356,7 +356,7 @@ def test_extract_dates_from_course_all_subsections(self):
(sequential3.location, {'due': timedelta(days=35)})
]
course = self.store.get_item(self.course.location)
- self.assertCountEqual(extract_dates_from_course(course), expected_dates)
+ self.assertCountEqual(extract_dates_from_course(course), expected_dates) # noqa: PT009
@override_waffle_flag(CUSTOM_RELATIVE_DATES, active=True)
def test_extract_dates_from_course_no_subsections(self):
@@ -369,4 +369,4 @@ def test_extract_dates_from_course_no_subsections(self):
BlockFactory.create(category='sequential', parent=self.chapter)
expected_dates = [(self.course.location, {})]
course = self.store.get_item(self.course.location)
- self.assertCountEqual(extract_dates_from_course(course), expected_dates)
+ self.assertCountEqual(extract_dates_from_course(course), expected_dates) # noqa: PT009
diff --git a/openedx/core/djangoapps/course_groups/cohorts.py b/openedx/core/djangoapps/course_groups/cohorts.py
index 4766dd1a9f73..a3cfe38086d8 100644
--- a/openedx/core/djangoapps/course_groups/cohorts.py
+++ b/openedx/core/djangoapps/course_groups/cohorts.py
@@ -397,7 +397,7 @@ def add_cohort(course_key, name, assignment_type):
try:
course = get_course_by_id(course_key)
except Http404:
- raise ValueError("Invalid course_key") # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValueError("Invalid course_key") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
cohort = CourseCohort.create(
cohort_name=name,
@@ -439,7 +439,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(f"User {username_or_email} was not present in cohort {cohort}") # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValueError(f"User {username_or_email} was not present in cohort {cohort}") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def add_user_to_cohort(cohort, username_or_email_or_user):
@@ -514,7 +514,7 @@ def add_user_to_cohort(cohort, username_or_email_or_user):
if "@" in username_or_email_or_user: # lint-amnesty, pylint: disable=no-else-raise
raise invalid
else:
- raise ex # lint-amnesty, pylint: disable=raise-missing-from
+ raise ex # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def get_group_info_for_cohort(cohort, use_cached=False):
diff --git a/openedx/core/djangoapps/course_groups/models.py b/openedx/core/djangoapps/course_groups/models.py
index 1e18378fbd27..21f2f42c8945 100644
--- a/openedx/core/djangoapps/course_groups/models.py
+++ b/openedx/core/djangoapps/course_groups/models.py
@@ -51,7 +51,7 @@ class CourseUserGroup(models.Model):
class Meta:
unique_together = (('name', 'course_id'), )
- name = models.CharField(max_length=255,
+ name = models.CharField(max_length=255, # noqa: DJ012
help_text=("What is the name of this group? "
"Must be unique within a course."))
users = models.ManyToManyField(User, db_index=True, related_name='course_groups',
@@ -87,11 +87,11 @@ def create(cls, name, course_id, group_type=COHORT):
name=name
)
- def __str__(self):
+ def __str__(self): # noqa: DJ012
return self.name
-class CohortMembership(models.Model):
+class CohortMembership(models.Model): # noqa: DJ008
"""
Used internally to enforce our particular definition of uniqueness.
@@ -142,7 +142,7 @@ def assign(cls, cohort, user):
membership.course_user_group.users.add(user)
previous_cohort = None
elif membership.course_user_group == cohort:
- raise ValueError("User {user_name} already present in cohort {cohort_name}".format(
+ raise ValueError("User {user_name} already present in cohort {cohort_name}".format( # noqa: UP032
user_name=user.username,
cohort_name=cohort.name))
else:
@@ -164,7 +164,7 @@ def assign(cls, cohort, user):
membership.save()
return membership, previous_cohort
- def save(self, *args, **kwargs):
+ def save(self, *args, **kwargs): # noqa: DJ012
self.full_clean(validate_unique=False)
# .. event_implemented_name: COHORT_MEMBERSHIP_CHANGED
@@ -202,7 +202,7 @@ def remove_user_from_cohort(sender, instance, **kwargs): # pylint: disable=unus
instance.course_user_group.save()
-class CourseUserGroupPartitionGroup(models.Model):
+class CourseUserGroupPartitionGroup(models.Model): # noqa: DJ008
"""
Create User Partition Info.
@@ -219,7 +219,7 @@ class CourseUserGroupPartitionGroup(models.Model):
updated_at = models.DateTimeField(auto_now=True)
-class CourseCohortsSettings(models.Model):
+class CourseCohortsSettings(models.Model): # noqa: DJ008
"""
This model represents cohort settings for courses.
The only non-deprecated fields are `is_cohorted` and `course_id`.
@@ -235,7 +235,7 @@ class CourseCohortsSettings(models.Model):
help_text="Which course are these settings associated with?",
)
- _cohorted_discussions = models.TextField(db_column='cohorted_discussions', null=True, blank=True) # JSON list
+ _cohorted_discussions = models.TextField(db_column='cohorted_discussions', null=True, blank=True) # JSON list # noqa: DJ001 # pylint: disable=line-too-long
# Note that although a default value is specified here for always_cohort_inline_discussions (False),
# in reality the default value at the time that cohorting is enabled for a course comes from
@@ -260,7 +260,7 @@ def cohorted_discussions(self, value):
self._cohorted_discussions = json.dumps(value)
-class CourseCohort(models.Model):
+class CourseCohort(models.Model): # noqa: DJ008
"""
This model represents cohort related info.
@@ -296,7 +296,7 @@ def create(cls, cohort_name=None, course_id=None, course_user_group=None, assign
return course_cohort
-class UnregisteredLearnerCohortAssignments(DeletableByUserValue, models.Model):
+class UnregisteredLearnerCohortAssignments(DeletableByUserValue, models.Model): # noqa: DJ008
"""
Tracks the assignment of an unregistered learner to a course's cohort.
@@ -308,6 +308,6 @@ class UnregisteredLearnerCohortAssignments(DeletableByUserValue, models.Model):
class Meta:
unique_together = (('course_id', 'email'), )
- course_user_group = models.ForeignKey(CourseUserGroup, on_delete=models.CASCADE)
+ course_user_group = models.ForeignKey(CourseUserGroup, on_delete=models.CASCADE) # noqa: DJ012
email = models.CharField(blank=True, max_length=255, db_index=True)
course_id = CourseKeyField(max_length=255)
diff --git a/openedx/core/djangoapps/course_groups/rest_api/tests/test_views.py b/openedx/core/djangoapps/course_groups/rest_api/tests/test_views.py
index a3b1505aa389..fb22189eb866 100644
--- a/openedx/core/djangoapps/course_groups/rest_api/tests/test_views.py
+++ b/openedx/core/djangoapps/course_groups/rest_api/tests/test_views.py
@@ -62,26 +62,26 @@ def test_list_content_groups_returns_json(self, mock_perm):
response = self.api_client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response['Content-Type'], 'application/json')
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response['Content-Type'], 'application/json') # noqa: PT009
data = response.json()
- self.assertIn('id', data)
- self.assertIn('groups', data)
- self.assertIn('studio_content_groups_link', data)
+ self.assertIn('id', data) # noqa: PT009
+ self.assertIn('groups', data) # noqa: PT009
+ self.assertIn('studio_content_groups_link', data) # noqa: PT009
# Verify partition ID is returned
- self.assertEqual(data['id'], 50)
+ self.assertEqual(data['id'], 50) # noqa: PT009
# Verify groups
groups = data['groups']
- self.assertEqual(len(groups), 2)
- self.assertEqual(groups[0]['name'], 'Content Group A')
- self.assertEqual(groups[1]['name'], 'Content Group B')
+ self.assertEqual(len(groups), 2) # noqa: PT009
+ self.assertEqual(groups[0]['name'], 'Content Group A') # noqa: PT009
+ self.assertEqual(groups[1]['name'], 'Content Group B') # noqa: PT009
# Verify full Studio URL
expected_studio_url = self._get_expected_studio_url()
- self.assertEqual(data['studio_content_groups_link'], expected_studio_url)
+ self.assertEqual(data['studio_content_groups_link'], expected_studio_url) # noqa: PT009
@patch('lms.djangoapps.instructor.permissions.InstructorPermission.has_permission')
def test_list_content_groups_filters_non_cohort_partitions(self, mock_perm):
@@ -111,12 +111,12 @@ def test_list_content_groups_filters_non_cohort_partitions(self, mock_perm):
data = response.json()
# Verify cohort partition ID is returned
- self.assertEqual(data['id'], 50)
+ self.assertEqual(data['id'], 50) # noqa: PT009
# Only groups from cohort partition should be returned
groups = data['groups']
- self.assertEqual(len(groups), 1)
- self.assertEqual(groups[0]['name'], 'Group A')
+ self.assertEqual(len(groups), 1) # noqa: PT009
+ self.assertEqual(groups[0]['name'], 'Group A') # noqa: PT009
@override_settings(MFE_CONFIG={"STUDIO_BASE_URL": TEST_STUDIO_BASE_URL})
@patch('lms.djangoapps.instructor.permissions.InstructorPermission.has_permission')
@@ -129,18 +129,18 @@ def test_list_returns_empty_groups_when_none_exist(self, mock_perm):
data = response.json()
# ID should be null when no partition exists
- self.assertIsNone(data['id'])
- self.assertEqual(len(data['groups']), 0)
+ self.assertIsNone(data['id']) # noqa: PT009
+ self.assertEqual(len(data['groups']), 0) # noqa: PT009
# Verify full Studio URL
expected_studio_url = self._get_expected_studio_url()
- self.assertEqual(data['studio_content_groups_link'], expected_studio_url)
+ self.assertEqual(data['studio_content_groups_link'], expected_studio_url) # noqa: PT009
def test_list_requires_authentication(self):
"""Verify endpoint requires authentication"""
client = APIClient()
response = client.get(self._get_url())
- self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
+ self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]) # noqa: PT009
@patch('lms.djangoapps.instructor.permissions.InstructorPermission.has_permission')
def test_list_invalid_course_key_returns_400(self, mock_perm):
@@ -148,7 +148,7 @@ def test_list_invalid_course_key_returns_400(self, mock_perm):
mock_perm.return_value = True
response = self.api_client.get('/api/cohorts/v2/courses/course-v1:invalid+course+key/group_configurations')
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
@skip_unless_lms
@@ -189,13 +189,13 @@ def test_get_configuration_details(self, mock_perm):
response = self.api_client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
data = response.json()
- self.assertEqual(data['id'], 50)
- self.assertEqual(data['name'], 'Test Content Groups')
- self.assertEqual(data['scheme'], COHORT_SCHEME)
- self.assertEqual(len(data['groups']), 2)
+ self.assertEqual(data['id'], 50) # noqa: PT009
+ self.assertEqual(data['name'], 'Test Content Groups') # noqa: PT009
+ self.assertEqual(data['scheme'], COHORT_SCHEME) # noqa: PT009
+ self.assertEqual(len(data['groups']), 2) # noqa: PT009
@skip_unless_lms
@@ -223,10 +223,10 @@ def test_staff_user_can_access(self, mock_perm):
client.force_authenticate(user=self.staff_user)
response = client.get(self._get_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_unauthenticated_user_denied(self):
"""Verify unauthenticated users are denied"""
client = APIClient()
response = client.get(self._get_url())
- self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
+ self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]) # noqa: PT009
diff --git a/openedx/core/djangoapps/course_groups/tests/helpers.py b/openedx/core/djangoapps/course_groups/tests/helpers.py
index abe917d8dcb6..8c43038a0049 100644
--- a/openedx/core/djangoapps/course_groups/tests/helpers.py
+++ b/openedx/core/djangoapps/course_groups/tests/helpers.py
@@ -105,8 +105,8 @@ def config_course_cohorts(
course,
is_cohorted,
discussion_division_scheme=CourseDiscussionSettings.COHORT,
- auto_cohorts=[],
- manual_cohorts=[],
+ auto_cohorts=[], # noqa: B006
+ manual_cohorts=[], # noqa: B006
):
"""
Set and configure cohorts for a course.
diff --git a/openedx/core/djangoapps/course_groups/tests/test_cohorts.py b/openedx/core/djangoapps/course_groups/tests/test_cohorts.py
index c18524b38668..1873e00769e9 100644
--- a/openedx/core/djangoapps/course_groups/tests/test_cohorts.py
+++ b/openedx/core/djangoapps/course_groups/tests/test_cohorts.py
@@ -239,7 +239,7 @@ def test_cannot_set_assignment_type(self):
assert cohorts.get_assignment_type(cohort) == CourseCohort.RANDOM
exception_msg = "There must be one cohort to which students can automatically be assigned."
- with pytest.raises(ValueError) as context_manager:
+ with pytest.raises(ValueError) as context_manager: # noqa: PT011
cohorts.set_assignment_type(cohort, CourseCohort.MANUAL)
assert exception_msg == str(context_manager.value)
@@ -647,7 +647,7 @@ def test_set_cohorted_with_invalid_data_type(self):
"""
course = modulestore().get_course(self.toy_course_key)
- with pytest.raises(ValueError) as value_error:
+ with pytest.raises(ValueError) as value_error: # noqa: PT011
cohorts.set_course_cohorted(course.id, 'not a boolean')
assert 'Cohorted must be a boolean' == str(value_error.value)
diff --git a/openedx/core/djangoapps/course_groups/tests/test_events.py b/openedx/core/djangoapps/course_groups/tests/test_events.py
index 055dc94106dd..b86406b4a98f 100644
--- a/openedx/core/djangoapps/course_groups/tests/test_events.py
+++ b/openedx/core/djangoapps/course_groups/tests/test_events.py
@@ -97,7 +97,7 @@ def test_send_cohort_membership_changed_event(self):
user=self.user,
)
- self.assertTrue(self.receiver_called)
+ self.assertTrue(self.receiver_called) # noqa: PT009
assert_dict_contains_subset(
self,
{
diff --git a/openedx/core/djangoapps/course_groups/tests/test_filters.py b/openedx/core/djangoapps/course_groups/tests/test_filters.py
index 3ae8ff14c7b6..22bb473d5a16 100755
--- a/openedx/core/djangoapps/course_groups/tests/test_filters.py
+++ b/openedx/core/djangoapps/course_groups/tests/test_filters.py
@@ -118,7 +118,7 @@ def test_cohort_change_filter_executed(self):
cohort_membership, _ = CohortMembership.assign(cohort=self.second_cohort, user=self.user)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
{"cohort_info": "Changed from Cohort FirstCohort to Cohort SecondCohort"},
cohort_membership.user.profile.get_meta(),
)
@@ -145,7 +145,7 @@ def test_cohort_assignment_filter_executed(self):
cohort_membership, _ = CohortMembership.assign(user=self.user, cohort=self.second_cohort, )
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
{"cohort_info": "User assigned to Cohort SecondCohort"},
cohort_membership.user.profile.get_meta(),
)
@@ -170,7 +170,7 @@ def test_cohort_change_filter_prevent_move(self):
"""
CohortMembership.assign(cohort=self.first_cohort, user=self.user)
- with self.assertRaises(CohortChangeNotAllowed):
+ with self.assertRaises(CohortChangeNotAllowed): # noqa: PT027
CohortMembership.assign(cohort=self.second_cohort, user=self.user)
@override_settings(
@@ -191,7 +191,7 @@ def test_cohort_assignment_filter_prevent_move(self):
- CohortAssignmentRequested is triggered and executes TestStopAssignmentChangeStep.
- The user can't be assigned to the cohort.
"""
- with self.assertRaises(CohortAssignmentNotAllowed):
+ with self.assertRaises(CohortAssignmentNotAllowed): # noqa: PT027
CohortMembership.assign(cohort=self.second_cohort, user=self.user)
@override_settings(OPEN_EDX_FILTERS_CONFIG={})
@@ -207,7 +207,7 @@ def test_cohort_change_without_filter_configuration(self):
cohort_membership, _ = CohortMembership.assign(cohort=self.second_cohort, user=self.user)
- self.assertEqual({}, cohort_membership.user.profile.get_meta())
+ self.assertEqual({}, cohort_membership.user.profile.get_meta()) # noqa: PT009
@override_settings(OPEN_EDX_FILTERS_CONFIG={})
def test_cohort_assignment_without_filter_configuration(self):
@@ -220,4 +220,4 @@ def test_cohort_assignment_without_filter_configuration(self):
"""
cohort_membership, _ = CohortMembership.assign(cohort=self.second_cohort, user=self.user)
- self.assertEqual({}, cohort_membership.user.profile.get_meta())
+ self.assertEqual({}, cohort_membership.user.profile.get_meta()) # noqa: PT009
diff --git a/openedx/core/djangoapps/course_groups/tests/test_partition_scheme.py b/openedx/core/djangoapps/course_groups/tests/test_partition_scheme.py
index dc047ee6b535..57e5fcd49a59 100644
--- a/openedx/core/djangoapps/course_groups/tests/test_partition_scheme.py
+++ b/openedx/core/djangoapps/course_groups/tests/test_partition_scheme.py
@@ -231,7 +231,7 @@ def test_missing_group(self):
with patch('openedx.core.djangoapps.course_groups.partition_scheme.log') as mock_log:
self.assert_student_in_group(None, new_user_partition)
assert mock_log.warning.called
- self.assertRegex(mock_log.warning.call_args[0][0], 'group not found')
+ self.assertRegex(mock_log.warning.call_args[0][0], 'group not found') # noqa: PT009
def test_missing_partition(self):
"""
@@ -256,7 +256,7 @@ def test_missing_partition(self):
with patch('openedx.core.djangoapps.course_groups.partition_scheme.log') as mock_log:
self.assert_student_in_group(None, new_user_partition)
assert mock_log.warning.called
- self.assertRegex(mock_log.warning.call_args[0][0], 'partition mismatch')
+ self.assertRegex(mock_log.warning.call_args[0][0], 'partition mismatch') # noqa: PT009
class TestExtension(django.test.TestCase):
@@ -267,7 +267,7 @@ class TestExtension(django.test.TestCase):
def test_get_scheme(self):
assert UserPartition.get_scheme('cohort') == CohortPartitionScheme
- with self.assertRaisesRegex(UserPartitionError, 'Unrecognized scheme'):
+ with self.assertRaisesRegex(UserPartitionError, 'Unrecognized scheme'): # noqa: PT027
UserPartition.get_scheme('other')
diff --git a/openedx/core/djangoapps/course_groups/tests/test_views.py b/openedx/core/djangoapps/course_groups/tests/test_views.py
index 7fe2f5fae759..ed109cea653f 100644
--- a/openedx/core/djangoapps/course_groups/tests/test_views.py
+++ b/openedx/core/djangoapps/course_groups/tests/test_views.py
@@ -94,7 +94,7 @@ def _verify_non_staff_cannot_access(self, view, request_method, view_args):
request = RequestFactory().request()
request.user = self.non_staff_user
view_args.insert(0, request)
- self.assertRaises(Http404, view, *view_args)
+ self.assertRaises(Http404, view, *view_args) # noqa: PT027
def get_handler(self, course, cohort=None, expected_response_code=200, handler=cohort_handler, user=None):
"""
@@ -998,7 +998,7 @@ def test_delimiters(self):
"""
unknown = "unknown_user"
response_dict = self.request_add_users_to_cohort(
- " {} {}\t{}, \r\n{}".format(
+ " {} {}\t{}, \r\n{}".format( # noqa: UP032
unknown,
self.cohort1_users[0].username,
self.cohort2_users[0].username,
diff --git a/openedx/core/djangoapps/course_groups/urls.py b/openedx/core/djangoapps/course_groups/urls.py
index 46fb0db85d80..508bb4650561 100644
--- a/openedx/core/djangoapps/course_groups/urls.py
+++ b/openedx/core/djangoapps/course_groups/urls.py
@@ -11,28 +11,28 @@
urlpatterns = [
re_path(
- r'^v1/settings/{}$'.format(
+ r'^v1/settings/{}$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
openedx.core.djangoapps.course_groups.views.CohortSettings.as_view(),
name='cohort_settings',
),
re_path(
- r'^v1/courses/{}/cohorts/(?P[0-9]+)?$'.format(
+ r'^v1/courses/{}/cohorts/(?P[0-9]+)?$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
openedx.core.djangoapps.course_groups.views.CohortHandler.as_view(),
name='cohort_handler',
),
re_path(
- r'^v1/courses/{}/cohorts/(?P[0-9]+)/users/(?P.+)?$'.format(
+ r'^v1/courses/{}/cohorts/(?P[0-9]+)/users/(?P.+)?$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
openedx.core.djangoapps.course_groups.views.CohortUsers.as_view(),
name='cohort_users',
),
re_path(
- r'^v1/courses/{}/users?$'.format(
+ r'^v1/courses/{}/users?$'.format( # noqa: UP032
settings.COURSE_KEY_PATTERN,
),
lms.djangoapps.instructor.views.api.CohortCSV.as_view(),
diff --git a/openedx/core/djangoapps/course_groups/views.py b/openedx/core/djangoapps/course_groups/views.py
index ad9d973af3da..8806e9649ecb 100644
--- a/openedx/core/djangoapps/course_groups/views.py
+++ b/openedx/core/djangoapps/course_groups/views.py
@@ -313,7 +313,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("Cohort (ID {cohort_id}) not found for {course_key_string}".format( # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404("Cohort (ID {cohort_id}) not found for {course_key_string}".format( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904, UP032
cohort_id=cohort_id,
course_key_string=course_key_string
))
@@ -518,7 +518,7 @@ def put(self, request, course_key_string):
try:
cohorts.set_course_cohorted(course_key, request.data.get('is_cohorted'))
except ValueError as err:
- raise self.api_error(status.HTTP_400_BAD_REQUEST, err)
+ raise self.api_error(status.HTTP_400_BAD_REQUEST, err) # noqa: B904
return _get_cohort_settings_response(course_key)
@@ -663,7 +663,7 @@ def patch(self, request, course_key_string, cohort_id=None):
try:
cohorts.set_assignment_type(cohort, assignment_type)
except ValueError as e:
- raise self.api_error(status.HTTP_400_BAD_REQUEST, str(e), 'last-random-cohort')
+ raise self.api_error(status.HTTP_400_BAD_REQUEST, str(e), 'last-random-cohort') # noqa: B904
# Handle group_id and user_partition_id for content group association
if has_group_id:
@@ -770,11 +770,11 @@ def _get_course_and_cohort(self, request, course_key_string, cohort_id):
try:
cohort = cohorts.get_cohort_by_id(course_key, cohort_id)
except CourseUserGroup.DoesNotExist:
- msg = 'Cohort (ID {cohort_id}) not found for {course_key_string}'.format(
+ msg = 'Cohort (ID {cohort_id}) not found for {course_key_string}'.format( # noqa: UP032
cohort_id=cohort_id,
course_key_string=course_key_string
)
- raise self.api_error(status.HTTP_404_NOT_FOUND, msg, 'cohort-not-found') # lint-amnesty, pylint: disable=raise-missing-from
+ raise self.api_error(status.HTTP_404_NOT_FOUND, msg, 'cohort-not-found') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return course_key, cohort
def get(self, request, course_key_string, cohort_id, username=None): # pylint: disable=unused-argument
@@ -807,9 +807,9 @@ def delete(self, request, course_key_string, cohort_id, username=None):
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') # lint-amnesty, pylint: disable=raise-missing-from
+ raise self.api_error(status.HTTP_404_NOT_FOUND, 'User does not exist.', 'user-not-found') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except CohortMembership.DoesNotExist: # pylint: disable=duplicate-except
- raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from
+ raise self.api_error( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
status.HTTP_400_BAD_REQUEST,
'User not assigned to the given cohort.',
'user-not-in-cohort'
diff --git a/openedx/core/djangoapps/course_live/plugins.py b/openedx/core/djangoapps/course_live/plugins.py
index 9facb8e6bc4b..b95c28bdfa27 100644
--- a/openedx/core/djangoapps/course_live/plugins.py
+++ b/openedx/core/djangoapps/course_live/plugins.py
@@ -1,7 +1,7 @@
"""
Course app configuration for live.
"""
-from typing import Dict, Optional
+from typing import Dict, Optional # noqa: UP035
from django.conf import settings
from django.contrib.auth import get_user_model
@@ -57,7 +57,7 @@ def set_enabled(cls, course_key: CourseKey, enabled: bool, user: User) -> bool:
return configuration.enabled
@classmethod
- def get_allowed_operations(cls, course_key: CourseKey, user: Optional[User] = None) -> Dict[str, bool]:
+ def get_allowed_operations(cls, course_key: CourseKey, user: Optional[User] = None) -> Dict[str, bool]: # noqa: UP006, UP045 # pylint: disable=line-too-long
"""
Return allowed operations for live app.
"""
diff --git a/openedx/core/djangoapps/course_live/providers.py b/openedx/core/djangoapps/course_live/providers.py
index 76e8728e19a5..f36cf8d18d47 100644
--- a/openedx/core/djangoapps/course_live/providers.py
+++ b/openedx/core/djangoapps/course_live/providers.py
@@ -2,7 +2,7 @@
LTI Providers for course live module
"""
from abc import ABC
-from typing import Dict, List
+from typing import Dict, List # noqa: UP035
from django.conf import settings
@@ -13,10 +13,10 @@ class LiveProvider(ABC):
"""
id: str
name: str
- features: List[str] = []
+ features: List[str] = [] # noqa: UP006
requires_username: bool = False
requires_email: bool = False
- additional_parameters: List[str] = []
+ additional_parameters: List[str] = [] # noqa: UP006
@property
def has_free_tier(self) -> bool:
@@ -67,7 +67,7 @@ class HasGlobalCredentials(ABC):
url: str
@staticmethod
- def get_global_keys() -> Dict:
+ def get_global_keys() -> Dict: # noqa: UP006
"""
Get keys from settings
"""
@@ -122,7 +122,7 @@ def is_enabled(self) -> bool:
return True
@staticmethod
- def get_global_keys() -> Dict:
+ def get_global_keys() -> Dict: # noqa: UP006
"""
Get keys from settings
"""
@@ -148,13 +148,13 @@ class ProviderManager:
"""
This class provides access to all available provider objects
"""
- providers: Dict[str, LiveProvider]
+ providers: Dict[str, LiveProvider] # noqa: UP006
def __init__(self):
# auto detect live providers.
self.providers = {provider.id: provider() for provider in LiveProvider.__subclasses__()}
- def get_enabled_providers(self) -> Dict[str, LiveProvider]:
+ def get_enabled_providers(self) -> Dict[str, LiveProvider]: # noqa: UP006
"""
Get Enabled providers
"""
diff --git a/openedx/core/djangoapps/course_live/tests/test_views.py b/openedx/core/djangoapps/course_live/tests/test_views.py
index 25063b07b97f..495dfccc969a 100644
--- a/openedx/core/djangoapps/course_live/tests/test_views.py
+++ b/openedx/core/djangoapps/course_live/tests/test_views.py
@@ -78,7 +78,7 @@ def test_pii_sharing_not_allowed(self):
Test response if PII sharing is not allowed
"""
response = self._get()
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
expected_data = {
'course_key': None,
'provider_type': '',
@@ -92,7 +92,7 @@ def test_pii_sharing_not_allowed(self):
'free_tier': False,
'pii_sharing_allowed': False
}
- self.assertEqual(response.data, expected_data)
+ self.assertEqual(response.data, expected_data) # noqa: PT009
def test_pii_sharing_is_allowed(self):
"""
@@ -100,7 +100,7 @@ def test_pii_sharing_is_allowed(self):
"""
CourseAllowPIISharingInLTIFlag.objects.create(course_id=self.course.id, enabled=True)
response = self._get()
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
expected_data = {
'enabled': True,
'course_key': None,
@@ -115,7 +115,7 @@ def test_pii_sharing_is_allowed(self):
'provider_type': ''
}
content = json.loads(response.content.decode('utf-8'))
- self.assertEqual(content, expected_data)
+ self.assertEqual(content, expected_data) # noqa: PT009
@ddt.data(('zoom', False, False), ('big_blue_button', False, True))
@ddt.unpack
@@ -126,26 +126,26 @@ def test_create_configurations_data(self, provider, share_email, share_username)
lti_config, data, response = self.create_course_live_config(provider)
course_live_configurations = CourseLiveConfiguration.get(self.course.id)
lti_configuration = course_live_configurations.get(self.course.id).lti_configuration
- self.assertEqual(self.course.id, course_live_configurations.course_key)
- self.assertEqual(data['enabled'], course_live_configurations.enabled)
- self.assertEqual(data['provider_type'], course_live_configurations.provider_type)
+ self.assertEqual(self.course.id, course_live_configurations.course_key) # noqa: PT009
+ self.assertEqual(data['enabled'], course_live_configurations.enabled) # noqa: PT009
+ self.assertEqual(data['provider_type'], course_live_configurations.provider_type) # noqa: PT009
- self.assertEqual(lti_config['lti_1p1_client_key'], lti_configuration.lti_1p1_client_key)
- self.assertEqual(lti_config['lti_1p1_client_secret'], lti_configuration.lti_1p1_client_secret)
- self.assertEqual(lti_config['lti_1p1_launch_url'], lti_configuration.lti_1p1_launch_url)
+ self.assertEqual(lti_config['lti_1p1_client_key'], lti_configuration.lti_1p1_client_key) # noqa: PT009
+ self.assertEqual(lti_config['lti_1p1_client_secret'], lti_configuration.lti_1p1_client_secret) # noqa: PT009
+ self.assertEqual(lti_config['lti_1p1_launch_url'], lti_configuration.lti_1p1_launch_url) # noqa: PT009
provider_instance = ProviderManager().get_enabled_providers().get(provider)
additional_param = {'additional_parameters': {}}
if provider_instance.additional_parameters:
additional_param = {'additional_parameters': {'custom_instructor_email': 'email@example.com'}}
- self.assertEqual({
+ self.assertEqual({ # noqa: PT009
'pii_share_username': share_username,
'pii_share_email': share_email,
**additional_param
}, lti_configuration.lti_config)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
@ddt.data(('zoom', False, False), ('big_blue_button', False, True))
@ddt.unpack
@@ -174,26 +174,26 @@ def test_update_configurations_data(self, provider, share_email, share_username)
live_configurations = CourseLiveConfiguration.get(self.course.id)
lti_configuration = live_configurations.get(self.course.id).lti_configuration
- self.assertEqual(self.course.id, live_configurations.course_key)
- self.assertEqual(updated_data['enabled'], live_configurations.enabled)
- self.assertEqual(updated_data['provider_type'], live_configurations.provider_type)
+ self.assertEqual(self.course.id, live_configurations.course_key) # noqa: PT009
+ self.assertEqual(updated_data['enabled'], live_configurations.enabled) # noqa: PT009
+ self.assertEqual(updated_data['provider_type'], live_configurations.provider_type) # noqa: PT009
- self.assertEqual(updated_lti_config.get('lti_1p1_client_key'), lti_configuration.lti_1p1_client_key)
- self.assertEqual(lti_config.get('lti_1p1_client_secret'), lti_configuration.lti_1p1_client_secret)
- self.assertEqual(updated_lti_config.get('lti_1p1_launch_url'), lti_configuration.lti_1p1_launch_url)
+ self.assertEqual(updated_lti_config.get('lti_1p1_client_key'), lti_configuration.lti_1p1_client_key) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(lti_config.get('lti_1p1_client_secret'), lti_configuration.lti_1p1_client_secret) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertEqual(updated_lti_config.get('lti_1p1_launch_url'), lti_configuration.lti_1p1_launch_url) # noqa: PT009 # pylint: disable=line-too-long
provider_instance = ProviderManager().get_enabled_providers().get(provider)
additional_param = {'additional_parameters': {}}
if provider_instance.additional_parameters:
additional_param = updated_lti_config.get('lti_config')
- self.assertEqual({
+ self.assertEqual({ # noqa: PT009
'pii_share_username': share_username,
'pii_share_email': share_email,
**additional_param
}, lti_configuration.lti_config)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
@ddt.data(('zoom', False, False), ('big_blue_button', False, True))
@ddt.unpack
@@ -227,8 +227,8 @@ def test_create_configurations_response(self, provider, share_email, share_usern
}
content = json.loads(response.content.decode('utf-8'))
- self.assertEqual(response.status_code, 200)
- self.assertEqual(content, expected_data)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(content, expected_data) # noqa: PT009
@ddt.data(('zoom', False, False), ('big_blue_button', False, True))
@ddt.unpack
@@ -253,7 +253,7 @@ def test_update_configurations_response(self, provider, share_email, share_usern
}
response = self._post(updated_data)
content = json.loads(response.content.decode('utf-8'))
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
provider_instance = ProviderManager().get_enabled_providers().get(provider)
additional_param = {'additional_parameters': {}}
@@ -277,7 +277,7 @@ def test_update_configurations_response(self, provider, share_email, share_usern
},
'pii_sharing_allowed': share_email or share_username
}
- self.assertEqual(content, expected_data)
+ self.assertEqual(content, expected_data) # noqa: PT009
def test_post_error_messages(self):
"""
@@ -289,8 +289,8 @@ def test_post_error_messages(self):
expected_data = {
'provider_type': ['This field is required.'],
}
- self.assertEqual(content, expected_data)
- self.assertEqual(response.status_code, 400)
+ self.assertEqual(content, expected_data) # noqa: PT009
+ self.assertEqual(response.status_code, 400) # noqa: PT009
def test_non_staff_user_access(self):
"""
@@ -299,13 +299,13 @@ def test_non_staff_user_access(self):
self.user = self.create_user_for_course(self.course, user_type=CourseUserType.UNENROLLED)
response = self._get()
content = json.loads(response.content.decode('utf-8'))
- self.assertEqual(response.status_code, 403)
- self.assertEqual(content, {'detail': 'You do not have permission to perform this action.'})
+ self.assertEqual(response.status_code, 403) # noqa: PT009
+ self.assertEqual(content, {'detail': 'You do not have permission to perform this action.'}) # noqa: PT009
response = self._post({})
content = json.loads(response.content.decode('utf-8'))
- self.assertEqual(response.status_code, 403)
- self.assertEqual(content, {'detail': 'You do not have permission to perform this action.'})
+ self.assertEqual(response.status_code, 403) # noqa: PT009
+ self.assertEqual(content, {'detail': 'You do not have permission to perform this action.'}) # noqa: PT009
def test_courseware_api_has_live_tab(self):
"""
@@ -316,7 +316,7 @@ def test_courseware_api_has_live_tab(self):
response = self.client.get(url)
content = json.loads(response.content.decode('utf-8'))
data = next((tab for tab in content['tabs'] if tab['tab_id'] == 'lti_live'), None)
- self.assertEqual(data, {
+ self.assertEqual(data, { # noqa: PT009
'tab_id': 'lti_live',
'title': 'Live',
'url': f'http://learning-mfe/course/{self.course.id}/live'
@@ -350,8 +350,8 @@ def test_create_configurations_response_free_tier(self, provider, share_email, s
}
content = json.loads(response.content.decode('utf-8'))
- self.assertEqual(response.status_code, 200)
- self.assertEqual(content, expected_data)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(content, expected_data) # noqa: PT009
class TestCourseLiveProvidersView(ModuleStoreTestCase, APITestCase):
@@ -384,7 +384,7 @@ def test_response_has_correct_data(self):
}
response = self.client.get(self.url)
content = json.loads(response.content.decode('utf-8'))
- self.assertEqual(content, expected_data)
+ self.assertEqual(content, expected_data) # noqa: PT009
class TestCourseLiveIFrameView(ModuleStoreTestCase, APITestCase):
@@ -430,9 +430,9 @@ def test_api_returns_live_iframe(self):
)
live_config.save()
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
- self.assertIsInstance(response.data['iframe'], Markup)
- self.assertIn('iframe', str(response.data['iframe']))
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertIsInstance(response.data['iframe'], Markup) # noqa: PT009
+ self.assertIn('iframe', str(response.data['iframe'])) # noqa: PT009
def test_non_authenticated_user(self):
"""
@@ -440,7 +440,7 @@ def test_non_authenticated_user(self):
"""
self.client.logout()
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 401)
+ self.assertEqual(response.status_code, 401) # noqa: PT009
def test_not_enrolled_user(self):
"""
@@ -448,7 +448,7 @@ def test_not_enrolled_user(self):
"""
self.user = self.create_user_for_course(self.course, user_type=CourseUserType.UNENROLLED)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 403)
+ self.assertEqual(response.status_code, 403) # noqa: PT009
def test_live_configuration_disabled(self):
"""
@@ -460,4 +460,4 @@ def test_live_configuration_disabled(self):
provider_type="zoom",
)
response = self.client.get(self.url)
- self.assertEqual(response.data['developer_message'], 'Course live is not enabled for this course.')
+ self.assertEqual(response.data['developer_message'], 'Course live is not enabled for this course.') # noqa: PT009 # pylint: disable=line-too-long
diff --git a/openedx/core/djangoapps/course_live/views.py b/openedx/core/djangoapps/course_live/views.py
index 59e8459134cd..a25358571f4c 100644
--- a/openedx/core/djangoapps/course_live/views.py
+++ b/openedx/core/djangoapps/course_live/views.py
@@ -1,7 +1,7 @@
"""
View for course live app
"""
-from typing import Dict
+from typing import Dict # noqa: UP035
import edx_api_doc_tools as apidocs
from edx_rest_framework_extensions.auth.jwt.authentication import JwtAuthentication
@@ -193,7 +193,7 @@ def get(self, request, course_id: str, **_kwargs) -> Response:
return Response(data)
@staticmethod
- def get_provider_data(course_id: str) -> Dict:
+ def get_provider_data(course_id: str) -> Dict: # noqa: UP006
"""
Get provider data for specified course
Args:
diff --git a/openedx/core/djangoapps/courseware_api/tests/pacts/views.py b/openedx/core/djangoapps/courseware_api/tests/pacts/views.py
index c7a6c2400c0d..345f9aaa42c1 100644
--- a/openedx/core/djangoapps/courseware_api/tests/pacts/views.py
+++ b/openedx/core/djangoapps/courseware_api/tests/pacts/views.py
@@ -129,7 +129,7 @@ def provider_state(request):
state = request_body.get('state')
if state in state_setup_mapping:
- print('Setting up provider state for state value: {}'.format(state))
+ print('Setting up provider state for state value: {}'.format(state)) # noqa: UP032
state_setup_mapping[state](request)
return JsonResponse({'result': state})
diff --git a/openedx/core/djangoapps/courseware_api/tests/test_views.py b/openedx/core/djangoapps/courseware_api/tests/test_views.py
index b921d26e8b2a..2d44fefdf2bf 100644
--- a/openedx/core/djangoapps/courseware_api/tests/test_views.py
+++ b/openedx/core/djangoapps/courseware_api/tests/test_views.py
@@ -181,7 +181,7 @@ def test_enrolled_course_metadata(self, logged_in, enrollment_mode):
request = RequestFactory().request()
cert_url = get_certificate_url(course_id=self.course.id, uuid=cert.verify_uuid)
linkedin_url_params = {
- 'name': '{platform_name} Verified Certificate for {course_name}'.format(
+ 'name': '{platform_name} Verified Certificate for {course_name}'.format( # noqa: UP032
platform_name=settings.PLATFORM_NAME, course_name=self.course.display_name,
),
'certUrl': request.build_absolute_uri(cert_url),
@@ -192,7 +192,7 @@ def test_enrolled_course_metadata(self, logged_in, enrollment_mode):
'issueMonth': cert.created_date.month,
}
expected_linkedin_url = (
- 'https://www.linkedin.com/profile/add?startTask=CERTIFICATION_NAME&{params}'.format(
+ 'https://www.linkedin.com/profile/add?startTask=CERTIFICATION_NAME&{params}'.format( # noqa: UP032
params=urlencode(linkedin_url_params)
)
)
@@ -279,7 +279,7 @@ def test_course_access(
mfe_is_visible: bool,
username: str,
enroll_user: bool,
- masquerade_role: Optional[str],
+ masquerade_role: Optional[str], # noqa: UP045
):
"""
Test that course_access is calculated correctly based on
@@ -437,7 +437,7 @@ def test_learning_assistant_enabled(self, setting_enabled):
response = self.client.get(self.url)
learning_assistant_enabled = response.json()['learning_assistant_enabled']
- self.assertEqual(learning_assistant_enabled, setting_enabled)
+ self.assertEqual(learning_assistant_enabled, setting_enabled) # noqa: PT009
@ddt.ddt
diff --git a/openedx/core/djangoapps/courseware_api/views.py b/openedx/core/djangoapps/courseware_api/views.py
index e9586930f75c..94622d66f58d 100644
--- a/openedx/core/djangoapps/courseware_api/views.py
+++ b/openedx/core/djangoapps/courseware_api/views.py
@@ -686,7 +686,7 @@ def set_last_seen_courseware_timezone(self, user):
if not user.id:
return
- cache_key = 'browser_timezone_{}'.format(str(user.id))
+ cache_key = 'browser_timezone_{}'.format(str(user.id)) # noqa: UP032
browser_timezone = self.request.query_params.get('browser_timezone', None)
cached_value = TieredCache.get_cached_response(cache_key)
if not cached_value.is_found:
diff --git a/openedx/core/djangoapps/credentials/apps.py b/openedx/core/djangoapps/credentials/apps.py
index 89fd1c43791b..0791d4795bd6 100644
--- a/openedx/core/djangoapps/credentials/apps.py
+++ b/openedx/core/djangoapps/credentials/apps.py
@@ -45,5 +45,5 @@ class CredentialsConfig(AppConfig):
def ready(self):
# Register celery workers
from openedx.core.djangoapps.credentials.tasks.v1 import ( # lint-amnesty, pylint: disable=unused-import, unused-variable
- tasks,
+ tasks, # noqa: F401
)
diff --git a/openedx/core/djangoapps/credentials/management/commands/notify_credentials.py b/openedx/core/djangoapps/credentials/management/commands/notify_credentials.py
index 2c418bb09ec7..a74b8b923c73 100644
--- a/openedx/core/djangoapps/credentials/management/commands/notify_credentials.py
+++ b/openedx/core/djangoapps/credentials/management/commands/notify_credentials.py
@@ -225,5 +225,5 @@ def _get_validated_course_run_keys(self, course_run_keys):
# keep the string; the celery task needs JSON serializable data.
validated_course_run_keys.append(str(CourseKey.from_string(course_run_key)))
except InvalidKeyError as exc:
- raise CommandError("{} is not a parsable CourseKey".format(course_run_key)) from exc
+ raise CommandError("{} is not a parsable CourseKey".format(course_run_key)) from exc # noqa: UP032
return validated_course_run_keys
diff --git a/openedx/core/djangoapps/credentials/management/commands/tests/test_notify_credentials.py b/openedx/core/djangoapps/credentials/management/commands/tests/test_notify_credentials.py
index 0ea139a5e8ce..e6ba97e034b5 100644
--- a/openedx/core/djangoapps/credentials/management/commands/tests/test_notify_credentials.py
+++ b/openedx/core/djangoapps/credentials/management/commands/tests/test_notify_credentials.py
@@ -148,35 +148,35 @@ def test_auto_execution_different_schedule(self, mock_task):
assert mock_task.call_args[0][0] == self.expected_options
def test_date_args(self, mock_task):
- self.expected_options['start_date'] = datetime(2017, 1, 31, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 1, 31, 0, 0, tzinfo=timezone.utc) # noqa: UP017
call_command(Command(), '--start-date', '2017-01-31')
assert mock_task.called
assert mock_task.call_args[0][0] == self.expected_options
mock_task.reset_mock()
- self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
- self.expected_options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
+ self.expected_options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc) # noqa: UP017
call_command(Command(), '--start-date', '2017-02-01', '--end-date', '2017-02-02')
assert mock_task.called
assert mock_task.call_args[0][0] == self.expected_options
mock_task.reset_mock()
self.expected_options['start_date'] = None
- self.expected_options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc) # noqa: UP017
call_command(Command(), '--end-date', '2017-02-02')
assert mock_task.called
assert mock_task.call_args[0][0] == self.expected_options
mock_task.reset_mock()
- self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
- self.expected_options['end_date'] = datetime(2017, 2, 1, 4, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
+ self.expected_options['end_date'] = datetime(2017, 2, 1, 4, 0, tzinfo=timezone.utc) # noqa: UP017
call_command(Command(), '--start-date', "2017-02-01 00:00:00", '--end-date', '2017-02-01 04:00:00')
assert mock_task.called
assert mock_task.call_args[0][0] == self.expected_options
def test_username_arg(self, mock_task):
- self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
- self.expected_options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
+ self.expected_options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.expected_options['user_ids'] = [str(self.user2.id)]
call_command(
'notify_credentials', '--start-date', '2017-02-01', '--end-date', '2017-02-02', '--user_ids', self.user2.id
@@ -195,8 +195,8 @@ def test_username_arg(self, mock_task):
assert mock_task.call_args[0][0] == self.expected_options
mock_task.reset_mock()
- self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
- self.expected_options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
+ self.expected_options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.expected_options['user_ids'] = [str(self.user.id)]
call_command(
'notify_credentials', '--start-date', '2017-02-01', '--end-date', '2017-02-02', '--user_ids', self.user.id
@@ -226,33 +226,33 @@ def test_username_arg(self, mock_task):
mock_task.reset_mock()
def test_no_args(self, mock_task):
- with self.assertRaisesRegex(CommandError, 'You must specify a filter.*'):
+ with self.assertRaisesRegex(CommandError, 'You must specify a filter.*'): # noqa: PT027
call_command(Command())
assert not mock_task.called
def test_dry_run(self, mock_task):
- self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.expected_options['dry_run'] = True
call_command(Command(), '--dry-run', '--start-date', '2017-02-01')
assert mock_task.called
assert mock_task.call_args[0][0] == self.expected_options
def test_hand_off(self, mock_task):
- self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.expected_options['notify_programs'] = True
call_command(Command(), '--start-date', '2017-02-01', '--notify_programs')
assert mock_task.called
assert mock_task.call_args[0][0] == self.expected_options
def test_delay(self, mock_task):
- self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.expected_options['delay'] = 0.2
call_command(Command(), '--start-date', '2017-02-01', '--delay', '0.2')
assert mock_task.called
assert mock_task.call_args[0][0] == self.expected_options
def test_page_size(self, mock_task):
- self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.expected_options['page_size'] = 2
call_command(Command(), '--start-date', '2017-02-01', '--page-size=2')
assert mock_task.called
@@ -263,7 +263,7 @@ def test_site(self, mock_task):
site_values={'course_org_filter': ['testX']}
)
self.expected_options['site'] = site_config.site.domain
- self.expected_options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
call_command(Command(), '--site', site_config.site.domain, '--start-date', '2017-01-01')
assert mock_task.called
@@ -271,7 +271,7 @@ def test_site(self, mock_task):
def test_args_from_database(self, mock_task):
# Nothing in the database, should default to disabled
- with self.assertRaisesRegex(CommandError, 'NotifyCredentialsConfig is disabled.*'):
+ with self.assertRaisesRegex(CommandError, 'NotifyCredentialsConfig is disabled.*'): # noqa: PT027
call_command(Command(), '--start-date', '2017-01-01', '--args-from-database')
# Add a config
@@ -281,13 +281,13 @@ def test_args_from_database(self, mock_task):
config.save()
# Not told to use config, should ignore it
- self.expected_options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
call_command(Command(), '--start-date', '2017-01-01')
assert mock_task.called
assert mock_task.call_args[0][0] == self.expected_options
# Told to use it, and enabled. Should use config in preference of command line
- self.expected_options['start_date'] = datetime(2017, 3, 1, 0, 0, tzinfo=timezone.utc)
+ self.expected_options['start_date'] = datetime(2017, 3, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.expected_options['skip_checks'] = False
call_command(Command(), '--start-date', '2017-01-01', '--args-from-database')
assert mock_task.called
@@ -297,7 +297,7 @@ def test_args_from_database(self, mock_task):
config.save()
# Explicitly disabled
- with self.assertRaisesRegex(CommandError, 'NotifyCredentialsConfig is disabled.*'):
+ with self.assertRaisesRegex(CommandError, 'NotifyCredentialsConfig is disabled.*'): # noqa: PT027
call_command(Command(), '--start-date', '2017-01-01', '--args-from-database')
def test_args_revoke_program_cert(self, mock_task):
diff --git a/openedx/core/djangoapps/credentials/tests/test_signals.py b/openedx/core/djangoapps/credentials/tests/test_signals.py
index e24408bfeb65..8e3c19c67e1c 100644
--- a/openedx/core/djangoapps/credentials/tests/test_signals.py
+++ b/openedx/core/djangoapps/credentials/tests/test_signals.py
@@ -3,8 +3,8 @@
from unittest import mock
-from django.conf import settings # lint-amnesty, pylint: disable=unused-import
-from django.test import TestCase, override_settings # lint-amnesty, pylint: disable=unused-import
+from django.conf import settings # lint-amnesty, pylint: disable=unused-import # noqa: F401
+from django.test import TestCase, override_settings # lint-amnesty, pylint: disable=unused-import # noqa: F401
from common.djangoapps.student.tests.factories import UserFactory
from lms.djangoapps.certificates.tests.factories import GeneratedCertificateFactory
diff --git a/openedx/core/djangoapps/credentials/tests/test_tasks.py b/openedx/core/djangoapps/credentials/tests/test_tasks.py
index 0f390b4f0f64..de0dd7f0c1fb 100644
--- a/openedx/core/djangoapps/credentials/tests/test_tasks.py
+++ b/openedx/core/djangoapps/credentials/tests/test_tasks.py
@@ -73,7 +73,7 @@ def test_happy_path(self, mock_get_api_client):
assert mock_get_api_client.call_args[0] == (self.user,)
assert api_client.post.call_count == 1
- self.assertDictEqual(api_client.post.call_args[1]['data'], {
+ self.assertDictEqual(api_client.post.call_args[1]['data'], { # noqa: PT009
'username': 'user',
'course_run': 'course-v1:org+course+run',
'letter_grade': 'A',
@@ -90,7 +90,7 @@ def test_retry(self, mock_get_api_client):
task = tasks.send_grade_to_credentials.delay('user', 'course-v1:org+course+run', True, 'A', 1.0, None)
- pytest.raises(Exception, task.get)
+ pytest.raises(Exception, task.get) # noqa: B017
assert mock_get_api_client.call_count == 11
@@ -196,8 +196,8 @@ def test_auto_execution(self, mock_send):
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [cert3, cert1, cert2])
- self.assertListEqual(list(mock_send.call_args[0][1]), [grade1, grade2])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [cert3, cert1, cert2]) # noqa: PT009
+ self.assertListEqual(list(mock_send.call_args[0][1]), [grade1, grade2]) # noqa: PT009
assert len(list(mock_send.call_args[0][0])) <= len(total_certificates)
assert len(list(mock_send.call_args[0][1])) <= len(total_grades)
@@ -258,52 +258,52 @@ def test_certs_with_modified_date_overrides(self, mock_send):
# The three certs should now be included in the arguments because of the
# the altered date overrides.
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert1, self.cert2, self.cert3])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert1, self.cert2, self.cert3]) # noqa: PT009
assert self.cert1 in mock_send.call_args[0][0]
assert self.cert2 in mock_send.call_args[0][0]
assert self.cert3 in mock_send.call_args[0][0]
@mock.patch(TASKS_MODULE + '.send_notifications')
def test_date_args(self, mock_send):
- self.options['start_date'] = datetime(2017, 1, 31, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 1, 31, 0, 0, tzinfo=timezone.utc) # noqa: UP017
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert2, self.cert4, self.cert3])
- self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade2, self.grade4, self.grade3])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert2, self.cert4, self.cert3]) # noqa: PT009
+ self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade2, self.grade4, self.grade3]) # noqa: PT009
mock_send.reset_mock()
- self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
- self.options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
+ self.options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc) # noqa: UP017
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert2, self.cert4])
- self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade2, self.grade4])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert2, self.cert4]) # noqa: PT009
+ self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade2, self.grade4]) # noqa: PT009
mock_send.reset_mock()
self.options['start_date'] = None
- self.options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc)
+ self.options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc) # noqa: UP017
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert1, self.cert2, self.cert4])
- self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade1, self.grade2, self.grade4])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert1, self.cert2, self.cert4]) # noqa: PT009
+ self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade1, self.grade2, self.grade4]) # noqa: PT009
mock_send.reset_mock()
- self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
- self.options['end_date'] = datetime(2017, 2, 1, 4, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
+ self.options['end_date'] = datetime(2017, 2, 1, 4, 0, tzinfo=timezone.utc) # noqa: UP017
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert2])
- self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade2])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert2]) # noqa: PT009
+ self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade2]) # noqa: PT009
@mock.patch(TASKS_MODULE + '.send_notifications')
def test_username_arg(self, mock_send):
- self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
- self.options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
+ self.options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.options['user_ids'] = [str(self.user2.id)]
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert4])
- self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade4])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert4]) # noqa: PT009
+ self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade4]) # noqa: PT009
mock_send.reset_mock()
self.options['start_date'] = None
@@ -311,17 +311,17 @@ def test_username_arg(self, mock_send):
self.options['user_ids'] = [str(self.user2.id)]
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert4])
- self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade4])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert4]) # noqa: PT009
+ self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade4]) # noqa: PT009
mock_send.reset_mock()
- self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
- self.options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
+ self.options['end_date'] = datetime(2017, 2, 2, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.options['user_ids'] = [str(self.user.id)]
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert2])
- self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade2])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert2]) # noqa: PT009
+ self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade2]) # noqa: PT009
mock_send.reset_mock()
self.options['start_date'] = None
@@ -329,8 +329,8 @@ def test_username_arg(self, mock_send):
self.options['user_ids'] = [str(self.user.id)]
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert1, self.cert2, self.cert3])
- self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade1, self.grade2, self.grade3])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert1, self.cert2, self.cert3]) # noqa: PT009
+ self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade1, self.grade2, self.grade3]) # noqa: PT009
mock_send.reset_mock()
self.options['start_date'] = None
@@ -338,13 +338,13 @@ def test_username_arg(self, mock_send):
self.options['user_ids'] = [str(self.user.id), str(self.user2.id)]
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_send.called
- self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert1, self.cert2, self.cert4, self.cert3])
- self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade1, self.grade2, self.grade4, self.grade3])
+ self.assertListEqual(list(mock_send.call_args[0][0]), [self.cert1, self.cert2, self.cert4, self.cert3]) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertListEqual(list(mock_send.call_args[0][1]), [self.grade1, self.grade2, self.grade4, self.grade3]) # noqa: PT009 # pylint: disable=line-too-long
mock_send.reset_mock()
@mock.patch(TASKS_MODULE + '.send_notifications')
def test_dry_run(self, mock_send):
- self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.options['dry_run'] = True
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert not mock_send.called
@@ -353,7 +353,7 @@ def test_dry_run(self, mock_send):
@mock.patch(TASKS_MODULE + '.send_grade_if_interesting')
@mock.patch(TASKS_MODULE + '.handle_course_cert_changed')
def test_hand_off(self, mock_grade_interesting, mock_program_changed, mock_program_awarded):
- self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_grade_interesting.call_count == 3
assert mock_program_changed.call_count == 3
@@ -362,7 +362,7 @@ def test_hand_off(self, mock_grade_interesting, mock_program_changed, mock_progr
mock_program_changed.reset_mock()
mock_program_awarded.reset_mock()
- self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.options['notify_programs'] = True
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_grade_interesting.call_count == 3
@@ -371,13 +371,13 @@ def test_hand_off(self, mock_grade_interesting, mock_program_changed, mock_progr
@mock.patch(TASKS_MODULE + '.time')
def test_delay(self, mock_time):
- self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.options['page_size'] = 2
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_time.sleep.call_count == 0
mock_time.sleep.reset_mock()
- self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 2, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.options['page_size'] = 2
self.options['delay'] = 0.2
tasks.handle_notify_credentials(options=self.options, course_keys=[])
@@ -387,19 +387,19 @@ def test_delay(self, mock_time):
@override_settings(DEBUG=True)
def test_page_size(self):
- self.options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
reset_queries()
tasks.handle_notify_credentials(options=self.options, course_keys=[])
baseline = len(connection.queries)
- self.options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.options['page_size'] = 1
reset_queries()
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert len(connection.queries) == (baseline + 6)
# two extra page queries each for certs & grades
- self.options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.options['page_size'] = 2
reset_queries()
tasks.handle_notify_credentials(options=self.options, course_keys=[])
@@ -412,23 +412,23 @@ def test_site(self, mock_grade_interesting):
site_values={'course_org_filter': ['testX']}
)
- self.options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 1, 1, 0, 0, tzinfo=timezone.utc) # noqa: UP017
self.options['site'] = site_config.site.domain
tasks.handle_notify_credentials(options=self.options, course_keys=[])
assert mock_grade_interesting.call_count == 1
@mock.patch(TASKS_MODULE + '.send_notifications')
def test_send_notifications_failure(self, mock_send):
- self.options['start_date'] = datetime(2017, 1, 31, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 1, 31, 0, 0, tzinfo=timezone.utc) # noqa: UP017
mock_send.side_effect = boom
- with pytest.raises(Exception):
+ with pytest.raises(Exception): # noqa: B017, PT011
tasks.handle_notify_credentials(options=self.options, course_keys=[])
@mock.patch(TASKS_MODULE + '.send_grade_if_interesting')
def test_send_grade_failure(self, mock_send_grade):
- self.options['start_date'] = datetime(2017, 1, 31, 0, 0, tzinfo=timezone.utc)
+ self.options['start_date'] = datetime(2017, 1, 31, 0, 0, tzinfo=timezone.utc) # noqa: UP017
mock_send_grade.side_effect = boom
- with pytest.raises(Exception):
+ with pytest.raises(Exception): # noqa: B017, PT011
tasks.handle_notify_credentials(options=self.options, course_keys=[])
@ddt.data([True], [False])
@@ -476,7 +476,7 @@ def setUp(self):
)
@ddt.unpack
def test_send_grade_if_right_cert(self, called, mode, status, mock_is_course_run_in_a_program,
- mock_send_grade_to_credentials, _mock_is_learner_issuance_enabled):
+ mock_send_grade_to_credentials, _mock_is_learner_issuance_enabled): # noqa: PT019
mock_is_course_run_in_a_program.return_value = True
# Test direct send
@@ -494,20 +494,20 @@ def test_send_grade_if_right_cert(self, called, mode, status, mock_is_course_run
tasks.send_grade_if_interesting(self.user, self.key, None, None, 'A', 1.0)
assert mock_send_grade_to_credentials.delay.called is called
- def test_send_grade_missing_cert(self, _, mock_send_grade_to_credentials, _mock_is_learner_issuance_enabled):
+ def test_send_grade_missing_cert(self, _, mock_send_grade_to_credentials, _mock_is_learner_issuance_enabled): # noqa: PT019 # pylint: disable=line-too-long
tasks.send_grade_if_interesting(self.user, self.key, None, None, 'A', 1.0)
assert not mock_send_grade_to_credentials.delay.called
@ddt.data([True], [False])
@ddt.unpack
def test_send_grade_if_in_a_program(self, in_program, mock_is_course_run_in_a_program,
- mock_send_grade_to_credentials, _mock_is_learner_issuance_enabled):
+ mock_send_grade_to_credentials, _mock_is_learner_issuance_enabled): # noqa: PT019 # pylint: disable=line-too-long
mock_is_course_run_in_a_program.return_value = in_program
tasks.send_grade_if_interesting(self.user, self.key, 'verified', 'downloadable', 'A', 1.0)
assert mock_send_grade_to_credentials.delay.called is in_program
def test_send_grade_queries_grade(self, mock_is_course_run_in_a_program, mock_send_grade_to_credentials,
- _mock_is_learner_issuance_enabled):
+ _mock_is_learner_issuance_enabled): # noqa: PT019
mock_is_course_run_in_a_program.return_value = True
last_updated = datetime.now()
@@ -519,15 +519,15 @@ def test_send_grade_queries_grade(self, mock_is_course_run_in_a_program, mock_se
)
mock_send_grade_to_credentials.delay.reset_mock()
- def test_send_grade_without_issuance_enabled(self, _mock_is_course_run_in_a_program,
+ def test_send_grade_without_issuance_enabled(self, _mock_is_course_run_in_a_program, # noqa: PT019
mock_send_grade_to_credentials, mock_is_learner_issuance_enabled):
mock_is_learner_issuance_enabled.return_value = False
tasks.send_grade_if_interesting(self.user, self.key, 'verified', 'downloadable', None, None)
assert mock_is_learner_issuance_enabled.called
assert not mock_send_grade_to_credentials.delay.called
- def test_send_grade_records_enabled(self, _mock_is_course_run_in_a_program, mock_send_grade_to_credentials,
- _mock_is_learner_issuance_enabled):
+ def test_send_grade_records_enabled(self, _mock_is_course_run_in_a_program, mock_send_grade_to_credentials, # noqa: PT019 # pylint: disable=line-too-long
+ _mock_is_learner_issuance_enabled): # noqa: PT019 # pylint: disable=line-too-long
site_config = SiteConfigurationFactory.create(
site_values={'course_org_filter': [self.key.org]}
)
@@ -544,8 +544,8 @@ def test_send_grade_records_enabled(self, _mock_is_course_run_in_a_program, mock
assert not mock_send_grade_to_credentials.delay.called
def test_send_grade_records_disabled_globally(
- self, _mock_is_course_run_in_a_program, mock_send_grade_to_credentials,
- _mock_is_learner_issuance_enabled
+ self, _mock_is_course_run_in_a_program, mock_send_grade_to_credentials, # noqa: PT019
+ _mock_is_learner_issuance_enabled # noqa: PT019
):
assert is_learner_records_enabled()
with override_settings(ENABLE_LEARNER_RECORDS=False):
@@ -791,7 +791,7 @@ def setUp(self):
self_paced=False,
)
self.co_instructor_paced_cdb_end_with_date = CourseOverviewFactory(
- certificate_available_date=(datetime.now(timezone.utc) + timedelta(days=30)),
+ certificate_available_date=(datetime.now(timezone.utc) + timedelta(days=30)), # noqa: UP017
certificates_display_behavior=CertificatesDisplayBehaviors.END_WITH_DATE,
id=CourseKey.from_string(self.co_instructor_paced_cdb_end_with_date_key),
self_paced=False,
diff --git a/openedx/core/djangoapps/credentials/utils.py b/openedx/core/djangoapps/credentials/utils.py
index 9e8ad6b04df0..e3fdc11ab5d5 100644
--- a/openedx/core/djangoapps/credentials/utils.py
+++ b/openedx/core/djangoapps/credentials/utils.py
@@ -1,7 +1,7 @@
"""Helper functions for working with Credentials."""
import logging
-from typing import Dict, List
+from typing import Dict, List # noqa: UP035
from urllib.parse import urljoin
import requests
@@ -71,7 +71,7 @@ def get_credentials(
program_uuid: str = None,
credential_type: str = None,
raise_on_error: bool = False,
-) -> List[Dict]:
+) -> List[Dict]: # noqa: UP006
"""
Given a user, get credentials earned from the credentials service.
diff --git a/openedx/core/djangoapps/credit/api/__init__.py b/openedx/core/djangoapps/credit/api/__init__.py
index 4f392d51838e..1c38e15e272b 100644
--- a/openedx/core/djangoapps/credit/api/__init__.py
+++ b/openedx/core/djangoapps/credit/api/__init__.py
@@ -4,5 +4,5 @@
This module aggregates the API functions from the eligibility and provider APIs.
"""
-from .eligibility import * # pylint: disable=wildcard-import
-from .provider import * # pylint: disable=wildcard-import
+from .eligibility import * # pylint: disable=wildcard-import # noqa: F403
+from .provider import * # pylint: disable=wildcard-import # noqa: F403
diff --git a/openedx/core/djangoapps/credit/api/eligibility.py b/openedx/core/djangoapps/credit/api/eligibility.py
index c9645dcf0361..317972078b8c 100644
--- a/openedx/core/djangoapps/credit/api/eligibility.py
+++ b/openedx/core/djangoapps/credit/api/eligibility.py
@@ -80,7 +80,7 @@ def set_credit_requirements(course_key, requirements):
try:
credit_course = CreditCourse.get_credit_course(course_key=course_key)
except CreditCourse.DoesNotExist:
- raise InvalidCreditCourse() # lint-amnesty, pylint: disable=raise-missing-from
+ raise InvalidCreditCourse() # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
old_requirements = CreditRequirement.get_course_requirements(course_key=course_key)
requirements_to_disable = _get_requirements_to_disable(old_requirements, requirements)
@@ -430,7 +430,7 @@ def _validate_requirements(requirements):
if invalid_params:
invalid_requirements.append(
- "{requirement} has missing/invalid parameters: {params}".format(
+ "{requirement} has missing/invalid parameters: {params}".format( # noqa: UP032
requirement=requirement,
params=invalid_params,
)
diff --git a/openedx/core/djangoapps/credit/api/provider.py b/openedx/core/djangoapps/credit/api/provider.py
index d4827397ca94..56272e2d6b15 100644
--- a/openedx/core/djangoapps/credit/api/provider.py
+++ b/openedx/core/djangoapps/credit/api/provider.py
@@ -119,7 +119,7 @@ def check_keys_exist(shared_secret_key, provider_id):
"""
# Accounts for old way of storing provider key
if shared_secret_key is None: # lint-amnesty, pylint: disable=no-else-raise
- msg = 'Credit provider with ID "{provider_id}" does not have a secret key configured.'.format(
+ msg = 'Credit provider with ID "{provider_id}" does not have a secret key configured.'.format( # noqa: UP032
provider_id=provider_id
)
log.error(msg)
@@ -128,7 +128,7 @@ def check_keys_exist(shared_secret_key, provider_id):
# Accounts for new way of storing provider key
elif isinstance(shared_secret_key, list) and not any(shared_secret_key):
msg = 'Could not retrieve secret key for credit provider [{}]. ' \
- 'Unable to validate requests from provider.'.format(provider_id)
+ 'Unable to validate requests from provider.'.format(provider_id) # noqa: UP032
log.error(msg)
raise CreditProviderNotConfigured(msg)
@@ -211,10 +211,10 @@ def create_credit_request(course_key, provider_id, username):
'but the user is not eligible for credit',
username, course_key
)
- raise UserIsNotEligible # lint-amnesty, pylint: disable=raise-missing-from
+ raise UserIsNotEligible # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except CreditProvider.DoesNotExist:
log.error('Credit provider with ID "%s" has not been configured.', provider_id)
- raise CreditProviderNotConfigured # lint-amnesty, pylint: disable=raise-missing-from
+ raise CreditProviderNotConfigured # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
# Check if we've enabled automatic integration with the credit
# provider. If not, we'll show the user a link to a URL
@@ -283,9 +283,9 @@ def create_credit_request(course_key, provider_id, username):
except (CreditRequirementStatus.DoesNotExist, TypeError, KeyError):
msg = 'Could not retrieve final grade from the credit eligibility table for ' \
- 'user [{user_id}] in course [{course_key}].'.format(user_id=user.id, course_key=course_key)
+ 'user [{user_id}] in course [{course_key}].'.format(user_id=user.id, course_key=course_key) # noqa: UP032
log.exception(msg)
- raise UserIsNotEligible(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise UserIsNotEligible(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
# Getting the students's enrollment date
course_enrollment = CourseEnrollment.get_enrollment(user, course_key)
@@ -375,13 +375,13 @@ def update_credit_request_status(request_uuid, provider_id, status):
request_uuid, old_status, status, provider_id
)
except CreditRequest.DoesNotExist:
- msg = (
+ msg = ( # noqa: UP032
'Credit provider with ID "{provider_id}" attempted to '
'update request with UUID "{request_uuid}", but no request '
'with this UUID is associated with the provider.'
).format(provider_id=provider_id, request_uuid=request_uuid)
log.warning(msg)
- raise CreditRequestNotFound(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CreditRequestNotFound(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def get_credit_requests_for_user(username):
diff --git a/openedx/core/djangoapps/credit/apps.py b/openedx/core/djangoapps/credit/apps.py
index e057cc5cab77..1f2785727aa5 100644
--- a/openedx/core/djangoapps/credit/apps.py
+++ b/openedx/core/djangoapps/credit/apps.py
@@ -15,7 +15,7 @@ class CreditConfig(AppConfig):
name = 'openedx.core.djangoapps.credit'
def ready(self):
- from .signals import handlers # lint-amnesty, pylint: disable=unused-import
+ from .signals import handlers # lint-amnesty, pylint: disable=unused-import # noqa: F401
if settings.FEATURES.get('ENABLE_SPECIAL_EXAMS'):
from .services import CreditService
set_runtime_service('credit', CreditService())
diff --git a/openedx/core/djangoapps/credit/email_utils.py b/openedx/core/djangoapps/credit/email_utils.py
index df33f74ae733..401ff8ff7f8b 100644
--- a/openedx/core/djangoapps/credit/email_utils.py
+++ b/openedx/core/djangoapps/credit/email_utils.py
@@ -249,7 +249,7 @@ def get_credit_provider_attribute_values(course_key, attribute_name):
attribute_values = None
if credit_config.is_cache_enabled:
- cache_key = '{key_prefix}.{course_key}.{attribute_name}'.format(
+ cache_key = '{key_prefix}.{course_key}.{attribute_name}'.format( # noqa: UP032
key_prefix=credit_config.CACHE_KEY,
course_key=course_id,
attribute_name=attribute_name
diff --git a/openedx/core/djangoapps/credit/models.py b/openedx/core/djangoapps/credit/models.py
index b9a4bc9b1f1e..0c6e87920485 100644
--- a/openedx/core/djangoapps/credit/models.py
+++ b/openedx/core/djangoapps/credit/models.py
@@ -17,7 +17,7 @@
from django.core.validators import RegexValidator
from django.db import IntegrityError, models, transaction
from django.dispatch import receiver
-from django.utils.translation import gettext as _ # lint-amnesty, pylint: disable=unused-import
+from django.utils.translation import gettext as _ # lint-amnesty, pylint: disable=unused-import # noqa: F401
from django.utils.translation import gettext_lazy
from edx_django_utils.cache import RequestCache
from jsonfield.fields import JSONField
@@ -105,7 +105,7 @@ class CreditProvider(TimeStampedModel):
)
)
- fulfillment_instructions = models.TextField(
+ fulfillment_instructions = models.TextField( # noqa: DJ001
null=True,
blank=True,
help_text=gettext_lazy(
@@ -262,7 +262,7 @@ def get_credit_course(cls, course_key):
"""
return cls.objects.get(course_key=course_key, enabled=True)
- def __str__(self):
+ def __str__(self): # noqa: DJ012
"""Unicode representation of the credit course. """
return str(self.course_key)
@@ -508,7 +508,7 @@ def remove_requirement_status(cls, username, requirement):
requirement_status.delete()
except cls.DoesNotExist:
log_msg = (
- 'The requirement status {requirement} does not exist for username {username}.'.format(
+ 'The requirement status {requirement} does not exist for username {username}.'.format( # noqa: UP032
requirement=requirement,
username=username
)
@@ -641,7 +641,7 @@ def is_user_eligible_for_credit(cls, course_key, username):
def __str__(self):
"""Unicode representation of the credit eligibility. """
- return "{user}, {course}".format(
+ return "{user}, {course}".format( # noqa: UP032
user=self.username,
course=self.course.course_key,
)
@@ -766,7 +766,7 @@ def get_user_request_status(cls, username, course_key):
def __str__(self):
"""Unicode representation of a credit request."""
- return "{course}, {provider}, {status}".format(
+ return "{course}, {provider}, {status}".format( # noqa: UP032
course=self.course.course_key,
provider=self.provider.provider_id,
status=self.status,
diff --git a/openedx/core/djangoapps/credit/serializers.py b/openedx/core/djangoapps/credit/serializers.py
index 5e22bcdd3bf1..ad649ea2b518 100644
--- a/openedx/core/djangoapps/credit/serializers.py
+++ b/openedx/core/djangoapps/credit/serializers.py
@@ -97,7 +97,7 @@ def _check_keys_exist_for_provider(self, secret_key, provider_id):
# Accounts for old way of storing provider key
if secret_key is None:
msg = 'Could not retrieve secret key for credit provider [{}]. ' \
- 'Unable to validate requests from provider.'.format(provider_id)
+ 'Unable to validate requests from provider.'.format(provider_id) # noqa: UP032
log.error(msg)
raise PermissionDenied(msg)
@@ -105,7 +105,7 @@ def _check_keys_exist_for_provider(self, secret_key, provider_id):
# We need at least 1 key here that we can use to validate the signature
if isinstance(secret_key, list) and not any(secret_key):
msg = 'Could not retrieve secret key for credit provider [{}]. ' \
- 'Unable to validate requests from provider.'.format(provider_id)
+ 'Unable to validate requests from provider.'.format(provider_id) # noqa: UP032
log.error(msg)
raise PermissionDenied(msg)
diff --git a/openedx/core/djangoapps/credit/services.py b/openedx/core/djangoapps/credit/services.py
index ee6c347a84eb..779b5fff5d68 100644
--- a/openedx/core/djangoapps/credit/services.py
+++ b/openedx/core/djangoapps/credit/services.py
@@ -147,7 +147,7 @@ def set_credit_requirement_status(self, user_id, course_key_or_id, req_namespace
# table. This will be to help debug any issues that might
# arise in production
log_msg = (
- 'set_credit_requirement_status was called with '
+ 'set_credit_requirement_status was called with ' # noqa: UP032
'user_id={user_id}, course_key_or_id={course_key_or_id} '
'req_namespace={req_namespace}, req_name={req_name}, '
'status={status}, reason={reason}'.format(
@@ -203,7 +203,7 @@ def remove_credit_requirement_status(self, user_id, course_key_or_id, req_namesp
# table. This will be to help debug any issues that might
# arise in production
log_msg = (
- 'remove_credit_requirement_status was called with '
+ 'remove_credit_requirement_status was called with ' # noqa: UP032
'user_id={user_id}, course_key_or_id={course_key_or_id} '
'req_namespace={req_namespace}, req_name={req_name}, '.format(
user_id=user_id,
diff --git a/openedx/core/djangoapps/credit/tasks.py b/openedx/core/djangoapps/credit/tasks.py
index 79ef613e3d19..b97d1cd72989 100644
--- a/openedx/core/djangoapps/credit/tasks.py
+++ b/openedx/core/djangoapps/credit/tasks.py
@@ -40,7 +40,7 @@ def update_credit_course_requirements(course_id):
set_credit_requirements(course_key, requirements)
except (InvalidKeyError, ItemNotFoundError, InvalidCreditRequirements) as exc:
LOGGER.error('Error on adding the requirements for course %s - %s', course_id, str(exc))
- raise update_credit_course_requirements.retry(args=[course_id], exc=exc)
+ raise update_credit_course_requirements.retry(args=[course_id], exc=exc) # noqa: B904
LOGGER.info('Requirements added for course %s', course_id)
@@ -144,7 +144,7 @@ def _get_proctoring_requirements(course_key):
if requirements:
log_msg = (
- 'Registering the following as \'proctored_exam\' credit requirements: {log_msg}'.format(
+ 'Registering the following as \'proctored_exam\' credit requirements: {log_msg}'.format( # noqa: UP032
log_msg=requirements
)
)
diff --git a/openedx/core/djangoapps/credit/tests/test_api.py b/openedx/core/djangoapps/credit/tests/test_api.py
index 754d32ef620c..801163b45563 100644
--- a/openedx/core/djangoapps/credit/tests/test_api.py
+++ b/openedx/core/djangoapps/credit/tests/test_api.py
@@ -1223,7 +1223,7 @@ def test_get_credit_provider_display_names_method(self):
"""Verify that parsed providers list is returns after getting course production information."""
self._mock_ecommerce_courses_api(self.course_key, self.COURSE_API_RESPONSE)
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
- self.assertListEqual(self.PROVIDERS_LIST, response_providers)
+ self.assertListEqual(self.PROVIDERS_LIST, response_providers) # noqa: PT009
@mock.patch('openedx.core.djangoapps.credit.email_utils.get_ecommerce_api_client')
def test_get_credit_provider_display_names_method_with_exception(self, mock_get_client):
@@ -1243,11 +1243,11 @@ def test_get_credit_provider_display_names_caching(self):
# Warm up the cache.
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
- self.assertListEqual(self.PROVIDERS_LIST, response_providers)
+ self.assertListEqual(self.PROVIDERS_LIST, response_providers) # noqa: PT009
# Hit the cache.
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
- self.assertListEqual(self.PROVIDERS_LIST, response_providers)
+ self.assertListEqual(self.PROVIDERS_LIST, response_providers) # noqa: PT009
# Verify only one request was made.
assert len(httpretty.httpretty.latest_requests) == 1
@@ -1262,10 +1262,10 @@ def test_get_credit_provider_display_names_without_caching(self):
self._mock_ecommerce_courses_api(self.course_key, self.COURSE_API_RESPONSE)
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
- self.assertListEqual(self.PROVIDERS_LIST, response_providers)
+ self.assertListEqual(self.PROVIDERS_LIST, response_providers) # noqa: PT009
response_providers = get_credit_provider_attribute_values(self.course_key, 'display_name')
- self.assertListEqual(self.PROVIDERS_LIST, response_providers)
+ self.assertListEqual(self.PROVIDERS_LIST, response_providers) # noqa: PT009
assert len(httpretty.httpretty.latest_requests) == 2
diff --git a/openedx/core/djangoapps/credit/tests/test_models.py b/openedx/core/djangoapps/credit/tests/test_models.py
index faedaa1edccb..4a7fa510ecb1 100644
--- a/openedx/core/djangoapps/credit/tests/test_models.py
+++ b/openedx/core/djangoapps/credit/tests/test_models.py
@@ -17,7 +17,7 @@
)
from openedx.core.djangoapps.user_api.accounts.tests.retirement_helpers import ( # pylint: disable=unused-import
RetirementTestCase,
- setup_retirement_states,
+ setup_retirement_states, # noqa: F401
)
from openedx.core.djangoapps.user_api.models import UserRetirementStatus
diff --git a/openedx/core/djangoapps/credit/tests/test_serializers.py b/openedx/core/djangoapps/credit/tests/test_serializers.py
index a2ddb30389e0..9e42817d7a99 100644
--- a/openedx/core/djangoapps/credit/tests/test_serializers.py
+++ b/openedx/core/djangoapps/credit/tests/test_serializers.py
@@ -26,7 +26,7 @@ def test_data(self):
'fulfillment_instructions': provider.fulfillment_instructions,
'thumbnail_url': provider.thumbnail_url,
}
- self.assertDictEqual(serializer.data, expected)
+ self.assertDictEqual(serializer.data, expected) # noqa: PT009
class CreditEligibilitySerializerTests(TestCase):
@@ -42,7 +42,7 @@ def test_data(self):
'deadline': eligibility.deadline.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
'username': user.username,
}
- self.assertDictEqual(serializer.data, expected)
+ self.assertDictEqual(serializer.data, expected) # noqa: PT009
class CreditProviderCallbackSerializerTests(TestCase):
diff --git a/openedx/core/djangoapps/credit/tests/test_signals.py b/openedx/core/djangoapps/credit/tests/test_signals.py
index 33caf5f9035c..0594b51c46d8 100644
--- a/openedx/core/djangoapps/credit/tests/test_signals.py
+++ b/openedx/core/djangoapps/credit/tests/test_signals.py
@@ -206,7 +206,7 @@ def _get_exam_event_metadata(event_signal):
minorversion=0,
source='openedx/lms/web',
sourcehost='lms.test',
- time=datetime.now(timezone.utc)
+ time=datetime.now(timezone.utc) # noqa: UP017
)
@mock.patch('openedx.core.djangoapps.credit.signals.handlers.remove_credit_requirement_status', autospec=True)
diff --git a/openedx/core/djangoapps/credit/tests/test_views.py b/openedx/core/djangoapps/credit/tests/test_views.py
index 9f74bcf9af21..b07b76877792 100644
--- a/openedx/core/djangoapps/credit/tests/test_views.py
+++ b/openedx/core/djangoapps/credit/tests/test_views.py
@@ -44,7 +44,7 @@ class ApiTestCaseMixin:
def assert_error_response(self, response, msg, status_code=400):
""" Validate the response's status and detail message. """
assert response.status_code == status_code
- self.assertDictEqual(response.data, {'detail': msg})
+ self.assertDictEqual(response.data, {'detail': msg}) # noqa: PT009
class UserMixin:
@@ -200,7 +200,7 @@ def assert_course_created(self, course_id, response):
assert response.status_code == 201
# Verify the API returns the serialized CreditCourse
- self.assertDictEqual(json.loads(response.content.decode('utf-8')), data)
+ self.assertDictEqual(json.loads(response.content.decode('utf-8')), data) # noqa: PT009
# Verify the CreditCourse was actually created
course_key = CourseKey.from_string(course_id)
@@ -241,7 +241,7 @@ def test_get(self):
assert response.status_code == 200
# Verify the API returns the serialized CreditCourse
- self.assertDictEqual(json.loads(response.content.decode('utf-8')), self._serialize_credit_course(cc1))
+ self.assertDictEqual(json.loads(response.content.decode('utf-8')), self._serialize_credit_course(cc1)) # noqa: PT009 # pylint: disable=line-too-long
def test_list(self):
""" Verify the endpoint supports listing all CreditCourse objects. """
@@ -253,7 +253,7 @@ def test_list(self):
assert response.status_code == 200
# Verify the API returns a list of serialized CreditCourse objects
- self.assertListEqual(json.loads(response.content.decode('utf-8')), expected)
+ self.assertListEqual(json.loads(response.content.decode('utf-8')), expected) # noqa: PT009
def test_update(self):
""" Verify the endpoint supports updating a CreditCourse object. """
@@ -267,7 +267,7 @@ def test_update(self):
assert response.status_code == 200
# Verify the serialized CreditCourse is returned
- self.assertDictEqual(json.loads(response.content.decode('utf-8')), data)
+ self.assertDictEqual(json.loads(response.content.decode('utf-8')), data) # noqa: PT009
# Verify the data was persisted
credit_course = CreditCourse.objects.get(course_key=credit_course.course_key)
@@ -430,7 +430,7 @@ def test_post_user_not_eligible(self):
course_key = credit_course.course_key
response = self.post_credit_request(username, course_key)
- msg = '[{username}] is not eligible for credit for [{course_key}].'.format(username=username,
+ msg = '[{username}] is not eligible for credit for [{course_key}].'.format(username=username, # noqa: UP032
course_key=course_key)
self.assert_error_response(response, msg)
@@ -659,7 +659,7 @@ def setUp(self):
def create_url(self, eligibility):
""" Returns a URL that can be used to view eligibility data. """
- return '{path}?username={username}&course_key={course_key}'.format(
+ return '{path}?username={username}&course_key={course_key}'.format( # noqa: UP032
path=reverse(self.view_name),
username=eligibility.username,
course_key=eligibility.course.course_key
@@ -671,7 +671,7 @@ def assert_valid_get_response(self, eligibility):
response = self.client.get(url)
assert response.status_code == 200
- self.assertListEqual(response.data, CreditEligibilitySerializer([eligibility], many=True).data)
+ self.assertListEqual(response.data, CreditEligibilitySerializer([eligibility], many=True).data) # noqa: PT009
def test_get(self):
""" Verify the endpoint returns eligibility information for the give user and course. """
@@ -682,7 +682,7 @@ def test_get_with_missing_parameters(self):
is not provided. """
response = self.client.get(reverse(self.view_name))
assert response.status_code == 400
- self.assertDictEqual(response.data,
+ self.assertDictEqual(response.data, # noqa: PT009
{'detail': 'Both the course_key and username querystring parameters must be supplied.'})
def test_get_with_invalid_course_key(self):
@@ -690,7 +690,7 @@ def test_get_with_invalid_course_key(self):
url = f'{reverse(self.view_name)}?username=edx&course_key=a'
response = self.client.get(url)
assert response.status_code == 400
- self.assertDictEqual(response.data, {'detail': '[a] is not a valid course key.'})
+ self.assertDictEqual(response.data, {'detail': '[a] is not a valid course key.'}) # noqa: PT009
def test_staff_can_view_all(self):
""" Verify that staff users can view eligibility data for all users. """
diff --git a/openedx/core/djangoapps/credit/views.py b/openedx/core/djangoapps/credit/views.py
index 0e3055714add..c29fb84d086b 100644
--- a/openedx/core/djangoapps/credit/views.py
+++ b/openedx/core/djangoapps/credit/views.py
@@ -86,7 +86,7 @@ def post(self, request, provider_id):
try:
course_key = CourseKey.from_string(course_key)
except InvalidKeyError:
- raise InvalidCourseKey(course_key) # lint-amnesty, pylint: disable=raise-missing-from
+ raise InvalidCourseKey(course_key) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
# Validate the username
username = request.data.get('username')
@@ -101,7 +101,7 @@ def post(self, request, provider_id):
credit_request = create_credit_request(course_key, provider.provider_id, username)
return Response(credit_request)
except CreditApiBadRequest as ex:
- raise InvalidCreditRequest(str(ex)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise InvalidCreditRequest(str(ex)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
class CreditProviderCallbackView(views.APIView):
@@ -162,7 +162,7 @@ def filter_queryset(self, queryset):
try:
course_key = CourseKey.from_string(course_key)
except InvalidKeyError:
- raise ValidationError({'detail': f'[{course_key}] is not a valid course key.'}) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError({'detail': f'[{course_key}] is not a valid course key.'}) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return queryset.filter(
username=username,
course__course_key=course_key,
diff --git a/openedx/core/djangoapps/discussions/apps.py b/openedx/core/djangoapps/discussions/apps.py
index a53a2a75db05..3bf4435bd2f9 100644
--- a/openedx/core/djangoapps/discussions/apps.py
+++ b/openedx/core/djangoapps/discussions/apps.py
@@ -31,4 +31,4 @@ class DiscussionsConfig(AppConfig):
}
def ready(self):
- from . import handlers # pylint: disable=unused-import
+ from . import handlers # pylint: disable=unused-import # noqa: F401
diff --git a/openedx/core/djangoapps/discussions/models.py b/openedx/core/djangoapps/discussions/models.py
index 3192bceed6a4..0eed39e500a0 100644
--- a/openedx/core/djangoapps/discussions/models.py
+++ b/openedx/core/djangoapps/discussions/models.py
@@ -6,7 +6,7 @@
import logging
from collections import namedtuple
from enum import Enum # lint-amnesty, pylint: disable=wrong-import-order
-from typing import List, Type, TypeVar
+from typing import List, Type, TypeVar # noqa: UP035
from django.conf import settings
from django.core.exceptions import ValidationError
@@ -305,7 +305,7 @@ def pii_sharing_required_message(provider_name):
}
-def get_supported_providers() -> List[str]:
+def get_supported_providers() -> List[str]: # noqa: UP006
"""
Return the list of supported discussion providers
@@ -376,7 +376,7 @@ def __str__(self):
)
@property
- def available_providers(self) -> List[str]:
+ def available_providers(self) -> List[str]: # noqa: UP006
"""
Return a filtered list of available providers
"""
@@ -396,7 +396,7 @@ def available_providers(self) -> List[str]:
return _providers
@classmethod
- def get_available_providers(cls, course_key: CourseKey) -> List[str]:
+ def get_available_providers(cls, course_key: CourseKey) -> List[str]: # noqa: UP006
_filter = cls.current(course_key=course_key)
providers = _filter.available_providers
return providers
@@ -480,7 +480,7 @@ def clean(self):
raise ValidationError('Context Key should be an existing learning context.')
def __str__(self):
- return "DiscussionsConfiguration(context_key='{context_key}', provider='{provider}', enabled={enabled})".format(
+ return "DiscussionsConfiguration(context_key='{context_key}', provider='{provider}', enabled={enabled})".format( # noqa: UP032 # pylint: disable=line-too-long
context_key=self.context_key,
provider=self.provider_type,
enabled=self.enabled,
@@ -515,7 +515,7 @@ def is_enabled(cls, context_key: CourseKey) -> bool:
return configuration.enabled
@classmethod
- def get(cls: Type[T], context_key: CourseKey) -> T:
+ def get(cls: Type[T], context_key: CourseKey) -> T: # noqa: UP006
"""
Lookup a model by context_key
"""
@@ -530,11 +530,11 @@ def get(cls: Type[T], context_key: CourseKey) -> T:
return configuration
@property
- def available_providers(self) -> List[str]:
+ def available_providers(self) -> List[str]: # noqa: UP006
return ProviderFilter.current(course_key=self.context_key).available_providers
@classmethod
- def get_available_providers(cls, context_key: CourseKey) -> List[str]:
+ def get_available_providers(cls, context_key: CourseKey) -> List[str]: # noqa: UP006
return ProviderFilter.current(course_key=context_key).available_providers
@classmethod
diff --git a/openedx/core/djangoapps/discussions/plugins.py b/openedx/core/djangoapps/discussions/plugins.py
index b4422b843c97..06b62e92aa23 100644
--- a/openedx/core/djangoapps/discussions/plugins.py
+++ b/openedx/core/djangoapps/discussions/plugins.py
@@ -1,7 +1,7 @@
"""
Course app configuration for discussions.
"""
-from typing import Dict, Optional
+from typing import Dict, Optional # noqa: UP035
from django.conf import settings
from django.contrib.auth import get_user_model
@@ -54,7 +54,7 @@ def set_enabled(cls, course_key: CourseKey, enabled: bool, user: 'User') -> bool
return configuration.enabled
@classmethod
- def get_allowed_operations(cls, course_key: CourseKey, user: Optional[User] = None) -> Dict[str, bool]:
+ def get_allowed_operations(cls, course_key: CourseKey, user: Optional[User] = None) -> Dict[str, bool]: # noqa: UP006, UP045 # pylint: disable=line-too-long
"""
Return allowed operations for discussions app.
"""
diff --git a/openedx/core/djangoapps/discussions/tests/test_admin.py b/openedx/core/djangoapps/discussions/tests/test_admin.py
index d16d73dd8bef..3ba12a66d68a 100644
--- a/openedx/core/djangoapps/discussions/tests/test_admin.py
+++ b/openedx/core/djangoapps/discussions/tests/test_admin.py
@@ -28,5 +28,5 @@ def test_change_view(self):
)
url = reverse('admin:discussions_discussionsconfiguration_change', args=[discussion_config.context_key])
response = self.client.get(url)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
self.assertContains(response, 'course-v1:test+test+06_25_2024')
diff --git a/openedx/core/djangoapps/discussions/tests/test_models.py b/openedx/core/djangoapps/discussions/tests/test_models.py
index 35fecbc6725c..ea8f25e3a2a4 100644
--- a/openedx/core/djangoapps/discussions/tests/test_models.py
+++ b/openedx/core/djangoapps/discussions/tests/test_models.py
@@ -45,7 +45,7 @@ def setUp(self):
self.provider_denied = SUPPORTED_PROVIDERS[1]
@patch('openedx.core.djangoapps.discussions.models.get_supported_providers', return_value=SUPPORTED_PROVIDERS)
- def test_get_nonexistent(self, _default_providers):
+ def test_get_nonexistent(self, _default_providers): # noqa: PT019
"""
Assert we retrieve defaults when no configuration set
"""
@@ -53,7 +53,7 @@ def test_get_nonexistent(self, _default_providers):
assert len(providers) == len(SUPPORTED_PROVIDERS)
@patch('openedx.core.djangoapps.discussions.models.get_supported_providers', return_value=SUPPORTED_PROVIDERS)
- def test_get_allow(self, _default_providers):
+ def test_get_allow(self, _default_providers): # noqa: PT019
"""
Assert we can set the allow list
"""
@@ -66,7 +66,7 @@ def test_get_allow(self, _default_providers):
assert len(providers) == 1
@patch('openedx.core.djangoapps.discussions.models.get_supported_providers', return_value=SUPPORTED_PROVIDERS)
- def test_get_deny(self, _default_providers):
+ def test_get_deny(self, _default_providers): # noqa: PT019
"""
Assert we can set the deny list
"""
@@ -78,7 +78,7 @@ def test_get_deny(self, _default_providers):
assert self.provider_denied not in providers
@patch('openedx.core.djangoapps.discussions.models.get_supported_providers', return_value=SUPPORTED_PROVIDERS)
- def test_get_allow_and_deny(self, _default_providers):
+ def test_get_allow_and_deny(self, _default_providers): # noqa: PT019
"""
Assert we can add an item to both allow and deny lists
"""
@@ -93,7 +93,7 @@ def test_get_allow_and_deny(self, _default_providers):
assert self.provider_allowed in providers
@patch('openedx.core.djangoapps.discussions.models.get_supported_providers', return_value=SUPPORTED_PROVIDERS)
- def test_get_allow_or_deny(self, _default_providers):
+ def test_get_allow_or_deny(self, _default_providers): # noqa: PT019
"""
Assert we can exclusively add an items to both allow and deny lists
"""
@@ -108,7 +108,7 @@ def test_get_allow_or_deny(self, _default_providers):
assert self.provider_allowed in providers
@patch('openedx.core.djangoapps.discussions.models.get_supported_providers', return_value=SUPPORTED_PROVIDERS)
- def test_override(self, _default_providers):
+ def test_override(self, _default_providers): # noqa: PT019
"""
Assert we can override a configuration and get the latest data
"""
diff --git a/openedx/core/djangoapps/discussions/tests/test_views.py b/openedx/core/djangoapps/discussions/tests/test_views.py
index 64c5e5da5644..bb0a275692ef 100644
--- a/openedx/core/djangoapps/discussions/tests/test_views.py
+++ b/openedx/core/djangoapps/discussions/tests/test_views.py
@@ -534,7 +534,7 @@ def test_post_legacy_invalid(self, plugin_configuration):
'provider_type': Provider.LEGACY,
'plugin_configuration': plugin_configuration,
}
- with self.assertRaises(ValidationError):
+ with self.assertRaises(ValidationError): # noqa: PT027
response = self._post(payload)
if status.is_client_error(response.status_code):
raise ValidationError(str(response.status_code))
@@ -573,7 +573,7 @@ def test_post_cohorts_invalid(self, key, value):
key: value,
}
}
- with self.assertRaises(ValidationError):
+ with self.assertRaises(ValidationError): # noqa: PT027
response = self._post(payload)
if status.is_client_error(response.status_code):
raise ValidationError(str(response.status_code))
@@ -641,7 +641,7 @@ def test_unable_to_change_provider_for_running_course(self, user_type):
"""
Ensure that certain users cannot change provider for a running course.
"""
- self.course.start = datetime.now(timezone.utc) - timedelta(days=5)
+ self.course.start = datetime.now(timezone.utc) - timedelta(days=5) # noqa: UP017
self.course = self.update_course(self.course, self.user.id)
# use the global staff user to do the initial config
@@ -664,7 +664,7 @@ def test_global_staff_can_change_provider_for_running_course(self):
"""
Ensure that global staff can change provider for a running course.
"""
- self.course.start = datetime.now(timezone.utc) - timedelta(days=5)
+ self.course.start = datetime.now(timezone.utc) - timedelta(days=5) # noqa: UP017
self.course = self.update_course(self.course, self.user.id)
# use the global staff user to do the initial config
@@ -880,8 +880,8 @@ def test_sync_discussion_topics_staff_user(self, mock_update):
self.client.force_authenticate(user=self.staff_user)
response = self.client.post(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['status'], 'success')
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['status'], 'success') # noqa: PT009
mock_update.assert_called_once_with(self.course_key_string)
@patch('openedx.core.djangoapps.discussions.views.update_discussions_settings_from_course_task')
@@ -896,8 +896,8 @@ def test_sync_discussion_topics_course_team(self, mock_update):
response = self.client.post(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['status'], 'success')
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['status'], 'success') # noqa: PT009
mock_update.assert_called_once()
def test_sync_discussion_topics_unauthorized(self):
@@ -907,7 +907,7 @@ def test_sync_discussion_topics_unauthorized(self):
# Don't authenticate the request
response = self.client.post(self.url)
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_sync_discussion_topics_forbidden(self):
"""
@@ -920,7 +920,7 @@ def test_sync_discussion_topics_forbidden(self):
response = self.client.post(self.url)
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # noqa: PT009
def test_invalid_http_method(self):
"""
@@ -929,4 +929,4 @@ def test_invalid_http_method(self):
self.client.force_authenticate(user=self.staff_user)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
+ self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) # noqa: PT009
diff --git a/openedx/core/djangoapps/discussions/url_helpers.py b/openedx/core/djangoapps/discussions/url_helpers.py
index 60b29d919762..d36e30bc6e03 100644
--- a/openedx/core/djangoapps/discussions/url_helpers.py
+++ b/openedx/core/djangoapps/discussions/url_helpers.py
@@ -8,7 +8,7 @@
from opaque_keys.edx.keys import CourseKey
-def _get_url_with_view_query_params(path: str, view: Optional[str] = None) -> str:
+def _get_url_with_view_query_params(path: str, view: Optional[str] = None) -> str: # noqa: UP045
"""
Helper function to build url if a url is configured
@@ -34,7 +34,7 @@ def _get_url_with_view_query_params(path: str, view: Optional[str] = None) -> st
return url
-def get_discussions_mfe_url(course_key: CourseKey, view: Optional[str] = None) -> str:
+def get_discussions_mfe_url(course_key: CourseKey, view: Optional[str] = None) -> str: # noqa: UP045
"""
Returns the url for discussions for the specified course in the discussions MFE.
@@ -48,7 +48,7 @@ def get_discussions_mfe_url(course_key: CourseKey, view: Optional[str] = None) -
return _get_url_with_view_query_params(f"{course_key}/", view)
-def get_discussions_mfe_topic_url(course_key: CourseKey, topic_id: str, view: Optional[str] = None) -> str:
+def get_discussions_mfe_topic_url(course_key: CourseKey, topic_id: str, view: Optional[str] = None) -> str: # noqa: UP045 # pylint: disable=line-too-long
"""
Returns the url for discussions for the specified course and topic in the discussions MFE.
diff --git a/openedx/core/djangoapps/discussions/utils.py b/openedx/core/djangoapps/discussions/utils.py
index 70da190c0fe4..9a5aa2365704 100644
--- a/openedx/core/djangoapps/discussions/utils.py
+++ b/openedx/core/djangoapps/discussions/utils.py
@@ -2,7 +2,7 @@
Shared utility code related to discussions.
"""
import logging
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, List, Optional, Tuple # noqa: UP035
from opaque_keys.edx.keys import CourseKey
@@ -27,7 +27,7 @@
def get_divided_discussions(
course: CourseBlock,
discussion_settings: CourseDiscussionSettings,
-) -> Tuple[List[str], List[str]]:
+) -> Tuple[List[str], List[str]]: # noqa: UP006
"""
Returns the course-wide and inline divided discussion ids separately.
"""
@@ -46,7 +46,7 @@ def get_divided_discussions(
return divided_course_wide_discussions, divided_inline_discussions
-def get_discussion_categories_ids(course: CourseBlock, user: Optional[User], include_all: bool = False) -> List[str]:
+def get_discussion_categories_ids(course: CourseBlock, user: Optional[User], include_all: bool = False) -> List[str]: # noqa: UP006, UP045 # pylint: disable=line-too-long
"""
Returns a list of available ids of categories for the course that
are accessible to the given user.
@@ -65,9 +65,9 @@ def get_discussion_categories_ids(course: CourseBlock, user: Optional[User], inc
def get_accessible_discussion_xblocks(
course: CourseBlock,
- user: Optional[User],
+ user: Optional[User], # noqa: UP045
include_all: bool = False,
-) -> List[DiscussionXBlock]:
+) -> List[DiscussionXBlock]: # noqa: UP006
"""
Return a list of all valid discussion xblocks in this course that
are accessible to the given user.
@@ -79,9 +79,9 @@ def get_accessible_discussion_xblocks(
@request_cached()
def get_accessible_discussion_xblocks_by_course_id(
course_id: CourseKey,
- user: Optional[User] = None,
+ user: Optional[User] = None, # noqa: UP045
include_all: bool = False
-) -> List[DiscussionXBlock]:
+) -> List[DiscussionXBlock]: # noqa: UP006
"""
Return a list of all valid discussion xblocks in this course.
Checks for the given user's access if include_all is False.
@@ -94,7 +94,7 @@ def get_accessible_discussion_xblocks_by_course_id(
]
-def available_division_schemes(course_key: CourseKey) -> List[str]:
+def available_division_schemes(course_key: CourseKey) -> List[str]: # noqa: UP006
"""
Returns a list of possible discussion division schemes for this course.
This takes into account if cohorts are enabled and if there are multiple
@@ -139,7 +139,7 @@ def enrollment_track_group_count(course_key: CourseKey) -> int:
return len(_get_enrollment_track_groups(course_key))
-def _get_enrollment_track_groups(course_key: CourseKey) -> List[Group]:
+def _get_enrollment_track_groups(course_key: CourseKey) -> List[Group]: # noqa: UP006
"""
Helper method that returns an array of the Groups in the EnrollmentTrackUserPartition for the given course.
If no such partition exists on the course, an empty array is returned.
@@ -149,7 +149,7 @@ def _get_enrollment_track_groups(course_key: CourseKey) -> List[Group]:
return partition.groups if partition else []
-def get_group_names_by_id(course_discussion_settings: CourseDiscussionSettings) -> Dict[str, str]:
+def get_group_names_by_id(course_discussion_settings: CourseDiscussionSettings) -> Dict[str, str]: # noqa: UP006
"""
Creates of a dict of group_id to learner-facing group names, for the division_scheme
in use as specified by course_discussion_settings.
diff --git a/openedx/core/djangoapps/discussions/views.py b/openedx/core/djangoapps/discussions/views.py
index c07cdd024a77..cafa78415aef 100644
--- a/openedx/core/djangoapps/discussions/views.py
+++ b/openedx/core/djangoapps/discussions/views.py
@@ -1,7 +1,7 @@
"""
Handle view-logic for the discussions app.
"""
-from typing import Dict
+from typing import Dict # noqa: UP035
import edx_api_doc_tools as apidocs
from edx_rest_framework_extensions.auth.jwt.authentication import JwtAuthentication
@@ -63,7 +63,7 @@ def get(self, request: Request, course_key_string: str, **_kwargs) -> Response:
return Response(data)
@staticmethod
- def get_configuration_data(request: Request, course_key_string: str) -> Dict:
+ def get_configuration_data(request: Request, course_key_string: str) -> Dict: # noqa: UP006
"""
Get discussions configuration data for the course
Args:
@@ -160,7 +160,7 @@ def get(self, request, course_key_string: str, **_kwargs) -> Response:
return Response(data)
@staticmethod
- def get_provider_data(course_key_string: str, show_all: bool = False) -> Dict:
+ def get_provider_data(course_key_string: str, show_all: bool = False) -> Dict: # noqa: UP006
"""
Get provider data for specified course
Args:
diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/__init__.py b/openedx/core/djangoapps/django_comment_common/comment_client/__init__.py
index 3f856f063d74..95f3eae4e429 100644
--- a/openedx/core/djangoapps/django_comment_common/comment_client/__init__.py
+++ b/openedx/core/djangoapps/django_comment_common/comment_client/__init__.py
@@ -1,3 +1,8 @@
# pylint: disable=missing-docstring,wildcard-import
-from .comment_client import *
-from .utils import CommentClient500Error, CommentClientError, CommentClientMaintenanceError, CommentClientRequestError
+from .comment_client import * # noqa: F403
+from .utils import ( # noqa: F401
+ CommentClient500Error,
+ CommentClientError,
+ CommentClientMaintenanceError,
+ CommentClientRequestError,
+)
diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/comment_client.py b/openedx/core/djangoapps/django_comment_common/comment_client/comment_client.py
index bfd7b687f45f..0011228cbe76 100644
--- a/openedx/core/djangoapps/django_comment_common/comment_client/comment_client.py
+++ b/openedx/core/djangoapps/django_comment_common/comment_client/comment_client.py
@@ -1,6 +1,6 @@
"""Import other classes here so they can be imported from here."""
# pylint: disable=unused-import
-from .comment import Comment
-from .commentable import Commentable
-from .thread import Thread
-from .user import User
+from .comment import Comment # noqa: F401
+from .commentable import Commentable # noqa: F401
+from .thread import Thread # noqa: F401
+from .user import User # noqa: F401
diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/course.py b/openedx/core/djangoapps/django_comment_common/comment_client/course.py
index ce8bcdf54e9f..2f7309ab592e 100644
--- a/openedx/core/djangoapps/django_comment_common/comment_client/course.py
+++ b/openedx/core/djangoapps/django_comment_common/comment_client/course.py
@@ -2,14 +2,14 @@
"""Provides base Commentable model class"""
from __future__ import annotations
-from typing import Dict, Optional
+from typing import Dict, Optional # noqa: UP035
from edx_django_utils.monitoring import function_trace
from forum import api as forum_api
from opaque_keys.edx.keys import CourseKey
-def get_course_commentable_counts(course_key: CourseKey) -> Dict[str, Dict[str, int]]:
+def get_course_commentable_counts(course_key: CourseKey) -> Dict[str, Dict[str, int]]: # noqa: UP006
"""
Get stats about the count of different types of threads for each commentable (topic).
@@ -32,7 +32,7 @@ def get_course_commentable_counts(course_key: CourseKey) -> Dict[str, Dict[str,
@function_trace("get_course_user_stats")
-def get_course_user_stats(course_key: CourseKey, params: Optional[Dict] = None) -> Dict[str, Dict[str, int]]:
+def get_course_user_stats(course_key: CourseKey, params: Optional[Dict] = None) -> Dict[str, Dict[str, int]]: # noqa: UP006, UP045 # pylint: disable=line-too-long
"""
Get stats about a user's participation in a course.
@@ -70,7 +70,7 @@ def get_course_user_stats(course_key: CourseKey, params: Optional[Dict] = None)
@function_trace("update_course_users_stats")
-def update_course_users_stats(course_key: CourseKey) -> Dict:
+def update_course_users_stats(course_key: CourseKey) -> Dict: # noqa: UP006
"""
Update the user stats for all users for a particular course.
diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/models.py b/openedx/core/djangoapps/django_comment_common/comment_client/models.py
index cdcce68afa5c..80001bdc7ad0 100644
--- a/openedx/core/djangoapps/django_comment_common/comment_client/models.py
+++ b/openedx/core/djangoapps/django_comment_common/comment_client/models.py
@@ -34,7 +34,7 @@ def __getattr__(self, name):
return self.attributes[name]
except KeyError:
if self.retrieved or self.id is None:
- raise AttributeError(f"Field {name} does not exist") # lint-amnesty, pylint: disable=raise-missing-from
+ raise AttributeError(f"Field {name} does not exist") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
self.retrieve()
return self.__getattr__(name)
@@ -108,7 +108,7 @@ def _update_from_response(self, response_data):
setattr(self, k, v)
else:
log.warning(
- "Unexpected field {field_name} in model {model_name}".format(
+ "Unexpected field {field_name} in model {model_name}".format( # noqa: UP032
field_name=k,
model_name=self.__class__.__name__
)
@@ -177,7 +177,7 @@ def url(cls, action, params=None):
try:
return cls.url_with_id(params)
except KeyError:
- raise CommentClientRequestError(f"Cannot perform action {action} without id") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommentClientRequestError(f"Cannot perform action {action} without id") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
else: # action must be in DEFAULT_ACTIONS_WITHOUT_ID now
return cls.url_without_id()
diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/thread.py b/openedx/core/djangoapps/django_comment_common/comment_client/thread.py
index d5572452f017..31f4319f2301 100644
--- a/openedx/core/djangoapps/django_comment_common/comment_client/thread.py
+++ b/openedx/core/djangoapps/django_comment_common/comment_client/thread.py
@@ -100,7 +100,7 @@ def search(cls, query_params):
}
)
log.info(
- 'forum_text_search query="{search_query}" corrected_text="{corrected_text}" course_id={course_id} '
+ 'forum_text_search query="{search_query}" corrected_text="{corrected_text}" course_id={course_id} ' # noqa: UP032 # pylint: disable=line-too-long
'group_id={group_id} page={requested_page} total_results={total_results}'.format(
search_query=search_query,
corrected_text=corrected_text,
diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/user.py b/openedx/core/djangoapps/django_comment_common/comment_client/user.py
index 7589143778bf..2e9c86469aca 100644
--- a/openedx/core/djangoapps/django_comment_common/comment_client/user.py
+++ b/openedx/core/djangoapps/django_comment_common/comment_client/user.py
@@ -37,7 +37,7 @@ def read(self, source):
Calls forum service to mark thread as read for the user
"""
course_id = self.attributes.get("course_id")
- course_key = utils.get_course_key(course_id)
+ course_key = utils.get_course_key(course_id) # noqa: F841
forum_api.mark_thread_as_read(self.id, source.id, course_id=str(course_id))
def follow(self, source, course_id=None):
@@ -171,7 +171,7 @@ def _retrieve(self, *args, **kwargs):
})
try:
response = forum_api.get_user(**params)
- except ForumV2RequestError as e:
+ except ForumV2RequestError as e: # noqa: F841
self.save({"course_id": course_id})
response = forum_api.get_user(**params)
self._update_from_response(response)
diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/utils.py b/openedx/core/djangoapps/django_comment_common/comment_client/utils.py
index ccdced767e00..c49581fdf165 100644
--- a/openedx/core/djangoapps/django_comment_common/comment_client/utils.py
+++ b/openedx/core/djangoapps/django_comment_common/comment_client/utils.py
@@ -4,7 +4,7 @@
import logging
-import requests # pylint: disable=unused-import
+import requests # pylint: disable=unused-import # noqa: F401
from opaque_keys.edx.keys import CourseKey
log = logging.getLogger(__name__)
diff --git a/openedx/core/djangoapps/django_comment_common/models.py b/openedx/core/djangoapps/django_comment_common/models.py
index 2dd8bf814ad8..109d2b94c212 100644
--- a/openedx/core/djangoapps/django_comment_common/models.py
+++ b/openedx/core/djangoapps/django_comment_common/models.py
@@ -78,7 +78,7 @@ class Role(models.Model):
objects = NoneToEmptyManager()
- name = models.CharField(max_length=30, null=False, blank=False)
+ name = models.CharField(max_length=30, null=False, blank=False) # noqa: DJ012
users = models.ManyToManyField(User, related_name="roles")
course_id = CourseKeyField(max_length=255, blank=True, db_index=True)
@@ -213,7 +213,7 @@ def has_permission(user, permission, course_id=None):
"""
assert isinstance(course_id, (type(None), CourseKey))
request_cache_dict = DEFAULT_REQUEST_CACHE.data
- cache_key = "django_comment_client.permissions.has_permission.all_permissions.{}.{}".format(
+ cache_key = "django_comment_client.permissions.has_permission.all_permissions.{}.{}".format( # noqa: UP032
user.id, course_id
)
if cache_key in request_cache_dict:
@@ -253,7 +253,7 @@ def __str__(self):
return f"ForumsConfig: timeout={self.connection_timeout}"
-class CourseDiscussionSettings(models.Model):
+class CourseDiscussionSettings(models.Model): # noqa: DJ008
"""
Settings for course discussions
@@ -272,7 +272,7 @@ class CourseDiscussionSettings(models.Model):
)
always_divide_inline_discussions = models.BooleanField(default=False)
reported_content_email_notifications = models.BooleanField(default=False)
- _divided_discussions = models.TextField(db_column='divided_discussions', null=True, blank=True) # JSON list
+ _divided_discussions = models.TextField(db_column='divided_discussions', null=True, blank=True) # JSON list # noqa: DJ001 # pylint: disable=line-too-long
COHORT = 'cohort'
ENROLLMENT_TRACK = 'enrollment_track'
@@ -341,7 +341,7 @@ def update(self, validated_data: dict):
return self
-class DiscussionsIdMapping(models.Model):
+class DiscussionsIdMapping(models.Model): # noqa: DJ008
"""
This model is a performance optimization, updated on course publish.
diff --git a/openedx/core/djangoapps/django_comment_common/tests.py b/openedx/core/djangoapps/django_comment_common/tests.py
index 25087e0b4951..05076a64c0b9 100644
--- a/openedx/core/djangoapps/django_comment_common/tests.py
+++ b/openedx/core/djangoapps/django_comment_common/tests.py
@@ -130,7 +130,7 @@ def test_invalid_data_types(self):
discussion_settings = CourseDiscussionSettings.get(self.course.id)
for field in fields:
- with pytest.raises(ValueError) as value_error:
+ with pytest.raises(ValueError) as value_error: # noqa: PT011
discussion_settings.update({field['name']: invalid_value})
assert str(value_error.value) == exception_msg_template.format(field['name'], field['type'].__name__)
diff --git a/openedx/core/djangoapps/embargo/api.py b/openedx/core/djangoapps/embargo/api.py
index 0934d13aab63..cba176f76363 100644
--- a/openedx/core/djangoapps/embargo/api.py
+++ b/openedx/core/djangoapps/embargo/api.py
@@ -7,7 +7,7 @@
"""
import logging
-from typing import List, Optional
+from typing import List, Optional # noqa: UP035
from django.conf import settings
from django.core.cache import cache
@@ -30,8 +30,8 @@ def redirect_if_blocked(
request: Request,
course_key: CourseKey,
access_point: str = 'enrollment',
- user: Optional[types.User] = None,
-) -> Optional[str]:
+ user: Optional[types.User] = None, # noqa: UP045
+) -> Optional[str]: # noqa: UP045
"""
Redirect if the user does not have access to the course.
@@ -61,9 +61,9 @@ def redirect_if_blocked(
def check_course_access(
course_key: CourseKey,
- user: Optional[types.User] = None,
- ip_addresses: Optional[List[str]] = None,
- url: Optional[str] = None,
+ user: Optional[types.User] = None, # noqa: UP045
+ ip_addresses: Optional[List[str]] = None, # noqa: UP006, UP045
+ url: Optional[str] = None, # noqa: UP045
) -> bool:
"""
Check is the user with this ip_addresses chain has access to the given course
@@ -178,7 +178,7 @@ def _get_user_country_from_profile(user: types.User) -> str:
return profile_country
-def get_embargo_response(request: Request, course_key: CourseKey, user: types.User) -> Optional[Response]:
+def get_embargo_response(request: Request, course_key: CourseKey, user: types.User) -> Optional[Response]: # noqa: UP045 # pylint: disable=line-too-long
"""
Check whether any country access rules block the user from enrollment.
@@ -196,7 +196,7 @@ def get_embargo_response(request: Request, course_key: CourseKey, user: types.Us
return Response(
status=status.HTTP_403_FORBIDDEN,
data={
- "message": (
+ "message": ( # noqa: UP032
"Users from this location cannot access the course '{course_id}'."
).format(course_id=str(course_key)),
"user_message_url": request.build_absolute_uri(redirect_url)
diff --git a/openedx/core/djangoapps/embargo/exceptions.py b/openedx/core/djangoapps/embargo/exceptions.py
index 9185b3aae195..ba140e14eb72 100644
--- a/openedx/core/djangoapps/embargo/exceptions.py
+++ b/openedx/core/djangoapps/embargo/exceptions.py
@@ -5,7 +5,7 @@ class InvalidAccessPoint(Exception):
"""The requested access point is not supported. """
def __init__(self, access_point, *args, **kwargs):
- msg = (
+ msg = ( # noqa: UP032
"Access point '{access_point}' should be either 'enrollment' or 'courseware'"
).format(access_point=access_point)
super().__init__(msg, *args, **kwargs)
diff --git a/openedx/core/djangoapps/embargo/forms.py b/openedx/core/djangoapps/embargo/forms.py
index 5f34022af5d8..8726bc41d1ad 100644
--- a/openedx/core/djangoapps/embargo/forms.py
+++ b/openedx/core/djangoapps/embargo/forms.py
@@ -28,7 +28,7 @@ class RestrictedCourseForm(forms.ModelForm):
"""
class Meta:
model = RestrictedCourse
- fields = '__all__'
+ fields = '__all__' # noqa: DJ007
def clean_course_key(self):
"""Validate the course key.
@@ -49,7 +49,7 @@ def clean_course_key(self):
try:
course_key = CourseKey.from_string(cleaned_id)
except InvalidKeyError:
- raise forms.ValidationError(error_msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise forms.ValidationError(error_msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not modulestore().has_course(course_key):
raise forms.ValidationError(error_msg)
@@ -62,7 +62,7 @@ class IPFilterForm(forms.ModelForm):
class Meta:
model = IPFilter
- fields = '__all__'
+ fields = '__all__' # noqa: DJ007
def _is_valid_ip(self, address):
"""Whether or not address is a valid ipv4 address or ipv6 address"""
diff --git a/openedx/core/djangoapps/embargo/middleware.py b/openedx/core/djangoapps/embargo/middleware.py
index b1c7a5c833ff..b5abe0d82717 100644
--- a/openedx/core/djangoapps/embargo/middleware.py
+++ b/openedx/core/djangoapps/embargo/middleware.py
@@ -67,7 +67,7 @@ def __init__(self, *args, **kwargs):
raise MiddlewareNotUsed()
super().__init__(*args, **kwargs)
- def process_request(self, request: Request) -> Optional[Response]:
+ def process_request(self, request: Request) -> Optional[Response]: # noqa: UP045
"""Block requests based on embargo rules.
This will perform the following checks:
@@ -133,7 +133,7 @@ def process_request(self, request: Request) -> Optional[Response]:
# This applies only to courseware URLs.
return self.country_access_rules(request)
- def country_access_rules(self, request: Request) -> Optional[Response]:
+ def country_access_rules(self, request: Request) -> Optional[Response]: # noqa: UP045
"""
Check the country access rules for a given course.
Applies only to courseware URLs.
diff --git a/openedx/core/djangoapps/embargo/models.py b/openedx/core/djangoapps/embargo/models.py
index b3a452079c78..79eadb7b6efa 100644
--- a/openedx/core/djangoapps/embargo/models.py
+++ b/openedx/core/djangoapps/embargo/models.py
@@ -15,7 +15,7 @@
import ipaddress
import json
import logging
-from typing import List, Optional
+from typing import List, Optional # noqa: UP035
from config_models.models import ConfigurationModel
from django.core.cache import cache
@@ -51,7 +51,7 @@ class EmbargoedCourse(models.Model):
course_id = CourseKeyField(max_length=255, db_index=True, unique=True)
# Whether or not to embargo
- embargoed = models.BooleanField(default=False)
+ embargoed = models.BooleanField(default=False) # noqa: DJ012
@classmethod
def is_embargoed(cls, course_id):
@@ -66,7 +66,7 @@ def is_embargoed(cls, course_id):
except cls.DoesNotExist:
return False
- def __str__(self):
+ def __str__(self): # noqa: DJ012
not_em = "Not "
if self.embargoed:
not_em = ""
@@ -244,7 +244,7 @@ def snapshot(self):
]
}
- def message_key_for_access_point(self, access_point: str) -> Optional[str]:
+ def message_key_for_access_point(self, access_point: str) -> Optional[str]: # noqa: UP045
"""Determine which message to show the user.
The message can be configured per-course and depends
@@ -263,7 +263,7 @@ def message_key_for_access_point(self, access_point: str) -> Optional[str]:
elif access_point == 'courseware':
return self.access_msg_key
- def __str__(self):
+ def __str__(self): # noqa: DJ012
return str(self.course_key)
@classmethod
@@ -381,12 +381,12 @@ class Country(models.Model):
)
def __str__(self):
- return "{name} ({code})".format(
+ return "{name} ({code})".format( # noqa: UP032
name=str(self.country.name),
code=str(self.country)
)
- class Meta:
+ class Meta: # noqa: DJ012
"""Default ordering is ascending by country code """
ordering = ['country']
@@ -475,7 +475,7 @@ def check_country_access(cls, course_key: CourseKey, country: str) -> bool:
return country == '' or country in allowed_countries
@classmethod
- def _get_country_access_list(cls, course_key: CourseKey) -> List[str]:
+ def _get_country_access_list(cls, course_key: CourseKey) -> List[str]: # noqa: UP006
"""
if a course is blacklist for two countries then course can be accessible from
any where except these two countries.
@@ -510,7 +510,7 @@ def _get_country_access_list(cls, course_key: CourseKey) -> List[str]:
# that have access to the course.
return list(whitelist_countries - blacklist_countries)
- def __str__(self):
+ def __str__(self): # noqa: DJ012
if self.rule_type == self.WHITELIST_RULE:
return _("Whitelist {country} for {course}").format(
course=str(self.restricted_course.course_key),
@@ -529,7 +529,7 @@ def invalidate_cache_for_course(cls, course_key: CourseKey) -> None:
cache.delete(cache_key)
log.info("Invalidated country access list for course %s", course_key)
- class Meta:
+ class Meta: # noqa: DJ012
"""a course can be added with either black or white list. """
unique_together = (
# This restriction ensures that a country is on
@@ -580,7 +580,7 @@ def invalidate_country_rule_cache(sender, instance, **kwargs): # pylint: disabl
post_delete.connect(invalidate_country_rule_cache, sender=RestrictedCourse)
-class CourseAccessRuleHistory(models.Model):
+class CourseAccessRuleHistory(models.Model): # noqa: DJ008
"""
History of course access rule changes.
@@ -590,7 +590,7 @@ class CourseAccessRuleHistory(models.Model):
timestamp = models.DateTimeField(db_index=True, auto_now_add=True)
course_key = CourseKeyField(max_length=255, db_index=True)
- snapshot = models.TextField(null=True, blank=True)
+ snapshot = models.TextField(null=True, blank=True) # noqa: DJ001
DELETED_PLACEHOLDER = "DELETED"
@@ -658,7 +658,7 @@ def snapshot_post_delete_receiver(sender, instance, **kwargs): # pylint: disabl
else:
CourseAccessRuleHistory.save_snapshot(restricted_course)
- class Meta:
+ class Meta: # noqa: DJ012
get_latest_by = 'timestamp'
@@ -715,7 +715,7 @@ def update_cache(cls):
"""
cache.set(cls.CACHE_KEY, cls._fetch_restricted_countries())
- def save(self, *args, **kwargs):
+ def save(self, *args, **kwargs): # noqa: DJ012
"""
Override save method to update cache on insert/update.
"""
@@ -729,10 +729,10 @@ def delete(self, *args, **kwargs):
super().delete(*args, **kwargs)
self.update_cache()
- def __str__(self):
+ def __str__(self): # noqa: DJ012
return f"{self.country.country.name} ({self.country.country})"
- class Meta:
+ class Meta: # noqa: DJ012
verbose_name = "Global Restricted Country"
verbose_name_plural = "Global Restricted Countries"
diff --git a/openedx/core/djangoapps/embargo/tests/test_api.py b/openedx/core/djangoapps/embargo/tests/test_api.py
index f71ffafd543e..10010a732d39 100644
--- a/openedx/core/djangoapps/embargo/tests/test_api.py
+++ b/openedx/core/djangoapps/embargo/tests/test_api.py
@@ -265,7 +265,7 @@ def test_redirect_if_blocked_ips(self, ips, allow_access, mock_country):
)
@ddt.unpack
@mock.patch('openedx.core.djangoapps.embargo.api.check_course_access', return_value=False)
- def test_redirect_if_blocked_courseware(self, access_point, check_disabled, allow_access, _mock_access):
+ def test_redirect_if_blocked_courseware(self, access_point, check_disabled, allow_access, _mock_access): # noqa: PT019 # pylint: disable=line-too-long
self.restricted_course.disable_access_check = check_disabled
self.restricted_course.save()
@@ -361,7 +361,7 @@ def test_message_url_stale_cache(self):
RestrictedCourse.objects.get(course_key=self.course.id).delete()
# Clear the message URL cache
- message_cache_key = (
+ message_cache_key = ( # noqa: UP032
'embargo.message_url_path.courseware.{course_key}'
).format(course_key=self.course.id)
cache.delete(message_cache_key)
diff --git a/openedx/core/djangoapps/embargo/tests/test_forms.py b/openedx/core/djangoapps/embargo/tests/test_forms.py
index b6b169f65fcc..1fe0418758b7 100644
--- a/openedx/core/djangoapps/embargo/tests/test_forms.py
+++ b/openedx/core/djangoapps/embargo/tests/test_forms.py
@@ -47,7 +47,7 @@ def _assert_course_field_error(self, form):
msg = 'COURSE NOT FOUND'
assert msg in form._errors['course_key'][0] # pylint: disable=protected-access
- with self.assertRaisesRegex(
+ with self.assertRaisesRegex( # noqa: PT027
ValueError, "The RestrictedCourse could not be created because the data didn't validate."
):
form.save()
@@ -122,5 +122,5 @@ def test_add_invalid_ips(self):
" Please fix the error(s) and try again."
assert bmsg == form._errors['blacklist'][0] # pylint: disable=protected-access
- with self.assertRaisesRegex(ValueError, "The IPFilter could not be created because the data didn't validate."):
+ with self.assertRaisesRegex(ValueError, "The IPFilter could not be created because the data didn't validate."): # noqa: PT027 # pylint: disable=line-too-long
form.save()
diff --git a/openedx/core/djangoapps/enrollments/api.py b/openedx/core/djangoapps/enrollments/api.py
index e0aefc44d43e..c096eda8dbc4 100644
--- a/openedx/core/djangoapps/enrollments/api.py
+++ b/openedx/core/djangoapps/enrollments/api.py
@@ -324,7 +324,7 @@ def update_enrollment(
}
"""
- log.info('Starting Update Enrollment process for user {user} in course {course} to mode {mode}'.format(
+ log.info('Starting Update Enrollment process for user {user} in course {course} to mode {mode}'.format( # noqa: UP032 # pylint: disable=line-too-long
user=username,
course=course_id,
mode=mode,
@@ -339,7 +339,7 @@ def update_enrollment(
else:
if enrollment_attributes is not None:
set_enrollment_attributes(username, course_id, enrollment_attributes)
- log.info('Course Enrollment updated for user {user} in course {course} to mode {mode}'.format(
+ log.info('Course Enrollment updated for user {user} in course {course} to mode {mode}'.format( # noqa: UP032
user=username,
course=course_id,
mode=mode
@@ -406,7 +406,7 @@ def get_course_enrollment_details(course_id, include_expired=False):
except Exception:
# Catch any unexpected errors during caching.
log.exception("Error occurred while caching course enrollment details for course %s", course_id)
- raise errors.CourseEnrollmentError("An unexpected error occurred while retrieving course enrollment details.") # lint-amnesty, pylint: disable=raise-missing-from
+ raise errors.CourseEnrollmentError("An unexpected error occurred while retrieving course enrollment details.") # lint-amnesty, pylint: disable=raise-missing-from,line-too-long # noqa: B904
return course_enrollment_details
@@ -615,4 +615,4 @@ def _data_api():
return importlib.import_module(api_path)
except (ImportError, ValueError):
log.exception(f"Could not load module at '{api_path}'")
- raise errors.EnrollmentApiLoadError(api_path) # lint-amnesty, pylint: disable=raise-missing-from
+ raise errors.EnrollmentApiLoadError(api_path) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
diff --git a/openedx/core/djangoapps/enrollments/data.py b/openedx/core/djangoapps/enrollments/data.py
index 9d6cbc12fb8d..87cd6e424a3e 100644
--- a/openedx/core/djangoapps/enrollments/data.py
+++ b/openedx/core/djangoapps/enrollments/data.py
@@ -145,7 +145,7 @@ def create_course_enrollment(username, course_id, mode, is_active, enterprise_uu
except User.DoesNotExist:
msg = f"Not user with username '{username}' found."
log.warning(msg)
- raise UserNotFoundError(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise UserNotFoundError(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
try:
enrollment = CourseEnrollment.enroll(
@@ -153,14 +153,14 @@ def create_course_enrollment(username, course_id, mode, is_active, enterprise_uu
)
return _update_enrollment(enrollment, is_active=is_active, mode=mode)
except NonExistentCourseError as err:
- raise CourseNotFoundError(str(err)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CourseNotFoundError(str(err)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except EnrollmentClosedError as err:
- raise CourseEnrollmentClosedError(str(err)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CourseEnrollmentClosedError(str(err)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except CourseFullError as err:
- raise CourseEnrollmentFullError(str(err)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CourseEnrollmentFullError(str(err)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except AlreadyEnrolledError as err:
enrollment = get_course_enrollment(username, course_id)
- raise CourseEnrollmentExistsError(str(err), enrollment) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CourseEnrollmentExistsError(str(err), enrollment) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def update_course_enrollment(username, course_id, mode=None, is_active=None):
@@ -185,7 +185,7 @@ def update_course_enrollment(username, course_id, mode=None, is_active=None):
except User.DoesNotExist:
msg = f"Not user with username '{username}' found."
log.warning(msg)
- raise UserNotFoundError(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise UserNotFoundError(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
try:
enrollment = CourseEnrollment.objects.get(user=user, course_id=course_key)
@@ -276,7 +276,7 @@ def _get_user(username):
except User.DoesNotExist:
msg = f"Not user with username '{username}' found."
log.warning(msg)
- raise UserNotFoundError(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise UserNotFoundError(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def _update_enrollment(enrollment, is_active=None, mode=None):
@@ -340,7 +340,7 @@ def get_course_enrollment_info(course_id, include_expired=False):
except CourseOverview.DoesNotExist:
msg = f"Requested enrollment information for unknown course {course_id}"
log.warning(msg)
- raise CourseNotFoundError(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CourseNotFoundError(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return CourseSerializer(course, include_expired=include_expired).data
diff --git a/openedx/core/djangoapps/enrollments/forms.py b/openedx/core/djangoapps/enrollments/forms.py
index e87210b3fee4..01b1bde61e39 100644
--- a/openedx/core/djangoapps/enrollments/forms.py
+++ b/openedx/core/djangoapps/enrollments/forms.py
@@ -30,7 +30,7 @@ def clean_course_id(self):
try:
return CourseKey.from_string(course_id)
except InvalidKeyError:
- raise ValidationError(f"'{course_id}' is not a valid course id.") # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(f"'{course_id}' is not a valid course id.") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return course_id
def clean_username(self):
@@ -42,7 +42,7 @@ def clean_username(self):
usernames = usernames_csv_string.split(',')
if len(usernames) > self.MAX_INPUT_COUNT:
raise ValidationError(
- "Too many usernames in a single request - {}. A maximum of {} is allowed".format(
+ "Too many usernames in a single request - {}. A maximum of {} is allowed".format( # noqa: UP032
len(usernames),
self.MAX_INPUT_COUNT,
)
@@ -61,7 +61,7 @@ def clean_course_ids(self):
course_ids = course_ids_csv_string.split(',')
if len(course_ids) > self.MAX_INPUT_COUNT:
raise ValidationError(
- "Too many course_ids in a single request - {}. A maximum of {} is allowed".format(
+ "Too many course_ids in a single request - {}. A maximum of {} is allowed".format( # noqa: UP032
len(course_ids),
self.MAX_INPUT_COUNT,
)
@@ -79,7 +79,7 @@ def clean_email(self):
emails = emails_csv_string.split(',')
if len(emails) > self.MAX_INPUT_COUNT:
raise ValidationError(
- "Too many emails in a single request - {}. A maximum of {} is allowed".format(
+ "Too many emails in a single request - {}. A maximum of {} is allowed".format( # noqa: UP032
len(emails),
self.MAX_INPUT_COUNT,
)
diff --git a/openedx/core/djangoapps/enrollments/tests/test_services.py b/openedx/core/djangoapps/enrollments/tests/test_services.py
index 47ff09399c03..0017bfb6000a 100644
--- a/openedx/core/djangoapps/enrollments/tests/test_services.py
+++ b/openedx/core/djangoapps/enrollments/tests/test_services.py
@@ -53,7 +53,7 @@ def test_get_active_enrollments_by_course(self):
Test that it returns a list of active enrollments for a course
"""
enrollments = self.service.get_active_enrollments_by_course(course_id=str(self.course.id))
- self.assertEqual(len(self.course_modes), len(enrollments))
+ self.assertEqual(len(self.course_modes), len(enrollments)) # noqa: PT009
def test_get_active_enrollments_by_course_and_user(self):
"""
@@ -64,7 +64,7 @@ def test_get_active_enrollments_by_course_and_user(self):
self.users[0].id,
)
expected_values = {'username': 'user0', 'mode': 'audit'}
- self.assertDictEqual(self.enrollment_to_dict(enrollment), expected_values)
+ self.assertDictEqual(self.enrollment_to_dict(enrollment), expected_values) # noqa: PT009
def test_get_active_enrollments_by_course_and_user_none_course(self):
"""
@@ -75,13 +75,13 @@ def test_get_active_enrollments_by_course_and_user_none_course(self):
'course-v1:testx+none+123',
self.users[0].id,
)
- self.assertIsNone(enrollments)
+ self.assertIsNone(enrollments) # noqa: PT009
def test_get_active_enrollments_by_course_and_user_none_user(self):
"""
Test getting enrollments for a course and non existing user raise error
"""
- with self.assertRaises(AssertionError):
+ with self.assertRaises(AssertionError): # noqa: PT027
self.service.get_active_enrollments_by_course_and_user(
str(self.course.id),
0000,
@@ -100,7 +100,7 @@ def test_get_enrollments_can_take_proctored_exams_by_course(self):
{'username': 'user5', 'mode': 'verified'}
]
actual_values = [self.enrollment_to_dict(e) for e in enrollments]
- self.assertEqual(actual_values, expected_values)
+ self.assertEqual(actual_values, expected_values) # noqa: PT009
def test_get_enrollments_can_take_proctored_exams_by_course_ignore_inactive(self):
"""
@@ -145,7 +145,7 @@ def test_get_enrollments_can_take_proctored_exams_allow_honor(self):
]
actual_values = [self.enrollment_to_dict(e) for e in enrollments]
- self.assertEqual(actual_values, expected_values)
+ self.assertEqual(actual_values, expected_values) # noqa: PT009
def test_get_enrollments_can_take_proctored_exams_not_enable_proctored_exams(self):
self.course.enable_proctored_exams = False
@@ -174,7 +174,7 @@ def test_text_search_partial_return_all(self, text_search):
{'username': 'user5', 'mode': 'verified'}
]
actual_values = [self.enrollment_to_dict(e) for e in enrollments]
- self.assertEqual(actual_values, expected_values)
+ self.assertEqual(actual_values, expected_values) # noqa: PT009
def test_text_search_partial_return_some(self):
enrollments = self.service.get_enrollments_can_take_proctored_exams(
@@ -186,7 +186,7 @@ def test_text_search_partial_return_some(self):
{'username': 'user3', 'mode': 'masters'}
]
actual_values = [self.enrollment_to_dict(e) for e in enrollments]
- self.assertEqual(actual_values, expected_values)
+ self.assertEqual(actual_values, expected_values) # noqa: PT009
@ddt.data('user1', 'USER1', 'LEARNER1@example.com', 'lEarNer1@eXAMPLE.com')
def test_text_search_exact_return_one(self, text_search):
@@ -199,7 +199,7 @@ def test_text_search_exact_return_one(self, text_search):
{'username': 'user1', 'mode': 'executive-education'}
]
actual_values = [self.enrollment_to_dict(e) for e in enrollments]
- self.assertEqual(actual_values, expected_values)
+ self.assertEqual(actual_values, expected_values) # noqa: PT009
def test_text_search_return_none(self):
enrollments = self.service.get_enrollments_can_take_proctored_exams(
diff --git a/openedx/core/djangoapps/enrollments/tests/test_views.py b/openedx/core/djangoapps/enrollments/tests/test_views.py
index d9e0f55e7a06..3f2c30bada4b 100644
--- a/openedx/core/djangoapps/enrollments/tests/test_views.py
+++ b/openedx/core/djangoapps/enrollments/tests/test_views.py
@@ -538,7 +538,7 @@ def _assert_enrollments_visible_in_list(self, courses, use_server_key=False):
response = self.client.get(reverse('courseenrollments'), {'user': self.user.username}, **kwargs)
assert response.status_code == status.HTTP_200_OK
data = json.loads(response.content.decode('utf-8'))
- self.assertCountEqual(
+ self.assertCountEqual( # noqa: PT009
[(datum['course_details']['course_id'], datum['course_details']['course_name']) for datum in data],
[(str(course.id), course.display_name_with_default) for course in courses]
)
@@ -1147,7 +1147,7 @@ def test_change_mode_from_server(self, old_mode, new_mode, old_is_active, new_is
assert is_active == old_is_active
assert course_mode == old_mode
# error message should contain specific text. Otto checks for this text in the message.
- self.assertRegex(
+ self.assertRegex( # noqa: PT009
json.loads(response.content.decode('utf-8'))['message'],
'Enrollment mode mismatch'
)
@@ -1762,7 +1762,7 @@ def test_roles_exception(self):
response = self.client.get(reverse('roles'))
assert response.status_code == status.HTTP_400_BAD_REQUEST
expected_response = {
- "message": (
+ "message": ( # noqa: UP032
"An error occurred while retrieving roles for user '{username}"
).format(username=self.user.username)
}
@@ -1925,7 +1925,7 @@ def test_response_valid_queries(self, args):
content = self._assert_list_of_enrollments(query_params, status.HTTP_200_OK)
results = content['results']
- self.assertCountEqual(results, expected_results)
+ self.assertCountEqual(results, expected_results) # noqa: PT009
@ddt.ddt
diff --git a/openedx/core/djangoapps/enrollments/urls.py b/openedx/core/djangoapps/enrollments/urls.py
index 828d4b61798b..d908b2f1ef2b 100644
--- a/openedx/core/djangoapps/enrollments/urls.py
+++ b/openedx/core/djangoapps/enrollments/urls.py
@@ -18,7 +18,7 @@
urlpatterns = [
re_path(
- r"^enrollment/{username},{course_key}$".format(
+ r"^enrollment/{username},{course_key}$".format( # noqa: UP032
username=settings.USERNAME_PATTERN, course_key=settings.COURSE_ID_PATTERN
),
EnrollmentView.as_view(),
diff --git a/openedx/core/djangoapps/enrollments/views.py b/openedx/core/djangoapps/enrollments/views.py
index 65d567ebdf1c..4796ee9d3c43 100644
--- a/openedx/core/djangoapps/enrollments/views.py
+++ b/openedx/core/djangoapps/enrollments/views.py
@@ -226,7 +226,7 @@ def get(self, request, course_id=None, username=None):
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
- "message": (
+ "message": ( # noqa: UP032
"An error occurred while retrieving enrollments for user "
"'{username}' in course '{course_id}'"
).format(username=username, course_id=course_id)
@@ -281,7 +281,7 @@ def get(self, request):
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
- "message": ("An error occurred while retrieving roles for user '{username}").format(
+ "message": ("An error occurred while retrieving roles for user '{username}").format( # noqa: UP032
username=request.user.username
)
},
@@ -384,7 +384,7 @@ def get(self, request, course_id=None):
except CourseNotFoundError:
return Response(
status=status.HTTP_400_BAD_REQUEST,
- data={"message": ("No course found for course ID '{course_id}'").format(course_id=course_id)},
+ data={"message": ("No course found for course ID '{course_id}'").format(course_id=course_id)}, # noqa: UP032 # pylint: disable=line-too-long
)
@@ -662,7 +662,7 @@ def get(self, request):
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
- "message": ("An error occurred while retrieving enrollments for user '{username}'").format(
+ "message": ("An error occurred while retrieving enrollments for user '{username}'").format( # noqa: UP032 # pylint: disable=line-too-long
username=username
)
},
@@ -746,7 +746,7 @@ def post(self, request):
return Response(
status=status.HTTP_403_FORBIDDEN,
data={
- "message": "User does not have permission to create enrollment with mode [{mode}].".format(
+ "message": "User does not have permission to create enrollment with mode [{mode}].".format( # noqa: UP032 # pylint: disable=line-too-long
mode=mode
)
},
@@ -771,7 +771,7 @@ def post(self, request):
if is_active is not None and not isinstance(is_active, bool):
return Response(
status=status.HTTP_400_BAD_REQUEST,
- data={"message": ("'{value}' is an invalid enrollment activation status.").format(value=is_active)},
+ data={"message": ("'{value}' is an invalid enrollment activation status.").format(value=is_active)}, # noqa: UP032 # pylint: disable=line-too-long
)
explicit_linked_enterprise = request.data.get("linked_enterprise_customer")
@@ -787,7 +787,7 @@ def post(self, request):
username,
course_id,
)
- raise CourseEnrollmentError(str(error)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CourseEnrollmentError(str(error)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
kwargs = {
"username": username,
"course_id": str(course_id),
@@ -802,7 +802,7 @@ def post(self, request):
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
- "message": ("'{value}' is an invalid force enrollment status.").format(value=force_enrollment)
+ "message": ("'{value}' is an invalid force enrollment status.").format(value=force_enrollment) # noqa: UP032 # pylint: disable=line-too-long
},
)
# Only a staff user role can enroll a user forcefully
@@ -826,7 +826,7 @@ def post(self, request):
return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": msg})
if missing_attrs:
- msg = "Missing enrollment attributes: requested mode={} required attributes={}".format(
+ msg = "Missing enrollment attributes: requested mode={} required attributes={}".format( # noqa: UP032 # pylint: disable=line-too-long
mode, REQUIRED_ATTRIBUTES.get(mode)
)
log.warning(msg)
@@ -891,7 +891,7 @@ def post(self, request):
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
- "message": (
+ "message": ( # noqa: UP032
"The [{mode}] course mode is expired or otherwise unavailable for course run [{course_id}]."
).format(mode=mode, course_id=course_id),
"course_details": error.data,
@@ -913,7 +913,7 @@ def post(self, request):
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
- "message": (
+ "message": ( # noqa: UP032
"An error occurred while creating the new course enrollment for user "
"'{username}' in course '{course_id}'"
).format(username=username, course_id=course_id)
@@ -924,7 +924,7 @@ def post(self, request):
log.exception("Missing cohort [%s] in course run [%s]", cohort_name, course_id)
return Response(
status=status.HTTP_400_BAD_REQUEST,
- data={"message": "An error occured while adding to cohort [%s]" % cohort_name},
+ data={"message": "An error occured while adding to cohort [%s]" % cohort_name}, # noqa: UP031
)
finally:
# Assumes that the ecommerce service uses an API key to authenticate.
diff --git a/openedx/core/djangoapps/external_user_ids/models.py b/openedx/core/djangoapps/external_user_ids/models.py
index 09fe47c4f317..d017a6a15b89 100644
--- a/openedx/core/djangoapps/external_user_ids/models.py
+++ b/openedx/core/djangoapps/external_user_ids/models.py
@@ -87,7 +87,7 @@ def add_new_user_id(cls, user, type_name):
type_obj = ExternalIdType.objects.get(name=type_name)
except ExternalIdType.DoesNotExist:
LOGGER.info(
- 'External ID Creation failed for user {user}, no external id type of {type}'.format(
+ 'External ID Creation failed for user {user}, no external id type of {type}'.format( # noqa: UP032
user=user.id,
type=type_name
)
@@ -99,7 +99,7 @@ def add_new_user_id(cls, user, type_name):
)
if created:
LOGGER.info(
- 'External ID Created for user {user}, of type {type}'.format(
+ 'External ID Created for user {user}, of type {type}'.format( # noqa: UP032
user=user.id,
type=type_name
)
@@ -128,7 +128,7 @@ def batch_get_or_create_user_ids(cls, users, type_name):
type_obj = ExternalIdType.objects.get(name=type_name)
except ExternalIdType.DoesNotExist:
LOGGER.info(
- 'Batch ID Creation failed, no external id type of {type!r}'.format(
+ 'Batch ID Creation failed, no external id type of {type!r}'.format( # noqa: UP032
type=type_name
)
)
diff --git a/openedx/core/djangoapps/heartbeat/runchecks.py b/openedx/core/djangoapps/heartbeat/runchecks.py
index 0bf0c2563b14..792c14aa41dc 100644
--- a/openedx/core/djangoapps/heartbeat/runchecks.py
+++ b/openedx/core/djangoapps/heartbeat/runchecks.py
@@ -35,7 +35,7 @@ def runchecks(include_extended=False):
'message': message
}
except ImportError as e:
- raise ImproperlyConfigured(f'Error importing module {module}: "{e}"') # lint-amnesty, pylint: disable=raise-missing-from
+ raise ImproperlyConfigured(f'Error importing module {module}: "{e}"') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except AttributeError:
- raise ImproperlyConfigured(f'Module "{module}" does not define a "{attr}" callable') # lint-amnesty, pylint: disable=raise-missing-from
+ raise ImproperlyConfigured(f'Module "{module}" does not define a "{attr}" callable') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return response_dict
diff --git a/openedx/core/djangoapps/lang_pref/tests/test_middleware.py b/openedx/core/djangoapps/lang_pref/tests/test_middleware.py
index b71b91605cf9..eba0467fdb6c 100644
--- a/openedx/core/djangoapps/lang_pref/tests/test_middleware.py
+++ b/openedx/core/djangoapps/lang_pref/tests/test_middleware.py
@@ -155,7 +155,7 @@ def test_preference_cookie_overrides_browser(self, logged_in, lang_cookie, accep
accept_lang_out = parse_accept_lang_header(accept_lang_out)
if accept_lang_out and accept_lang_result:
- self.assertCountEqual(accept_lang_result, accept_lang_out)
+ self.assertCountEqual(accept_lang_result, accept_lang_out) # noqa: PT009
else:
assert accept_lang_result == accept_lang_out
diff --git a/openedx/core/djangoapps/models/tests/test_course_details.py b/openedx/core/djangoapps/models/tests/test_course_details.py
index a5ba23df4ad8..383281aac4d1 100644
--- a/openedx/core/djangoapps/models/tests/test_course_details.py
+++ b/openedx/core/djangoapps/models/tests/test_course_details.py
@@ -145,7 +145,7 @@ def test_fetch_about_attribute_error(self):
attribute_name = 'not_an_about_attribute'
with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, self.course.id):
CourseDetails.update_about_item(self.course, attribute_name, 'test_value', self.user.id)
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
CourseDetails.fetch_about_attribute(self.course.id, attribute_name)
def test_fetch_video(self):
@@ -154,7 +154,7 @@ def test_fetch_video(self):
CourseDetails.update_about_video(self.course, video_value, self.user.id)
assert CourseDetails.fetch_youtube_video_id(self.course.id) == video_value
video_url = CourseDetails.fetch_video_url(self.course.id)
- self.assertRegex(video_url, fr'http://.*{video_value}')
+ self.assertRegex(video_url, fr'http://.*{video_value}') # noqa: PT009
@ddt.data(
(
diff --git a/openedx/core/djangoapps/notifications/apps.py b/openedx/core/djangoapps/notifications/apps.py
index ffad68eccde6..9d2ce2bf05bb 100644
--- a/openedx/core/djangoapps/notifications/apps.py
+++ b/openedx/core/djangoapps/notifications/apps.py
@@ -17,5 +17,5 @@ def ready(self):
Import signals
"""
# pylint: disable=unused-import
- from . import handlers
- from .email import tasks
+ from . import handlers # noqa: F401
+ from .email import tasks # noqa: F401
diff --git a/openedx/core/djangoapps/notifications/audience_filters.py b/openedx/core/djangoapps/notifications/audience_filters.py
index af833be93131..555b87ad0944 100644
--- a/openedx/core/djangoapps/notifications/audience_filters.py
+++ b/openedx/core/djangoapps/notifications/audience_filters.py
@@ -4,7 +4,7 @@
import logging
from abc import abstractmethod
-from typing import List
+from typing import List # noqa: UP035
from django.utils import timezone
from opaque_keys.edx.keys import CourseKey
@@ -160,7 +160,7 @@ class NotificationFilter:
"""
@staticmethod
- def get_users_with_course_role(user_ids: List[int], course_id: str) -> List[int]:
+ def get_users_with_course_role(user_ids: List[int], course_id: str) -> List[int]: # noqa: UP006
"""
Get users with a course role for the given course.
"""
@@ -170,7 +170,7 @@ def get_users_with_course_role(user_ids: List[int], course_id: str) -> List[int]
).values_list('user_id', flat=True)
@staticmethod
- def get_users_with_forum_roles(user_ids: List[int], course_id: str) -> List[int]:
+ def get_users_with_forum_roles(user_ids: List[int], course_id: str) -> List[int]: # noqa: UP006
"""
Get users with forum roles for the given course.
"""
diff --git a/openedx/core/djangoapps/notifications/email/tasks.py b/openedx/core/djangoapps/notifications/email/tasks.py
index 1250e4cc92db..7cdf2feec3f3 100644
--- a/openedx/core/djangoapps/notifications/email/tasks.py
+++ b/openedx/core/djangoapps/notifications/email/tasks.py
@@ -497,4 +497,4 @@ def send_buffered_digest(
except Exception as exc:
logger.exception(f'Email Buffered Digest: Failed to send buffered digest: {exc}')
retry_countdown = 60 * (2 ** self.request.retries)
- raise self.retry(exc=exc, countdown=retry_countdown)
+ raise self.retry(exc=exc, countdown=retry_countdown) # noqa: B904
diff --git a/openedx/core/djangoapps/notifications/email/tests/test_tasks.py b/openedx/core/djangoapps/notifications/email/tests/test_tasks.py
index 7977b2b26e32..3fb6cbe9fbf9 100644
--- a/openedx/core/djangoapps/notifications/email/tests/test_tasks.py
+++ b/openedx/core/djangoapps/notifications/email/tests/test_tasks.py
@@ -2,7 +2,7 @@
Test cases for notifications/email/tasks.py
"""
import datetime
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta # noqa: F811
from unittest.mock import Mock, patch
import ddt
@@ -540,7 +540,7 @@ def test_race_condition_protection(self):
notification2 = self._create_notification()
# Both should see no recent email initially
- with patch('openedx.core.djangoapps.notifications.email.tasks.logger') as mock_logger:
+ with patch('openedx.core.djangoapps.notifications.email.tasks.logger') as mock_logger: # noqa: F841
decision1 = decide_email_action(self.user, self.course_key, notification1)
# Mark first as sent to simulate race
@@ -937,7 +937,7 @@ def test_digest_retries_on_failure(self, mock_ace_send):
mock_task = Mock()
mock_task.request.retries = 0
- with self.assertRaises(Exception):
+ with self.assertRaises(Exception): # noqa: B017, PT027
send_buffered_digest.bind(mock_task)(
user_id=self.user.id,
course_key=self.course_key,
@@ -1109,7 +1109,7 @@ def test_multiple_courses_independent_buffers(self):
course2 = CourseFactory.create()
# Notifications in course 1
- notif1 = Notification.objects.create(
+ notif1 = Notification.objects.create( # noqa: F841
user=self.user,
course_id=self.course.id,
app_name='discussion',
diff --git a/openedx/core/djangoapps/notifications/email/tests/test_utils.py b/openedx/core/djangoapps/notifications/email/tests/test_utils.py
index f41c18e4c4fc..a1bdffe7f0bf 100644
--- a/openedx/core/djangoapps/notifications/email/tests/test_utils.py
+++ b/openedx/core/djangoapps/notifications/email/tests/test_utils.py
@@ -274,6 +274,6 @@ def test_user_preference_created_on_email_unsubscribe(self):
"""
encrypted_username = encrypt_string(self.user.username)
update_user_preferences_from_patch(encrypted_username)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
UserPreference.objects.filter(user=self.user, key=ONE_CLICK_EMAIL_UNSUB_KEY).exists()
)
diff --git a/openedx/core/djangoapps/notifications/email/utils.py b/openedx/core/djangoapps/notifications/email/utils.py
index 8b147991a7cb..d63a1f4a49f1 100644
--- a/openedx/core/djangoapps/notifications/email/utils.py
+++ b/openedx/core/djangoapps/notifications/email/utils.py
@@ -73,7 +73,7 @@ def create_email_template_context(username):
for social_platform in social_media_urls.keys()
if social_media_icons.get(social_platform)
}
- patch = {
+ patch = { # noqa: F841
'channel': 'email',
'value': False
}
diff --git a/openedx/core/djangoapps/notifications/grouping_notifications.py b/openedx/core/djangoapps/notifications/grouping_notifications.py
index 19abed761ce6..cb38ddc002bf 100644
--- a/openedx/core/djangoapps/notifications/grouping_notifications.py
+++ b/openedx/core/djangoapps/notifications/grouping_notifications.py
@@ -3,7 +3,7 @@
"""
import datetime
from abc import ABC, abstractmethod
-from typing import Dict, Type, Union
+from typing import Dict, Type, Union # noqa: UP035
from pytz import utc
@@ -27,7 +27,7 @@ class NotificationRegistry:
"""
Registry for notification groupers.
"""
- _groupers: Dict[str, Type[BaseNotificationGrouper]] = {}
+ _groupers: Dict[str, Type[BaseNotificationGrouper]] = {} # noqa: UP006
@classmethod
def register(cls, notification_type: str):
@@ -40,7 +40,7 @@ def register(cls, notification_type: str):
A decorator that registers the grouper class for the given notification type.
"""
- def decorator(grouper_class: Type[BaseNotificationGrouper]) -> Type[BaseNotificationGrouper]:
+ def decorator(grouper_class: Type[BaseNotificationGrouper]) -> Type[BaseNotificationGrouper]: # noqa: UP006
"""
Registers the grouper class for the given notification type.
"""
@@ -54,7 +54,7 @@ def decorator(grouper_class: Type[BaseNotificationGrouper]) -> Type[BaseNotifica
return decorator
@classmethod
- def get_grouper(cls, notification_type: str) -> Union[BaseNotificationGrouper, None]:
+ def get_grouper(cls, notification_type: str) -> Union[BaseNotificationGrouper, None]: # noqa: UP007
"""Retrieves the appropriate notification grouper based on the given notification type.
Args:
diff --git a/openedx/core/djangoapps/notifications/management/tests/test_delete_notifications.py b/openedx/core/djangoapps/notifications/management/tests/test_delete_notifications.py
index c15a06da3f0d..f8d3acd25dbb 100644
--- a/openedx/core/djangoapps/notifications/management/tests/test_delete_notifications.py
+++ b/openedx/core/djangoapps/notifications/management/tests/test_delete_notifications.py
@@ -28,7 +28,7 @@ def test_management_command_fails_if_required_param_is_missing(self, param):
default_dict.pop(param)
try:
call_command('delete_notifications', **default_dict)
- assert False
+ assert False # noqa: B011, PT015
except Exception: # pylint: disable=broad-except
pass
diff --git a/openedx/core/djangoapps/notifications/models.py b/openedx/core/djangoapps/notifications/models.py
index ad9860a6bb77..3052e89d78a7 100644
--- a/openedx/core/djangoapps/notifications/models.py
+++ b/openedx/core/djangoapps/notifications/models.py
@@ -47,7 +47,7 @@ class Notification(TimeStampedModel):
app_name = models.CharField(max_length=64, db_index=True)
notification_type = models.CharField(max_length=64)
content_context = models.JSONField(default=dict)
- content_url = models.URLField(null=True, blank=True)
+ content_url = models.URLField(null=True, blank=True) # noqa: DJ001
web = models.BooleanField(default=True, null=False, blank=False)
email = models.BooleanField(default=False, null=False, blank=False)
push = models.BooleanField(default=False, null=False, blank=False)
diff --git a/openedx/core/djangoapps/notifications/notification_content.py b/openedx/core/djangoapps/notifications/notification_content.py
index aa1e87d00254..f7ead44235ae 100644
--- a/openedx/core/djangoapps/notifications/notification_content.py
+++ b/openedx/core/djangoapps/notifications/notification_content.py
@@ -1,7 +1,7 @@
"""
Helper functions for overriding notification content for given notification type.
"""
-from typing import Dict
+from typing import Dict # noqa: UP035
def get_notification_type_context_function(notification_type) -> callable:
@@ -15,7 +15,7 @@ def get_notification_type_context_function(notification_type) -> callable:
return lambda context: context
-def get_notification_context_with_author_pronoun(context: Dict) -> Dict:
+def get_notification_context_with_author_pronoun(context: Dict) -> Dict: # noqa: UP006
"""
Returns the context for the given notification type with the author pronoun.
diff --git a/openedx/core/djangoapps/notifications/serializers.py b/openedx/core/djangoapps/notifications/serializers.py
index 78d0998db99e..d50b180115ac 100644
--- a/openedx/core/djangoapps/notifications/serializers.py
+++ b/openedx/core/djangoapps/notifications/serializers.py
@@ -180,7 +180,7 @@ def validate(self, attrs):
"""
Cross-field validation for notification preference update.
"""
- notification_app = attrs.get('notification_app')
+ notification_app = attrs.get('notification_app') # noqa: F841
notification_type = attrs.get('notification_type')
notification_channel = attrs.get('notification_channel')
email_cadence = attrs.get('email_cadence')
diff --git a/openedx/core/djangoapps/notifications/settings_override.py b/openedx/core/djangoapps/notifications/settings_override.py
index 4ba81060e7b0..760c870546f4 100644
--- a/openedx/core/djangoapps/notifications/settings_override.py
+++ b/openedx/core/djangoapps/notifications/settings_override.py
@@ -5,16 +5,16 @@
via Django settings.
"""
from copy import deepcopy
-from typing import Any, Dict, Set
+from typing import Any, Dict, Set # noqa: UP035
from django.conf import settings
def _apply_overrides(
- default_config: Dict[str, Any],
+ default_config: Dict[str, Any], # noqa: UP006
setting_name: str,
- allowed_keys: Set[str]
-) -> Dict[str, Any]:
+ allowed_keys: Set[str] # noqa: UP006
+) -> Dict[str, Any]: # noqa: UP006
"""
Internal helper to apply settings overrides to a default configuration dictionary.
@@ -37,7 +37,7 @@ def _apply_overrides(
return config
-def get_notification_types_config() -> Dict[str, Any]:
+def get_notification_types_config() -> Dict[str, Any]: # noqa: UP006
"""
Get COURSE_NOTIFICATION_TYPES configuration with settings overrides applied.
"""
@@ -50,7 +50,7 @@ def get_notification_types_config() -> Dict[str, Any]:
)
-def get_notification_apps_config() -> Dict[str, Any]:
+def get_notification_apps_config() -> Dict[str, Any]: # noqa: UP006
"""
Get COURSE_NOTIFICATION_APPS configuration with settings overrides applied.
"""
diff --git a/openedx/core/djangoapps/notifications/tests/test_filters.py b/openedx/core/djangoapps/notifications/tests/test_filters.py
index a580788d0e40..983cb182fd9f 100644
--- a/openedx/core/djangoapps/notifications/tests/test_filters.py
+++ b/openedx/core/djangoapps/notifications/tests/test_filters.py
@@ -83,14 +83,14 @@ def test_audit_expired_filter_with_no_role(
[self.user.id, self.user_1.id],
self.course,
)
- self.assertEqual([self.user_1.id], result)
+ self.assertEqual([self.user_1.id], result) # noqa: PT009
mock_get_course_run_details.return_value = {'weeks_to_complete': 7}
result = NotificationFilter().filter_audit_expired_users_with_no_role(
[self.user.id, self.user_1.id],
self.course,
)
- self.assertEqual([self.user.id, self.user_1.id], result)
+ self.assertEqual([self.user.id, self.user_1.id], result) # noqa: PT009
CourseDurationLimitConfig.objects.create(
enabled=True,
@@ -103,7 +103,7 @@ def test_audit_expired_filter_with_no_role(
[self.user.id, self.user_1.id],
self.course,
)
- self.assertEqual([self.user.id, self.user_1.id], result)
+ self.assertEqual([self.user.id, self.user_1.id], result) # noqa: PT009
@mock.patch("openedx.core.djangoapps.course_date_signals.utils.get_course_run_details")
@mock.patch(
@@ -124,7 +124,7 @@ def test_apply_filter(
self.course.id,
'new_comment_on_response'
)
- self.assertEqual([self.user.id, self.user_1.id], result)
+ self.assertEqual([self.user.id, self.user_1.id], result) # noqa: PT009
mock_filter_audit_expired.assert_called_once()
@mock.patch("openedx.core.djangoapps.course_date_signals.utils.get_course_run_details")
@@ -141,13 +141,13 @@ def test_audit_expired_for_course_staff(
[self.user.id, self.user_1.id],
self.course,
)
- self.assertEqual([self.user_1.id], result)
+ self.assertEqual([self.user_1.id], result) # noqa: PT009
CourseInstructorRole(self.course.id).add_users(self.user)
result = NotificationFilter().filter_audit_expired_users_with_no_role(
[self.user.id, self.user_1.id],
self.course,
)
- self.assertEqual([self.user.id, self.user_1.id], result)
+ self.assertEqual([self.user.id, self.user_1.id], result) # noqa: PT009
@mock.patch("openedx.core.djangoapps.course_date_signals.utils.get_course_run_details")
@ddt.data(
@@ -171,14 +171,14 @@ def test_audit_expired_for_forum_roles(
[self.user.id, self.user_1.id],
self.course,
)
- self.assertEqual([self.user_1.id], result)
+ self.assertEqual([self.user_1.id], result) # noqa: PT009
role = Role.objects.get_or_create(course_id=self.course.id, name=role_name)[0]
role.users.add(self.user.id)
result = NotificationFilter().filter_audit_expired_users_with_no_role(
[self.user.id, self.user_1.id],
self.course,
)
- self.assertEqual([self.user.id, self.user_1.id], result)
+ self.assertEqual([self.user.id, self.user_1.id], result) # noqa: PT009
def assign_enrollment_mode_to_users(course_id, users, mode):
@@ -231,12 +231,12 @@ def setUp(self):
def test_valid_enrollment_filter(self, enrollment_modes, expected_count):
enrollment_filter = EnrollmentAudienceFilter(self.course.id)
filtered_users = enrollment_filter.filter(enrollment_modes)
- self.assertEqual(len(filtered_users), expected_count)
+ self.assertEqual(len(filtered_users), expected_count) # noqa: PT009
def test_invalid_enrollment_filter(self):
enrollment_filter = EnrollmentAudienceFilter(self.course.id)
enrollment_modes = ["INVALID_MODE"]
- with self.assertRaises(ValueError):
+ with self.assertRaises(ValueError): # noqa: PT027
enrollment_filter.filter(enrollment_modes)
@@ -282,12 +282,12 @@ def setUp(self):
def test_valid_role_filter(self, role_names, expected_count):
role_filter = ForumRoleAudienceFilter(self.course.id)
filtered_users = role_filter.filter(role_names)
- self.assertEqual(len(filtered_users), expected_count)
+ self.assertEqual(len(filtered_users), expected_count) # noqa: PT009
def test_invalid_role_filter(self):
role_filter = ForumRoleAudienceFilter(self.course.id)
role_names = ["INVALID_MODE"]
- with self.assertRaises(ValueError):
+ with self.assertRaises(ValueError): # noqa: PT027
role_filter.filter(role_names)
@@ -319,12 +319,12 @@ def setUp(self):
def test_valid_role_filter(self, role_names, expected_count):
course_role_filter = CourseRoleAudienceFilter(self.course.id)
filtered_users = course_role_filter.filter(role_names)
- self.assertEqual(len(filtered_users), expected_count)
+ self.assertEqual(len(filtered_users), expected_count) # noqa: PT009
def test_invalid_role_filter(self):
course_role_filter = CourseRoleAudienceFilter(self.course.id)
role_names = ["INVALID_MODE"]
- with self.assertRaises(ValueError):
+ with self.assertRaises(ValueError): # noqa: PT027
course_role_filter.filter(role_names)
@@ -357,12 +357,12 @@ def setUp(self):
def test_valid_cohort_filter(self, cohort_ids, expected_count):
cohort_filter = CohortAudienceFilter(self.course.id)
filtered_users = cohort_filter.filter(cohort_ids)
- self.assertEqual(len(filtered_users), expected_count)
+ self.assertEqual(len(filtered_users), expected_count) # noqa: PT009
def test_invalid_cohort_filter(self):
cohort_filter = CohortAudienceFilter(self.course.id)
cohort_ids = ["INVALID_MODE"]
- with self.assertRaises(ValueError):
+ with self.assertRaises(ValueError): # noqa: PT027
cohort_filter.filter(cohort_ids)
@@ -399,12 +399,12 @@ def setUp(self):
def test_valid_team_filter(self, team_ids, expected_count):
team_filter = TeamAudienceFilter(self.course.id)
filtered_users = team_filter.filter(team_ids)
- self.assertEqual(len(filtered_users), expected_count)
+ self.assertEqual(len(filtered_users), expected_count) # noqa: PT009
def test_invalid_team_filter(self):
team_filter = TeamAudienceFilter(self.course.id)
team_ids = ["INVALID_MODE"]
- with self.assertRaises(ValueError):
+ with self.assertRaises(ValueError): # noqa: PT027
team_filter.filter(team_ids)
@@ -459,11 +459,11 @@ def setUp(self):
@ddt.unpack
def test_combination_of_audience_filters(self, audience_filters, expected_count):
user_ids = calculate_course_wide_notification_audience(self.course.id, audience_filters)
- self.assertEqual(len(user_ids), expected_count)
+ self.assertEqual(len(user_ids), expected_count) # noqa: PT009
def test_invalid_audience_filter(self):
audience_filters = {
"invalid_filter": ["invalid_filter_type"],
}
- with self.assertRaises(ValueError):
+ with self.assertRaises(ValueError): # noqa: PT027
calculate_course_wide_notification_audience(self.course.id, audience_filters)
diff --git a/openedx/core/djangoapps/notifications/tests/test_handlers.py b/openedx/core/djangoapps/notifications/tests/test_handlers.py
index a058a4e80d42..1714a7577e1c 100644
--- a/openedx/core/djangoapps/notifications/tests/test_handlers.py
+++ b/openedx/core/djangoapps/notifications/tests/test_handlers.py
@@ -36,4 +36,4 @@ def test_generate_course_notifications(self, mock_send_notifications, mock_calcu
# Check if the sender_id was removed from the user_ids
expected_user_ids = [1, 2, 4] # 3 should be removed
notification_data = mock_send_notifications.delay.call_args[1]
- self.assertEqual(notification_data['user_ids'], expected_user_ids)
+ self.assertEqual(notification_data['user_ids'], expected_user_ids) # noqa: PT009
diff --git a/openedx/core/djangoapps/notifications/tests/test_notification_grouping.py b/openedx/core/djangoapps/notifications/tests/test_notification_grouping.py
index 4f9219af06fe..7501f6a16ea0 100644
--- a/openedx/core/djangoapps/notifications/tests/test_notification_grouping.py
+++ b/openedx/core/djangoapps/notifications/tests/test_notification_grouping.py
@@ -44,14 +44,14 @@ def group(self, new_notification, old_notification):
NotificationRegistry.register('test_notification')(TestGrouper)
grouper = NotificationRegistry.get_grouper('test_notification')
- self.assertIsInstance(grouper, TestGrouper)
+ self.assertIsInstance(grouper, TestGrouper) # noqa: PT009
def test_get_grouper_returns_none_for_unregistered_type(self):
"""
Test that get_grouper returns None for an unregistered notification type
"""
grouper = NotificationRegistry.get_grouper('non_existent')
- self.assertIsNone(grouper)
+ self.assertIsNone(grouper) # noqa: PT009
class TestNewPostGrouper(unittest.TestCase):
@@ -72,8 +72,8 @@ def test_group(self):
updated_context = NewPostGrouper().group(new_notification, old_notification)
- self.assertTrue(updated_context['grouped'])
- self.assertEqual(updated_context['replier_name'], new_notification.content_context['replier_name'])
+ self.assertTrue(updated_context['grouped']) # noqa: PT009
+ self.assertEqual(updated_context['replier_name'], new_notification.content_context['replier_name']) # noqa: PT009 # pylint: disable=line-too-long
def test_new_post_with_same_user(self):
"""
@@ -92,7 +92,7 @@ def test_new_post_with_same_user(self):
updated_context = NewPostGrouper().group(new_notification, old_notification)
- self.assertFalse(updated_context.get('grouped', False))
+ self.assertFalse(updated_context.get('grouped', False)) # noqa: PT009
@ddt.ddt
@@ -117,10 +117,10 @@ def test_group_user_notifications(self, grouper_class, mock_get_grouper):
group_user_notifications(new_notification, old_notification)
mock_grouper.group.assert_called_once_with(new_notification, old_notification)
- self.assertTrue(old_notification.save.called)
- self.assertIsNone(old_notification.last_read)
- self.assertIsNone(old_notification.last_seen)
- self.assertIsNotNone(old_notification.created)
+ self.assertTrue(old_notification.save.called) # noqa: PT009
+ self.assertIsNone(old_notification.last_read) # noqa: PT009
+ self.assertIsNone(old_notification.last_seen) # noqa: PT009
+ self.assertIsNotNone(old_notification.created) # noqa: PT009
def test_group_user_notifications_no_grouper(self):
"""
@@ -131,7 +131,7 @@ def test_group_user_notifications_no_grouper(self):
group_user_notifications(new_notification, old_notification)
- self.assertFalse(old_notification.save.called)
+ self.assertFalse(old_notification.save.called) # noqa: PT009
@ddt.data(datetime(2023, 1, 1, tzinfo=ZoneInfo("UTC")), None)
def test_not_grouped_when_notification_is_seen(self, last_seen):
@@ -193,5 +193,5 @@ def test_get_user_existing_notifications(self, mock_filter):
result = get_user_existing_notifications(user_ids, notification_type, group_by_id, course_id)
# Verify the results
- self.assertEqual(result[1], mock_notification2)
- self.assertIsNone(result[2]) # user 2 has no notifications
+ self.assertEqual(result[1], mock_notification2) # noqa: PT009
+ self.assertIsNone(result[2]) # user 2 has no notifications # noqa: PT009
diff --git a/openedx/core/djangoapps/notifications/tests/test_settings_override.py b/openedx/core/djangoapps/notifications/tests/test_settings_override.py
index 9e71f212d869..f06de829e2ec 100644
--- a/openedx/core/djangoapps/notifications/tests/test_settings_override.py
+++ b/openedx/core/djangoapps/notifications/tests/test_settings_override.py
@@ -34,17 +34,17 @@ def test_override_notification_types_real_config(self):
target_notification = config['new_comment_on_response']
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
target_notification['email'],
"The 'email' setting should be overridden to True."
)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
target_notification['use_app_defaults'],
"The 'use_app_defaults' field should not be overridable via settings."
)
# IMMUTABILITY CHECK: Ensure the global module variable wasn't touched
- self.assertFalse(
+ self.assertFalse( # noqa: PT009
_COURSE_NOTIFICATION_TYPES['new_discussion_post']['email'],
"The original global _COURSE_NOTIFICATION_TYPES must remain immutable."
)
@@ -58,7 +58,7 @@ def test_override_types_ignores_unknown_keys(self):
is safely ignored.
"""
config = get_notification_types_config()
- self.assertNotIn('non_existent_notification', config)
+ self.assertNotIn('non_existent_notification', config) # noqa: PT009
@override_settings(NOTIFICATION_APPS_OVERRIDE={
'discussion': {
@@ -74,17 +74,17 @@ def test_override_notification_apps_real_config(self):
target_app = config['discussion']
- self.assertFalse(
+ self.assertFalse( # noqa: PT009
target_app['email'],
"The 'email' setting should be overridden to False."
)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
target_app['enabled'],
"The 'enabled' field should not be overridable via settings."
)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
_COURSE_NOTIFICATION_APPS['discussion']['email'],
"The original global _COURSE_NOTIFICATION_APPS must remain immutable."
)
@@ -99,9 +99,9 @@ def test_partial_update_preserves_other_fields(self):
config = get_notification_types_config()
target = config['course_updates']
- self.assertFalse(target['web'])
+ self.assertFalse(target['web']) # noqa: PT009
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
target['email'],
"The 'email' field should be preserved from the default config."
)
@@ -119,7 +119,7 @@ def test_override_notification_types_email_cadence(self):
config = get_notification_types_config()
target = config['new_discussion_post']
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
target.get('email_cadence'),
'Weekly',
"The 'email_cadence' setting should be overridden to 'Weekly'."
@@ -138,7 +138,7 @@ def test_override_notification_apps_email_cadence(self):
config = get_notification_apps_config()
target_app = config['discussion']
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
target_app.get('email_cadence'),
'Immediately',
"The 'email_cadence' setting should be overridden to 'Immediately'."
diff --git a/openedx/core/djangoapps/notifications/tests/test_tasks_with_account_level_pref.py b/openedx/core/djangoapps/notifications/tests/test_tasks_with_account_level_pref.py
index 6092e460dfca..65bbc80aaa41 100644
--- a/openedx/core/djangoapps/notifications/tests/test_tasks_with_account_level_pref.py
+++ b/openedx/core/djangoapps/notifications/tests/test_tasks_with_account_level_pref.py
@@ -69,12 +69,12 @@ def test_send_notifications(self, app_name, notification_type):
if 'uuid' in notification.content_context:
notification.content_context.pop('uuid')
# Assert that the `Notification` objects have the correct properties.
- self.assertEqual(notification.user_id, self.user.id)
- self.assertEqual(notification.app_name, app_name)
- self.assertEqual(notification.notification_type, notification_type)
- self.assertEqual(notification.content_context, context)
- self.assertEqual(notification.content_url, content_url)
- self.assertEqual(notification.course_id, self.course_1.id)
+ self.assertEqual(notification.user_id, self.user.id) # noqa: PT009
+ self.assertEqual(notification.app_name, app_name) # noqa: PT009
+ self.assertEqual(notification.notification_type, notification_type) # noqa: PT009
+ self.assertEqual(notification.content_context, context) # noqa: PT009
+ self.assertEqual(notification.content_url, content_url) # noqa: PT009
+ self.assertEqual(notification.course_id, self.course_1.id) # noqa: PT009
@ddt.data(True, False)
def test_enable_notification_flag(self, flag_value):
@@ -92,7 +92,7 @@ def test_enable_notification_flag(self, flag_value):
with override_waffle_flag(DISABLE_NOTIFICATIONS, active=flag_value):
send_notifications([self.user.id], str(self.course_1.id), app_name, notification_type, context, content_url)
created_notifications_count = 0 if flag_value else 1
- self.assertEqual(len(Notification.objects.all()), created_notifications_count)
+ self.assertEqual(len(Notification.objects.all()), created_notifications_count) # noqa: PT009
def test_notification_not_send_with_preference_disabled(self):
"""
@@ -117,7 +117,7 @@ def test_notification_not_send_with_preference_disabled(self):
account_preferences.save()
send_notifications([self.user.id], str(self.course_1.id), app_name, notification_type, context, content_url)
- self.assertEqual(len(Notification.objects.all()), 0)
+ self.assertEqual(len(Notification.objects.all()), 0) # noqa: PT009
def test_send_notification_with_grouping_enabled(self):
"""
@@ -154,14 +154,14 @@ def test_send_notification_with_grouping_enabled(self):
{**context},
content_url
)
- self.assertEqual(Notification.objects.filter(user_id=self.user.id).count(), 1)
+ self.assertEqual(Notification.objects.filter(user_id=self.user.id).count(), 1) # noqa: PT009
user_notifications_mock.assert_called_once()
def test_notification_not_created_when_context_is_incomplete(self):
try:
send_notifications([self.user.id], str(self.course_1.id), "discussion", "new_comment", {}, "")
except Exception as exc: # pylint: disable=broad-except
- assert isinstance(exc, ValidationError)
+ assert isinstance(exc, ValidationError) # noqa: PT017
@ddt.ddt
@@ -283,7 +283,7 @@ def test_preference_enabled_in_batch_audience(self, notification_type, generated
}
content_url = 'https://example.com/'
send_notifications(user_ids, str(self.course.id), app_name, notification_type, context, content_url)
- self.assertEqual(len(Notification.objects.all()), generated_count)
+ self.assertEqual(len(Notification.objects.all()), generated_count) # noqa: PT009
class TestDeleteNotificationTask(ModuleStoreTestCase):
@@ -337,7 +337,7 @@ def test_created_param(self):
}
}
delete_notifications(kwargs)
- self.assertEqual(Notification.objects.all().count(), 1)
+ self.assertEqual(Notification.objects.all().count(), 1) # noqa: PT009
def test_course_id_param(self):
"""
@@ -405,7 +405,7 @@ def test_notification_is_created_when_any_channel_is_account_level(self, web_val
'username': 'user name',
},
}
- with patch('openedx.core.djangoapps.notifications.tasks.notification_generated_event') as event_mock:
+ with patch('openedx.core.djangoapps.notifications.tasks.notification_generated_event') as event_mock: # noqa: F841 # pylint: disable=line-too-long
send_notifications(**kwargs)
notifications = Notification.objects.all()
assert len(notifications) == generated_count
diff --git a/openedx/core/djangoapps/notifications/tests/test_views.py b/openedx/core/djangoapps/notifications/tests/test_views.py
index f7656aedf875..4622d3aec037 100644
--- a/openedx/core/djangoapps/notifications/tests/test_views.py
+++ b/openedx/core/djangoapps/notifications/tests/test_views.py
@@ -68,13 +68,13 @@ def test_list_notifications(self):
# Assert that the response is successful.
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
data = response.data['results']
# Assert that the response contains the notification.
- self.assertEqual(len(data), 1)
- self.assertEqual(data[0]['app_name'], 'discussion')
- self.assertEqual(data[0]['notification_type'], 'new_response')
- self.assertEqual(
+ self.assertEqual(len(data), 1) # noqa: PT009
+ self.assertEqual(data[0]['app_name'], 'discussion') # noqa: PT009
+ self.assertEqual(data[0]['notification_type'], 'new_response') # noqa: PT009
+ self.assertEqual( # noqa: PT009
data[0]['content'],
'test_user responded to your post This is a test post.
'
)
@@ -104,14 +104,14 @@ def test_list_notifications_with_app_name_filter(self):
response = self.client.get(self.url + "?app_name=discussion")
# Assert that the response is successful.
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
# Assert that the response contains only the notification for app1.
data = response.data['results']
- self.assertEqual(len(data), 1)
- self.assertEqual(data[0]['app_name'], 'discussion')
- self.assertEqual(data[0]['notification_type'], 'new_response')
- self.assertEqual(
+ self.assertEqual(len(data), 1) # noqa: PT009
+ self.assertEqual(data[0]['app_name'], 'discussion') # noqa: PT009
+ self.assertEqual(data[0]['notification_type'], 'new_response') # noqa: PT009
+ self.assertEqual( # noqa: PT009
data[0]['content'],
'test_user responded to your post This is a test post.
'
)
@@ -147,11 +147,11 @@ def test_list_notifications_with_channels(self, channels, expected_count):
response = self.client.get(self.url + "?app_name=discussion")
# Assert that the response is successful.
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
# Assert that the response contains expected results i.e. channels contains web or is null.
data = response.data['results']
- self.assertEqual(len(data), expected_count)
+ self.assertEqual(len(data), expected_count) # noqa: PT009
@mock.patch("eventtracking.tracker.emit")
def test_list_notifications_with_tray_opened_param(self, mock_emit):
@@ -164,12 +164,12 @@ def test_list_notifications_with_tray_opened_param(self, mock_emit):
response = self.client.get(self.url + "?tray_opened=True")
# Assert that the response is successful.
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
event_name, event_data = mock_emit.call_args[0]
- self.assertEqual(event_name, 'edx.notifications.tray_opened')
- self.assertEqual(event_data['user_id'], self.user.id)
- self.assertEqual(event_data['unseen_notifications_count'], 0)
+ self.assertEqual(event_name, 'edx.notifications.tray_opened') # noqa: PT009
+ self.assertEqual(event_data['user_id'], self.user.id) # noqa: PT009
+ self.assertEqual(event_data['unseen_notifications_count'], 0) # noqa: PT009
def test_list_notifications_without_authentication(self):
"""
@@ -179,7 +179,7 @@ def test_list_notifications_without_authentication(self):
response = self.client.get(self.url)
# Assert that the response is unauthorized.
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_list_notifications_with_expiry_date(self):
"""
@@ -204,12 +204,12 @@ def test_list_notifications_with_expiry_date(self):
response = self.client.get(self.url)
# Assert that the response is successful.
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
# Assert that the response contains only the notification for current date.
data = response.data['results']
- self.assertEqual(len(data), 1)
- self.assertEqual(data[0]['created'], today.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
+ self.assertEqual(len(data), 1) # noqa: PT009
+ self.assertEqual(data[0]['created'], today.strftime('%Y-%m-%dT%H:%M:%S.%fZ')) # noqa: PT009
def test_list_notifications_with_order_by_reverse_id(self):
"""
@@ -231,12 +231,12 @@ def test_list_notifications_with_order_by_reverse_id(self):
response = self.client.get(self.url)
# Assert that the response is successful.
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
# Assert that the response id list is in reverse order.
data = response.data['results']
- self.assertEqual(len(data), 2)
- self.assertEqual([data[0]['id'], data[1]['id']], [notification2.id, notification1.id])
+ self.assertEqual(len(data), 2) # noqa: PT009
+ self.assertEqual([data[0]['id'], data[1]['id']], [notification2.id, notification1.id]) # noqa: PT009
@ddt.ddt
@@ -283,19 +283,19 @@ def test_get_unseen_notifications_count_with_show_notifications_tray(self):
# Make a request to the view
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.data['count'], 4)
- self.assertEqual(response.data['count_by_app_name'], {
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(response.data['count'], 4) # noqa: PT009
+ self.assertEqual(response.data['count_by_app_name'], { # noqa: PT009
'App Name 1': 2, 'App Name 2': 1, 'App Name 3': 1, 'discussion': 0,
'updates': 0, 'grading': 0})
- self.assertEqual(response.data['show_notifications_tray'], True)
+ self.assertEqual(response.data['show_notifications_tray'], True) # noqa: PT009
def test_get_unseen_notifications_count_for_unauthenticated_user(self):
"""
Test that the endpoint returns 401 for an unauthenticated user.
"""
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
def test_get_unseen_notifications_count_for_user_with_no_notifications(self):
"""
@@ -306,9 +306,9 @@ def test_get_unseen_notifications_count_for_user_with_no_notifications(self):
self.client.login(username=user.username, password=self.TEST_PASSWORD)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.data['count'], 0)
- self.assertEqual(response.data['count_by_app_name'], {'discussion': 0, 'updates': 0,
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(response.data['count'], 0) # noqa: PT009
+ self.assertEqual(response.data['count_by_app_name'], {'discussion': 0, 'updates': 0, # noqa: PT009
'grading': 0})
def test_get_expiry_days_in_count_view(self):
@@ -318,8 +318,8 @@ def test_get_expiry_days_in_count_view(self):
user = UserFactory()
self.client.login(username=user.username, password=self.TEST_PASSWORD)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.data['notification_expiry_days'], 60)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(response.data['notification_expiry_days'], 60) # noqa: PT009
class MarkNotificationsSeenAPIViewTestCase(APITestCase):
@@ -344,15 +344,15 @@ def test_mark_notifications_seen(self):
self.client.login(username=self.user.username, password=self.TEST_PASSWORD)
response = self.client.put(url)
# Assert the response status code is 200 (OK)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
# Assert the response data contains the expected message
expected_data = {'message': 'Notifications marked as seen.'}
- self.assertEqual(response.data, expected_data)
+ self.assertEqual(response.data, expected_data) # noqa: PT009
# Assert the notifications for 'App Name 1' are marked as seen for the user
notifications = Notification.objects.filter(user=self.user, app_name=app_name, last_seen__isnull=False)
- self.assertEqual(notifications.count(), 2)
+ self.assertEqual(notifications.count(), 2) # noqa: PT009
class NotificationReadAPIViewTestCase(APITestCase):
@@ -380,13 +380,13 @@ def test_mark_all_notifications_read_with_app_name(self, mock_emit):
response = self.client.patch(self.url, data)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data, {'message': 'Notifications marked read.'})
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data, {'message': 'Notifications marked read.'}) # noqa: PT009
notifications = Notification.objects.filter(user=self.user, app_name=app_name, last_read__isnull=False)
- self.assertEqual(notifications.count(), 2)
+ self.assertEqual(notifications.count(), 2) # noqa: PT009
event_name, event_data = mock_emit.call_args[0]
- self.assertEqual(event_name, 'edx.notifications.app_all_read')
- self.assertEqual(event_data['notification_app'], 'discussion')
+ self.assertEqual(event_name, 'edx.notifications.app_all_read') # noqa: PT009
+ self.assertEqual(event_data['notification_app'], 'discussion') # noqa: PT009
def test_mark_all_notifications_read_with_invalid_app_name(self):
# Create a PATCH request to mark all notifications as read for 'app_name_1'
@@ -395,8 +395,8 @@ def test_mark_all_notifications_read_with_invalid_app_name(self):
response = self.client.patch(self.url, data)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(response.data, {'error': 'Invalid app_name or notification_id.'})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertEqual(response.data, {'error': 'Invalid app_name or notification_id.'}) # noqa: PT009
@mock.patch("eventtracking.tracker.emit")
def test_mark_notification_read_with_notification_id(self, mock_emit):
@@ -406,16 +406,16 @@ def test_mark_notification_read_with_notification_id(self, mock_emit):
response = self.client.patch(self.url, data)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data, {'message': 'Notification marked read.'})
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data, {'message': 'Notification marked read.'}) # noqa: PT009
notifications = Notification.objects.filter(user=self.user, id=notification_id, last_read__isnull=False)
- self.assertEqual(notifications.count(), 1)
+ self.assertEqual(notifications.count(), 1) # noqa: PT009
event_name, event_data = mock_emit.call_args[0]
- self.assertEqual(event_name, 'edx.notifications.read')
- self.assertEqual(event_data.get('notification_metadata').get('notification_id'), notification_id)
- self.assertEqual(event_data['notification_app'], 'discussion')
- self.assertEqual(event_data['notification_type'], 'Type A')
- self.assertEqual(event_data['first_read'], True)
+ self.assertEqual(event_name, 'edx.notifications.read') # noqa: PT009
+ self.assertEqual(event_data.get('notification_metadata').get('notification_id'), notification_id) # noqa: PT009
+ self.assertEqual(event_data['notification_app'], 'discussion') # noqa: PT009
+ self.assertEqual(event_data['notification_type'], 'Type A') # noqa: PT009
+ self.assertEqual(event_data['first_read'], True) # noqa: PT009
def test_mark_notification_read_with_other_user_notification_id(self):
# Create a PATCH request to mark notification as read for notification_id: 2 through a different user
@@ -427,9 +427,9 @@ def test_mark_notification_read_with_other_user_notification_id(self):
data = {'notification_id': notification_id}
response = self.client.patch(self.url, data)
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
notifications = Notification.objects.filter(user=self.user, id=notification_id, last_read__isnull=False)
- self.assertEqual(notifications.count(), 0)
+ self.assertEqual(notifications.count(), 0) # noqa: PT009
def test_mark_notification_read_with_invalid_notification_id(self):
# Create a PATCH request to mark notification as read for notification_id: 23345
@@ -438,8 +438,8 @@ def test_mark_notification_read_with_invalid_notification_id(self):
response = self.client.patch(self.url, data)
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- self.assertEqual(response.data["detail"].code, 'not_found')
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # noqa: PT009
+ self.assertEqual(response.data["detail"].code, 'not_found') # noqa: PT009
def test_mark_notification_read_with_app_name_and_notification_id(self):
# Create a PATCH request to mark notification as read for existing app e.g 'discussion' and notification_id: 2
@@ -450,21 +450,21 @@ def test_mark_notification_read_with_app_name_and_notification_id(self):
response = self.client.patch(self.url, data)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data, {'message': 'Notification marked read.'})
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data, {'message': 'Notification marked read.'}) # noqa: PT009
notifications = Notification.objects.filter(
user=self.user,
id=notification_id,
last_read__isnull=False
)
- self.assertEqual(notifications.count(), 1)
+ self.assertEqual(notifications.count(), 1) # noqa: PT009
def test_mark_notification_read_without_app_name_and_notification_id(self):
# Create a PATCH request to mark notification as read without app_name and notification_id
response = self.client.patch(self.url, {})
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(response.data, {'error': 'Invalid app_name or notification_id.'})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # noqa: PT009
+ self.assertEqual(response.data, {'error': 'Invalid app_name or notification_id.'}) # noqa: PT009
@ddt.ddt
@@ -541,7 +541,7 @@ def remove_notifications_with_visibility_settings(expected_response):
"""
not_visible = get_notification_types_with_visibility_settings()
for expected_response_app in expected_response['notification_preference_config']:
- for notification_type, visibility_settings in not_visible.items():
+ for notification_type, visibility_settings in not_visible.items(): # noqa: B007
types = expected_response['notification_preference_config'][expected_response_app]['notification_types']
if notification_type in types:
expected_response['notification_preference_config'][expected_response_app]['notification_types'].pop(
@@ -688,24 +688,24 @@ def test_get_notification_preferences(self, role_type, role, visible_apps, hidde
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['status'], 'success')
- self.assertIn('data', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['status'], 'success') # noqa: PT009
+ self.assertIn('data', response.data) # noqa: PT009
expected_data = exclude_inaccessible_preferences(self.default_data['data'], self.user)
expected_data = add_non_editable_in_preference(expected_data)
- self.assertEqual(response.data['data'], expected_data)
+ self.assertEqual(response.data['data'], expected_data) # noqa: PT009
notification_apps = {}
for app in ['discussion', 'grading']:
notification_apps.update(response.data['data'][app]['notification_types'])
for app in visible_apps:
- self.assertIn(app, notification_apps, msg=f"{app} should be visible for role: {role_type}")
+ self.assertIn(app, notification_apps, msg=f"{app} should be visible for role: {role_type}") # noqa: PT009
for app in hidden_apps:
- self.assertNotIn(app, notification_apps, msg=f"{app} should NOT be visible for role: {role_type}")
+ self.assertNotIn(app, notification_apps, msg=f"{app} should NOT be visible for role: {role_type}") # noqa: PT009 # pylint: disable=line-too-long
if role_type == "forum":
role_instance.users.clear()
@@ -727,9 +727,9 @@ def test_if_data_is_correctly_aggregated(self):
email=False,
)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['status'], 'success')
- self.assertIn('data', response.data)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['status'], 'success') # noqa: PT009
+ self.assertIn('data', response.data) # noqa: PT009
data = {
"status": "success",
"show_preferences": True,
@@ -809,7 +809,7 @@ def test_if_data_is_correctly_aggregated(self):
},
}
}
- self.assertEqual(response.data, data)
+ self.assertEqual(response.data, data) # noqa: PT009
def test_api_view_permissions(self):
"""
@@ -818,12 +818,12 @@ def test_api_view_permissions(self):
# Check if the view requires authentication
self.client.logout()
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) # noqa: PT009
# Re-authenticate and check again
self.client.force_authenticate(user=self.user)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
def test_update_preferences_grouped(self):
"""
@@ -842,13 +842,13 @@ def test_update_preferences_grouped(self):
]
self.client.get(self.url)
response = self.client.put(self.url, update_data, format='json')
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['status'], 'success')
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['status'], 'success') # noqa: PT009
cadence_set = NotificationPreference.objects.filter(user=self.user, type__in=grouped_types).values_list(
'email_cadence', flat=True
)
- self.assertEqual(len(set(cadence_set)), 1)
- self.assertIn('Weekly', set(cadence_set))
+ self.assertEqual(len(set(cadence_set)), 1) # noqa: PT009
+ self.assertIn('Weekly', set(cadence_set)) # noqa: PT009
def test_update_preferences(self):
"""
@@ -862,13 +862,13 @@ def test_update_preferences(self):
}
self.client.get(self.url)
response = self.client.put(self.url, update_data, format='json')
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['status'], 'success')
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['status'], 'success') # noqa: PT009
preference = NotificationPreference.objects.get(
type='new_discussion_post',
user__id=self.user.id
)
- self.assertEqual(preference.web, True)
+ self.assertEqual(preference.web, True) # noqa: PT009
def test_update_preferences_non_grouped_email(self):
"""
@@ -882,10 +882,10 @@ def test_update_preferences_non_grouped_email(self):
}
self.client.get(self.url)
response = self.client.put(self.url, update_data, format='json')
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertEqual(response.data['status'], 'success')
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
+ self.assertEqual(response.data['status'], 'success') # noqa: PT009
preference = NotificationPreference.objects.get(
type='new_discussion_post',
user__id=self.user.id
)
- self.assertEqual(preference.email_cadence, 'Weekly')
+ self.assertEqual(preference.email_cadence, 'Weekly') # noqa: PT009
diff --git a/openedx/core/djangoapps/notifications/utils.py b/openedx/core/djangoapps/notifications/utils.py
index 8a8f9b6bed47..75996d904749 100644
--- a/openedx/core/djangoapps/notifications/utils.py
+++ b/openedx/core/djangoapps/notifications/utils.py
@@ -1,7 +1,7 @@
"""
Utils function for notifications app
"""
-from typing import Dict, List
+from typing import Dict, List # noqa: UP035
from common.djangoapps.student.models import CourseAccessRole
from openedx.core.djangoapps.django_comment_common.models import Role
@@ -27,7 +27,7 @@ def get_list_in_batches(input_list, batch_size):
@request_cached()
-def get_notification_types_with_visibility_settings() -> Dict[str, List[str]]:
+def get_notification_types_with_visibility_settings() -> Dict[str, List[str]]: # noqa: UP006
"""
Get notification types with their visibility settings.
@@ -45,9 +45,9 @@ def get_notification_types_with_visibility_settings() -> Dict[str, List[str]]:
def filter_out_visible_notifications(
user_preferences: dict,
- notifications_with_visibility: Dict[str, List[str]],
- user_forum_roles: List[str],
- user_course_roles: List[str]
+ notifications_with_visibility: Dict[str, List[str]], # noqa: UP006
+ user_forum_roles: List[str], # noqa: UP006
+ user_course_roles: List[str] # noqa: UP006
) -> dict:
"""
Filter out notifications visible to forum roles from user preferences.
@@ -88,7 +88,7 @@ def clean_arguments(kwargs):
return clean_kwargs
-def get_user_forum_access_roles(user_id: int) -> List[str]:
+def get_user_forum_access_roles(user_id: int) -> List[str]: # noqa: UP006
"""
Get forum roles for the given user in all course.
diff --git a/openedx/core/djangoapps/oauth_dispatch/adapters/__init__.py b/openedx/core/djangoapps/oauth_dispatch/adapters/__init__.py
index e41e9ca3ed0e..645f0ac25fee 100644
--- a/openedx/core/djangoapps/oauth_dispatch/adapters/__init__.py
+++ b/openedx/core/djangoapps/oauth_dispatch/adapters/__init__.py
@@ -3,4 +3,4 @@
django-oauth-toolkit (DOT).
"""
-from .dot import DOTAdapter
+from .dot import DOTAdapter # noqa: F401
diff --git a/openedx/core/djangoapps/oauth_dispatch/management/commands/create_dot_application.py b/openedx/core/djangoapps/oauth_dispatch/management/commands/create_dot_application.py
index 4041b00e15ad..200e1c99bc33 100644
--- a/openedx/core/djangoapps/oauth_dispatch/management/commands/create_dot_application.py
+++ b/openedx/core/djangoapps/oauth_dispatch/management/commands/create_dot_application.py
@@ -79,7 +79,7 @@ def _create_application(self, user, app_name, application_kwargs):
application = Application.objects.create(
user=user, name=app_name, **application_kwargs
)
- logger.info('Created {} application with id: {}, client_id: {}, and client_secret: {}'.format(
+ logger.info('Created {} application with id: {}, client_id: {}, and client_secret: {}'.format( # noqa: UP032
app_name,
application.id,
application.client_id,
@@ -94,7 +94,7 @@ def _update_application(self, application, application_kwargs):
for key, value in application_kwargs.items():
setattr(application, key, value)
application.save()
- logger.info('Updated {} application with id: {}, client_id: {}, and client_secret: {}'.format(
+ logger.info('Updated {} application with id: {}, client_id: {}, and client_secret: {}'.format( # noqa: UP032
application.name,
application.id,
application.client_id,
@@ -114,12 +114,12 @@ def _create_or_update_access(self, application, scopes, update):
if access and update:
access.scopes = scopes
access.save()
- logger.info('Updated application access for {} with scopes: {}'.format(
+ logger.info('Updated application access for {} with scopes: {}'.format( # noqa: UP032
application.name,
scopes,
))
elif access:
- logger.info('Application access for application {} already exists.'.format(
+ logger.info('Application access for application {} already exists.'.format( # noqa: UP032
application.name,
))
else:
@@ -127,7 +127,7 @@ def _create_or_update_access(self, application, scopes, update):
application_id=application.id,
scopes=scopes,
)
- logger.info('Created application access for {} with scopes: {}'.format(
+ logger.info('Created application access for {} with scopes: {}'.format( # noqa: UP032
application.name,
application_access.scopes,
))
@@ -160,7 +160,7 @@ def handle(self, *args, **options):
if application and update:
self._update_application(application, application_kwargs)
elif application:
- logger.info('Application with name {} and user {} already exists.'.format(
+ logger.info('Application with name {} and user {} already exists.'.format( # noqa: UP032
app_name,
username
))
diff --git a/openedx/core/djangoapps/oauth_dispatch/management/commands/edx_clear_expired_tokens.py b/openedx/core/djangoapps/oauth_dispatch/management/commands/edx_clear_expired_tokens.py
index de587a89deac..fd22c0b727b1 100644
--- a/openedx/core/djangoapps/oauth_dispatch/management/commands/edx_clear_expired_tokens.py
+++ b/openedx/core/djangoapps/oauth_dispatch/management/commands/edx_clear_expired_tokens.py
@@ -77,7 +77,7 @@ def get_expiration_time(self, now): # lint-amnesty, pylint: disable=missing-fun
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) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ImproperlyConfigured(e) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return now - refresh_token_expire_seconds
def handle(self, *args, **options):
diff --git a/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_clear_expired_tokens.py b/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_clear_expired_tokens.py
index 657b238aec22..b4e6faa4a826 100644
--- a/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_clear_expired_tokens.py
+++ b/openedx/core/djangoapps/oauth_dispatch/management/commands/tests/test_clear_expired_tokens.py
@@ -53,7 +53,7 @@ class EdxClearExpiredTokensTests(TestCase): # lint-amnesty, pylint: disable=mis
@patch('oauth2_provider.settings.oauth2_settings.REFRESH_TOKEN_EXPIRE_SECONDS', 'xyz')
def test_invalid_expiration_time(self):
with LogCapture(LOGGER_NAME) as log:
- with pytest.raises(ImproperlyConfigured):
+ with pytest.raises(ImproperlyConfigured): # noqa: PT012
call_command('edx_clear_expired_tokens')
log.check(
(
@@ -141,7 +141,7 @@ def test_clear_revoked_refresh_tokens(self):
assert QuerySet.delete.invocations == 2
assert RefreshToken.objects.filter(revoked__lt=refresh_expires).count() == 0
# revoked token has been deleted
- with self.assertRaises(RefreshToken.DoesNotExist):
+ with self.assertRaises(RefreshToken.DoesNotExist): # noqa: PT027
RefreshToken.objects.get(token=revoke_token.token)
# normal token is still there
assert RefreshToken.objects.get(token=keep_token.token) == keep_token
diff --git a/openedx/core/djangoapps/oauth_dispatch/models.py b/openedx/core/djangoapps/oauth_dispatch/models.py
index 344b3a2133ec..ce5cef193ddf 100644
--- a/openedx/core/djangoapps/oauth_dispatch/models.py
+++ b/openedx/core/djangoapps/oauth_dispatch/models.py
@@ -109,18 +109,18 @@ def get_filter_values(cls, application, filter_name): # lint-amnesty, pylint: d
if name == filter_name:
yield filter_value
- def __str__(self):
+ def __str__(self): # noqa: DJ012
"""
Return a unicode representation of this object.
"""
- return "{application_name}:{scopes}:{filters}".format(
+ return "{application_name}:{scopes}:{filters}".format( # noqa: UP032
application_name=self.application.name,
scopes=self.scopes,
filters=self.filters,
)
-class ApplicationOrganization(models.Model):
+class ApplicationOrganization(models.Model): # noqa: DJ008
"""
DEPRECATED: Associates a DOT Application to an Organization.
diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_adapter.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_adapter.py
index 0c9f662fb04e..ddb054ec7c9c 100644
--- a/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_adapter.py
+++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_adapter.py
@@ -55,7 +55,7 @@ def test_restricted_app_unicode(self):
Make sure unicode representation of RestrictedApplication is correct
"""
assert str(self.restricted_app) == ""\
- .format(name=self.restricted_client.name)
+ .format(name=self.restricted_client.name) # noqa: UP032
@ddt.data(
('confidential', models.Application.CLIENT_CONFIDENTIAL),
diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_overrides.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_overrides.py
index d658574eb2c5..2847ae3f8a5e 100644
--- a/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_overrides.py
+++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_dot_overrides.py
@@ -89,7 +89,7 @@ def test_get_default_scopes_with_user_id(self):
request = mock.Mock(grant_type='client_credentials', client=application_access.application, scopes=None)
overriden_default_scopes = self.validator.get_default_scopes(request=request, client_id='client_id')
- self.assertEqual(overriden_default_scopes, self.default_scopes + ['user_id'])
+ self.assertEqual(overriden_default_scopes, self.default_scopes + ['user_id']) # noqa: PT009
def test_get_default_scopes(self):
"""
@@ -98,7 +98,7 @@ def test_get_default_scopes(self):
request = mock.Mock(grant_type='client_credentials', client=None, scopes=None)
overriden_default_scopes = self.validator.get_default_scopes(request=request, client_id='client_id')
- self.assertEqual(overriden_default_scopes, self.default_scopes)
+ self.assertEqual(overriden_default_scopes, self.default_scopes) # noqa: PT009
@skip_unless_lms
diff --git a/openedx/core/djangoapps/oauth_dispatch/tests/test_views.py b/openedx/core/djangoapps/oauth_dispatch/tests/test_views.py
index 8387cf095f0d..b8e056f4064e 100644
--- a/openedx/core/djangoapps/oauth_dispatch/tests/test_views.py
+++ b/openedx/core/djangoapps/oauth_dispatch/tests/test_views.py
@@ -55,7 +55,7 @@ def login_with_access_token(self, access_token=None):
return self.client.post(
self.login_with_access_token_url,
- HTTP_AUTHORIZATION=f"Bearer {access_token if access_token else self.access_token}".encode('utf-8')
+ HTTP_AUTHORIZATION=f"Bearer {access_token if access_token else self.access_token}".encode('utf-8') # noqa: UP012 # pylint: disable=line-too-long
)
def _assert_access_token_is_valid(self, access_token=None):
@@ -709,7 +709,7 @@ def assert_is_view(self, view_candidate):
_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
+ assert hasattr(view_candidate, '__call__'), msg_not_callable # noqa: B004
args = view_candidate.__code__.co_varnames
assert args, msg_no_request
assert args[0] == 'request'
@@ -748,7 +748,7 @@ def test_get_view_for_dot(self):
def test_get_view_for_no_backend(self):
view_object = views.AccessTokenView()
- self.assertRaises(KeyError, view_object.get_view_for_backend, None)
+ self.assertRaises(KeyError, view_object.get_view_for_backend, None) # noqa: PT027
class TestRevokeTokenView(AccessTokenLoginMixin, _DispatchingViewTestCase): # pylint: disable=abstract-method
diff --git a/openedx/core/djangoapps/olx_rest_api/test_views.py b/openedx/core/djangoapps/olx_rest_api/test_views.py
index 603ccbb47364..b4f715df00e1 100644
--- a/openedx/core/djangoapps/olx_rest_api/test_views.py
+++ b/openedx/core/djangoapps/olx_rest_api/test_views.py
@@ -41,7 +41,7 @@ def setUp(self):
def assertXmlEqual(self, xml_str_a: str, xml_str_b: str) -> bool:
""" Assert that the given XML strings are equal, ignoring attribute order and some whitespace variations. """
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
ElementTree.canonicalize(xml_str_a, strip_text=True),
ElementTree.canonicalize(xml_str_b, strip_text=True),
)
diff --git a/openedx/core/djangoapps/olx_rest_api/views.py b/openedx/core/djangoapps/olx_rest_api/views.py
index c3d3ba528f0c..1d4d12814fb1 100644
--- a/openedx/core/djangoapps/olx_rest_api/views.py
+++ b/openedx/core/djangoapps/olx_rest_api/views.py
@@ -27,7 +27,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') # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError('Invalid usage key') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
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
@@ -91,7 +91,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') # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError('Invalid usage key') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
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
diff --git a/openedx/core/djangoapps/password_policy/forms.py b/openedx/core/djangoapps/password_policy/forms.py
index 7651583053b7..77d0cf47f852 100644
--- a/openedx/core/djangoapps/password_policy/forms.py
+++ b/openedx/core/djangoapps/password_policy/forms.py
@@ -28,6 +28,6 @@ def clean(self):
messages.warning(self.request, HTML(str(e)))
except password_policy_compliance.NonCompliantPasswordException as e:
# Prevent the login attempt.
- raise ValidationError(HTML(str(e))) # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValidationError(HTML(str(e))) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return cleaned_data
diff --git a/openedx/core/djangoapps/password_policy/hibp.py b/openedx/core/djangoapps/password_policy/hibp.py
index 5821df9816b1..5ee049701bd2 100644
--- a/openedx/core/djangoapps/password_policy/hibp.py
+++ b/openedx/core/djangoapps/password_policy/hibp.py
@@ -55,7 +55,7 @@ def range(password):
if not is_encrypted:
password = hashlib.sha1(password.encode('utf-8')).hexdigest().upper()
- range_url = PwnedPasswordsAPI.API_URL + '/range/{}'.format(password[:5])
+ range_url = PwnedPasswordsAPI.API_URL + '/range/{}'.format(password[:5]) # noqa: UP032
if ENABLE_PWNED_PASSWORD_API.is_enabled():
try:
@@ -65,7 +65,7 @@ def range(password):
return entries
except ReadTimeout:
- log.warning('Request timed out for {}'.format(password))
+ log.warning('Request timed out for {}'.format(password)) # noqa: UP032
return HTTP_408_REQUEST_TIMEOUT
except Exception as exc: # pylint: disable=W0703
@@ -80,7 +80,7 @@ def is_sha1(maybe_sha):
return False
try:
- sha_int = int(maybe_sha, HEX_BASE)
+ sha_int = int(maybe_sha, HEX_BASE) # noqa: F841
except ValueError:
return False
diff --git a/openedx/core/djangoapps/password_policy/tests/test_hibp.py b/openedx/core/djangoapps/password_policy/tests/test_hibp.py
index 7913b4b54d8d..06daaa09c9f7 100644
--- a/openedx/core/djangoapps/password_policy/tests/test_hibp.py
+++ b/openedx/core/djangoapps/password_policy/tests/test_hibp.py
@@ -34,7 +34,7 @@ def test_matched_pwned_passwords(self, mock_get):
mock_get.return_value = response
response = PwnedPasswordsAPI.range('7ecd7')
- self.assertEqual(response, pwned_password)
+ self.assertEqual(response, pwned_password) # noqa: PT009
@override_waffle_switch(ENABLE_PWNED_PASSWORD_API, True)
@patch('requests.get', side_effect=ReadTimeout)
@@ -50,14 +50,14 @@ def test_warning_log_on_timeout(self, mock_get): # pylint: disable=unused-argum
(
log.name,
'WARNING',
- 'Request timed out for {}'.format(password_hash_hex)
+ 'Request timed out for {}'.format(password_hash_hex) # noqa: UP032
)
)
- assert 'Request timed out for {}'.format(password_hash_hex) in log_capture.records[0].getMessage()
+ assert 'Request timed out for {}'.format(password_hash_hex) in log_capture.records[0].getMessage() # noqa: UP032 # pylint: disable=line-too-long
def test_provided_string_is_sha1_or_not(self):
hashed_password = '8BB6118F8FD6935AD0876A3BE34A717D32708FFD'
- self.assertTrue(PwnedPasswordsAPI.is_sha1(hashed_password))
+ self.assertTrue(PwnedPasswordsAPI.is_sha1(hashed_password)) # noqa: PT009
raw_password = 'testpassword'
- self.assertFalse(PwnedPasswordsAPI.is_sha1(raw_password))
+ self.assertFalse(PwnedPasswordsAPI.is_sha1(raw_password)) # noqa: PT009
diff --git a/openedx/core/djangoapps/plugins/constants.py b/openedx/core/djangoapps/plugins/constants.py
index 0464ece54d32..3e21949f33d2 100644
--- a/openedx/core/djangoapps/plugins/constants.py
+++ b/openedx/core/djangoapps/plugins/constants.py
@@ -4,14 +4,14 @@
# expose constants from edx-django-utils so plugins using these continue to work
from edx_django_utils.plugins import ( # lint-amnesty, pylint: disable=unused-import
- PluginContexts,
- PluginSettings,
- PluginSignals,
- PluginURLs,
+ PluginContexts, # noqa: F401
+ PluginSettings, # noqa: F401
+ PluginSignals, # noqa: F401
+ PluginURLs, # noqa: F401
)
-class ProjectType():
+class ProjectType(): # noqa: UP039
"""
The ProjectType enum defines the possible values for the Django Projects
that are available in the edx-platform. Plugin apps use these values to
@@ -22,7 +22,7 @@ class ProjectType():
CMS = 'cms.djangoapp'
-class SettingsType():
+class SettingsType(): # noqa: UP039
"""
The SettingsType enum defines the possible values for the settings files
that are available for extension in the edx-platform. Plugin apps use these
diff --git a/openedx/core/djangoapps/plugins/tests/test_i18n_api.py b/openedx/core/djangoapps/plugins/tests/test_i18n_api.py
index 0bbf77b600bb..f1b0e87b1148 100644
--- a/openedx/core/djangoapps/plugins/tests/test_i18n_api.py
+++ b/openedx/core/djangoapps/plugins/tests/test_i18n_api.py
@@ -88,7 +88,7 @@ def test_base_atlas_pull_command(tmp_path):
command = BaseAtlasPullCommand()
assert command.ensure_empty_directory(tmp_path) is None, 'Should not raise an exception if the directory is empty'
- with pytest.raises(CommandError):
+ with pytest.raises(CommandError): # noqa: PT012
with open(tmp_path / 'test.txt', 'w'):
# Directory is not empty anymore
pass
diff --git a/openedx/core/djangoapps/profile_images/tests/test_images.py b/openedx/core/djangoapps/profile_images/tests/test_images.py
index c0ada2c82b63..9ebb16686815 100644
--- a/openedx/core/djangoapps/profile_images/tests/test_images.py
+++ b/openedx/core/djangoapps/profile_images/tests/test_images.py
@@ -36,7 +36,7 @@ class TestValidateUploadedImage(TestCase):
Test validate_uploaded_image
"""
FILE_UPLOAD_BAD_TYPE = (
- 'The file must be one of the following types: {valid_file_types}.'.format(
+ 'The file must be one of the following types: {valid_file_types}.'.format( # noqa: UP032
valid_file_types=_get_valid_file_types()
)
)
@@ -61,7 +61,7 @@ def check_validation_result(self, uploaded_file, expected_failure_message):
)
@ddt.unpack
@override_settings(PROFILE_IMAGE_MIN_BYTES=100, PROFILE_IMAGE_MAX_BYTES=1024)
- def test_file_size(self, upload_size, expected_failure_message=None):
+ def test_file_size(self, upload_size, expected_failure_message=None): # noqa: PT028
"""
Ensure that files outside the accepted size range fail validation.
"""
@@ -79,7 +79,7 @@ def test_file_size(self, upload_size, expected_failure_message=None):
(".tif", "image/tiff", FILE_UPLOAD_BAD_TYPE),
)
@ddt.unpack
- def test_extension(self, extension, content_type, expected_failure_message=None):
+ def test_extension(self, extension, content_type, expected_failure_message=None): # noqa: PT028
"""
Ensure that files whose extension is not supported fail validation.
"""
diff --git a/openedx/core/djangoapps/profile_images/tests/test_views.py b/openedx/core/djangoapps/profile_images/tests/test_views.py
index 50835da450be..b3b7d5bc22b6 100644
--- a/openedx/core/djangoapps/profile_images/tests/test_views.py
+++ b/openedx/core/djangoapps/profile_images/tests/test_views.py
@@ -167,7 +167,7 @@ def test_anonymous_access(self, mock_log):
'openedx.core.djangoapps.profile_images.views._make_upload_dt',
side_effect=[TEST_UPLOAD_DT, TEST_UPLOAD_DT2],
)
- def test_upload_self(self, extension, _mock_make_image_version, mock_log):
+ def test_upload_self(self, extension, _mock_make_image_version, mock_log): # noqa: PT019
"""
Test that an authenticated user can POST to their own upload endpoint.
"""
@@ -200,7 +200,7 @@ def test_upload_self(self, extension, _mock_make_image_version, mock_log):
)
@ddt.unpack
@patch('openedx.core.djangoapps.profile_images.views._make_upload_dt', return_value=TEST_UPLOAD_DT)
- def test_upload_by_mimetype(self, content_type, extension, _mock_make_image_version, mock_log):
+ def test_upload_by_mimetype(self, content_type, extension, _mock_make_image_version, mock_log): # noqa: PT019
"""
Test that a user can upload raw content with the appropriate mimetype
"""
@@ -348,7 +348,7 @@ def test_upload_failure(self, image_open, mock_log):
"""
image_open.side_effect = [Exception("whoops"), None]
with make_image_file() as image_file:
- with pytest.raises(Exception):
+ with pytest.raises(Exception): # noqa: B017, PT011
self.client.post(self.url, {'file': image_file}, format='multipart')
self.check_images(False)
self.check_has_profile_image(False)
@@ -446,7 +446,7 @@ def test_remove_failure(self, user_profile_save, mock_log):
messages are returned.
"""
user_profile_save.side_effect = [Exception("whoops"), None]
- with pytest.raises(Exception):
+ with pytest.raises(Exception): # noqa: B017, PT011
self.client.delete(self.url)
self.check_images(True) # thumbnails should remain intact.
self.check_has_profile_image(True)
diff --git a/openedx/core/djangoapps/programs/apps.py b/openedx/core/djangoapps/programs/apps.py
index 7136834e9a0e..249d6fd0cd11 100644
--- a/openedx/core/djangoapps/programs/apps.py
+++ b/openedx/core/djangoapps/programs/apps.py
@@ -14,4 +14,4 @@ class ProgramsConfig(AppConfig):
def ready(self):
# noinspection PyUnresolvedReferences
- from . import signals, tasks # lint-amnesty, pylint: disable=unused-import, unused-variable
+ from . import signals, tasks # lint-amnesty, pylint: disable=unused-import, unused-variable # noqa: F401
diff --git a/openedx/core/djangoapps/programs/forms.py b/openedx/core/djangoapps/programs/forms.py
index ac4bff5b7212..a7853e95a687 100644
--- a/openedx/core/djangoapps/programs/forms.py
+++ b/openedx/core/djangoapps/programs/forms.py
@@ -31,7 +31,7 @@ def save(self, commit=True):
class Meta:
model = ProgramDiscussionsConfiguration
- fields = '__all__'
+ fields = '__all__' # noqa: DJ007
class ProgramLiveConfigurationForm(forms.ModelForm):
@@ -59,4 +59,4 @@ def save(self, commit=True):
class Meta:
model = ProgramLiveConfiguration
- fields = '__all__'
+ fields = '__all__' # noqa: DJ007
diff --git a/openedx/core/djangoapps/programs/rest_api/v1/tests/test_views.py b/openedx/core/djangoapps/programs/rest_api/v1/tests/test_views.py
index 0f670cd2f80d..9d69545bdebb 100644
--- a/openedx/core/djangoapps/programs/rest_api/v1/tests/test_views.py
+++ b/openedx/core/djangoapps/programs/rest_api/v1/tests/test_views.py
@@ -105,7 +105,7 @@ def test_api_returns_correct_program_data(self, mock_get_programs, mock_get_path
certs.return_value = [{"type": "program", "url": "/"}]
response = self.client.get(self.url)
- self.assertEqual(200, response.status_code)
+ self.assertEqual(200, response.status_code) # noqa: PT009
self.assert_program_data_present(response)
self.assert_pathway_data_present(response)
@@ -122,7 +122,7 @@ def test_login_required(self, mock_get_programs, mock_get_pathways):
response = self.client.get(self.url)
assert response.status_code == 401
- def test_404_if_no_program_data(self, mock_get_programs, _mock_get_pathways):
+ def test_404_if_no_program_data(self, mock_get_programs, _mock_get_pathways): # noqa: PT019
"""
Verify that the API returns 404 if program data is not available.
"""
@@ -199,7 +199,7 @@ def test_program_list_enterprise(self):
)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
program = response.data[0]
assert len(program)
@@ -233,8 +233,8 @@ def test_program_empty_list_if_no_enterprise_enrollments(self):
)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.data, [])
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(response.data, []) # noqa: PT009
@skip_unless_lms
@@ -291,7 +291,7 @@ def test_program_list_b2c(self):
)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
program = response.data[0]
assert len(program)
@@ -322,5 +322,5 @@ def test_program_empty_list_if_no_enrollments(self):
)
response = self.client.get(self.url)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.data, [])
+ self.assertEqual(response.status_code, 200) # noqa: PT009
+ self.assertEqual(response.data, []) # noqa: PT009
diff --git a/openedx/core/djangoapps/programs/rest_api/v1/views.py b/openedx/core/djangoapps/programs/rest_api/v1/views.py
index 41024837ff69..005aa9e546cd 100644
--- a/openedx/core/djangoapps/programs/rest_api/v1/views.py
+++ b/openedx/core/djangoapps/programs/rest_api/v1/views.py
@@ -89,7 +89,7 @@ def get(self, request: "HttpRequest", enterprise_uuid: str = "") -> "HttpRespons
}
]
"""
- user: "AnonymousUser | User" = request.user
+ user: "AnonymousUser | User" = request.user # noqa: UP037
if enterprise_uuid:
enrollments = list(self._get_enterprise_course_enrollments(enterprise_uuid, user))
@@ -316,8 +316,8 @@ def get(self, request: "HttpRequest", program_uuid: str) -> "HttpResponse":
]
}
"""
- user: "AnonymousUser | User" = request.user
- site: "Site" = request.site
+ user: "AnonymousUser | User" = request.user # noqa: UP037
+ site: "Site" = request.site # noqa: UP037
program_data, course_data = get_program_and_course_data(site, user, program_uuid)
if not program_data:
return Response(status=404, data={"error_code": "No program data available."})
diff --git a/openedx/core/djangoapps/programs/tasks.py b/openedx/core/djangoapps/programs/tasks.py
index 2cb7e48c7cd0..f6ea31981689 100644
--- a/openedx/core/djangoapps/programs/tasks.py
+++ b/openedx/core/djangoapps/programs/tasks.py
@@ -3,7 +3,7 @@
between the monolith and the Credentials IDA.
"""
-from typing import TYPE_CHECKING, Dict, List, Optional
+from typing import TYPE_CHECKING, Dict, List, Optional # noqa: UP035
from urllib.parse import urljoin
from celery import shared_task
@@ -50,7 +50,7 @@
DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
-def get_completed_programs(site: Site, student: "UserType") -> Dict:
+def get_completed_programs(site: Site, student: "UserType") -> Dict: # noqa: UP006
"""
Given a set of completed courses, determine which programs are completed.
@@ -85,7 +85,7 @@ def get_inverted_programs(student: "UserType"):
return inverted_programs
-def get_certified_programs(student: "UserType", raise_on_error: bool = False) -> List[str]:
+def get_certified_programs(student: "UserType", raise_on_error: bool = False) -> List[str]: # noqa: UP006
"""
Find the UUIDs of all the programs for which the student has already been awarded
a certificate.
@@ -110,7 +110,7 @@ def get_certified_programs(student: "UserType", raise_on_error: bool = False) ->
return certified_programs
-def get_revokable_program_uuids(course_specific_programs: List[Dict], student: "UserType") -> List[str]:
+def get_revokable_program_uuids(course_specific_programs: List[Dict], student: "UserType") -> List[str]: # noqa: UP006
"""
Get program uuids for which certificate to be revoked.
@@ -198,7 +198,7 @@ def post_course_certificate(
username: str,
certificate: GeneratedCertificateData,
date_override: Optional["datetime"] = None,
- org: Optional[str] = None,
+ org: Optional[str] = None, # noqa: UP045
):
"""
POST a certificate that has been updated to Credentials
@@ -510,7 +510,7 @@ def award_course_certificate(self, username, course_run_key):
LOGGER.info(f"Running task award_course_certificate for user {user.id}")
try:
course_key = CourseKey.from_string(course_run_key)
- except InvalidKeyError as exc:
+ except InvalidKeyError as exc: # noqa: F841
error_msg = "Failed to determine course key"
LOGGER.warning(
f"Failed to award course certificate for user {user.id} for course {course_run_key}. Reason: {error_msg}"
diff --git a/openedx/core/djangoapps/programs/tests/test_utils.py b/openedx/core/djangoapps/programs/tests/test_utils.py
index de09dc2e5175..043367cfee5e 100644
--- a/openedx/core/djangoapps/programs/tests/test_utils.py
+++ b/openedx/core/djangoapps/programs/tests/test_utils.py
@@ -744,7 +744,7 @@ def available_date_fake(_course, cert):
meter = ProgramProgressMeter(self.site, self.user)
available_dates = meter.completed_programs_with_available_dates
- self.assertDictEqual(available_dates, {
+ self.assertDictEqual(available_dates, { # noqa: PT009
program_complete['uuid']: datetime.datetime(2017, 1, 1)
})
@@ -773,7 +773,7 @@ def test_completed_course_runs(self, mock_get_programs):
self._create_certificates(unknown['key'], status='unknown')
meter = ProgramProgressMeter(self.site, self.user)
- self.assertCountEqual(
+ self.assertCountEqual( # noqa: PT009
meter.completed_course_runs,
[
{'course_run_id': str(downloadable['key']), 'type': CourseMode.VERIFIED},
@@ -1380,7 +1380,7 @@ def setUp(self):
# Give all course runs a certificate URL, but only expect one to come
# back. This verifies the break in the function under test that ensures
# only one certificate per course comes back.
- for index, course_run in enumerate(course['course_runs']): # lint-amnesty, pylint: disable=unused-variable
+ for index, course_run in enumerate(course['course_runs']): # lint-amnesty, pylint: disable=unused-variable # noqa: B007
course_run['certificate_url'] = self.course_certificate_url
course_run['may_certify'] = True
@@ -1423,7 +1423,7 @@ def test_course_run_certificates_missing(self, mock_get_credentials):
"""
# make the first course have no certification, the second have no url...
for course_index, course in enumerate(self.program['courses']):
- for index, course_run in enumerate(course['course_runs']): # lint-amnesty, pylint: disable=unused-variable
+ for index, course_run in enumerate(course['course_runs']): # lint-amnesty, pylint: disable=unused-variable # noqa: B007
if course_index == 0:
course_run['may_certify'] = False
elif course_index == 1:
@@ -1744,7 +1744,7 @@ def test_user_enrolled_in_paid_only_with_no_matching_paid_course_modes(self, moc
assert not is_user_enrolled_in_program_type(user=self.user, program_type_slug=self.MICROBACHELORS, paid_modes_only=True)
# We should continue to return false even if they do contain paid modes
- Mode = namedtuple('Mode', ['slug']) # lint-amnesty, pylint: disable=unused-variable
+ Mode = namedtuple('Mode', ['slug']) # lint-amnesty, pylint: disable=unused-variable # noqa: F841
# mock_get_paid_modes_for_course.return_value = [Mode(CourseMode.VERIFIED)]
assert not is_user_enrolled_in_program_type(user=self.user, program_type_slug=self.MICROBACHELORS, paid_modes_only=True)
diff --git a/openedx/core/djangoapps/safe_sessions/middleware.py b/openedx/core/djangoapps/safe_sessions/middleware.py
index 60de38284a6d..6d11a5e4cf8d 100644
--- a/openedx/core/djangoapps/safe_sessions/middleware.py
+++ b/openedx/core/djangoapps/safe_sessions/middleware.py
@@ -241,12 +241,12 @@ def parse(cls, safe_cookie_string):
raw_cookie_components = str(safe_cookie_string).split(cls.SEPARATOR)
safe_cookie_data = SafeCookieData(*raw_cookie_components)
except TypeError:
- raise SafeCookieError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise SafeCookieError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
f"SafeCookieData BWC parse error: {safe_cookie_string!r}."
)
if safe_cookie_data.version != cls.CURRENT_VERSION:
raise SafeCookieError(
- "SafeCookieData version {!r} is not supported. Current version is {}.".format(
+ "SafeCookieData version {!r} is not supported. Current version is {}.".format( # noqa: UP032
safe_cookie_data.version,
cls.CURRENT_VERSION,
))
@@ -281,7 +281,7 @@ def verify(self, user_id):
log.error("SafeCookieData '%r' is not bound to user '%s'.", str(self), user_id)
except signing.BadSignature as sig_error:
log.error(
- "SafeCookieData signature error for cookie data {!r}: {}".format( # pylint: disable=logging-format-interpolation
+ "SafeCookieData signature error for cookie data {!r}: {}".format( # pylint: disable=logging-format-interpolation # noqa: UP032
str(self),
str(sig_error),
)
@@ -311,7 +311,7 @@ def _validate_cookie_params(session_id, user_id):
if not session_id or session_id == str(None):
# The session ID should always be valid in the cookie.
raise SafeCookieError(
- "SafeCookieData not created due to invalid value for session_id '{}' for user_id '{}'.".format(
+ "SafeCookieData not created due to invalid value for session_id '{}' for user_id '{}'.".format( # noqa: UP032 # pylint: disable=line-too-long
session_id,
user_id,
))
@@ -539,7 +539,7 @@ def _verify_user_and_log_mismatch(request, response, userid_in_session):
)
set_custom_attribute('safe_sessions.headers_logged', True)
- except BaseException as e:
+ except BaseException as e: # noqa: F841
log.exception("SafeCookieData error while logging request headers.")
return True
@@ -607,7 +607,7 @@ def _verify_user_and_log_mismatch(request, response, userid_in_session):
f'Safe session request headers: {SafeSessionMiddleware._get_encrypted_request_headers(request)}'
)
- except BaseException as e:
+ except BaseException as e: # noqa: F841
log.exception("SafeCookieData error while computing additional logs.")
if request_user_object_mismatch and not session_user_mismatch:
@@ -853,7 +853,7 @@ def _set_session_email_match_custom_attributes(are_emails_mismatched):
set_custom_attribute('is_enforce_session_email_match_enabled', settings.ENFORCE_SESSION_EMAIL_MATCH)
-def obscure_token(value: Union[str, None]) -> Union[str, None]:
+def obscure_token(value: Union[str, None]) -> Union[str, None]: # noqa: UP007
"""
Return a short string that can be used to detect other occurrences
of this string without revealing the original. Return None if value
@@ -947,7 +947,7 @@ def __setattr__(self, name, value):
if name == 'user':
stack = inspect.stack()
# Written this way in case you need more of the stack for debugging.
- location = "\n".join("%30s : %s:%d" % (t[3], t[1], t[2]) for t in stack[0:12])
+ location = "\n".join("%30s : %s:%d" % (t[3], t[1], t[2]) for t in stack[0:12]) # noqa: UP031
if not hasattr(self, 'debug_user_changes'):
# list of string debugging info for each user change (e.g. user id, stack trace, etc.)
diff --git a/openedx/core/djangoapps/safe_sessions/tests/test_middleware.py b/openedx/core/djangoapps/safe_sessions/tests/test_middleware.py
index ff47f7b0e5c4..ae52a219e2fb 100644
--- a/openedx/core/djangoapps/safe_sessions/tests/test_middleware.py
+++ b/openedx/core/djangoapps/safe_sessions/tests/test_middleware.py
@@ -702,9 +702,9 @@ def test_process_request_emails_match_with_toggle_enabled(
EmailChangeMiddleware.register_email_change(request=self.request, email=self.user.email)
# Ensure email is set in the session
- self.assertEqual(self.request.session.get('email'), self.user.email)
+ self.assertEqual(self.request.session.get('email'), self.user.email) # noqa: PT009
# Ensure session cookie exist
- self.assertEqual(len(self.client.response.cookies), 1)
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
# No email change occurred in any browser
@@ -717,9 +717,9 @@ def test_process_request_emails_match_with_toggle_enabled(
mock_set_custom_attribute.assert_has_calls([call('is_enforce_session_email_match_enabled', True)])
# Assert that the session and cookies are not affected
- self.assertEqual(self.request.session.get('email'), self.user.email)
- self.assertEqual(len(self.client.response.cookies), 1)
- self.assertEqual(self.client.response.cookies[settings.SESSION_COOKIE_NAME].value, 'authenticated')
+ self.assertEqual(self.request.session.get('email'), self.user.email) # noqa: PT009
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
+ self.assertEqual(self.client.response.cookies[settings.SESSION_COOKIE_NAME].value, 'authenticated') # noqa: PT009 # pylint: disable=line-too-long
# Assert that _mark_cookie_for_deletion not called
mock_mark_cookie_for_deletion.assert_not_called()
@@ -745,9 +745,9 @@ def test_process_request_emails_match_with_toggle_disabled(
EmailChangeMiddleware.register_email_change(request=self.request, email=self.user.email)
# Ensure email is set in the session
- self.assertEqual(self.request.session.get('email'), self.user.email)
+ self.assertEqual(self.request.session.get('email'), self.user.email) # noqa: PT009
# Ensure session cookie exist
- self.assertEqual(len(self.client.response.cookies), 1)
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
# No email change occurred in any browser
@@ -760,9 +760,9 @@ def test_process_request_emails_match_with_toggle_disabled(
mock_set_custom_attribute.assert_has_calls([call('is_enforce_session_email_match_enabled', False)])
# Assert that the session and cookies are not affected
- self.assertEqual(self.request.session.get('email'), self.user.email)
- self.assertEqual(len(self.client.response.cookies), 1)
- self.assertEqual(self.client.response.cookies[settings.SESSION_COOKIE_NAME].value, 'authenticated')
+ self.assertEqual(self.request.session.get('email'), self.user.email) # noqa: PT009
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
+ self.assertEqual(self.client.response.cookies[settings.SESSION_COOKIE_NAME].value, 'authenticated') # noqa: PT009 # pylint: disable=line-too-long
# Assert that _mark_cookie_for_deletion not called
mock_mark_cookie_for_deletion.assert_not_called()
@@ -789,9 +789,9 @@ def test_process_request_emails_mismatch_with_toggle_enabled(
EmailChangeMiddleware.register_email_change(request=self.request, email=self.user.email)
# Ensure email is set in the session
- self.assertEqual(self.request.session.get('email'), self.user.email)
+ self.assertEqual(self.request.session.get('email'), self.user.email) # noqa: PT009
# Ensure session cookie exist
- self.assertEqual(len(self.client.response.cookies), 1)
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
# simulating email changed in some other browser
self.user.email = 'new_email@test.com'
@@ -832,9 +832,9 @@ def test_process_request_emails_mismatch_with_toggle_disabled(
EmailChangeMiddleware.register_email_change(request=self.request, email=self.user.email)
# Ensure email is set in the session
- self.assertEqual(self.request.session.get('email'), self.user.email)
+ self.assertEqual(self.request.session.get('email'), self.user.email) # noqa: PT009
# Ensure session cookie exist
- self.assertEqual(len(self.client.response.cookies), 1)
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
# simulating email changed in some other browser
self.user.email = 'new_email@test.com'
@@ -849,9 +849,9 @@ def test_process_request_emails_mismatch_with_toggle_disabled(
mock_set_custom_attribute.assert_has_calls([call('is_enforce_session_email_match_enabled', False)])
# Assert that the session and cookies are not affected
- self.assertNotEqual(self.request.session.get('email'), self.user.email)
- self.assertEqual(len(self.client.response.cookies), 1)
- self.assertEqual(self.client.response.cookies[settings.SESSION_COOKIE_NAME].value, 'authenticated')
+ self.assertNotEqual(self.request.session.get('email'), self.user.email) # noqa: PT009
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
+ self.assertEqual(self.client.response.cookies[settings.SESSION_COOKIE_NAME].value, 'authenticated') # noqa: PT009 # pylint: disable=line-too-long
# Assert that _mark_cookie_for_deletion not called
mock_mark_cookie_for_deletion.assert_not_called()
@@ -873,10 +873,10 @@ def test_process_request_no_email_change_history_with_toggle_enabled(
self.client.response.set_cookie(settings.SESSION_COOKIE_NAME, 'authenticated') # Add some logged-in cookie
# Ensure there is no email in the session denoting no previous history of email change
- self.assertEqual(self.request.session.get('email'), None)
+ self.assertEqual(self.request.session.get('email'), None) # noqa: PT009
# Ensure session cookie exist
- self.assertEqual(len(self.client.response.cookies), 1)
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
# simulating email changed in some other browser
self.user.email = 'new_email@test.com'
@@ -886,8 +886,8 @@ def test_process_request_no_email_change_history_with_toggle_enabled(
EmailChangeMiddleware(get_response=lambda request: None).process_request(self.request)
# Assert that the session and cookies are not affected
- self.assertEqual(len(self.client.response.cookies), 1)
- self.assertEqual(self.client.response.cookies[settings.SESSION_COOKIE_NAME].value, 'authenticated')
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
+ self.assertEqual(self.client.response.cookies[settings.SESSION_COOKIE_NAME].value, 'authenticated') # noqa: PT009 # pylint: disable=line-too-long
# Assert that _mark_cookie_for_deletion not called
mock_mark_cookie_for_deletion.assert_not_called()
@@ -909,10 +909,10 @@ def test_process_request_no_email_change_history_with_toggle_disabled(
self.client.response.set_cookie(settings.SESSION_COOKIE_NAME, 'authenticated') # Add some logged-in cookie
# Ensure there is no email in the session denoting no previous history of email change
- self.assertEqual(self.request.session.get('email'), None)
+ self.assertEqual(self.request.session.get('email'), None) # noqa: PT009
# Ensure session cookie exist
- self.assertEqual(len(self.client.response.cookies), 1)
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
# simulating email changed in some other browser
self.user.email = 'new_email@test.com'
@@ -922,8 +922,8 @@ def test_process_request_no_email_change_history_with_toggle_disabled(
EmailChangeMiddleware(get_response=lambda request: None).process_request(self.request)
# Assert that the session and cookies are not affected
- self.assertEqual(len(self.client.response.cookies), 1)
- self.assertEqual(self.client.response.cookies[settings.SESSION_COOKIE_NAME].value, 'authenticated')
+ self.assertEqual(len(self.client.response.cookies), 1) # noqa: PT009
+ self.assertEqual(self.client.response.cookies[settings.SESSION_COOKIE_NAME].value, 'authenticated') # noqa: PT009 # pylint: disable=line-too-long
# Assert that _mark_cookie_for_deletion not called
mock_mark_cookie_for_deletion.assert_not_called()
@@ -1018,7 +1018,7 @@ def test_process_response_no_email_in_session(self):
self.client.response.set_cookie(settings.SESSION_COOKIE_NAME, 'authenticated') # Add some logged-in cookie
# Ensure there is no email in the session
- self.assertEqual(self.request.session.get('email'), None)
+ self.assertEqual(self.request.session.get('email'), None) # noqa: PT009
# Call process_response
response = EmailChangeMiddleware(get_response=lambda request: None).process_response(
@@ -1027,7 +1027,7 @@ def test_process_response_no_email_in_session(self):
assert response.status_code == 200
# Verify that email is set in the session
- self.assertEqual(self.request.session.get('email'), self.user.email)
+ self.assertEqual(self.request.session.get('email'), self.user.email) # noqa: PT009
@patch.dict("django.conf.settings.FEATURES", {"DISABLE_SET_JWT_COOKIES_FOR_TESTS": False})
def test_user_remain_authenticated_on_email_change_in_other_browser_with_toggle_disabled(self):
@@ -1105,11 +1105,11 @@ def test_cookies_are_updated_with_new_email_on_email_change_with_toggle_enabled(
# Verify that jwt cookies are updated with new email and
# not equal to old logged-in cookies in current browser
- self.assertNotEqual(
+ self.assertNotEqual( # noqa: PT009
login_response.cookies[jwt_cookies.jwt_cookie_header_payload_name()].value,
email_change_response.cookies[jwt_cookies.jwt_cookie_header_payload_name()].value
)
- self.assertNotEqual(
+ self.assertNotEqual( # noqa: PT009
login_response.cookies[jwt_cookies.jwt_cookie_signature_name()].value,
email_change_response.cookies[jwt_cookies.jwt_cookie_signature_name()].value
)
@@ -1158,11 +1158,11 @@ def test_cookies_are_updated_with_new_email_on_email_change_with_toggle_disabled
# Verify that jwt cookies are updated with new email and
# not equal to old logged-in cookies in current browser
- self.assertNotEqual(
+ self.assertNotEqual( # noqa: PT009
login_response.cookies[jwt_cookies.jwt_cookie_header_payload_name()].value,
email_change_response.cookies[jwt_cookies.jwt_cookie_header_payload_name()].value
)
- self.assertNotEqual(
+ self.assertNotEqual( # noqa: PT009
login_response.cookies[jwt_cookies.jwt_cookie_signature_name()].value,
email_change_response.cookies[jwt_cookies.jwt_cookie_signature_name()].value
)
@@ -1348,10 +1348,10 @@ def _assert_logged_in_cookies_present(self, response):
for cookie in all_cookies:
# Check if the cookie is present in response.cookies.keys()
- self.assertIn(cookie, response.cookies.keys())
+ self.assertIn(cookie, response.cookies.keys()) # noqa: PT009
# Assert that the value is not an empty string
- self.assertNotEqual(response.cookies[cookie].value, "")
+ self.assertNotEqual(response.cookies[cookie].value, "") # noqa: PT009
def _assert_logged_in_cookies_not_present(self, response):
"""
@@ -1362,7 +1362,7 @@ def _assert_logged_in_cookies_not_present(self, response):
for cookie in all_cookies:
# Check if the cookie is present in response.cookies.keys()
- self.assertIn(cookie, response.cookies.keys())
+ self.assertIn(cookie, response.cookies.keys()) # noqa: PT009
# Assert that the value is not an empty string
- self.assertEqual(response.cookies[cookie].value, "")
+ self.assertEqual(response.cookies[cookie].value, "") # noqa: PT009
diff --git a/openedx/core/djangoapps/safe_sessions/tests/test_safe_cookie_data.py b/openedx/core/djangoapps/safe_sessions/tests/test_safe_cookie_data.py
index 3ec863095fda..0cbd9e9d024b 100644
--- a/openedx/core/djangoapps/safe_sessions/tests/test_safe_cookie_data.py
+++ b/openedx/core/djangoapps/safe_sessions/tests/test_safe_cookie_data.py
@@ -34,7 +34,7 @@ def assert_cookie_data_equal(self, cookie_data1, cookie_data2):
Asserts equivalency of the given cookie datas by comparing
their member variables.
"""
- self.assertDictEqual(cookie_data1.__dict__, cookie_data2.__dict__)
+ self.assertDictEqual(cookie_data1.__dict__, cookie_data2.__dict__) # noqa: PT009
#---- Test Success ----#
diff --git a/openedx/core/djangoapps/safe_sessions/tests/test_utils.py b/openedx/core/djangoapps/safe_sessions/tests/test_utils.py
index 54bf9ceb302c..586b233ecf01 100644
--- a/openedx/core/djangoapps/safe_sessions/tests/test_utils.py
+++ b/openedx/core/djangoapps/safe_sessions/tests/test_utils.py
@@ -21,7 +21,7 @@ def assert_logged(self, log_string, log_level='error'):
with patch('openedx.core.djangoapps.safe_sessions.middleware.log.' + log_level) as mock_log:
yield
assert mock_log.called
- self.assertRegex(mock_log.call_args_list[0][0][0], log_string)
+ self.assertRegex(mock_log.call_args_list[0][0][0], log_string) # noqa: PT009
@contextmanager
def assert_regex_not_logged(self, log_string, log_level):
@@ -135,7 +135,7 @@ def assert_logged_for_request_user_mismatch(self, user_at_request, user_at_respo
"""
session_suffix = 'Session changed.' if session_changed else 'Session did not change.'
with self.assert_logged_with_message(
- (
+ ( # noqa: UP032
"SafeCookieData user at initial request '{}' does not match user at response time: '{}' "
"for request path '{}'.\n{}"
).format(
@@ -154,7 +154,7 @@ def assert_logged_for_session_user_mismatch(self, user_at_request, user_in_sessi
session_suffix = 'Session changed.' if session_changed else 'Session did not change.'
with self.assert_logged_with_message(
- (
+ ( # noqa: UP032
"SafeCookieData user at initial request '{}' does not match user in session: '{}' "
"for request path '{}'.\n{}"
).format(
@@ -174,7 +174,7 @@ def assert_logged_for_both_mismatch(self, user_at_request, user_in_session, user
session_suffix = 'Session changed.' if session_changed else 'Session did not change.'
with self.assert_logged_with_message(
- (
+ ( # noqa: UP032
"SafeCookieData user at initial request '{}' matches neither user in session: '{}' "
"nor user at response time: '{}' for request path '{}'.\n{}"
).format(
diff --git a/openedx/core/djangoapps/schedules/admin.py b/openedx/core/djangoapps/schedules/admin.py
index 4f5a9cad7b83..f900bcb462d5 100644
--- a/openedx/core/djangoapps/schedules/admin.py
+++ b/openedx/core/djangoapps/schedules/admin.py
@@ -39,7 +39,7 @@ def _set_experience(db_name, human_name, modeladmin, request, queryset): # lint
)
modeladmin.message_user(
request,
- "{} schedule(s) were changed to use the {} experience".format(
+ "{} schedule(s) were changed to use the {} experience".format( # noqa: UP032
rows_updated,
human_name,
)
diff --git a/openedx/core/djangoapps/schedules/apps.py b/openedx/core/djangoapps/schedules/apps.py
index 69216097b06f..397c22584c17 100644
--- a/openedx/core/djangoapps/schedules/apps.py
+++ b/openedx/core/djangoapps/schedules/apps.py
@@ -2,9 +2,12 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
-from edx_django_utils.plugins import PluginSignals # lint-amnesty, pylint: disable=unused-import
+from edx_django_utils.plugins import PluginSignals # pylint: disable=unused-import # noqa: F401
-from openedx.core.djangoapps.plugins.constants import ProjectType # lint-amnesty, pylint: disable=unused-import
+# pylint: disable-next=unused-import
+from openedx.core.djangoapps.plugins.constants import (
+ ProjectType, # noqa: F401
+)
class SchedulesConfig(AppConfig): # lint-amnesty, pylint: disable=missing-class-docstring
@@ -13,4 +16,4 @@ class SchedulesConfig(AppConfig): # lint-amnesty, pylint: disable=missing-class
def ready(self):
# noinspection PyUnresolvedReferences
- from . import signals, tasks # lint-amnesty, pylint: disable=unused-import, unused-variable
+ from . import signals, tasks # lint-amnesty, pylint: disable=unused-import, unused-variable # noqa: F401
diff --git a/openedx/core/djangoapps/schedules/content_highlights.py b/openedx/core/djangoapps/schedules/content_highlights.py
index d6c330fdcef3..a1730e640f3d 100644
--- a/openedx/core/djangoapps/schedules/content_highlights.py
+++ b/openedx/core/djangoapps/schedules/content_highlights.py
@@ -167,7 +167,7 @@ def _get_highlights_for_week(sections, week_num, course_key):
num_sections = len(sections)
if not 1 <= week_num <= num_sections:
raise CourseUpdateDoesNotExist(
- 'Requested week {} but {} has only {} sections.'.format(
+ 'Requested week {} but {} has only {} sections.'.format( # noqa: UP032
week_num, course_key, num_sections
)
)
diff --git a/openedx/core/djangoapps/schedules/management/commands/tests/test_send_upgrade_reminder.py b/openedx/core/djangoapps/schedules/management/commands/tests/test_send_upgrade_reminder.py
index 9dc2dfb3ec70..bd03380cf791 100644
--- a/openedx/core/djangoapps/schedules/management/commands/tests/test_send_upgrade_reminder.py
+++ b/openedx/core/djangoapps/schedules/management/commands/tests/test_send_upgrade_reminder.py
@@ -85,7 +85,7 @@ def test_filter_out_verified_schedules(self):
messages = [Message.from_string(m) for m in sent_messages]
assert len(messages) == 1
message = messages[0]
- self.assertCountEqual(
+ self.assertCountEqual( # noqa: PT009
message.context['course_ids'],
[str(schedules[i].enrollment.course.id) for i in (1, 2, 4)]
)
diff --git a/openedx/core/djangoapps/schedules/models.py b/openedx/core/djangoapps/schedules/models.py
index 2db574cf0e6c..76b73af1b53f 100644
--- a/openedx/core/djangoapps/schedules/models.py
+++ b/openedx/core/djangoapps/schedules/models.py
@@ -62,7 +62,7 @@ class ScheduleConfig(ConfigurationModel):
deliver_course_update = models.BooleanField(default=False)
-class ScheduleExperience(models.Model):
+class ScheduleExperience(models.Model): # noqa: DJ008
"""
.. no_pii:
"""
diff --git a/openedx/core/djangoapps/schedules/resolvers.py b/openedx/core/djangoapps/schedules/resolvers.py
index 24ec08be8ed5..12f104f0291e 100644
--- a/openedx/core/djangoapps/schedules/resolvers.py
+++ b/openedx/core/djangoapps/schedules/resolvers.py
@@ -384,7 +384,7 @@ def send(self, msg_type):
context,
)
LOG.info(
- 'Sending email to user: {} for Instructor-paced course with course-key: {} and language: {}'.format(
+ 'Sending email to user: {} for Instructor-paced course with course-key: {} and language: {}'.format( # noqa: UP032 # pylint: disable=line-too-long
user.username,
self.course_id,
language
@@ -414,7 +414,7 @@ def schedules_for_bin(self):
week_highlights = get_week_highlights(user, enrollment.course_id, week_num)
except CourseUpdateDoesNotExist:
LOG.warning(
- 'Weekly highlights for user {} in week {} of course {} does not exist or is disabled'.format(
+ 'Weekly highlights for user {} in week {} of course {} does not exist or is disabled'.format( # noqa: UP032 # pylint: disable=line-too-long
user, week_num, enrollment.course_id
)
)
@@ -472,13 +472,13 @@ def send(self): # lint-amnesty, pylint: disable=arguments-differ
context,
)
LOG.info(
- 'Sending email to user: {} for course-key: {}'.format(
+ 'Sending email to user: {} for course-key: {}'.format( # noqa: UP032
user.username,
self.course_id
)
)
LOG.info(
- 'Sending email to user: {} for Self-paced course with course-key: {} and language: {}'.format(
+ 'Sending email to user: {} for Self-paced course with course-key: {} and language: {}'.format( # noqa: UP032 # pylint: disable=line-too-long
user.username,
self.course_id,
language
@@ -518,7 +518,7 @@ def get_schedules(self):
user = schedule.enrollment.user
start_date = max(filter(None, (schedule.start_date, course.start)))
- LOG.info('Received a schedule for user {} in course {} for date {}'.format(
+ LOG.info('Received a schedule for user {} in course {} for date {}'.format( # noqa: UP032
user.username, self.course_id, target_date,
))
diff --git a/openedx/core/djangoapps/schedules/signals.py b/openedx/core/djangoapps/schedules/signals.py
index 772a966d1d94..9165500cae50 100644
--- a/openedx/core/djangoapps/schedules/signals.py
+++ b/openedx/core/djangoapps/schedules/signals.py
@@ -50,7 +50,7 @@ def create_schedule(sender, **kwargs): # pylint: disable=unused-argument
except Exception: # pylint: disable=broad-except
# We do not want to block the creation of a CourseEnrollment because of an error in creating a Schedule.
# No Schedule is acceptable, but no CourseEnrollment is not.
- log.exception('Encountered error in creating a Schedule for CourseEnrollment for user {} in course {}'.format(
+ log.exception('Encountered error in creating a Schedule for CourseEnrollment for user {} in course {}'.format( # noqa: UP032 # pylint: disable=line-too-long
enrollment.user.id if (enrollment and enrollment.user) else None,
enrollment.course_id if enrollment else None
))
diff --git a/openedx/core/djangoapps/schedules/tasks.py b/openedx/core/djangoapps/schedules/tasks.py
index 71c8b12be76f..70eb3d5a2820 100644
--- a/openedx/core/djangoapps/schedules/tasks.py
+++ b/openedx/core/djangoapps/schedules/tasks.py
@@ -60,7 +60,7 @@ def update_course_schedules(self, **kwargs): # lint-amnesty, pylint: disable=mi
except Exception as exc:
if not isinstance(exc, KNOWN_RETRY_ERRORS):
LOG.exception(f"Unexpected failure: task id: {self.request.id}, kwargs={kwargs}")
- raise self.retry(kwargs=kwargs, exc=exc)
+ raise self.retry(kwargs=kwargs, exc=exc) # noqa: B904
class ScheduleMessageBaseTask(LoggedTask): # lint-amnesty, pylint: disable=abstract-method
diff --git a/openedx/core/djangoapps/schedules/tests/test_content_highlights.py b/openedx/core/djangoapps/schedules/tests/test_content_highlights.py
index 4f0f31038c59..fb8d4f3a1d04 100644
--- a/openedx/core/djangoapps/schedules/tests/test_content_highlights.py
+++ b/openedx/core/djangoapps/schedules/tests/test_content_highlights.py
@@ -157,7 +157,7 @@ def test_get_next_section_highlights(self, mock_duration):
assert get_next_section_highlights(self.user, self.course_key, two_days_ago, three_days.date()) == (None, None)
assert get_next_section_highlights(self.user, self.course_key, two_days_ago, four_days.date()) ==\
(['final week!'], 4)
- exception_message = f'Last section was reached. There are no more highlights for {self.course_key}'
+ exception_message = f'Last section was reached. There are no more highlights for {self.course_key}' # noqa: F841 # pylint: disable=line-too-long
with pytest.raises(CourseUpdateDoesNotExist):
get_next_section_highlights(self.user, self.course_key, two_days_ago, six_days.date())
@@ -168,10 +168,10 @@ def test_get_highlights_without_block(self, mock_get_block):
with self.store.bulk_operations(self.course_key):
self._create_chapter(highlights=['Test highlight'])
- with self.assertRaisesRegex(CourseUpdateDoesNotExist, 'Course block .* not found'):
+ with self.assertRaisesRegex(CourseUpdateDoesNotExist, 'Course block .* not found'): # noqa: PT027
get_week_highlights(self.user, self.course_key, 1)
yesterday = datetime.datetime.utcnow() - datetime.timedelta(days=1)
today = datetime.datetime.utcnow()
- with self.assertRaisesRegex(CourseUpdateDoesNotExist, 'Course block .* not found'):
+ with self.assertRaisesRegex(CourseUpdateDoesNotExist, 'Course block .* not found'): # noqa: PT027
get_next_section_highlights(self.user, self.course_key, yesterday, today.date())
diff --git a/openedx/core/djangoapps/schedules/tests/test_filters.py b/openedx/core/djangoapps/schedules/tests/test_filters.py
index 9f7efa050447..44a27a665de1 100644
--- a/openedx/core/djangoapps/schedules/tests/test_filters.py
+++ b/openedx/core/djangoapps/schedules/tests/test_filters.py
@@ -61,11 +61,11 @@ def test_schedule_with_queryset_requested_filter_enabled(self) -> None:
"""Test to verify the schedule queryset was modified by the pipeline step."""
schedules = self.resolver.get_schedules_with_target_date_by_bin_and_orgs()
- self.assertEqual(TestScheduleQuerySetRequestedPipelineStep.filtered_schedules, schedules)
+ self.assertEqual(TestScheduleQuerySetRequestedPipelineStep.filtered_schedules, schedules) # noqa: PT009
@override_settings(OPEN_EDX_FILTERS_CONFIG={})
def test_schedule_with_queryset_requested_filter_disabled(self) -> None:
"""Test to verify the schedule queryset was not modified when the pipeline step is not configured."""
schedules = self.resolver.get_schedules_with_target_date_by_bin_and_orgs()
- self.assertNotEqual(TestScheduleQuerySetRequestedPipelineStep.filtered_schedules, schedules)
+ self.assertNotEqual(TestScheduleQuerySetRequestedPipelineStep.filtered_schedules, schedules) # noqa: PT009
diff --git a/openedx/core/djangoapps/schedules/tests/test_resolvers.py b/openedx/core/djangoapps/schedules/tests/test_resolvers.py
index ffe75a1b9b61..3d3ea4293b3f 100644
--- a/openedx/core/djangoapps/schedules/tests/test_resolvers.py
+++ b/openedx/core/djangoapps/schedules/tests/test_resolvers.py
@@ -338,7 +338,7 @@ def test_schedule_context_error(self):
resolver = self.create_resolver(user_start_date_offset=29)
with LogCapture(LOG.name) as log_capture:
list(resolver.get_schedules())
- log_message = ('Next Section Course Update: Last section was reached. '
+ log_message = ('Next Section Course Update: Last section was reached. ' # noqa: UP032
'There are no more highlights for {}'.format(self.course.id))
log_capture.check_present((LOG.name, 'WARNING', log_message))
@@ -347,4 +347,4 @@ def test_no_updates_if_course_ended(self):
self.course = self.update_course(self.course, self.user.id)
resolver = self.create_resolver()
schedules = list(resolver.get_schedules())
- self.assertListEqual(schedules, [])
+ self.assertListEqual(schedules, []) # noqa: PT009
diff --git a/openedx/core/djangoapps/schedules/tests/test_signals.py b/openedx/core/djangoapps/schedules/tests/test_signals.py
index b4fb763883a5..5e8ab6ded627 100644
--- a/openedx/core/djangoapps/schedules/tests/test_signals.py
+++ b/openedx/core/djangoapps/schedules/tests/test_signals.py
@@ -55,17 +55,17 @@ def assert_schedule_not_created(self): # lint-amnesty, pylint: disable=missing-
mode=CourseMode.AUDIT,
)
with pytest.raises(Schedule.DoesNotExist):
- enrollment.schedule # lint-amnesty, pylint: disable=pointless-statement
+ enrollment.schedule # lint-amnesty, pylint: disable=pointless-statement # noqa: B018
def test_create_schedule(self):
self.assert_schedule_created()
@patch.object(CourseOverview, '_get_course_has_highlights', return_value=True)
- def test_schedule_config_creation_enabled_instructor_paced(self, _mock_highlights):
+ def test_schedule_config_creation_enabled_instructor_paced(self, _mock_highlights): # noqa: PT019
self.assert_schedule_created(is_self_paced=False, experience_type=ScheduleExperience.EXPERIENCES.course_updates)
@patch.object(CourseOverview, '_get_course_has_highlights', return_value=True)
- def test_create_schedule_course_updates_experience(self, _mock_highlights):
+ def test_create_schedule_course_updates_experience(self, _mock_highlights): # noqa: PT019
self.assert_schedule_created(experience_type=ScheduleExperience.EXPERIENCES.course_updates)
@patch('openedx.core.djangoapps.schedules.signals.log.exception')
diff --git a/openedx/core/djangoapps/session_inactivity_timeout/tests/test_middleware.py b/openedx/core/djangoapps/session_inactivity_timeout/tests/test_middleware.py
index 43f1def794b6..0d886635f6e8 100644
--- a/openedx/core/djangoapps/session_inactivity_timeout/tests/test_middleware.py
+++ b/openedx/core/djangoapps/session_inactivity_timeout/tests/test_middleware.py
@@ -81,7 +81,7 @@ def test_process_request_invalid_timestamp_handling(
# The middleware should raise an exception when it tries to parse the invalid timestamp
# in the save delay logic (after already catching it once in the timeout logic)
- with self.assertRaises(ValueError):
+ with self.assertRaises(ValueError): # noqa: PT027
self.middleware.process_request(self.request)
mock_log.warning.assert_called_once()
diff --git a/openedx/core/djangoapps/site_configuration/management/commands/create_or_update_site_configuration.py b/openedx/core/djangoapps/site_configuration/management/commands/create_or_update_site_configuration.py
index c97944b91012..b924f15fded6 100644
--- a/openedx/core/djangoapps/site_configuration/management/commands/create_or_update_site_configuration.py
+++ b/openedx/core/djangoapps/site_configuration/management/commands/create_or_update_site_configuration.py
@@ -100,7 +100,7 @@ def handle(self, *args, **options):
site_configuration, created = SiteConfiguration.objects.get_or_create(site=site)
if created:
LOG.info(
- "Site configuration does not exist. Created new instance for '{site_name}'".format(
+ "Site configuration does not exist. Created new instance for '{site_name}'".format( # noqa: UP032
site_name=site.domain
)
)
diff --git a/openedx/core/djangoapps/site_configuration/management/commands/tests/test_create_or_update_site_configuration.py b/openedx/core/djangoapps/site_configuration/management/commands/tests/test_create_or_update_site_configuration.py
index 87a356de9dc1..c33d706ceb7a 100644
--- a/openedx/core/djangoapps/site_configuration/management/commands/tests/test_create_or_update_site_configuration.py
+++ b/openedx/core/djangoapps/site_configuration/management/commands/tests/test_create_or_update_site_configuration.py
@@ -149,7 +149,7 @@ def test_site_configuration_created_with_parameters(self):
self.assert_site_configuration_does_not_exist()
call_command(self.command, '--configuration', json.dumps(self.input_configuration), *self.site_id_arg)
site_configuration = self.get_site_configuration()
- self.assertDictEqual(site_configuration.site_values, self.input_configuration)
+ self.assertDictEqual(site_configuration.site_values, self.input_configuration) # noqa: PT009
def test_site_configuration_created_with_json_file_parameters(self):
"""
diff --git a/openedx/core/djangoapps/site_configuration/models.py b/openedx/core/djangoapps/site_configuration/models.py
index 17ad37879110..3bf23e851f73 100644
--- a/openedx/core/djangoapps/site_configuration/models.py
+++ b/openedx/core/djangoapps/site_configuration/models.py
@@ -181,7 +181,7 @@ class Meta:
def __str__(self):
# pylint: disable=line-too-long
- return "".format( # xss-lint: disable=python-wrap-html
+ return "".format( # xss-lint: disable=python-wrap-html # noqa: UP032
modified=self.modified,
site=self.site,
)
diff --git a/openedx/core/djangoapps/site_configuration/tests/test_helpers.py b/openedx/core/djangoapps/site_configuration/tests/test_helpers.py
index 1eaa5a1000b3..f957f770eab0 100644
--- a/openedx/core/djangoapps/site_configuration/tests/test_helpers.py
+++ b/openedx/core/djangoapps/site_configuration/tests/test_helpers.py
@@ -77,7 +77,7 @@ def test_get_dict(self):
Test that get_dict returns correct value for any given key.
"""
# Make sure entry is saved and retrieved correctly
- self.assertCountEqual(
+ self.assertCountEqual( # noqa: PT009
configuration_helpers.get_dict("REGISTRATION_EXTRA_FIELDS"),
test_config['REGISTRATION_EXTRA_FIELDS'],
)
@@ -87,7 +87,7 @@ def test_get_dict(self):
expected.update(test_config['REGISTRATION_EXTRA_FIELDS'])
# Test that the default value is returned if the value for the given key is not found in the configuration
- self.assertCountEqual(
+ self.assertCountEqual( # noqa: PT009
configuration_helpers.get_dict("REGISTRATION_EXTRA_FIELDS", default),
expected,
)
@@ -125,7 +125,7 @@ def test_get_value_for_org(self):
assert configuration_helpers.get_value_for_org(test_org, 'css_overrides_file') ==\
test_config['css_overrides_file']
- self.assertCountEqual(
+ self.assertCountEqual( # noqa: PT009
configuration_helpers.get_value_for_org(test_org, "REGISTRATION_EXTRA_FIELDS"),
test_config['REGISTRATION_EXTRA_FIELDS']
)
@@ -155,7 +155,7 @@ def test_get_all_orgs(self):
"""
test_orgs = [test_config['course_org_filter']]
with with_site_configuration_context(configuration=test_config):
- self.assertCountEqual(
+ self.assertCountEqual( # noqa: PT009
list(configuration_helpers.get_all_orgs()),
test_orgs,
)
@@ -163,7 +163,7 @@ def test_get_all_orgs(self):
@with_site_configuration(configuration=test_config_multi_org)
def test_get_current_site_orgs(self):
test_orgs = test_config_multi_org['course_org_filter']
- self.assertCountEqual(
+ self.assertCountEqual( # noqa: PT009
list(configuration_helpers.get_current_site_orgs()),
test_orgs
)
@@ -173,11 +173,11 @@ def test_get_current_site_configuration_values(self):
Test get_current_site_configuration_values helper function
"""
site_values = configuration_helpers.get_current_site_configuration_values()
- self.assertTrue(isinstance(site_values, dict))
+ self.assertTrue(isinstance(site_values, dict)) # noqa: PT009
# without any site configuration it should return empty dict
- self.assertEqual(site_values, {})
+ self.assertEqual(site_values, {}) # noqa: PT009
with with_site_configuration_context(configuration=test_config):
site_values = configuration_helpers.get_current_site_configuration_values()
- self.assertEqual(site_values, test_config)
+ self.assertEqual(site_values, test_config) # noqa: PT009
diff --git a/openedx/core/djangoapps/site_configuration/tests/test_models.py b/openedx/core/djangoapps/site_configuration/tests/test_models.py
index 2b0c44db70be..a05a977c362c 100644
--- a/openedx/core/djangoapps/site_configuration/tests/test_models.py
+++ b/openedx/core/djangoapps/site_configuration/tests/test_models.py
@@ -301,7 +301,7 @@ def test_get_all_orgs(self):
)
# Test that the default value is returned if the value for the given key is not found in the configuration
- self.assertCountEqual(SiteConfiguration.get_all_orgs(), expected_orgs)
+ self.assertCountEqual(SiteConfiguration.get_all_orgs(), expected_orgs) # noqa: PT009
def test_get_all_orgs_returns_only_enabled(self):
"""
@@ -320,4 +320,4 @@ def test_get_all_orgs_returns_only_enabled(self):
)
# Test that the default value is returned if the value for the given key is not found in the configuration
- self.assertCountEqual(SiteConfiguration.get_all_orgs(), expected_orgs)
+ self.assertCountEqual(SiteConfiguration.get_all_orgs(), expected_orgs) # noqa: PT009
diff --git a/openedx/core/djangoapps/theming/apps.py b/openedx/core/djangoapps/theming/apps.py
index 39301e23f3db..ab54b30ca5b5 100644
--- a/openedx/core/djangoapps/theming/apps.py
+++ b/openedx/core/djangoapps/theming/apps.py
@@ -20,4 +20,4 @@ class ThemingConfig(AppConfig): # lint-amnesty, pylint: disable=missing-class-d
def ready(self):
# settings validations related to theming.
- from . import checks # lint-amnesty, pylint: disable=unused-import
+ from . import checks # lint-amnesty, pylint: disable=unused-import # noqa: F401
diff --git a/openedx/core/djangoapps/theming/helpers.py b/openedx/core/djangoapps/theming/helpers.py
index 0652dd8639e5..ba6e8c97eb5d 100644
--- a/openedx/core/djangoapps/theming/helpers.py
+++ b/openedx/core/djangoapps/theming/helpers.py
@@ -240,7 +240,7 @@ def get_theme_base_dir(theme_dir_name, suppress_error=False):
return None
raise ValueError(
- "Theme '{theme}' not found in any of the following themes dirs, \nTheme dirs: \n{dir}".format(
+ "Theme '{theme}' not found in any of the following themes dirs, \nTheme dirs: \n{dir}".format( # noqa: UP032
theme=theme_dir_name,
dir=get_theme_base_dirs(),
))
diff --git a/openedx/core/djangoapps/theming/management/commands/create_sites_and_configurations.py b/openedx/core/djangoapps/theming/management/commands/create_sites_and_configurations.py
index 4805c5f6246f..6ec171ce8f56 100644
--- a/openedx/core/djangoapps/theming/management/commands/create_sites_and_configurations.py
+++ b/openedx/core/djangoapps/theming/management/commands/create_sites_and_configurations.py
@@ -78,11 +78,11 @@ def _create_oauth2_client(self, url, site_name, service_name, service_user):
client_id=client_id,
defaults={
"user": service_user,
- "name": "{service_name}-sso-{site_name}".format(
+ "name": "{service_name}-sso-{site_name}".format( # noqa: UP032
site_name=site_name,
service_name=service_name,
),
- "client_secret": "{service_name}-secret".format(
+ "client_secret": "{service_name}-secret".format( # noqa: UP032
service_name=service_name
),
"client_type": Application.CLIENT_CONFIDENTIAL,
@@ -126,7 +126,7 @@ def find(self, pattern, path):
Matched the given pattern in given path and returns the list of matching files
"""
result = []
- for root, dirs, files in os.walk(path): # pylint: disable=unused-variable
+ for root, dirs, files in os.walk(path): # pylint: disable=unused-variable # noqa: B007
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
@@ -213,21 +213,21 @@ def handle(self, *args, **options):
if options['devstack']:
configuration_prefix = "devstack"
- self.discovery_oauth_complete_url = "http://discovery-{}.e2e.devstack:18381/complete/edx-oauth2/".format(
+ self.discovery_oauth_complete_url = "http://discovery-{}.e2e.devstack:18381/complete/edx-oauth2/".format( # noqa: UP032 # pylint: disable=line-too-long
self.dns_name
)
self.discovery_base_url_fmt = "http://discovery-{site_domain}:18381/"
- self.ecommerce_oauth_complete_url = "http://ecommerce-{}.e2e.devstack:18130/complete/edx-oauth2/".format(
+ self.ecommerce_oauth_complete_url = "http://ecommerce-{}.e2e.devstack:18130/complete/edx-oauth2/".format( # noqa: UP032 # pylint: disable=line-too-long
self.dns_name
)
self.ecommerce_base_url_fmt = "http://ecommerce-{site_domain}:18130/"
else:
configuration_prefix = "sandbox"
- self.discovery_oauth_complete_url = "https://discovery-{}.sandbox.edx.org/complete/edx-oauth2/".format(
+ self.discovery_oauth_complete_url = "https://discovery-{}.sandbox.edx.org/complete/edx-oauth2/".format( # noqa: UP032 # pylint: disable=line-too-long
self.dns_name
)
self.discovery_base_url_fmt = "https://discovery-{site_domain}/"
- self.ecommerce_oauth_complete_url = "https://ecommerce-{}.sandbox.edx.org/complete/edx-oauth2/".format(
+ self.ecommerce_oauth_complete_url = "https://ecommerce-{}.sandbox.edx.org/complete/edx-oauth2/".format( # noqa: UP032 # pylint: disable=line-too-long
self.dns_name
)
self.ecommerce_base_url_fmt = "https://ecommerce-{site_domain}/"
diff --git a/openedx/core/djangoapps/theming/management/commands/tests/test_create_sites_and_configurations.py b/openedx/core/djangoapps/theming/management/commands/tests/test_create_sites_and_configurations.py
index 044bfc41a38c..0416b6948f49 100644
--- a/openedx/core/djangoapps/theming/management/commands/tests/test_create_sites_and_configurations.py
+++ b/openedx/core/djangoapps/theming/management/commands/tests/test_create_sites_and_configurations.py
@@ -72,7 +72,7 @@ def _assert_sites_are_valid(self):
assert site_theme.theme_dir_name == f'{site.name}_dir_name'
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
dict(site.configuration.values),
_generate_site_config(self.dns_name, site.name)
)
diff --git a/openedx/core/djangoapps/theming/templatetags/optional_include.py b/openedx/core/djangoapps/theming/templatetags/optional_include.py
index e559568dc8ef..fb09041c517f 100644
--- a/openedx/core/djangoapps/theming/templatetags/optional_include.py
+++ b/openedx/core/djangoapps/theming/templatetags/optional_include.py
@@ -46,7 +46,7 @@ def do_include(parser, token):
"""
bits = token.split_contents()
if len(bits) < 2:
- msg = (
+ msg = ( # noqa: UP031
"%r tag takes at least one argument: the name of the template "
"to be optionally included."
) % bits[0]
@@ -56,17 +56,17 @@ def do_include(parser, token):
while remaining_bits:
option = remaining_bits.pop(0)
if option in options:
- raise TemplateSyntaxError('The %r option was specified more '
+ raise TemplateSyntaxError('The %r option was specified more ' # noqa: UP031
'than once.' % option)
if option == 'with':
value = token_kwargs(remaining_bits, parser, support_legacy=False)
if not value:
- raise TemplateSyntaxError('"with" in %r tag needs at least '
+ raise TemplateSyntaxError('"with" in %r tag needs at least ' # noqa: UP031
'one keyword argument.' % bits[0])
elif option == 'only':
value = True
else:
- raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
+ raise TemplateSyntaxError('Unknown argument for %r tag: %r.' % # noqa: UP031
(bits[0], option))
options[option] = value
isolated_context = options.get('only', False)
diff --git a/openedx/core/djangoapps/theming/templatetags/theme_pipeline.py b/openedx/core/djangoapps/theming/templatetags/theme_pipeline.py
index 804a7a857b87..c27c8595efb0 100644
--- a/openedx/core/djangoapps/theming/templatetags/theme_pipeline.py
+++ b/openedx/core/djangoapps/theming/templatetags/theme_pipeline.py
@@ -56,8 +56,8 @@ def stylesheet(parser, token): # pylint: disable=unused-argument
try:
_, name = token.split_contents()
except ValueError:
- raise template.TemplateSyntaxError( # lint-amnesty, pylint: disable=raise-missing-from
- '%r requires exactly one argument: the name of a group in the PIPELINE["STYLESHEETS"] setting' %
+ raise template.TemplateSyntaxError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
+ '%r requires exactly one argument: the name of a group in the PIPELINE["STYLESHEETS"] setting' % # noqa: UP031 # pylint: disable=line-too-long
token.split_contents()[0]
)
return ThemeStylesheetNode(name)
@@ -71,8 +71,8 @@ def javascript(parser, token): # pylint: disable=unused-argument
try:
_, name = token.split_contents()
except ValueError:
- raise template.TemplateSyntaxError( # lint-amnesty, pylint: disable=raise-missing-from
- '%r requires exactly one argument: the name of a group in the PIPELINE["JAVASCRIPT"] setting' %
+ raise template.TemplateSyntaxError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
+ '%r requires exactly one argument: the name of a group in the PIPELINE["JAVASCRIPT"] setting' % # noqa: UP031 # pylint: disable=line-too-long
token.split_contents()[0]
)
return ThemeJavascriptNode(name)
diff --git a/openedx/core/djangoapps/theming/tests/test_helpers.py b/openedx/core/djangoapps/theming/tests/test_helpers.py
index 461acd98bfb0..1db0b76a6a4e 100644
--- a/openedx/core/djangoapps/theming/tests/test_helpers.py
+++ b/openedx/core/djangoapps/theming/tests/test_helpers.py
@@ -48,7 +48,7 @@ def test_get_themes(self):
Theme('empty-theme', 'empty-theme', get_theme_base_dir('empty-theme'), settings.PROJECT_ROOT),
]
actual_themes = get_themes()
- self.assertCountEqual(expected_themes, actual_themes)
+ self.assertCountEqual(expected_themes, actual_themes) # noqa: PT009
@override_settings(COMPREHENSIVE_THEME_DIRS=[settings.TEST_THEME.dirname()])
def test_get_themes_2(self):
@@ -59,7 +59,7 @@ def test_get_themes_2(self):
Theme('test-theme', 'test-theme', get_theme_base_dir('test-theme'), settings.PROJECT_ROOT),
]
actual_themes = get_themes()
- self.assertCountEqual(expected_themes, actual_themes)
+ self.assertCountEqual(expected_themes, actual_themes) # noqa: PT009
def test_get_value_returns_override(self):
"""
diff --git a/openedx/core/djangoapps/theming/tests/test_util.py b/openedx/core/djangoapps/theming/tests/test_util.py
index 2591c661ac9e..809c14465487 100644
--- a/openedx/core/djangoapps/theming/tests/test_util.py
+++ b/openedx/core/djangoapps/theming/tests/test_util.py
@@ -77,4 +77,4 @@ def dump_theming_info():
continue
with open(os.path.join(dirname, filename)) as f:
content = len(f.read())
- print(" %s: %d" % (filename, content))
+ print(" %s: %d" % (filename, content)) # noqa: UP031
diff --git a/openedx/core/djangoapps/theming/tests/test_views.py b/openedx/core/djangoapps/theming/tests/test_views.py
index d4a990d11f54..992bf92db249 100644
--- a/openedx/core/djangoapps/theming/tests/test_views.py
+++ b/openedx/core/djangoapps/theming/tests/test_views.py
@@ -31,7 +31,7 @@ def test_preview_theme_access(self):
expected_target_status_code = 200 if settings.ROOT_URLCONF == 'lms.urls' else 302
self.assertRedirects(
response,
- '{login_url}?next={url}'.format(
+ '{login_url}?next={url}'.format( # noqa: UP032
login_url=settings.LOGIN_URL,
url=THEMING_ADMIN_URL,
),
diff --git a/openedx/core/djangoapps/user_api/accounts/api.py b/openedx/core/djangoapps/user_api/accounts/api.py
index 70200c850adb..b3d1218f2952 100644
--- a/openedx/core/djangoapps/user_api/accounts/api.py
+++ b/openedx/core/djangoapps/user_api/accounts/api.py
@@ -180,11 +180,11 @@ def update_account_settings(requesting_user, update, username=None):
_update_state_if_needed(update, user_profile)
except PreferenceValidationError as err:
- raise AccountValidationError(err.preference_errors) # lint-amnesty, pylint: disable=raise-missing-from
+ raise AccountValidationError(err.preference_errors) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except (AccountUpdateError, AccountValidationError) as err:
raise err
except Exception as err:
- raise AccountUpdateError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise AccountUpdateError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
f"Error thrown when saving account updates: '{str(err)}'"
)
@@ -387,7 +387,7 @@ def _send_email_change_requests_if_needed(data, user):
try:
student_views.do_email_change_request(user, new_email)
except ValueError as err:
- raise AccountUpdateError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise AccountUpdateError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
f"Error thrown from do_email_change_request: '{str(err)}'",
user_message=str(err)
)
@@ -401,7 +401,7 @@ def _send_email_change_requests_if_needed(data, user):
secondary_email_change_request=True,
)
except ValueError as err:
- raise AccountUpdateError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise AccountUpdateError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
f"Error thrown from do_email_change_request: '{str(err)}'",
user_message=str(err)
)
@@ -563,7 +563,7 @@ def _get_user_and_profile(username):
try:
existing_user = User.objects.get(username=username)
except ObjectDoesNotExist:
- raise errors.UserNotFound() # lint-amnesty, pylint: disable=raise-missing-from
+ raise errors.UserNotFound() # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
existing_user_profile, _ = UserProfile.objects.get_or_create(user=existing_user)
@@ -615,9 +615,9 @@ def _validate_username(username):
# message by convention.
validate_username(username)
except (UnicodeError, errors.AccountDataBadType, errors.AccountDataBadLength) as username_err:
- raise errors.AccountUsernameInvalid(str(username_err))
+ raise errors.AccountUsernameInvalid(str(username_err)) # noqa: B904
except ValidationError as validation_err:
- raise errors.AccountUsernameInvalid(validation_err.message)
+ raise errors.AccountUsernameInvalid(validation_err.message) # noqa: B904
def _validate_email(email):
@@ -640,9 +640,9 @@ def _validate_email(email):
validate_email.message = accounts.AUTHN_EMAIL_INVALID_MSG
validate_email(email)
except (UnicodeError, errors.AccountDataBadType, errors.AccountDataBadLength) as invalid_email_err:
- raise errors.AccountEmailInvalid(str(invalid_email_err))
+ raise errors.AccountEmailInvalid(str(invalid_email_err)) # noqa: B904
except ValidationError as validation_err:
- raise errors.AccountEmailInvalid(validation_err.message)
+ raise errors.AccountEmailInvalid(validation_err.message) # noqa: B904
def _validate_confirm_email(confirm_email, email):
@@ -682,9 +682,9 @@ def _validate_password(password, username=None, email=None, reset_password_page=
temp_user = User(username=username, email=email) if username else None
validate_password(password, user=temp_user)
except errors.AccountDataBadType as invalid_password_err:
- raise errors.AccountPasswordInvalid(str(invalid_password_err))
+ raise errors.AccountPasswordInvalid(str(invalid_password_err)) # noqa: B904
except ValidationError as validation_err:
- raise errors.AccountPasswordInvalid(' '.join(validation_err.messages))
+ raise errors.AccountPasswordInvalid(' '.join(validation_err.messages)) # noqa: B904
if (
(settings.ENABLE_AUTHN_RESET_PASSWORD_HIBP_POLICY and reset_password_page) or
@@ -818,4 +818,4 @@ def _validate_unicode(data, err="Input not valid unicode"):
# In some cases we pass the above, but it's still inappropriate utf-8.
str(data)
except UnicodeError:
- raise UnicodeError(err) # lint-amnesty, pylint: disable=raise-missing-from
+ raise UnicodeError(err) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
diff --git a/openedx/core/djangoapps/user_api/accounts/forms.py b/openedx/core/djangoapps/user_api/accounts/forms.py
index 771b6a7ccf39..95a635a5154a 100644
--- a/openedx/core/djangoapps/user_api/accounts/forms.py
+++ b/openedx/core/djangoapps/user_api/accounts/forms.py
@@ -26,7 +26,7 @@ def save(self, retirement):
None,
# Translators: 'current_state' is a string from an enumerated list indicating the learner's retirement
# state. Example: FORUMS_COMPLETE
- "Retirement requests can only be cancelled for users in the PENDING state."
+ "Retirement requests can only be cancelled for users in the PENDING state." # noqa: UP032
" Current request state for '{original_username}': {current_state}".format(
original_username=retirement.original_username,
current_state=retirement.current_state.state_name
diff --git a/openedx/core/djangoapps/user_api/accounts/image_helpers.py b/openedx/core/djangoapps/user_api/accounts/image_helpers.py
index eff2ad272b28..054fd64b2881 100644
--- a/openedx/core/djangoapps/user_api/accounts/image_helpers.py
+++ b/openedx/core/djangoapps/user_api/accounts/image_helpers.py
@@ -187,7 +187,7 @@ def set_has_profile_image(username, is_uploaded, upload_dt=None):
try:
profile = UserProfile.objects.get(user__username=username)
except ObjectDoesNotExist:
- raise UserNotFound() # lint-amnesty, pylint: disable=raise-missing-from
+ raise UserNotFound() # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
profile.profile_image_uploaded_at = upload_dt
profile.save()
diff --git a/openedx/core/djangoapps/user_api/accounts/serializers.py b/openedx/core/djangoapps/user_api/accounts/serializers.py
index 29ec436d03e8..a23ba772986e 100644
--- a/openedx/core/djangoapps/user_api/accounts/serializers.py
+++ b/openedx/core/djangoapps/user_api/accounts/serializers.py
@@ -435,7 +435,7 @@ def _update_social_links(self, instance, requested_social_links):
except ValueError as err:
# If we have encountered any validation errors, return them to the user.
- raise errors.AccountValidationError({
+ raise errors.AccountValidationError({ # noqa: B904
'social_links': {
"developer_message": f"Error when adding new social link: '{str(err)}'",
"user_message": str(err)
diff --git a/openedx/core/djangoapps/user_api/accounts/tests/test_api.py b/openedx/core/djangoapps/user_api/accounts/tests/test_api.py
index 8c6e09d34c5a..c56cf20eca8b 100644
--- a/openedx/core/djangoapps/user_api/accounts/tests/test_api.py
+++ b/openedx/core/djangoapps/user_api/accounts/tests/test_api.py
@@ -41,7 +41,7 @@
from openedx.core.djangoapps.user_api.accounts.tests.retirement_helpers import ( # pylint: disable=unused-import
RetirementTestCase,
fake_requested_retirement,
- setup_retirement_states,
+ setup_retirement_states, # noqa: F401
)
from openedx.core.djangoapps.user_api.errors import (
AccountUpdateError,
@@ -305,7 +305,7 @@ def test_update_validation_error_for_enterprise(
with patch('openedx.core.djangoapps.user_api.accounts.api.student_views.do_email_change_request'):
# expect field un-editability only when all of the following conditions are met
if is_enterprise_user and is_synch_learner_profile_data and not user_fullname_editable:
- with pytest.raises(AccountValidationError) as validation_error:
+ with pytest.raises(AccountValidationError) as validation_error: # noqa: PT012
update_account_settings(self.user, update_data)
field_errors = validation_error.value.field_errors
assert 'This field is not editable via this API' == \
@@ -393,7 +393,7 @@ def test_validate_name_change_same_name(self):
update_account_settings(self.user, {'name': account_settings['name']})
# The name should not be added to profile metadata
updated_meta = user_profile.get_meta()
- self.assertEqual(meta, updated_meta)
+ self.assertEqual(meta, updated_meta) # noqa: PT009
@patch('openedx.core.djangoapps.user_api.accounts.api._does_name_change_require_verification',
Mock(return_value=True))
@@ -587,7 +587,7 @@ def test_change_to_disabled_country(self):
assert account_settings['country'] == UserProfile.COUNTRY_WITH_STATES
assert account_settings['state'] == 'MA'
- with self.assertRaises(AccountValidationError):
+ with self.assertRaises(AccountValidationError): # noqa: PT027
update_account_settings(self.user, {"country": "KP"})
def test_get_name_validation_error_too_long(self):
diff --git a/openedx/core/djangoapps/user_api/accounts/tests/test_image_helpers.py b/openedx/core/djangoapps/user_api/accounts/tests/test_image_helpers.py
index a1c244a4115b..96bfc67b799c 100644
--- a/openedx/core/djangoapps/user_api/accounts/tests/test_image_helpers.py
+++ b/openedx/core/djangoapps/user_api/accounts/tests/test_image_helpers.py
@@ -39,7 +39,7 @@ def verify_url(self, actual_url, expected_name, expected_pixels, expected_versio
Verify correct url structure.
"""
assert actual_url == 'http://example-storage.com/profile-images/{name}_{size}.jpg?v={version}'\
- .format(name=expected_name, size=expected_pixels, version=expected_version)
+ .format(name=expected_name, size=expected_pixels, version=expected_version) # noqa: UP032
def verify_default_url(self, actual_url, expected_pixels):
"""
diff --git a/openedx/core/djangoapps/user_api/accounts/tests/test_models.py b/openedx/core/djangoapps/user_api/accounts/tests/test_models.py
index ffd5716b526e..a181ea73db35 100644
--- a/openedx/core/djangoapps/user_api/accounts/tests/test_models.py
+++ b/openedx/core/djangoapps/user_api/accounts/tests/test_models.py
@@ -14,7 +14,7 @@
UserRetirementStatus,
)
-from .retirement_helpers import setup_retirement_states # pylint: disable=unused-import
+from .retirement_helpers import setup_retirement_states # pylint: disable=unused-import # noqa: F401
# Tell pytest it's ok to use the database
pytestmark = pytest.mark.django_db
@@ -40,7 +40,7 @@ def _assert_retirementstatus_is_user(retirement, user):
assert pending.state_name in retirement.responses
-def test_retirement_create_success(setup_retirement_states): # pylint: disable=unused-argument, redefined-outer-name
+def test_retirement_create_success(setup_retirement_states): # pylint: disable=unused-argument, redefined-outer-name # noqa: F811
"""
Basic test to make sure default creation succeeds
"""
@@ -59,7 +59,7 @@ def test_retirement_create_no_default_state():
UserRetirementStatus.create_retirement(user)
-def test_retirement_create_already_retired(setup_retirement_states): # pylint: disable=unused-argument, redefined-outer-name
+def test_retirement_create_already_retired(setup_retirement_states): # pylint: disable=unused-argument, redefined-outer-name # noqa: F811
"""
Confirm the correct error bubbles up if the user already has a retirement row
"""
@@ -80,7 +80,7 @@ def test_retirement_request_create_success():
assert UserRetirementRequest.has_user_requested_retirement(user)
-def test_retirement_request_created_upon_status(setup_retirement_states): # pylint: disable=unused-argument, redefined-outer-name
+def test_retirement_request_created_upon_status(setup_retirement_states): # pylint: disable=unused-argument, redefined-outer-name # noqa: F811
"""
Ensure that retirement request record is created upon retirement status creation.
"""
@@ -89,7 +89,7 @@ def test_retirement_request_created_upon_status(setup_retirement_states): # pyl
assert UserRetirementRequest.has_user_requested_retirement(user)
-def test_retirement_request_deleted_upon_pending_status_delete(setup_retirement_states): # pylint: disable=unused-argument, redefined-outer-name
+def test_retirement_request_deleted_upon_pending_status_delete(setup_retirement_states): # pylint: disable=unused-argument, redefined-outer-name # noqa: F811
"""
Ensure that retirement request record is deleted upon deletion of a PENDING retirement status.
"""
@@ -102,7 +102,7 @@ def test_retirement_request_deleted_upon_pending_status_delete(setup_retirement_
assert not UserRetirementRequest.has_user_requested_retirement(user)
-def test_retirement_request_preserved_upon_non_pending_status_delete(setup_retirement_states): # pylint: disable=unused-argument, redefined-outer-name
+def test_retirement_request_preserved_upon_non_pending_status_delete(setup_retirement_states): # pylint: disable=unused-argument, redefined-outer-name # noqa: F811
"""
Ensure that retirement request record is not deleted upon deletion of a non-PENDING retirement status.
"""
diff --git a/openedx/core/djangoapps/user_api/accounts/tests/test_retirement_views.py b/openedx/core/djangoapps/user_api/accounts/tests/test_retirement_views.py
index 74f85ae2a09a..dfc07b643b9d 100644
--- a/openedx/core/djangoapps/user_api/accounts/tests/test_retirement_views.py
+++ b/openedx/core/djangoapps/user_api/accounts/tests/test_retirement_views.py
@@ -75,7 +75,7 @@
RetirementTestCase,
create_retirement_status,
fake_completed_retirement,
- setup_retirement_states,
+ setup_retirement_states, # noqa: F401
)
@@ -593,7 +593,7 @@ def assert_status_and_user_list(self, expected_users, expected_status=status.HTT
for config in orgs_config:
config[AccountRetirementPartnerReportView.ORGS_CONFIG_FIELD_HEADINGS_KEY].sort()
- self.assertCountEqual(returned_users, expected_users)
+ self.assertCountEqual(returned_users, expected_users) # noqa: PT009
def test_success(self):
"""
@@ -690,7 +690,7 @@ def assert_status_and_user_list(
del retirement['created']
del retirement['modified']
- self.assertCountEqual(response_data, expected_data)
+ self.assertCountEqual(response_data, expected_data) # noqa: PT009
def test_empty(self):
"""
@@ -875,7 +875,7 @@ def assert_status_and_user_list(
except KeyError:
pass
- self.assertCountEqual(response_data, expected_data)
+ self.assertCountEqual(response_data, expected_data) # noqa: PT009
def test_empty(self):
"""
@@ -996,7 +996,7 @@ def assert_status_and_user_data(self, expected_data, expected_status=status.HTTP
del data['created']
del data['modified']
- self.assertDictEqual(response_data, expected_data)
+ self.assertDictEqual(response_data, expected_data) # noqa: PT009
return response_data
def test_no_retirement(self):
diff --git a/openedx/core/djangoapps/user_api/accounts/tests/test_utils.py b/openedx/core/djangoapps/user_api/accounts/tests/test_utils.py
index 10b0ff83e96d..77ac4ab1ba80 100644
--- a/openedx/core/djangoapps/user_api/accounts/tests/test_utils.py
+++ b/openedx/core/djangoapps/user_api/accounts/tests/test_utils.py
@@ -125,7 +125,7 @@ def test_retrieve_last_sitewide_block_completed(self):
)
assert block_url ==\
'test_url:9999/courses/course-v1:{org}+{course}+{run}/jump_to/'\
- 'block-v1:{org}+{course}+{run}+type@vertical+block@{vertical_id}'.format(
+ 'block-v1:{org}+{course}+{run}+type@vertical+block@{vertical_id}'.format( # noqa: UP032
org=self.course.location.course_key.org,
course=self.course.location.course_key.course,
run=self.course.location.course_key.run,
diff --git a/openedx/core/djangoapps/user_api/accounts/tests/test_views.py b/openedx/core/djangoapps/user_api/accounts/tests/test_views.py
index a11f14891ac4..194c2f30a316 100644
--- a/openedx/core/djangoapps/user_api/accounts/tests/test_views.py
+++ b/openedx/core/djangoapps/user_api/accounts/tests/test_views.py
@@ -890,7 +890,7 @@ def test_patch_account_unknown_user(self, api_client, user):
# Note that language_proficiencies is tested below as there are multiple error and success conditions.
)
@ddt.unpack
- def test_patch_account(self, field, value, fails_validation_value=None, developer_validation_message=None):
+ def test_patch_account(self, field, value, fails_validation_value=None, developer_validation_message=None): # noqa: PT028 # pylint: disable=line-too-long
"""
Test the behavior of patch, when using the correct content_type.
"""
@@ -914,7 +914,7 @@ def test_patch_account(self, field, value, fails_validation_value=None, develope
assert expected_user_message == error_response.data['field_errors'][field]['user_message']
- assert "Value '{value}' is not valid for field '{field}': {messages}".format(
+ assert "Value '{value}' is not valid for field '{field}': {messages}".format( # noqa: UP032
value=fails_validation_value,
field=field,
messages=[developer_validation_message]
@@ -946,7 +946,7 @@ def verify_error_response(field_name, data):
Internal helper to check the error messages returned
"""
assert 'This field is not editable via this API' == data['field_errors'][field_name]['developer_message']
- assert "The '{}' field cannot be edited.".format(
+ assert "The '{}' field cannot be edited.".format( # noqa: UP032
field_name
) == data['field_errors'][field_name]['user_message']
@@ -1171,7 +1171,7 @@ def test_patch_language_proficiencies(self):
# than django model id.
for proficiencies in ([{"code": "en"}, {"code": "fr"}, {"code": "es"}], [{"code": "fr"}], [{"code": "aa"}], []):
response = self.send_patch(client, {"language_proficiencies": proficiencies})
- self.assertCountEqual(response.data["language_proficiencies"], proficiencies)
+ self.assertCountEqual(response.data["language_proficiencies"], proficiencies) # noqa: PT009
@ddt.data(
(
@@ -1224,11 +1224,11 @@ def test_profile_image_backend(self):
# so it returns the default storage.
storage = get_profile_image_storage()
storage_class = storage.__class__
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
settings.PROFILE_IMAGE_BACKEND['class'],
f"{storage_class.__module__}.{storage_class.__name__}",
)
- self.assertEqual(storage.base_url, settings.PROFILE_IMAGE_BACKEND['options']['base_url'])
+ self.assertEqual(storage.base_url, settings.PROFILE_IMAGE_BACKEND['options']['base_url']) # noqa: PT009
@override_settings(PROFILE_IMAGE_BACKEND={
'class': 'storages.backends.s3boto3.S3Boto3Storage',
@@ -1240,15 +1240,15 @@ def test_profile_image_backend(self):
})
def test_profile_backend_with_params(self):
storage = get_profile_image_storage()
- self.assertIsInstance(storage, S3Boto3Storage)
- self.assertEqual(storage.bucket_name, "test")
- self.assertEqual(storage.default_acl, 'public')
- self.assertEqual(storage.location, "abc/def")
+ self.assertIsInstance(storage, S3Boto3Storage) # noqa: PT009
+ self.assertEqual(storage.bucket_name, "test") # noqa: PT009
+ self.assertEqual(storage.default_acl, 'public') # noqa: PT009
+ self.assertEqual(storage.location, "abc/def") # noqa: PT009
@override_settings(PROFILE_IMAGE_BACKEND={'class': None, 'options': {}})
def test_profile_backend_without_backend(self):
storage = get_profile_image_storage()
- self.assertIsInstance(storage, FileSystemStorage)
+ self.assertIsInstance(storage, FileSystemStorage) # noqa: PT009
@override_settings(PROFILE_IMAGE_BACKEND=TEST_PROFILE_IMAGE_BACKEND)
def test_convert_relative_profile_url(self):
@@ -1280,10 +1280,10 @@ def test_convert_relative_profile_url(self):
def test_profile_backend_with_profile_image_settings(self):
""" It will use the storages dict with profile_images backend"""
storage = get_profile_image_storage()
- self.assertIsInstance(storage, S3Boto3Storage)
- self.assertEqual(storage.bucket_name, "profiles")
- self.assertEqual(storage.default_acl, 'public')
- self.assertEqual(storage.location, "profile/images")
+ self.assertIsInstance(storage, S3Boto3Storage) # noqa: PT009
+ self.assertEqual(storage.bucket_name, "profiles") # noqa: PT009
+ self.assertEqual(storage.default_acl, 'public') # noqa: PT009
+ self.assertEqual(storage.location, "profile/images") # noqa: PT009
@override_settings(
PROFILE_IMAGE_BACKEND={},
@@ -1292,7 +1292,7 @@ def test_profile_backend_with_default_hardcoded_backend(self):
""" In case of empty storages scenario uses the hardcoded backend."""
del settings.STORAGES
storage = get_profile_image_storage()
- self.assertIsInstance(storage, FileSystemStorage)
+ self.assertIsInstance(storage, FileSystemStorage) # noqa: PT009
@ddt.data(
("client", "user", True),
@@ -1403,14 +1403,14 @@ def test_create_request_succeeds(self):
"""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
response = self._send_create(self.client, {'name': 'New Name'})
- self.assertEqual(response.status_code, 201)
+ self.assertEqual(response.status_code, 201) # noqa: PT009
def test_create_unauthenticated(self):
"""
Test that a name change request fails for an unauthenticated user.
"""
response = self._send_create(self.client, {'name': 'New Name'})
- self.assertEqual(response.status_code, 401)
+ self.assertEqual(response.status_code, 401) # noqa: PT009
def test_create_empty_request(self):
"""
@@ -1418,7 +1418,7 @@ def test_create_empty_request(self):
"""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
response = self._send_create(self.client, {})
- self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.status_code, 400) # noqa: PT009
def test_create_blank_name(self):
"""
@@ -1426,7 +1426,7 @@ def test_create_blank_name(self):
"""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
response = self._send_create(self.client, {'name': ''})
- self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.status_code, 400) # noqa: PT009
@ddt.data('invalid name', 'https://invalid.com')
def test_create_fails_validation(self, invalid_name):
@@ -1435,7 +1435,7 @@ def test_create_fails_validation(self, invalid_name):
"""
self.client.login(username=self.user.username, password=TEST_PASSWORD)
response = self._send_create(self.client, {'name': invalid_name})
- self.assertEqual(response.status_code, 400)
+ self.assertEqual(response.status_code, 400) # noqa: PT009
def test_confirm_succeeds(self):
"""
@@ -1444,8 +1444,8 @@ def test_confirm_succeeds(self):
self.staff_client.login(username=self.staff_user.username, password=TEST_PASSWORD)
do_name_change_request(self.user, 'New Name', 'test')
response = self._send_confirm(self.staff_client, self.user.username)
- self.assertEqual(response.status_code, 204)
- self.assertIsNone(get_pending_name_change(self.user))
+ self.assertEqual(response.status_code, 204) # noqa: PT009
+ self.assertIsNone(get_pending_name_change(self.user)) # noqa: PT009
def test_confirm_non_staff(self):
"""
@@ -1454,8 +1454,8 @@ def test_confirm_non_staff(self):
self.client.login(username=self.user.username, password=TEST_PASSWORD)
do_name_change_request(self.user, 'New Name', 'test')
response = self._send_confirm(self.client, self.user.username)
- self.assertEqual(response.status_code, 403)
- self.assertEqual(get_pending_name_change(self.user).new_name, 'New Name')
+ self.assertEqual(response.status_code, 403) # noqa: PT009
+ self.assertEqual(get_pending_name_change(self.user).new_name, 'New Name') # noqa: PT009
def test_confirm_no_pending_name_change(self):
"""
@@ -1463,7 +1463,7 @@ def test_confirm_no_pending_name_change(self):
"""
self.staff_client.login(username=self.staff_user.username, password=TEST_PASSWORD)
response = self._send_confirm(self.staff_client, self.user.username)
- self.assertEqual(response.status_code, 404)
+ self.assertEqual(response.status_code, 404) # noqa: PT009
@ddt.ddt
diff --git a/openedx/core/djangoapps/user_api/accounts/utils.py b/openedx/core/djangoapps/user_api/accounts/utils.py
index 826dbd42cd13..ab70b8f15c8d 100644
--- a/openedx/core/djangoapps/user_api/accounts/utils.py
+++ b/openedx/core/djangoapps/user_api/accounts/utils.py
@@ -179,7 +179,7 @@ def retrieve_last_sitewide_block_completed(user):
if not (lms_root and item):
return
- return "{lms_root}/courses/{course_key}/jump_to/{location}".format(
+ return "{lms_root}/courses/{course_key}/jump_to/{location}".format( # noqa: UP032
lms_root=lms_root,
course_key=str(item.location.course_key),
location=str(item.location),
diff --git a/openedx/core/djangoapps/user_api/accounts/views.py b/openedx/core/djangoapps/user_api/accounts/views.py
index 37d467a6493b..90d7ba70cb86 100644
--- a/openedx/core/djangoapps/user_api/accounts/views.py
+++ b/openedx/core/djangoapps/user_api/accounts/views.py
@@ -48,7 +48,7 @@
get_retired_email_by_email,
get_retired_username_by_username,
is_email_retired,
- is_username_retired,
+ is_username_retired, # noqa: F401
)
from common.djangoapps.student.models_api import confirm_name_change, do_name_change_request, get_pending_name_change
from common.djangoapps.track import segment
diff --git a/openedx/core/djangoapps/user_api/admin.py b/openedx/core/djangoapps/user_api/admin.py
index 91d2e6f871cd..976fa0d79ab5 100644
--- a/openedx/core/djangoapps/user_api/admin.py
+++ b/openedx/core/djangoapps/user_api/admin.py
@@ -194,8 +194,8 @@ def reset_state_false(self, request, queryset):
if rows_updated == 1:
message_bit = "one user was"
else:
- message_bit = "%s users were" % rows_updated
- self.message_user(request, "%s successfully reset to False." % message_bit)
+ message_bit = "%s users were" % rows_updated # noqa: UP031
+ self.message_user(request, "%s successfully reset to False." % message_bit) # noqa: UP031
reset_state_false.short_description = "Reset is_being_processed to False"
@@ -207,8 +207,8 @@ def reset_state_true(self, request, queryset):
if rows_updated == 1:
message_bit = "one user was"
else:
- message_bit = "%s users were" % rows_updated
- self.message_user(request, "%s successfully reset to True." % message_bit)
+ message_bit = "%s users were" % rows_updated # noqa: UP031
+ self.message_user(request, "%s successfully reset to True." % message_bit) # noqa: UP031
reset_state_true.short_description = "Reset is_being_processed to True"
diff --git a/openedx/core/djangoapps/user_api/helpers.py b/openedx/core/djangoapps/user_api/helpers.py
index 6c4aabe6f42a..e71880057417 100644
--- a/openedx/core/djangoapps/user_api/helpers.py
+++ b/openedx/core/djangoapps/user_api/helpers.py
@@ -83,7 +83,7 @@ def _wrapped(*args, **kwargs):
caller=caller.strip(),
)
LOGGER.exception(msg)
- raise api_error(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise api_error(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return _wrapped
return _decorator
diff --git a/openedx/core/djangoapps/user_api/management/commands/bulk_user_org_email_optout.py b/openedx/core/djangoapps/user_api/management/commands/bulk_user_org_email_optout.py
index d194e58ee880..b383bd27de82 100644
--- a/openedx/core/djangoapps/user_api/management/commands/bulk_user_org_email_optout.py
+++ b/openedx/core/djangoapps/user_api/management/commands/bulk_user_org_email_optout.py
@@ -115,7 +115,7 @@ def handle(self, *args, **options):
query = 'INSERT INTO user_api_userorgtag (`user_id`, `org`, `key`, `value`, `created`, `modified`) VALUES '
query_values = []
for idx in range(start_idx, end_idx + 1):
- query_values.append('({},"{}","email-optin","False",NOW(),NOW())'.format(
+ query_values.append('({},"{}","email-optin","False",NOW(),NOW())'.format( # noqa: UP032
optout_rows[idx][0], optout_rows[idx][1])
)
query += ','.join(query_values)
diff --git a/openedx/core/djangoapps/user_api/management/commands/cancel_user_retirement_request.py b/openedx/core/djangoapps/user_api/management/commands/cancel_user_retirement_request.py
index adb29a4fd3a8..c9ac6ac4bf2c 100644
--- a/openedx/core/djangoapps/user_api/management/commands/cancel_user_retirement_request.py
+++ b/openedx/core/djangoapps/user_api/management/commands/cancel_user_retirement_request.py
@@ -37,12 +37,12 @@ def handle(self, *args, **options):
original_email=email_address
)
except UserRetirementStatus.DoesNotExist:
- raise CommandError(f"No retirement request with email address '{email_address}' exists.") # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(f"No retirement request with email address '{email_address}' exists.") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
# Check if the user has started the retirement process -or- not.
if retirement_status.current_state.state_name != 'PENDING':
raise CommandError(
- "Retirement requests can only be cancelled for users in the PENDING state."
+ "Retirement requests can only be cancelled for users in the PENDING state." # noqa: UP032
" Current request state for '{}': {}".format(
email_address,
retirement_status.current_state.state_name
diff --git a/openedx/core/djangoapps/user_api/management/commands/email_opt_in_list.py b/openedx/core/djangoapps/user_api/management/commands/email_opt_in_list.py
index 8b98193b6c54..045ac19a13fa 100644
--- a/openedx/core/djangoapps/user_api/management/commands/email_opt_in_list.py
+++ b/openedx/core/djangoapps/user_api/management/commands/email_opt_in_list.py
@@ -241,7 +241,7 @@ def _write_email_opt_in_prefs(self, file_handle, org_aliases, courses):
user_id, username, email, full_name, course_id, is_opted_in, pref_set_datetime = row
if pref_set_datetime:
- pref_set_datetime = timezone.make_aware(pref_set_datetime, dt_timezone.utc)
+ pref_set_datetime = timezone.make_aware(pref_set_datetime, dt_timezone.utc) # noqa: UP017
else:
pref_set_datetime = self.DEFAULT_DATETIME_STR
diff --git a/openedx/core/djangoapps/user_api/management/commands/migrate_user_profile_langs.py b/openedx/core/djangoapps/user_api/management/commands/migrate_user_profile_langs.py
index da3251794a9a..c73b777ddc91 100644
--- a/openedx/core/djangoapps/user_api/management/commands/migrate_user_profile_langs.py
+++ b/openedx/core/djangoapps/user_api/management/commands/migrate_user_profile_langs.py
@@ -62,12 +62,12 @@ def handle(self, *args, **options):
langs += dark_lang_config.beta_languages_list if dark_lang_config.enable_beta_languages else []
if new_lang_code not in langs:
- raise CommandError('{} is not a configured language code in settings.LANGUAGES '
+ raise CommandError('{} is not a configured language code in settings.LANGUAGES ' # noqa: UP032
'or the current DarkLangConfig.'.format(new_lang_code))
max_id = UserPreference.objects.all().aggregate(Max('id'))['id__max']
- print('Updating user language preferences from {} to {}. '
+ print('Updating user language preferences from {} to {}. ' # noqa: UP032
'Start id is {}, current max id is {}. '
'Chunk size is of {}'.format(old_lang_code, new_lang_code, start, max_id, chunk_size))
@@ -98,7 +98,7 @@ def handle(self, *args, **options):
end += chunk_size
sleep(sleep_time_secs)
- print('Finished! Updated {} total preferences from {} to {}'.format(
+ print('Finished! Updated {} total preferences from {} to {}'.format( # noqa: UP032
updated_count,
old_lang_code,
new_lang_code
diff --git a/openedx/core/djangoapps/user_api/management/commands/populate_enterprise_learner_current_job.py b/openedx/core/djangoapps/user_api/management/commands/populate_enterprise_learner_current_job.py
index a1323cb32d5f..c7dad94fc03b 100644
--- a/openedx/core/djangoapps/user_api/management/commands/populate_enterprise_learner_current_job.py
+++ b/openedx/core/djangoapps/user_api/management/commands/populate_enterprise_learner_current_job.py
@@ -67,7 +67,7 @@ def _get_user_profile(self, username):
try:
existing_user = User.objects.get(username=username)
except ObjectDoesNotExist:
- raise errors.UserNotFound() # lint-amnesty, pylint: disable=raise-missing-from
+ raise errors.UserNotFound() # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
existing_user_profile, _ = UserProfile.objects.get_or_create(user=existing_user)
return existing_user_profile
diff --git a/openedx/core/djangoapps/user_api/management/commands/populate_retirement_states.py b/openedx/core/djangoapps/user_api/management/commands/populate_retirement_states.py
index 5ab54a781b96..faa55d46982a 100644
--- a/openedx/core/djangoapps/user_api/management/commands/populate_retirement_states.py
+++ b/openedx/core/djangoapps/user_api/management/commands/populate_retirement_states.py
@@ -50,7 +50,7 @@ def _validate_new_states(self, new_states):
raise CommandError('settings.RETIREMENT_STATES does not exist or is empty.')
if not set(REQUIRED_STATES).issubset(set(new_states)):
- raise CommandError('settings.RETIREMENT_STATES ({}) does not contain all required states '
+ raise CommandError('settings.RETIREMENT_STATES ({}) does not contain all required states ' # noqa: UP032
'({})'.format(new_states, REQ_STR))
# Confirm that the start and end states are in the right places
@@ -60,7 +60,7 @@ def _validate_new_states(self, new_states):
num_end_states = len(END_STATES)
if new_states[-num_end_states:] != END_STATES:
- raise CommandError('The last {} states must be these (in this order): '
+ raise CommandError('The last {} states must be these (in this order): ' # noqa: UP032
'{}'.format(num_end_states, END_STATES))
def _check_current_users(self):
@@ -69,13 +69,13 @@ def _check_current_users(self):
"""
if UserRetirementStatus.objects.exclude(current_state__state_name__in=REQUIRED_STATES).exists():
raise CommandError(
- 'Users are currently being processed. All users must be in one of these states to run this command: '
+ 'Users are currently being processed. All users must be in one of these states to run this command: ' # noqa: UP032 # pylint: disable=line-too-long
'{}'.format(REQ_STR)
)
def _check_users_in_states_to_delete(self, states_to_delete):
if UserRetirementStatus.objects.filter(current_state__state_name__in=states_to_delete).exists():
- raise CommandError('Users exist in a state that is marked for deletion! States to delete'
+ raise CommandError('Users exist in a state that is marked for deletion! States to delete' # noqa: UP032
'are: {}'.format(states_to_delete))
def _delete_old_states_and_create_new(self, new_states, dry_run=False):
diff --git a/openedx/core/djangoapps/user_api/management/commands/retire_user.py b/openedx/core/djangoapps/user_api/management/commands/retire_user.py
index e2db5c48b33b..1b3b497ea5c7 100644
--- a/openedx/core/djangoapps/user_api/management/commands/retire_user.py
+++ b/openedx/core/djangoapps/user_api/management/commands/retire_user.py
@@ -59,13 +59,13 @@ def append_users_lists(self, file_handler, user_model):
try:
if isinstance(file_handler, str):
- userinfo = open(file_handler, 'r')
+ userinfo = open(file_handler, 'r') # noqa: UP015
else:
userinfo = file_handler.open('r')
except Exception as exc:
error_message = f'Error while reading file: {exc}'
logger.error(error_message)
- raise CommandError(error_message) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(error_message) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
for record in userinfo:
if isinstance(record, bytes):
@@ -161,13 +161,13 @@ def handle(self, *args, **options):
except KeyError:
error_message = f'Username not specified {user}'
logger.error(error_message)
- raise CommandError(error_message) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(error_message) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except user_model.DoesNotExist:
error_message = f'The user "{user.username}" does not exist.'
logger.error(error_message)
- raise CommandError(error_message) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(error_message) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
except Exception as exc: # pylint: disable=broad-except
error_message = f'500 error deactivating account: {exc}'
logger.error(error_message)
- raise CommandError(error_message) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(error_message) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
logger.info("User successfully moved to the retirement pipeline")
diff --git a/openedx/core/djangoapps/user_api/management/commands/sync_hubspot_contacts.py b/openedx/core/djangoapps/user_api/management/commands/sync_hubspot_contacts.py
index ef1f386317a5..2ae247cf7d7a 100644
--- a/openedx/core/djangoapps/user_api/management/commands/sync_hubspot_contacts.py
+++ b/openedx/core/djangoapps/user_api/management/commands/sync_hubspot_contacts.py
@@ -68,7 +68,7 @@ def _get_batched_users(self, site_domain, users_queryset, offset, users_query_ba
"""
self.stdout.write(
- 'Fetching Users for site {site} from {start} to {end}'.format(
+ 'Fetching Users for site {site} from {start} to {end}'.format( # noqa: UP032
site=site_domain, start=offset, end=offset + users_query_batch_size
)
)
@@ -145,7 +145,7 @@ def _sync_with_hubspot(self, users_batch, site_conf):
response.raise_for_status()
return len(contacts)
except HTTPError as ex:
- message = 'An error occurred while syncing batch of contacts for site {domain}, {message}'.format(
+ message = 'An error occurred while syncing batch of contacts for site {domain}, {message}'.format( # noqa: UP032 # pylint: disable=line-too-long
domain=site_conf.site.domain, message=str(ex)
)
self.stderr.write(message)
@@ -166,7 +166,7 @@ def _sync_site(self, site_conf, users_queryset, users_count, contacts_batch_size
while offset < users_count:
is_last_iteration = (offset + users_query_batch_size) >= users_count
self.stdout.write(
- 'Syncing users batch from {start} to {end} for site {site}'.format(
+ 'Syncing users batch from {start} to {end} for site {site}'.format( # noqa: UP032
start=offset, end=offset + users_query_batch_size, site=site_domain
)
)
@@ -178,14 +178,14 @@ def _sync_site(self, site_conf, users_queryset, users_count, contacts_batch_size
successfully_synced_contacts += self._sync_with_hubspot(users_batch, site_conf)
time.sleep(0.1) # to make sure request per second could not exceed by 10
self.stdout.write(
- 'Successfully synced users batch from {start} to {end} for site {site}'.format(
+ 'Successfully synced users batch from {start} to {end} for site {site}'.format( # noqa: UP032
start=offset, end=offset + users_query_batch_size, site=site_domain
)
)
offset += users_query_batch_size
self.stdout.write(
- '{count} contacts found and sycned for site {site}'.format(
+ '{count} contacts found and sycned for site {site}'.format( # noqa: UP032
count=successfully_synced_contacts, site=site_domain
)
)
@@ -227,4 +227,4 @@ def handle(self, *args, **options):
except Exception as ex:
traceback.print_exc()
- raise CommandError('Command failed with traceback %s' % str(ex)) # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError('Command failed with traceback %s' % str(ex)) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904, UP031
diff --git a/openedx/core/djangoapps/user_api/management/tests/test_bulk_user_org_email_optout.py b/openedx/core/djangoapps/user_api/management/tests/test_bulk_user_org_email_optout.py
index 342afc69c425..35bfb6caea15 100644
--- a/openedx/core/djangoapps/user_api/management/tests/test_bulk_user_org_email_optout.py
+++ b/openedx/core/djangoapps/user_api/management/tests/test_bulk_user_org_email_optout.py
@@ -3,7 +3,7 @@
"""
-import io # lint-amnesty, pylint: disable=unused-import
+import io # lint-amnesty, pylint: disable=unused-import # noqa: F401
import os
import tempfile
from contextlib import contextmanager
diff --git a/openedx/core/djangoapps/user_api/management/tests/test_cancel_retirement.py b/openedx/core/djangoapps/user_api/management/tests/test_cancel_retirement.py
index 7a441888d966..46f3d0ffdc39 100644
--- a/openedx/core/djangoapps/user_api/management/tests/test_cancel_retirement.py
+++ b/openedx/core/djangoapps/user_api/management/tests/test_cancel_retirement.py
@@ -10,15 +10,15 @@
from common.djangoapps.student.tests.factories import UserFactory
from openedx.core.djangoapps.user_api.accounts.tests.retirement_helpers import ( # pylint: disable=unused-import
- logged_out_retirement_request,
- setup_retirement_states,
+ logged_out_retirement_request, # noqa: F401
+ setup_retirement_states, # noqa: F401
)
from openedx.core.djangoapps.user_api.models import RetirementState, UserRetirementRequest, UserRetirementStatus
pytestmark = pytest.mark.django_db
-def test_successful_cancellation(setup_retirement_states, logged_out_retirement_request, capsys): # pylint: disable=redefined-outer-name, unused-argument
+def test_successful_cancellation(setup_retirement_states, logged_out_retirement_request, capsys): # pylint: disable=redefined-outer-name, unused-argument # noqa: F811
"""
Test a successfully cancelled retirement request.
"""
@@ -38,7 +38,7 @@ def test_successful_cancellation(setup_retirement_states, logged_out_retirement_
assert logged_out_retirement_request.original_email in output
-def test_cancellation_in_unrecoverable_state(setup_retirement_states, logged_out_retirement_request): # pylint: disable=redefined-outer-name, unused-argument
+def test_cancellation_in_unrecoverable_state(setup_retirement_states, logged_out_retirement_request): # pylint: disable=redefined-outer-name, unused-argument # noqa: F811
"""
Test a failed cancellation of a retirement request due to the retirement already beginning.
"""
@@ -49,7 +49,7 @@ def test_cancellation_in_unrecoverable_state(setup_retirement_states, logged_out
call_command('cancel_user_retirement_request', logged_out_retirement_request.original_email)
-def test_cancellation_unknown_email_address(setup_retirement_states, logged_out_retirement_request): # pylint: disable=redefined-outer-name, unused-argument
+def test_cancellation_unknown_email_address(setup_retirement_states, logged_out_retirement_request): # pylint: disable=redefined-outer-name, unused-argument # noqa: F811
"""
Test attempting to cancel a non-existent request of a user.
"""
diff --git a/openedx/core/djangoapps/user_api/management/tests/test_email_opt_in_list.py b/openedx/core/djangoapps/user_api/management/tests/test_email_opt_in_list.py
index 93842a6e919c..21b4cb9b0842 100644
--- a/openedx/core/djangoapps/user_api/management/tests/test_email_opt_in_list.py
+++ b/openedx/core/djangoapps/user_api/management/tests/test_email_opt_in_list.py
@@ -187,7 +187,7 @@ def test_no_courses_for_org_name(self):
self._set_opt_in_pref(self.user, self.TEST_ORG, True)
# No course available for this particular org
- with self.assertRaisesRegex(CommandError, "^No courses found for orgs:"):
+ with self.assertRaisesRegex(CommandError, "^No courses found for orgs:"): # noqa: PT027
self._run_command("other_org")
def test_specify_subset_of_courses(self):
@@ -272,7 +272,7 @@ def test_not_enough_args(self, num_args):
expected_msg_regex = (
"^Error: the following arguments are required: OUTPUT_FILENAME, ORG_ALIASES$"
)
- with self.assertRaisesRegex(CommandError, expected_msg_regex):
+ with self.assertRaisesRegex(CommandError, expected_msg_regex): # noqa: PT027
call_command('email_opt_in_list', *args)
def test_file_already_exists(self):
@@ -281,7 +281,7 @@ def test_file_already_exists(self):
def _cleanup():
temp_file.close()
- with self.assertRaisesRegex(CommandError, "^File already exists"):
+ with self.assertRaisesRegex(CommandError, "^File already exists"): # noqa: PT027
call_command('email_opt_in_list', temp_file.name, self.TEST_ORG)
def test_no_user_profile(self):
diff --git a/openedx/core/djangoapps/user_api/management/tests/test_retire_user.py b/openedx/core/djangoapps/user_api/management/tests/test_retire_user.py
index 0cec6fff7302..6de2287fc4ba 100644
--- a/openedx/core/djangoapps/user_api/management/tests/test_retire_user.py
+++ b/openedx/core/djangoapps/user_api/management/tests/test_retire_user.py
@@ -12,7 +12,7 @@
from common.djangoapps.student.tests.factories import UserFactory # lint-amnesty, pylint: disable=wrong-import-order
from openedx.core.djangoapps.user_api.accounts.tests.retirement_helpers import ( # lint-amnesty, pylint: disable=unused-import, wrong-import-order
- setup_retirement_states,
+ setup_retirement_states, # noqa: F401
)
from openedx.core.djangolib.testing.utils import skip_unless_lms # lint-amnesty, pylint: disable=wrong-import-order
@@ -32,7 +32,7 @@ def generate_dummy_users():
user = UserFactory.create(username=f"user{i}", email=f"user{i}@example.com")
users.append(user.username)
emails.append(user.email)
- users_list = [{'username': user, 'email': email} for user, email in zip(users, emails)]
+ users_list = [{'username': user, 'email': email} for user, email in zip(users, emails)] # noqa: B905
return users_list
@@ -61,7 +61,7 @@ def remove_user_file():
@skip_unless_lms
-def test_successful_retire_with_userfile(setup_retirement_states): # lint-amnesty, pylint: disable=redefined-outer-name, unused-argument
+def test_successful_retire_with_userfile(setup_retirement_states): # lint-amnesty, pylint: disable=redefined-outer-name, unused-argument # noqa: F811
user = UserFactory.create(username='user0', email="user0@example.com")
username = user.username
user_email = user.email
@@ -77,7 +77,7 @@ def test_successful_retire_with_userfile(setup_retirement_states): # lint-amnes
@skip_unless_lms
-def test_retire_user_with_usename_email_mismatch(setup_retirement_states): # lint-amnesty, pylint: disable=redefined-outer-name, unused-argument
+def test_retire_user_with_usename_email_mismatch(setup_retirement_states): # lint-amnesty, pylint: disable=redefined-outer-name, unused-argument # noqa: F811
create_user_file(True)
with pytest.raises(CommandError, match=r'Could not find users with specified username and email '):
call_command('retire_user', user_file=user_file)
@@ -85,7 +85,7 @@ def test_retire_user_with_usename_email_mismatch(setup_retirement_states): # li
@skip_unless_lms
-def test_successful_retire_with_username_email(setup_retirement_states): # lint-amnesty, pylint: disable=redefined-outer-name, unused-argument
+def test_successful_retire_with_username_email(setup_retirement_states): # lint-amnesty, pylint: disable=redefined-outer-name, unused-argument # noqa: F811
user = UserFactory.create(username='user0', email="user0@example.com")
username = user.username
user_email = user.email
@@ -99,7 +99,7 @@ def test_successful_retire_with_username_email(setup_retirement_states): # lint
@skip_unless_lms
-def test_retire_with_username_email_userfile(setup_retirement_states): # lint-amnesty, pylint: disable=redefined-outer-name, unused-argument
+def test_retire_with_username_email_userfile(setup_retirement_states): # lint-amnesty, pylint: disable=redefined-outer-name, unused-argument # noqa: F811
user = UserFactory.create(username='user0', email="user0@example.com")
username = user.username
user_email = user.email
diff --git a/openedx/core/djangoapps/user_api/models.py b/openedx/core/djangoapps/user_api/models.py
index 3aec9f060d37..2982e1ff764f 100644
--- a/openedx/core/djangoapps/user_api/models.py
+++ b/openedx/core/djangoapps/user_api/models.py
@@ -32,7 +32,7 @@ class RetirementStateError(Exception):
pass
-class UserPreference(models.Model):
+class UserPreference(models.Model): # noqa: DJ008
"""
A user's preference, stored as generic text to be processed by client
@@ -146,7 +146,7 @@ def post_delete_callback(sender, **kwargs):
)
-class UserCourseTag(models.Model):
+class UserCourseTag(models.Model): # noqa: DJ008
"""
Per-course user tags, to be used by various things that want to store tags about
the user. Added initially to store assignment to experimental groups.
@@ -196,7 +196,7 @@ class RetirementState(models.Model):
def __str__(self):
return f'{self.state_name} (step {self.state_execution_order})'
- class Meta:
+ class Meta: # noqa: DJ012
ordering = ('state_execution_order',)
@classmethod
@@ -239,7 +239,7 @@ class Meta:
verbose_name_plural = 'User Retirement Reporting Statuses'
def __str__(self):
- return 'UserRetirementPartnerReportingStatus: {} is being processed: {}'.format(
+ return 'UserRetirementPartnerReportingStatus: {} is being processed: {}'.format( # noqa: UP032
self.user,
self.is_being_processed
)
@@ -316,7 +316,7 @@ def _validate_state_update(self, new_state):
raise ValueError()
except ValueError:
err = f'{new_state} does not exist or is an eariler state than current state {self.current_state}'
- raise RetirementStateError(err) # lint-amnesty, pylint: disable=raise-missing-from
+ raise RetirementStateError(err) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def _validate_update_data(self, data):
"""
@@ -343,7 +343,7 @@ def create_retirement(cls, user):
try:
pending = RetirementState.objects.all().order_by('state_execution_order')[0]
except IndexError:
- raise RetirementStateError('Default state does not exist! Populate retirement states to retire users.') # lint-amnesty, pylint: disable=raise-missing-from
+ raise RetirementStateError('Default state does not exist! Populate retirement states to retire users.') # lint-amnesty, pylint: disable=raise-missing-from,line-too-long # noqa: B904
if cls.objects.filter(user=user).exists():
raise RetirementStateError(f'User {user} already has a retirement status row!')
@@ -407,13 +407,13 @@ def get_retirement_for_retirement_action(cls, username):
break
if retirement is None:
- raise UserRetirementStatus.DoesNotExist('{} does not have an exact match in UserRetirementStatus. '
+ raise UserRetirementStatus.DoesNotExist('{} does not have an exact match in UserRetirementStatus. ' # noqa: UP032 # pylint: disable=line-too-long
'{} similar rows found.'.format(username, len(retirements)))
state = retirement.current_state
if state.required or state.state_name.endswith('_COMPLETE'):
- raise RetirementStateError('{} is in {}, not a valid state to perform retirement '
+ raise RetirementStateError('{} is in {}, not a valid state to perform retirement ' # noqa: UP032
'actions on.'.format(retirement, state.state_name))
return retirement
diff --git a/openedx/core/djangoapps/user_api/preferences/api.py b/openedx/core/djangoapps/user_api/preferences/api.py
index c70b40c9ba77..76acf999ccf6 100644
--- a/openedx/core/djangoapps/user_api/preferences/api.py
+++ b/openedx/core/djangoapps/user_api/preferences/api.py
@@ -18,7 +18,7 @@
from openedx.core.lib.time_zone_utils import get_display_time_zone
from ..errors import ( # lint-amnesty, pylint: disable=unused-import
- CountryCodeError,
+ CountryCodeError, # noqa: F401
PreferenceUpdateError,
PreferenceValidationError,
UserAPIInternalError,
@@ -168,7 +168,7 @@ def update_user_preferences(requesting_user, update, user=None):
if serializer_is_dirty(serializer):
serializer.save()
except Exception as error:
- raise _create_preference_update_error(preference_key, preference_value, error) # lint-amnesty, pylint: disable=raise-missing-from
+ raise _create_preference_update_error(preference_key, preference_value, error) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
else:
delete_user_preference(requesting_user, preference_key)
@@ -208,7 +208,7 @@ def set_user_preference(requesting_user, preference_key, preference_value, usern
try:
serializer.save()
except Exception as error:
- raise _create_preference_update_error(preference_key, preference_value, error) # lint-amnesty, pylint: disable=raise-missing-from
+ raise _create_preference_update_error(preference_key, preference_value, error) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
@intercept_errors(UserAPIInternalError, ignore_errors=[UserAPIRequestError])
@@ -246,8 +246,8 @@ def delete_user_preference(requesting_user, preference_key, username=None):
try:
user_preference.delete()
except Exception as error:
- raise PreferenceUpdateError( # lint-amnesty, pylint: disable=raise-missing-from
- developer_message="Delete failed for user preference '{preference_key}': {error}".format(
+ raise PreferenceUpdateError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
+ developer_message="Delete failed for user preference '{preference_key}': {error}".format( # noqa: UP032
preference_key=preference_key, error=error
),
user_message=_("Delete failed for user preference '{preference_key}'.").format(
@@ -284,7 +284,7 @@ def update_email_opt_in(user, org, opt_in):
try:
user_profile = UserProfile.objects.get(user=user)
except ObjectDoesNotExist:
- raise UserNotFound() # lint-amnesty, pylint: disable=raise-missing-from
+ raise UserNotFound() # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if user_profile.requires_parental_consent(
age_limit=getattr(settings, 'EMAIL_OPTIN_MINIMUM_AGE', 13),
default_requires_consent=False,
@@ -344,7 +344,7 @@ def _get_authorized_user(requesting_user, username=None, allow_staff=False):
try:
existing_user = User.objects.get(username=username)
except ObjectDoesNotExist:
- raise UserNotFound() # lint-amnesty, pylint: disable=raise-missing-from
+ raise UserNotFound() # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return existing_user
@@ -412,7 +412,7 @@ def validate_user_preference_serializer(serializer, preference_key, preference_v
# messages into the strings only.
for key in errors:
errors[key] = [str(el) for el in errors[key]]
- developer_message = "Value '{preference_value}' not valid for preference '{preference_key}': {error}".format(
+ developer_message = "Value '{preference_value}' not valid for preference '{preference_key}': {error}".format( # noqa: UP032 # pylint: disable=line-too-long
preference_key=preference_key, preference_value=preference_value, error=errors
)
if "key" in serializer.errors:
@@ -445,7 +445,7 @@ def validate_user_preference_serializer(serializer, preference_key, preference_v
def _create_preference_update_error(preference_key, preference_value, error):
""" Creates a PreferenceUpdateError with developer_message and user_message. """
return PreferenceUpdateError(
- developer_message="Save failed for user preference '{key}' with value '{value}': {error}".format(
+ developer_message="Save failed for user preference '{key}' with value '{value}': {error}".format( # noqa: UP032
key=preference_key, value=preference_value, error=error
),
user_message=_("Save failed for user preference '{key}' with value '{value}'.").format(
diff --git a/openedx/core/djangoapps/user_api/preferences/tests/test_api.py b/openedx/core/djangoapps/user_api/preferences/tests/test_api.py
index 80c56824a2ba..dbc5b61539b4 100644
--- a/openedx/core/djangoapps/user_api/preferences/tests/test_api.py
+++ b/openedx/core/djangoapps/user_api/preferences/tests/test_api.py
@@ -24,7 +24,7 @@
from xmodule.modulestore.tests.factories import CourseFactory # lint-amnesty, pylint: disable=wrong-import-order
from ...errors import ( # lint-amnesty, pylint: disable=unused-import
- CountryCodeError,
+ CountryCodeError, # noqa: F401
PreferenceUpdateError,
PreferenceValidationError,
UserNotAuthorized,
diff --git a/openedx/core/djangoapps/user_api/tests/test_helpers.py b/openedx/core/djangoapps/user_api/tests/test_helpers.py
index 274e1a265bba..4904cc034158 100644
--- a/openedx/core/djangoapps/user_api/tests/test_helpers.py
+++ b/openedx/core/djangoapps/user_api/tests/test_helpers.py
@@ -47,7 +47,7 @@ def test_ignores_no_error(self):
intercepted_function()
def test_ignores_expected_errors(self):
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError): # noqa: PT011
intercepted_function(raise_error=ValueError)
@mock.patch('openedx.core.djangoapps.user_api.helpers.LOGGER')
diff --git a/openedx/core/djangoapps/user_api/tests/test_partition_schemes.py b/openedx/core/djangoapps/user_api/tests/test_partition_schemes.py
index 979a8e4d10a7..e1cf70b3b947 100644
--- a/openedx/core/djangoapps/user_api/tests/test_partition_schemes.py
+++ b/openedx/core/djangoapps/user_api/tests/test_partition_schemes.py
@@ -99,7 +99,7 @@ def test_empty_partition(self):
scheme=RandomUserPartitionScheme
)
# get a group assigned to the user
- with self.assertRaisesRegex(UserPartitionError, "Cannot assign user to an empty user partition"):
+ with self.assertRaisesRegex(UserPartitionError, "Cannot assign user to an empty user partition"): # noqa: PT027
RandomUserPartitionScheme.get_group_for_user(self.MOCK_COURSE_ID, self.user, empty_partition)
def test_user_in_deleted_group(self):
@@ -148,5 +148,5 @@ class TestExtension(TestCase):
def test_get_scheme(self):
assert UserPartition.get_scheme('random') == RandomUserPartitionScheme
- with self.assertRaisesRegex(UserPartitionError, 'Unrecognized scheme'):
+ with self.assertRaisesRegex(UserPartitionError, 'Unrecognized scheme'): # noqa: PT027
UserPartition.get_scheme('other')
diff --git a/openedx/core/djangoapps/user_api/tests/test_views.py b/openedx/core/djangoapps/user_api/tests/test_views.py
index a6eec77d8bf3..48507d54e986 100644
--- a/openedx/core/djangoapps/user_api/tests/test_views.py
+++ b/openedx/core/djangoapps/user_api/tests/test_views.py
@@ -18,9 +18,9 @@
from xmodule.modulestore.tests.factories import CourseFactory # lint-amnesty, pylint: disable=wrong-import-order
from ..accounts.tests.retirement_helpers import ( # pylint: disable=unused-import
- RetirementTestCase,
- fake_requested_retirement,
- setup_retirement_states,
+ RetirementTestCase, # noqa: F401
+ fake_requested_retirement, # noqa: F401
+ setup_retirement_states, # noqa: F401
)
from ..models import UserOrgTag
from ..tests.factories import UserPreferenceFactory
@@ -55,8 +55,8 @@ def get_uri_for_pref(self, target_pref):
def assertUserIsValid(self, user):
"""Assert that the given user result is valid"""
- self.assertCountEqual(list(user.keys()), ["email", "id", "name", "username", "preferences", "url"])
- self.assertCountEqual(
+ self.assertCountEqual(list(user.keys()), ["email", "id", "name", "username", "preferences", "url"]) # noqa: PT009 # pylint: disable=line-too-long
+ self.assertCountEqual( # noqa: PT009
list(user["preferences"].items()),
[(pref.key, pref.value) for pref in self.prefs if pref.user.id == user["id"]] # lint-amnesty, pylint: disable=no-member
)
@@ -66,7 +66,7 @@ def assertPrefIsValid(self, pref):
"""
Assert that the given preference is acknowledged by the system
"""
- self.assertCountEqual(list(pref.keys()), ["user", "key", "value", "url"])
+ self.assertCountEqual(list(pref.keys()), ["user", "key", "value", "url"]) # noqa: PT009
self.assertSelfReferential(pref)
self.assertUserIsValid(pref["user"])
diff --git a/openedx/core/djangoapps/user_api/verification_api/views.py b/openedx/core/djangoapps/user_api/verification_api/views.py
index 1ef159150cda..78f481f6224a 100644
--- a/openedx/core/djangoapps/user_api/verification_api/views.py
+++ b/openedx/core/djangoapps/user_api/verification_api/views.py
@@ -35,7 +35,7 @@ def get(self, request, **kwargs): # lint-amnesty, pylint: disable=missing-funct
})
except User.DoesNotExist:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
class IDVerificationStatusDetailsView(ListAPIView):
@@ -59,4 +59,4 @@ def get_queryset(self):
return sorted(verifications, key=lambda x: x.updated_at, reverse=True)
except User.DoesNotExist:
- raise Http404 # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404 # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
diff --git a/openedx/core/djangoapps/user_authn/api/tests/test_serializers.py b/openedx/core/djangoapps/user_authn/api/tests/test_serializers.py
index 77d0dbb27153..3b22508958aa 100644
--- a/openedx/core/djangoapps/user_authn/api/tests/test_serializers.py
+++ b/openedx/core/djangoapps/user_authn/api/tests/test_serializers.py
@@ -27,7 +27,7 @@ def test_mfe_context_serializer(self):
MFE_CONTEXT_WITH_TPA_DATA
).data
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
output_data,
SERIALIZED_MFE_CONTEXT_WITH_TPA_DATA
)
@@ -40,7 +40,7 @@ def test_mfe_context_serializer_default_response(self):
MFE_CONTEXT_WITHOUT_TPA_DATA
).data
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
serialized_data,
SERIALIZED_MFE_CONTEXT_WITHOUT_TPA_DATA
)
diff --git a/openedx/core/djangoapps/user_authn/api/tests/test_views.py b/openedx/core/djangoapps/user_authn/api/tests/test_views.py
index 78db3d81de1c..42372bb375e4 100644
--- a/openedx/core/djangoapps/user_authn/api/tests/test_views.py
+++ b/openedx/core/djangoapps/user_authn/api/tests/test_views.py
@@ -258,7 +258,7 @@ def test_optional_field_has_no_description(self):
'goals': {
'name': 'goals',
'type': 'textarea',
- 'label': "Tell us why you're interested in {platform_name}".format(
+ 'label': "Tell us why you're interested in {platform_name}".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME
),
'error_message': '',
@@ -360,13 +360,13 @@ def test_mfe_context_api_serialized_response(self):
Test MFE Context API serialized response
"""
response = self.client.get(self.url, self.query_params)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
params = {
'next': self.query_params['next']
}
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
response.data,
self.get_context(params)
)
@@ -376,10 +376,10 @@ def test_mfe_context_api_response_keys(self):
Test MFE Context API response keys
"""
response = self.client.get(self.url, self.query_params)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_200_OK) # noqa: PT009
response_keys = set(response.data.keys())
- self.assertSetEqual(
+ self.assertSetEqual( # noqa: PT009
response_keys,
{
'contextData',
diff --git a/openedx/core/djangoapps/user_authn/cookies.py b/openedx/core/djangoapps/user_authn/cookies.py
index f6db33181619..349c40b8d167 100644
--- a/openedx/core/djangoapps/user_authn/cookies.py
+++ b/openedx/core/djangoapps/user_authn/cookies.py
@@ -361,6 +361,6 @@ def _get_login_oauth_client():
try:
return Application.objects.get(client_id=login_client_id)
except Application.DoesNotExist:
- raise AuthFailedError( # lint-amnesty, pylint: disable=raise-missing-from
+ raise AuthFailedError( # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
f"OAuth Client for the Login service, '{login_client_id}', is not configured."
)
diff --git a/openedx/core/djangoapps/user_authn/exceptions.py b/openedx/core/djangoapps/user_authn/exceptions.py
index 984aa7e4c10b..c5cbbd499dfc 100644
--- a/openedx/core/djangoapps/user_authn/exceptions.py
+++ b/openedx/core/djangoapps/user_authn/exceptions.py
@@ -10,7 +10,7 @@ class AuthFailedError(Exception):
message.
"""
def __init__( # lint-amnesty, pylint: disable=dangerous-default-value
- self, value=None, redirect=None, redirect_url=None, error_code=None, context={},
+ self, value=None, redirect=None, redirect_url=None, error_code=None, context={}, # noqa: B006
):
super().__init__()
self.value = Text(value)
diff --git a/openedx/core/djangoapps/user_authn/signals.py b/openedx/core/djangoapps/user_authn/signals.py
index a5c3517fc01e..dcab05cc3e96 100644
--- a/openedx/core/djangoapps/user_authn/signals.py
+++ b/openedx/core/djangoapps/user_authn/signals.py
@@ -2,7 +2,7 @@
Signals for user_authn
"""
-from typing import Any, Dict, Optional, Tuple
+from typing import Any, Dict, Optional, Tuple # noqa: UP035
from common.djangoapps.student.models import UserProfile
from common.djangoapps.track import segment
@@ -11,7 +11,7 @@
def user_fields_changed(
user=None,
table=None,
- changed_fields: Optional[Dict[str, Tuple[Any, Any]]] = None,
+ changed_fields: Optional[Dict[str, Tuple[Any, Any]]] = None, # noqa: UP006, UP045
**_kwargs,
):
"""
diff --git a/openedx/core/djangoapps/user_authn/tasks.py b/openedx/core/djangoapps/user_authn/tasks.py
index c1c781d2f26f..5ca32fd8e445 100644
--- a/openedx/core/djangoapps/user_authn/tasks.py
+++ b/openedx/core/djangoapps/user_authn/tasks.py
@@ -75,7 +75,7 @@ def send_activation_email(self, msg_string, from_address=None, site_id=None):
with emulate_http_request(site=site, user=user):
ace.send(msg)
except RecoverableChannelDeliveryError:
- log.info('Retrying sending email to user {dest_addr}, attempt # {attempt} of {max_attempts}'.format(
+ log.info('Retrying sending email to user {dest_addr}, attempt # {attempt} of {max_attempts}'.format( # noqa: UP032 # pylint: disable=line-too-long
dest_addr=dest_addr,
attempt=retries,
max_attempts=max_retries
@@ -95,4 +95,4 @@ def send_activation_email(self, msg_string, from_address=None, site_id=None):
from_address,
dest_addr,
)
- raise Exception # lint-amnesty, pylint: disable=raise-missing-from
+ raise Exception # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
diff --git a/openedx/core/djangoapps/user_authn/tests/test_cookies.py b/openedx/core/djangoapps/user_authn/tests/test_cookies.py
index 3e0a88a88728..a40eeb1a9933 100644
--- a/openedx/core/djangoapps/user_authn/tests/test_cookies.py
+++ b/openedx/core/djangoapps/user_authn/tests/test_cookies.py
@@ -89,7 +89,7 @@ def _assert_recreate_jwt_from_cookies(self, response, can_recreate):
def _assert_cookies_present(self, response, expected_cookies):
""" Verify all expected_cookies are present in the response. """
- self.assertSetEqual(set(response.cookies.keys()), set(expected_cookies))
+ self.assertSetEqual(set(response.cookies.keys()), set(expected_cookies)) # noqa: PT009
def _assert_consistent_expires(self, response, num_of_unique_expires=1):
""" Verify cookies in the response have the same expiration, as expected. """
@@ -112,7 +112,7 @@ def test_get_user_info_cookie_data(self):
'user_image_urls': get_profile_image_urls_for_user(self.user),
}
- self.assertDictEqual(actual, expected)
+ self.assertDictEqual(actual, expected) # noqa: PT009
def test_set_logged_in_cookies_anonymous_user(self):
anonymous_user = AnonymousUserFactory()
diff --git a/openedx/core/djangoapps/user_authn/tests/test_tasks.py b/openedx/core/djangoapps/user_authn/tests/test_tasks.py
index d2cd13f8d563..993bfcf0fffc 100644
--- a/openedx/core/djangoapps/user_authn/tests/test_tasks.py
+++ b/openedx/core/djangoapps/user_authn/tests/test_tasks.py
@@ -63,7 +63,7 @@ def test_RetrySendUntilFail(self, mock_log):
# Asserts sending email retry logging.
for attempt in range(email_max_attempts):
mock_log.info.assert_any_call(
- 'Retrying sending email to user {dest_addr}, attempt # {attempt} of {max_attempts}'.format(
+ 'Retrying sending email to user {dest_addr}, attempt # {attempt} of {max_attempts}'.format( # noqa: UP032 # pylint: disable=line-too-long
dest_addr=self.student.email,
attempt=attempt,
max_attempts=email_max_attempts
diff --git a/openedx/core/djangoapps/user_authn/utils.py b/openedx/core/djangoapps/user_authn/utils.py
index e5a75637ec2d..12ef7f6ce09a 100644
--- a/openedx/core/djangoapps/user_authn/utils.py
+++ b/openedx/core/djangoapps/user_authn/utils.py
@@ -7,7 +7,7 @@
import random
import re
from urllib.parse import urlparse # pylint: disable=import-error
-from uuid import uuid4 # lint-amnesty, pylint: disable=unused-import
+from uuid import uuid4 # lint-amnesty, pylint: disable=unused-import # noqa: F401
from django.conf import settings
from django.utils import http
diff --git a/openedx/core/djangoapps/user_authn/views/login.py b/openedx/core/djangoapps/user_authn/views/login.py
index 0dd9a4819d5e..a4ac2cd24705 100644
--- a/openedx/core/djangoapps/user_authn/views/login.py
+++ b/openedx/core/djangoapps/user_authn/views/login.py
@@ -59,7 +59,6 @@
from openedx.core.djangoapps.user_authn.views.utils import API_V1, ENTERPRISE_ENROLLMENT_URL_REGEX, UUID4_REGEX
from openedx.core.djangoapps.util.user_messages import PageLevelMessages
from openedx.core.djangolib.markup import HTML, Text
-from openedx.core.lib.api.view_utils import require_post_params # lint-amnesty, pylint: disable=unused-import
from openedx.features.enterprise_support.api import activate_learner_enterprise, get_enterprise_learner_data_from_api
log = logging.getLogger("edx.student")
@@ -83,7 +82,7 @@ def _do_third_party_auth(request):
return pipeline.get_authenticated_user(requested_provider, username, third_party_uid)
except USER_MODEL.DoesNotExist:
AUDIT_LOG.info(
- "Login failed - user with username {username} has no social auth "
+ "Login failed - user with username {username} has no social auth " # noqa: UP032
"with backend_name {backend_name}".format(username=username, backend_name=backend_name)
)
message = Text(
@@ -102,7 +101,7 @@ def _do_third_party_auth(request):
register_label_strong=HTML("{register_text}").format(register_text=_("Register")),
)
- raise AuthFailedError(message, error_code="third-party-auth-with-no-linked-account") # lint-amnesty, pylint: disable=raise-missing-from
+ raise AuthFailedError(message, error_code="third-party-auth-with-no-linked-account") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def _get_user_by_email(email):
@@ -211,7 +210,7 @@ def _enforce_password_policy_compliance(request, user): # lint-amnesty, pylint:
send_password_reset_email_for_user(user, request)
# Prevent the login attempt.
- raise AuthFailedError(HTML(str(e)), error_code=e.__class__.__name__) # lint-amnesty, pylint: disable=raise-missing-from
+ raise AuthFailedError(HTML(str(e)), error_code=e.__class__.__name__) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
def _log_and_raise_inactive_user_auth_error(unauthenticated_user):
@@ -801,4 +800,4 @@ def _parse_analytics_param_for_course_id(request):
modified_request["course_id"] = analytics.get("enroll_course_id")
except (ValueError, TypeError):
set_custom_attribute("shim_analytics_course_id", "parse-error")
- log.error("Could not parse analytics object sent to user API: {analytics}".format(analytics=analytics))
+ log.error("Could not parse analytics object sent to user API: {analytics}".format(analytics=analytics)) # noqa: UP032 # pylint: disable=line-too-long
diff --git a/openedx/core/djangoapps/user_authn/views/password_reset.py b/openedx/core/djangoapps/user_authn/views/password_reset.py
index 1fb72c0e2928..934ee02cf8bb 100644
--- a/openedx/core/djangoapps/user_authn/views/password_reset.py
+++ b/openedx/core/djangoapps/user_authn/views/password_reset.py
@@ -460,7 +460,7 @@ def _handle_primary_email_update(self, updated_user): # lint-amnesty, pylint: d
}
)
except ObjectDoesNotExist:
- log.error('Account recovery process initiated without AccountRecovery instance for user {username}'
+ log.error('Account recovery process initiated without AccountRecovery instance for user {username}' # noqa: UP032 # pylint: disable=line-too-long
.format(username=updated_user.username))
def _handle_password_creation(self, request, updated_user):
@@ -659,7 +659,7 @@ def password_change_request_handler(request):
)
ace.send(msg)
except errors.UserAPIInternalError as err:
- log.exception('Error occurred during password change for user {email}: {error}'
+ log.exception('Error occurred during password change for user {email}: {error}' # noqa: UP032
.format(email=email, error=err))
return HttpResponse(_("Some error occurred during password change. Please try again"), status=500)
diff --git a/openedx/core/djangoapps/user_authn/views/register.py b/openedx/core/djangoapps/user_authn/views/register.py
index 38f470c5ae0f..563f73c235be 100644
--- a/openedx/core/djangoapps/user_authn/views/register.py
+++ b/openedx/core/djangoapps/user_authn/views/register.py
@@ -699,7 +699,7 @@ def _create_account(self, request, data):
response = self._create_response(request, errors, status_code=409, error_code=err.error_code)
except ValidationError as err:
# Should only get field errors from this exception
- assert NON_FIELD_ERRORS not in err.message_dict
+ assert NON_FIELD_ERRORS not in err.message_dict # noqa: PT017
# Error messages are returned as arrays from ValidationError
error_code = err.message_dict.get('error_code', ['validation-error'])[0]
diff --git a/openedx/core/djangoapps/user_authn/views/registration_form.py b/openedx/core/djangoapps/user_authn/views/registration_form.py
index 114da4ef61b8..7c84b224f518 100644
--- a/openedx/core/djangoapps/user_authn/views/registration_form.py
+++ b/openedx/core/djangoapps/user_authn/views/registration_form.py
@@ -535,7 +535,7 @@ def get_registration_form(self, request):
FormDescription.FIELD_TYPE_MAP.get(field.__class__))
if not field_type:
raise ImproperlyConfigured(
- "Field type '{}' not recognized for registration extension field '{}'.".format(
+ "Field type '{}' not recognized for registration extension field '{}'.".format( # noqa: UP032 # pylint: disable=line-too-long
field_type,
field_name
)
diff --git a/openedx/core/djangoapps/user_authn/views/tests/test_events.py b/openedx/core/djangoapps/user_authn/views/tests/test_events.py
index 5393a24adccc..0fea686b1a0d 100644
--- a/openedx/core/djangoapps/user_authn/views/tests/test_events.py
+++ b/openedx/core/djangoapps/user_authn/views/tests/test_events.py
@@ -83,7 +83,7 @@ def test_send_registration_event(self):
self.client.post(self.url, self.user_info)
user = User.objects.get(username=self.user_info.get("username"))
- self.assertTrue(self.receiver_called)
+ self.assertTrue(self.receiver_called) # noqa: PT009
assert_dict_contains_subset(
self,
{
@@ -166,7 +166,7 @@ def test_send_login_event(self):
self.client.post(self.url, data)
user = User.objects.get(username=self.user.username)
- self.assertTrue(self.receiver_called)
+ self.assertTrue(self.receiver_called) # noqa: PT009
assert_dict_contains_subset(
self,
{
diff --git a/openedx/core/djangoapps/user_authn/views/tests/test_filters.py b/openedx/core/djangoapps/user_authn/views/tests/test_filters.py
index dbca91830028..41f994501ef7 100644
--- a/openedx/core/djangoapps/user_authn/views/tests/test_filters.py
+++ b/openedx/core/djangoapps/user_authn/views/tests/test_filters.py
@@ -137,7 +137,7 @@ def test_register_filter_executed(self):
self.client.post(self.url, self.user_info)
user = User.objects.filter(username=f"{self.user_info.get('username')}-OpenEdx-Test")
- self.assertTrue(user)
+ self.assertTrue(user) # noqa: PT009
@override_settings(
OPEN_EDX_FILTERS_CONFIG={
@@ -160,7 +160,7 @@ def test_register_filter_prevent_registration(self):
"""
response = self.client.post(self.url, self.user_info)
- self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code)
+ self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code) # noqa: PT009
@override_settings(OPEN_EDX_FILTERS_CONFIG={})
def test_register_without_filter_configuration(self):
@@ -174,7 +174,7 @@ def test_register_without_filter_configuration(self):
self.client.post(self.url, self.user_info)
user = User.objects.filter(username=f"{self.user_info.get('username')}")
- self.assertTrue(user)
+ self.assertTrue(user) # noqa: PT009
@skip_unless_lms
@@ -225,7 +225,7 @@ def test_login_filter_executed(self):
self.client.post(self.url, data)
user = User.objects.get(username=self.user.username)
- self.assertDictEqual({"logged_in": True, "another_logged_in": True}, user.profile.get_meta())
+ self.assertDictEqual({"logged_in": True, "another_logged_in": True}, user.profile.get_meta()) # noqa: PT009
@override_settings(
OPEN_EDX_FILTERS_CONFIG={
@@ -253,7 +253,7 @@ def test_login_filter_prevent_login(self):
response = self.client.post(self.url, data)
- self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code) # noqa: PT009
@override_settings(OPEN_EDX_FILTERS_CONFIG={})
def test_login_without_filter_configuration(self):
@@ -271,4 +271,4 @@ def test_login_without_filter_configuration(self):
response = self.client.post(self.url, data)
- self.assertEqual(status.HTTP_200_OK, response.status_code)
+ self.assertEqual(status.HTTP_200_OK, response.status_code) # noqa: PT009
diff --git a/openedx/core/djangoapps/user_authn/views/tests/test_login.py b/openedx/core/djangoapps/user_authn/views/tests/test_login.py
index 8397d03a8914..e57552183deb 100644
--- a/openedx/core/djangoapps/user_authn/views/tests/test_login.py
+++ b/openedx/core/djangoapps/user_authn/views/tests/test_login.py
@@ -173,7 +173,7 @@ def test_public_login_failure_with_only_third_part_auth_enabled(self):
'next_url': None,
'course_id': 'coursekey',
'expected_redirect': (
- '{root_url}/account/finish_auth?course_id=coursekey&next=%2Fdashboard'.
+ '{root_url}/account/finish_auth?course_id=coursekey&next=%2Fdashboard'. # noqa: UP032
format(root_url=settings.LMS_ROOT_URL)
),
},
@@ -192,7 +192,7 @@ def test_public_login_failure_with_only_third_part_auth_enabled(self):
'next_url': 'http://scam.scam',
'course_id': 'coursekey',
'expected_redirect': (
- '{root_url}/account/finish_auth?course_id=coursekey&next=%2Fdashboard'.
+ '{root_url}/account/finish_auth?course_id=coursekey&next=%2Fdashboard'. # noqa: UP032
format(root_url=settings.LMS_ROOT_URL)
),
},
@@ -838,7 +838,7 @@ def _assert_response(self, response, success=None, value=None, status_code=None,
try:
response_dict = json.loads(response.content.decode('utf-8'))
except ValueError:
- self.fail("Could not parse response content as JSON: %s"
+ self.fail("Could not parse response content as JSON: %s" # noqa: UP031
% str(response.content))
if success is not None:
@@ -848,7 +848,7 @@ def _assert_response(self, response, success=None, value=None, status_code=None,
assert response_dict['error_code'] == error_code
if value is not None:
- msg = ("'%s' did not contain '%s'" %
+ msg = ("'%s' did not contain '%s'" % # noqa: UP031
(str(response_dict['value']), str(value)))
assert value in response_dict['value'], msg
@@ -861,7 +861,7 @@ def _assert_redirect_url(self, response, expected_redirect_url):
"""
response_dict = json.loads(response.content.decode('utf-8'))
assert 'redirect_url' in response_dict, (
- "Response JSON unexpectedly does not have redirect_url: {!r}".format(
+ "Response JSON unexpectedly does not have redirect_url: {!r}".format( # noqa: UP032
response_dict
)
)
@@ -1102,7 +1102,7 @@ def test_login_form(self):
assert form_desc['submit_url'] == reverse('user_api_login_session', kwargs={'api_version': 'v1'})
assert form_desc['fields'] == [{'name': 'email', 'defaultValue': '', 'type': 'email', 'exposed': True,
'required': True, 'label': 'Email', 'placeholder': '',
- 'instructions': 'The email address you used to register with {platform_name}'
+ 'instructions': 'The email address you used to register with {platform_name}' # noqa: UP032 # pylint: disable=line-too-long
.format(platform_name=settings.PLATFORM_NAME),
'restrictions': {'min_length': EMAIL_MIN_LENGTH,
'max_length': EMAIL_MAX_LENGTH},
diff --git a/openedx/core/djangoapps/user_authn/views/tests/test_logistration.py b/openedx/core/djangoapps/user_authn/views/tests/test_logistration.py
index 9dcc21a84aa1..1b43d24d19ed 100644
--- a/openedx/core/djangoapps/user_authn/views/tests/test_logistration.py
+++ b/openedx/core/djangoapps/user_authn/views/tests/test_logistration.py
@@ -413,7 +413,7 @@ def test_hinted_login_dialog_disabled(self, url_name, auth_entry):
params = [("next", "/courses/something/?tpa_hint=oa2-google-oauth2")]
response = self.client.get(reverse(url_name), params, HTTP_ACCEPT="text/html")
expected_url = '/auth/login/google-oauth2/?auth_entry={}&next=%2Fcourses'\
- '%2Fsomething%2F%3Ftpa_hint%3Doa2-google-oauth2'.format(auth_entry)
+ '%2Fsomething%2F%3Ftpa_hint%3Doa2-google-oauth2'.format(auth_entry) # noqa: UP032
self.assertRedirects(
response,
expected_url,
@@ -458,7 +458,7 @@ def test_settings_tpa_hinted_login_dialog_disabled(self, url_name, auth_entry):
params = [("next", "/courses/something/")]
response = self.client.get(reverse(url_name), params, HTTP_ACCEPT="text/html")
expected_url = '/auth/login/google-oauth2/?auth_entry={}&next=%2Fcourses'\
- '%2Fsomething%2F%3Ftpa_hint%3Doa2-google-oauth2'.format(auth_entry)
+ '%2Fsomething%2F%3Ftpa_hint%3Doa2-google-oauth2'.format(auth_entry) # noqa: UP032
self.assertRedirects(
response,
expected_url,
@@ -579,7 +579,7 @@ def _assert_third_party_auth_data(self, response, current_backend, current_provi
auth_info['providers'] = []
auth_info = dump_js_escaped_json(auth_info)
- expected_data = '"third_party_auth": {auth_info}'.format(
+ expected_data = '"third_party_auth": {auth_info}'.format( # noqa: UP032
auth_info=auth_info
)
self.assertContains(response, expected_data)
@@ -608,7 +608,7 @@ def _assert_saml_auth_data_with_error(
}
auth_info = dump_js_escaped_json(auth_info)
- expected_data = '"third_party_auth": {auth_info}'.format(
+ expected_data = '"third_party_auth": {auth_info}'.format( # noqa: UP032
auth_info=auth_info
)
self.assertContains(response, expected_data)
diff --git a/openedx/core/djangoapps/user_authn/views/tests/test_password.py b/openedx/core/djangoapps/user_authn/views/tests/test_password.py
index 930be723c406..958ec3d941e9 100644
--- a/openedx/core/djangoapps/user_authn/views/tests/test_password.py
+++ b/openedx/core/djangoapps/user_authn/views/tests/test_password.py
@@ -213,7 +213,7 @@ def test_password_change_failure(self):
side_effect=UserAPIInternalError,
):
self._change_password()
- self.assertRaises(UserAPIInternalError)
+ self.assertRaises(UserAPIInternalError) # noqa: PT027
@patch.dict(settings.FEATURES, {'ENABLE_PASSWORD_RESET_FAILURE_EMAIL': True})
def test_password_reset_failure_email(self):
@@ -234,7 +234,7 @@ def test_password_reset_failure_email(self):
html_body = sent_message.alternatives[0][0]
for email_body in [text_body, html_body]:
- msg = 'However, there is currently no user account associated with your email address: {email}'.format(
+ msg = 'However, there is currently no user account associated with your email address: {email}'.format( # noqa: UP032 # pylint: disable=line-too-long
email=bad_email
)
diff --git a/openedx/core/djangoapps/user_authn/views/tests/test_register.py b/openedx/core/djangoapps/user_authn/views/tests/test_register.py
index 039090a0bdb4..2f336826b2b5 100644
--- a/openedx/core/djangoapps/user_authn/views/tests/test_register.py
+++ b/openedx/core/djangoapps/user_authn/views/tests/test_register.py
@@ -59,7 +59,7 @@
from openedx.core.djangoapps.user_api.accounts.tests.retirement_helpers import ( # pylint: disable=unused-import
RetirementTestCase,
fake_requested_retirement,
- setup_retirement_states,
+ setup_retirement_states, # noqa: F401
)
from openedx.core.djangoapps.user_api.tests.test_constants import SORTED_COUNTRIES
from openedx.core.djangoapps.user_api.tests.test_helpers import TestCaseForm
@@ -156,7 +156,7 @@ def test_register_retired_email_validation_error(self):
assert response.status_code == 409
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"email": [{
@@ -198,7 +198,7 @@ def test_register_duplicate_retired_username_account_validation_error(self):
response_json = json.loads(response.content.decode('utf-8'))
username_suggestions = response_json.pop('username_suggestions')
assert len(username_suggestions) == 3
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"username": [{
@@ -231,7 +231,7 @@ def test_register_duplicate_email_validation_error(self):
assert response.status_code == 409
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"email": [{
@@ -268,7 +268,7 @@ def test_register_duplicate_email_validation_error_with_recovery(self):
assert response.status_code == 409
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"email": [{
@@ -291,7 +291,7 @@ def test_register_fullname_url_validation_error(self):
})
assert response.status_code == 400
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"name": [{"user_message": 'Enter a valid name'}],
@@ -309,7 +309,7 @@ def test_register_fullname_url_validation_error(self):
})
assert response.status_code == 400
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"name": [{"user_message": 'Enter a valid name'}],
@@ -333,7 +333,7 @@ def test_register_fullname_max_lenghth_validation_error(self):
assert response.status_code == 400
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"name": [{"user_message": expected_error_message}],
@@ -354,7 +354,7 @@ def test_register_fullname_html_validation_error(self):
})
assert response.status_code == 400
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
'name': [{'user_message': 'Full Name cannot contain the following characters: < >'}],
@@ -386,7 +386,7 @@ def test_register_duplicate_username_account_validation_error(self):
response_json = json.loads(response.content.decode('utf-8'))
username_suggestions = response_json.pop('username_suggestions')
assert len(username_suggestions) == 3
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"username": [{
@@ -420,7 +420,7 @@ def test_register_duplicate_username_and_email_validation_errors(self):
response_json = json.loads(response.content.decode('utf-8'))
username_suggestions = response_json.pop('username_suggestions')
assert len(username_suggestions) == 3
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"username": [{
@@ -458,7 +458,7 @@ def test_duplicate_email_username_error(self):
assert response.status_code == 409
username_suggestions = response_json.pop('username_suggestions')
assert len(username_suggestions) == 3
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"username": [{
@@ -483,7 +483,7 @@ def test_invalid_country_code_error(self):
response_json = json.loads(response.content.decode('utf-8'))
self.assertHttpBadRequest(response)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"country": [{
@@ -984,7 +984,7 @@ def test_register_form_marketing_emails_opt_in_field(self):
"name": "marketing_emails_opt_in",
"type": "checkbox",
"required": False,
- "label": 'I agree that {platform_name} may send me marketing messages.'.format(
+ "label": 'I agree that {platform_name} may send me marketing messages.'.format( # noqa: UP032
platform_name=settings.PLATFORM_NAME,
),
"exposed": True,
@@ -1081,7 +1081,7 @@ def test_registration_form_goals(self):
"name": "goals",
"type": "textarea",
"required": False,
- "label": "Tell us why you're interested in {platform_name}".format(
+ "label": "Tell us why you're interested in {platform_name}".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME
),
"errorMessages": {
@@ -1177,7 +1177,7 @@ def test_registration_honor_code_mktg_site_enabled(self):
"type": "plaintext",
"required": True,
"errorMessages": {
- "required": "You must agree to the {platform_name} {link_label}".format(
+ "required": "You must agree to the {platform_name} {link_label}".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME,
link_label=link_label
)
@@ -1209,7 +1209,7 @@ def test_registration_honor_code_mktg_site_disabled(self):
"type": "plaintext",
"required": True,
"errorMessages": {
- "required": "You must agree to the {platform_name} {link_label}".format(
+ "required": "You must agree to the {platform_name} {link_label}".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME,
link_label=link_label
)
@@ -1231,7 +1231,7 @@ def test_registration_separate_terms_of_service_mktg_site_enabled(self):
self._assert_reg_field(
{"honor_code": "required", "terms_of_service": "required"},
{
- "label": "I agree to the {platform_name} {link_label}".format(
+ "label": "I agree to the {platform_name} {link_label}".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME,
link_label=link_template.format(link_label=link_label)
),
@@ -1240,7 +1240,7 @@ def test_registration_separate_terms_of_service_mktg_site_enabled(self):
"type": "checkbox",
"required": True,
"errorMessages": {
- "required": "You must agree to the {platform_name} {link_label}".format(
+ "required": "You must agree to the {platform_name} {link_label}".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME,
link_label=link_label
)
@@ -1254,7 +1254,7 @@ def test_registration_separate_terms_of_service_mktg_site_enabled(self):
self._assert_reg_field(
{"honor_code": "required", "terms_of_service": "required"},
{
- "label": "I agree to the {platform_name} {link_label}".format(
+ "label": "I agree to the {platform_name} {link_label}".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME,
link_label=link_template.format(link_label=link_label)
),
@@ -1263,7 +1263,7 @@ def test_registration_separate_terms_of_service_mktg_site_enabled(self):
"type": "checkbox",
"required": True,
"errorMessages": {
- "required": "You must agree to the {platform_name} {link_label}".format(
+ "required": "You must agree to the {platform_name} {link_label}".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME,
link_label=link_label
)
@@ -1280,7 +1280,7 @@ def test_registration_separate_terms_of_service_mktg_site_disabled(self):
self._assert_reg_field(
{"honor_code": "required", "terms_of_service": "required"},
{
- "label": "I agree to the {platform_name} {link_label}".format(
+ "label": "I agree to the {platform_name} {link_label}".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME,
link_label=self.link_template.format(link_label=link_label)
),
@@ -1289,7 +1289,7 @@ def test_registration_separate_terms_of_service_mktg_site_disabled(self):
"type": "checkbox",
"required": True,
"errorMessages": {
- "required": "You must agree to the {platform_name} Honor Code".format(
+ "required": "You must agree to the {platform_name} Honor Code".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME
)
}
@@ -1302,7 +1302,7 @@ def test_registration_separate_terms_of_service_mktg_site_disabled(self):
self._assert_reg_field(
{"honor_code": "required", "terms_of_service": "required"},
{
- "label": "I agree to the {platform_name} {link_label}".format(
+ "label": "I agree to the {platform_name} {link_label}".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME,
link_label=link_template.format(link_label=link_label)
),
@@ -1311,7 +1311,7 @@ def test_registration_separate_terms_of_service_mktg_site_disabled(self):
"type": "checkbox",
"required": True,
"errorMessages": {
- "required": "You must agree to the {platform_name} Terms of Service".format(
+ "required": "You must agree to the {platform_name} Terms of Service".format( # noqa: UP032
platform_name=settings.PLATFORM_NAME
)
}
@@ -1641,7 +1641,7 @@ def test_register_missing_country_required_field(self):
response_json = json.loads(response.content.decode('utf-8'))
self.assertHttpBadRequest(response)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"country": [{
@@ -1665,7 +1665,7 @@ def test_register_invalid_country_required_field(self):
response_json = json.loads(response.content.decode('utf-8'))
self.assertHttpBadRequest(response)
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"country": [{
@@ -1697,7 +1697,7 @@ def test_register_duplicate_email(self):
assert response.status_code == 409
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"email": [{
@@ -1731,7 +1731,7 @@ def test_register_duplicate_username(self):
response_json = json.loads(response.content.decode('utf-8'))
username_suggestions = response_json.pop('username_suggestions')
assert len(username_suggestions) == 3
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"username": [{
@@ -1765,7 +1765,7 @@ def test_register_duplicate_username_and_email(self):
response_json = json.loads(response.content.decode('utf-8'))
username_suggestions = response_json.pop('username_suggestions')
assert len(username_suggestions) == 3
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"username": [{
@@ -1799,7 +1799,7 @@ def test_missing_fields(self):
)
assert response.status_code == 400
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"username": [{"user_message": USERNAME_BAD_LENGTH_MSG}],
@@ -1905,7 +1905,7 @@ def test_register_with_empty_name(self):
})
assert response.status_code == 400
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"name": [{"user_message": 'Your legal name must be a minimum of one character long'}],
@@ -1958,7 +1958,7 @@ def test_register_autogenerated_duplicate_username(self,
assert response.status_code == 409
response_json = json.loads(response.content.decode('utf-8'))
response_json.pop('username_suggestions')
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"username": [{
@@ -1976,7 +1976,7 @@ def _assert_fields_match(self, actual_field, expected_field):
for key in expected_field:
assert actual_field[key] == expected_field[key], \
- "Expected {expected} for {key} but got {actual} instead".format(
+ "Expected {expected} for {key} but got {actual} instead".format( # noqa: UP032
key=key, actual=actual_field[key], expected=expected_field[key])
def _populate_always_present_fields(self, field):
@@ -2051,7 +2051,7 @@ def _assert_reg_absent_field(self, extra_fields_setting, expected_absent_field:
current_present_field_names = [field["name"] for field in form_desc["fields"]]
assert expected_absent_field not in current_present_field_names, \
- "Expected absent field {expected}".format(expected=expected_absent_field)
+ "Expected absent field {expected}".format(expected=expected_absent_field) # noqa: UP032
def _assert_password_field_hidden(self, field_settings):
self._assert_reg_field(field_settings, {
@@ -2308,7 +2308,7 @@ def _assert_redirect_url(self, response, expected_redirect_url):
"""
response_dict = json.loads(response.content.decode('utf-8'))
assert 'redirect_url' in response_dict, (
- "Response JSON unexpectedly does not have redirect_url: {!r}".format(
+ "Response JSON unexpectedly does not have redirect_url: {!r}".format( # noqa: UP032
response_dict
)
)
@@ -2479,7 +2479,7 @@ def test_register_with_disabled_country(self):
})
assert response.status_code == 400
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{'country':
[
@@ -2507,7 +2507,7 @@ def test_registration_allowed_when_embargo_disabled(self):
"country": "KP",
})
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 200) # noqa: PT009
@httpretty.activate
@@ -2574,7 +2574,7 @@ def _assert_access_token_error(self, response, expected_error_message, error_cod
"""Assert that the given response was an error for the access_token field with the given error message."""
assert response.status_code == 400
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"access_token": [{"user_message": expected_error_message}],
@@ -2586,7 +2586,7 @@ def _assert_third_party_session_expired_error(self, response, expected_error_mes
"""Assert that given response is an error due to third party session expiry"""
assert response.status_code == 400
response_json = json.loads(response.content.decode('utf-8'))
- self.assertDictEqual(
+ self.assertDictEqual( # noqa: PT009
response_json,
{
"session_expired": [{"user_message": expected_error_message}],
@@ -2600,7 +2600,7 @@ def _verify_user_existence(self, user_exists, social_link_exists, user_is_active
assert users.exists() == user_exists
if user_exists:
assert users[0].is_active == user_is_active
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
UserSocialAuth.objects.filter(user=users[0], provider=self.BACKEND).exists(),
social_link_exists
)
diff --git a/openedx/core/djangoapps/user_authn/views/tests/test_reset_password.py b/openedx/core/djangoapps/user_authn/views/tests/test_reset_password.py
index 19b03959ce65..ad4076ce4bd7 100644
--- a/openedx/core/djangoapps/user_authn/views/tests/test_reset_password.py
+++ b/openedx/core/djangoapps/user_authn/views/tests/test_reset_password.py
@@ -653,7 +653,7 @@ def test_reset_password_with_other_user_link(self):
reset_request = self.request_factory.get(self.password_reset_confirm_url)
reset_request.user = UserFactory.create()
- self.assertRaises(Http404, PasswordResetConfirmWrapper.as_view(), reset_request, uidb36=self.uidb36,
+ self.assertRaises(Http404, PasswordResetConfirmWrapper.as_view(), reset_request, uidb36=self.uidb36, # noqa: PT027 # pylint: disable=line-too-long
token=self.token)
@override_settings(FEATURES={'ENABLE_MAX_FAILED_LOGIN_ATTEMPTS': True}, MAX_FAILED_LOGIN_ATTEMPTS_ALLOWED=1)
@@ -757,7 +757,7 @@ def test_password_reset_form(self):
assert form_desc['fields'] ==\
[{'name': 'email', 'defaultValue': '', 'type': 'email', 'exposed': True,
'required': True, 'label': 'Email', 'placeholder': 'username@domain.com',
- 'instructions': 'The email address you used to register with {platform_name}'
+ 'instructions': 'The email address you used to register with {platform_name}' # noqa: UP032
.format(platform_name=settings.PLATFORM_NAME),
'restrictions': {'min_length': EMAIL_MIN_LENGTH,
'max_length': EMAIL_MAX_LENGTH},
@@ -775,7 +775,7 @@ def setUp(self):
self.user = UserFactory.create()
self.user.is_active = False
self.user.save()
- self.token = '{uidb36}-{token}'.format(
+ self.token = '{uidb36}-{token}'.format( # noqa: UP032
uidb36=int_to_base36(self.user.id),
token=default_token_generator.make_token(self.user)
)
diff --git a/openedx/core/djangoapps/user_authn/views/tests/test_saml_optional_checkboxes.py b/openedx/core/djangoapps/user_authn/views/tests/test_saml_optional_checkboxes.py
index bf269b9769c8..d759f6009f98 100644
--- a/openedx/core/djangoapps/user_authn/views/tests/test_saml_optional_checkboxes.py
+++ b/openedx/core/djangoapps/user_authn/views/tests/test_saml_optional_checkboxes.py
@@ -80,7 +80,7 @@ def test_marketing_checkbox_hidden_with_marketing_opt_in_setting(self, mock_is_e
# Even though MARKETING_EMAILS_OPT_IN=True globally,
# the field should not be present when skipped via SAML config
- self.assertIsNone(
+ self.assertIsNone( # noqa: PT009
marketing_field,
"marketing_emails_opt_in field should not be present when skipped via SAML config, "
"even when MARKETING_EMAILS_OPT_IN=True"
@@ -127,18 +127,18 @@ def test_marketing_checkbox_visible_with_marketing_opt_in_setting_no_skip(self,
# When MARKETING_EMAILS_OPT_IN=True and SAML config doesn't skip,
# the field should be present
- self.assertIsNotNone(
+ self.assertIsNotNone( # noqa: PT009
marketing_field,
"marketing_emails_opt_in field should be present when MARKETING_EMAILS_OPT_IN=True "
"and SAML config does not skip checkboxes"
)
# The field should be visible (exposed)
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
marketing_field.get('exposed', False),
"Marketing checkbox should be visible when SAML config does not skip checkboxes"
)
# The field should be optional (not required) when MARKETING_EMAILS_OPT_IN=True
- self.assertFalse(
+ self.assertFalse( # noqa: PT009
marketing_field.get('required', False),
"Marketing checkbox should be optional when MARKETING_EMAILS_OPT_IN=True"
)
@@ -165,11 +165,11 @@ def test_marketing_checkbox_optional_without_saml_config(self):
marketing_field = field
break
- self.assertIsNotNone(marketing_field, "marketing_emails_opt_in field not found")
+ self.assertIsNotNone(marketing_field, "marketing_emails_opt_in field not found") # noqa: PT009
# When REGISTRATION_EXTRA_FIELDS is optional, the field should not be required
- self.assertFalse(marketing_field.get('required', False))
+ self.assertFalse(marketing_field.get('required', False)) # noqa: PT009
# The field should be visible (exposed=True) by default
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
marketing_field.get('exposed', False),
"Marketing checkbox should be visible when no SAML config skips it"
)
@@ -216,7 +216,7 @@ def test_marketing_checkbox_optional_with_saml_config(self, mock_is_enabled):
# When SAML provider config sets skip_registration_optional_checkboxes=True,
# the field should not be present in the form at all
- self.assertIsNone(
+ self.assertIsNone( # noqa: PT009
marketing_field,
"marketing_emails_opt_in field should not be present when skipped via SAML config"
)
@@ -261,12 +261,12 @@ def test_marketing_checkbox_still_optional_when_config_false(self, mock_is_enabl
marketing_field = field
break
- self.assertIsNotNone(marketing_field, "marketing_emails_opt_in field not found")
+ self.assertIsNotNone(marketing_field, "marketing_emails_opt_in field not found") # noqa: PT009
# When SAML provider config sets skip_registration_optional_checkboxes=False,
# it should use the global setting (required in this test)
- self.assertTrue(marketing_field.get('required', False))
+ self.assertTrue(marketing_field.get('required', False)) # noqa: PT009
# The field should be visible (exposed=True) when config is False
- self.assertTrue(
+ self.assertTrue( # noqa: PT009
marketing_field.get('exposed', False),
"Marketing checkbox should be visible when SAML config is False"
)
@@ -313,7 +313,7 @@ def test_marketing_checkbox_hidden_with_saml_config(self, mock_is_enabled):
# When SAML provider config sets skip_registration_optional_checkboxes=True,
# the field should not be present in the form at all
- self.assertIsNone(
+ self.assertIsNone( # noqa: PT009
marketing_field,
"marketing_emails_opt_in field should not be present when skipped via SAML config"
)
diff --git a/openedx/core/djangoapps/user_authn/views/tests/test_utils.py b/openedx/core/djangoapps/user_authn/views/tests/test_utils.py
index ffb2e62f7d1e..50f98dd2ab7d 100644
--- a/openedx/core/djangoapps/user_authn/views/tests/test_utils.py
+++ b/openedx/core/djangoapps/user_authn/views/tests/test_utils.py
@@ -36,7 +36,7 @@ def test_generate_username_from_data(self, data, expected_initials):
username = get_auto_generated_username(data)
expected_username = expected_initials + current_year_month + random_string
- self.assertEqual(username, expected_username)
+ self.assertEqual(username, expected_username) # noqa: PT009
@ddt.data(
({'first_name': 'John', 'last_name': 'Doe'}, "JD"),
@@ -59,7 +59,7 @@ def test_get_username_prefix(self, data, expected_initials):
Test _get_username_prefix function.
"""
username_prefix = _get_username_prefix(data)
- self.assertEqual(username_prefix, expected_initials)
+ self.assertEqual(username_prefix, expected_initials) # noqa: PT009
@patch('openedx.core.djangoapps.user_authn.views.utils._get_username_prefix')
@patch('openedx.core.djangoapps.user_authn.views.utils.random.choices')
@@ -78,4 +78,4 @@ def test_get_auto_generated_username_no_prefix(self, mock_datetime, mock_choices
expected_username = current_year_month + random_string
username = get_auto_generated_username({})
- self.assertEqual(username, expected_username)
+ self.assertEqual(username, expected_username) # noqa: PT009
diff --git a/openedx/core/djangoapps/user_authn/views/utils.py b/openedx/core/djangoapps/user_authn/views/utils.py
index f0a0f385cf0f..56ecf37c6f5c 100644
--- a/openedx/core/djangoapps/user_authn/views/utils.py
+++ b/openedx/core/djangoapps/user_authn/views/utils.py
@@ -6,7 +6,7 @@
import re
import string
from datetime import datetime
-from typing import Dict
+from typing import Dict # noqa: UP035
from django.conf import settings
from django.contrib import messages
@@ -189,7 +189,7 @@ def get_auto_generated_username(data):
return f"{username_prefix}_{username_suffix}" if username_prefix else username_suffix
-def remove_disabled_country_from_list(countries: Dict) -> Dict:
+def remove_disabled_country_from_list(countries: Dict) -> Dict: # noqa: UP006
"""
Remove disabled countries from the list of countries.
diff --git a/openedx/core/djangoapps/util/apps.py b/openedx/core/djangoapps/util/apps.py
index 993021c0146f..8ad7c426826a 100644
--- a/openedx/core/djangoapps/util/apps.py
+++ b/openedx/core/djangoapps/util/apps.py
@@ -19,4 +19,4 @@ def ready(self):
Registers signal handlers at startup.
"""
import openedx.core.djangoapps.util.checks # pylint: disable=unused-import, unused-variable
- import openedx.core.djangoapps.util.signals # pylint: disable=unused-import, unused-variable
+ import openedx.core.djangoapps.util.signals # pylint: disable=unused-import, unused-variable # noqa: F401
diff --git a/openedx/core/djangoapps/util/management/commands/print_setting.py b/openedx/core/djangoapps/util/management/commands/print_setting.py
index c53f49d23a19..6353d8a51333 100644
--- a/openedx/core/djangoapps/util/management/commands/print_setting.py
+++ b/openedx/core/djangoapps/util/management/commands/print_setting.py
@@ -44,7 +44,7 @@ def handle(self, *args, **options):
for setting in settings_to_print:
if not hasattr(settings, setting):
- raise CommandError('%s not found in settings.' % setting)
+ raise CommandError('%s not found in settings.' % setting) # noqa: UP031
setting_value = getattr(settings, setting)
diff --git a/openedx/core/djangoapps/util/management/commands/reset_db.py b/openedx/core/djangoapps/util/management/commands/reset_db.py
index 7f1f6a026e9f..d7b8974db6e3 100644
--- a/openedx/core/djangoapps/util/management/commands/reset_db.py
+++ b/openedx/core/djangoapps/util/management/commands/reset_db.py
@@ -39,7 +39,7 @@ def handle(self, *args, **options): # lint-amnesty, pylint: disable=too-many-st
router = options.get('router')
dbinfo = settings.DATABASES.get(router)
if dbinfo is None:
- raise CommandError("Unknown database router %s" % router)
+ raise CommandError("Unknown database router %s" % router) # noqa: UP031
engine = dbinfo.get('ENGINE').split('.')[-1]
@@ -83,7 +83,7 @@ def handle(self, *args, **options): # lint-amnesty, pylint: disable=too-many-st
kwargs['port'] = int(database_port)
connection = Database.connect(**kwargs)
- drop_query = 'DROP DATABASE IF EXISTS `%s`' % database_name
+ drop_query = 'DROP DATABASE IF EXISTS `%s`' % database_name # noqa: UP031
utf8_support = 'CHARACTER SET utf8'
create_query = f'CREATE DATABASE `{database_name}` {utf8_support}'
logging.info('Executing... "' + drop_query + '"') # lint-amnesty, pylint: disable=logging-not-lazy
@@ -111,16 +111,16 @@ def handle(self, *args, **options): # lint-amnesty, pylint: disable=too-many-st
connection.set_isolation_level(0) # autocommit false
cursor = connection.cursor()
- drop_query = "DROP DATABASE \"%s\";" % database_name
+ drop_query = "DROP DATABASE \"%s\";" % database_name # noqa: UP031
logging.info('Executing... "' + drop_query + '"') # lint-amnesty, pylint: disable=logging-not-lazy
try:
cursor.execute(drop_query)
except Database.ProgrammingError as e:
logging.exception("Error: %s", e)
- create_query = "CREATE DATABASE \"%s\"" % database_name
+ create_query = "CREATE DATABASE \"%s\"" % database_name # noqa: UP031
if owner:
- create_query += " WITH OWNER = \"%s\" " % owner
+ create_query += " WITH OWNER = \"%s\" " % owner # noqa: UP031
create_query += " ENCODING = 'UTF8'"
if engine == 'postgis' and django.VERSION < (1, 9):
@@ -128,10 +128,10 @@ def handle(self, *args, **options): # lint-amnesty, pylint: disable=too-many-st
from django.contrib.gis.db.backends.postgis.base import DatabaseWrapper
postgis_template = DatabaseWrapper(dbinfo).template_postgis # lint-amnesty, pylint: disable=no-member
if postgis_template is not None:
- create_query += ' TEMPLATE = %s' % postgis_template
+ create_query += ' TEMPLATE = %s' % postgis_template # noqa: UP031
if settings.DEFAULT_TABLESPACE:
- create_query += ' TABLESPACE = %s;' % settings.DEFAULT_TABLESPACE
+ create_query += ' TABLESPACE = %s;' % settings.DEFAULT_TABLESPACE # noqa: UP031
else:
create_query += ';'
@@ -139,7 +139,7 @@ def handle(self, *args, **options): # lint-amnesty, pylint: disable=too-many-st
cursor.execute(create_query)
else:
- raise CommandError("Unknown database engine %s" % engine)
+ raise CommandError("Unknown database engine %s" % engine) # noqa: UP031
if verbosity >= 2:
print("Reset successful.")
diff --git a/openedx/core/djangoapps/util/row_delete.py b/openedx/core/djangoapps/util/row_delete.py
index a0ecc240b210..8c1ff8b975ac 100644
--- a/openedx/core/djangoapps/util/row_delete.py
+++ b/openedx/core/djangoapps/util/row_delete.py
@@ -81,7 +81,7 @@ def delete_rows(model_mgr,
log.info("Deleting around %s rows between ids %s and %s...", deletions_now, lower_id, upper_id)
with transaction.atomic():
# xss-lint: disable=python-wrap-html
- delete_sql = 'DELETE FROM {} WHERE {} >= {} AND {} < {}'.format( # lint-amnesty, pylint: disable=duplicate-string-formatting-argument
+ delete_sql = 'DELETE FROM {} WHERE {} >= {} AND {} < {}'.format( # lint-amnesty, pylint: disable=duplicate-string-formatting-argument # noqa: UP032
table_name, primary_id_name, lower_id, primary_id_name, upper_id
)
log.info(delete_sql)
diff --git a/openedx/core/djangoapps/util/signals.py b/openedx/core/djangoapps/util/signals.py
index ec7474b41ba0..dd6267f8dca4 100644
--- a/openedx/core/djangoapps/util/signals.py
+++ b/openedx/core/djangoapps/util/signals.py
@@ -19,7 +19,7 @@ def record_request_exception(sender, **kwargs):
Logs the stack trace whenever an exception
occurs in processing a request.
"""
- logging.exception("Uncaught exception from {sender}".format(
+ logging.exception("Uncaught exception from {sender}".format( # noqa: UP032
sender=sender
))
diff --git a/openedx/core/djangoapps/util/test_forms.py b/openedx/core/djangoapps/util/test_forms.py
index 9f6c585848ee..cd8f7ee33f99 100644
--- a/openedx/core/djangoapps/util/test_forms.py
+++ b/openedx/core/djangoapps/util/test_forms.py
@@ -28,7 +28,7 @@ def assert_valid(self, expected_cleaned_data):
Check that the form returns the expected data
"""
form = self.get_form(expected_valid=True)
- self.assertDictEqual(form.cleaned_data, expected_cleaned_data)
+ self.assertDictEqual(form.cleaned_data, expected_cleaned_data) # noqa: PT009
def assert_field_value(self, field, expected_value):
"""
diff --git a/openedx/core/djangoapps/util/tests/test_signals.py b/openedx/core/djangoapps/util/tests/test_signals.py
index cc2711bc1ab1..73f5c7bfa968 100644
--- a/openedx/core/djangoapps/util/tests/test_signals.py
+++ b/openedx/core/djangoapps/util/tests/test_signals.py
@@ -6,7 +6,7 @@
from celery import shared_task
from django.test.utils import override_settings
from edx_django_utils.cache import RequestCache
-from pytest import mark
+from pytest import mark # noqa: PT013
@mark.django_db
diff --git a/openedx/core/djangoapps/util/user_messages.py b/openedx/core/djangoapps/util/user_messages.py
index 2b6962f39f55..213814944880 100644
--- a/openedx/core/djangoapps/util/user_messages.py
+++ b/openedx/core/djangoapps/util/user_messages.py
@@ -52,7 +52,7 @@ class UserMessageType(Enum):
}
-class UserMessage():
+class UserMessage(): # noqa: UP039
"""
Representation of a message to be shown to a user.
"""
@@ -76,7 +76,7 @@ def icon_class(self):
return ICON_CLASSES[self.type]
-class UserMessageCollection():
+class UserMessageCollection(): # noqa: UP039
"""
A collection of messages to be shown to a user.
"""
@@ -228,7 +228,7 @@ def user_messages(cls, request):
message_html=str(cls.get_message_html(Text(notice_message))),
))
except BaseException as e:
- warnings.warn(f"Could not register global notice: {e!r}", UserWarning)
+ warnings.warn(f"Could not register global notice: {e!r}", UserWarning) # noqa: B028
return msgs
diff --git a/openedx/core/djangoapps/video_config/forms.py b/openedx/core/djangoapps/video_config/forms.py
index 856b9e58de8e..e0071154bb07 100644
--- a/openedx/core/djangoapps/video_config/forms.py
+++ b/openedx/core/djangoapps/video_config/forms.py
@@ -39,7 +39,7 @@ class CourseHLSPlaybackFlagAdminForm(CourseSpecificFlagAdminBaseForm):
class Meta:
model = CourseHLSPlaybackEnabledFlag
- fields = '__all__'
+ fields = '__all__' # noqa: DJ007
class CourseYoutubeBlockedFlagAdminForm(CourseSpecificFlagAdminBaseForm):
@@ -49,7 +49,7 @@ class CourseYoutubeBlockedFlagAdminForm(CourseSpecificFlagAdminBaseForm):
class Meta:
model = CourseYoutubeBlockedFlag
- fields = '__all__'
+ fields = '__all__' # noqa: DJ007
class CourseVideoTranscriptFlagAdminForm(CourseSpecificFlagAdminBaseForm):
@@ -59,4 +59,4 @@ class CourseVideoTranscriptFlagAdminForm(CourseSpecificFlagAdminBaseForm):
class Meta:
model = CourseVideoTranscriptEnabledFlag
- fields = '__all__'
+ fields = '__all__' # noqa: DJ007
diff --git a/openedx/core/djangoapps/video_config/models.py b/openedx/core/djangoapps/video_config/models.py
index 9a54585475f2..16051fb1acf3 100644
--- a/openedx/core/djangoapps/video_config/models.py
+++ b/openedx/core/djangoapps/video_config/models.py
@@ -58,7 +58,7 @@ def feature_enabled(cls, course_id):
def __str__(self):
current_model = HLSPlaybackEnabledFlag.current()
- return "HLSPlaybackEnabledFlag: enabled {is_enabled}".format(
+ return "HLSPlaybackEnabledFlag: enabled {is_enabled}".format( # noqa: UP032
is_enabled=current_model.is_enabled()
)
@@ -87,7 +87,7 @@ def __str__(self):
if self.enabled:
not_en = ""
- return "Course '{course_key}': HLS Playback {not_enabled}Enabled".format(
+ return "Course '{course_key}': HLS Playback {not_enabled}Enabled".format( # noqa: UP032
course_key=str(self.course_id),
not_enabled=not_en
)
@@ -123,7 +123,7 @@ def __str__(self):
if self.enabled:
not_en = ""
- return "Course '{course_key}': Youtube Block {not_enabled}Enabled".format(
+ return "Course '{course_key}': Youtube Block {not_enabled}Enabled".format( # noqa: UP032
course_key=str(self.course_id),
not_enabled=not_en
)
@@ -169,7 +169,7 @@ def feature_enabled(cls, course_id):
def __str__(self):
current_model = VideoTranscriptEnabledFlag.current()
- return "VideoTranscriptEnabledFlag: enabled {is_enabled}".format(
+ return "VideoTranscriptEnabledFlag: enabled {is_enabled}".format( # noqa: UP032
is_enabled=current_model.is_enabled()
)
@@ -192,7 +192,7 @@ def __str__(self):
if self.enabled:
not_en = ""
- return "Course '{course_key}': Video Transcript {not_enabled}Enabled".format(
+ return "Course '{course_key}': Video Transcript {not_enabled}Enabled".format( # noqa: UP032
course_key=str(self.course_id),
not_enabled=not_en
)
@@ -251,7 +251,7 @@ class MigrationEnqueuedCourse(TimeStampedModel):
command_run = PositiveIntegerField(default=0)
def __str__(self):
- return 'MigrationEnqueuedCourse: ID={course_id}, Run={command_run}'.format(
+ return 'MigrationEnqueuedCourse: ID={course_id}, Run={command_run}'.format( # noqa: UP032
course_id=self.course_id, command_run=self.command_run
)
@@ -312,6 +312,6 @@ class Meta:
unique_together = ('course_id', 'edx_video_id')
def __str__(self):
- return 'UpdatedCourseVideos: CourseID={course_id}, VideoID={video_id}, Run={command_run}'.format(
+ return 'UpdatedCourseVideos: CourseID={course_id}, VideoID={video_id}, Run={command_run}'.format( # noqa: UP032
course_id=self.course_id, video_id=self.edx_video_id, command_run=self.command_run
)
diff --git a/openedx/core/djangoapps/video_config/sharing.py b/openedx/core/djangoapps/video_config/sharing.py
index 4cc66cdb0530..d37a3889e2ee 100644
--- a/openedx/core/djangoapps/video_config/sharing.py
+++ b/openedx/core/djangoapps/video_config/sharing.py
@@ -41,7 +41,7 @@ def is_public_sharing_enabled(usage_key: UsageKey, public_access: bool) -> bool:
try:
# Video share feature must be enabled for sharing settings to take effect
feature_enabled = PUBLIC_VIDEO_SHARE.is_enabled(usage_key.context_key)
- except Exception as err: # pylint: disable=broad-except
+ except Exception as err: # pylint: disable=broad-except # noqa: F841
log.exception(f"Error retrieving course for course ID: {usage_key.context_key}")
return False
@@ -76,6 +76,6 @@ def get_course_video_sharing_override(usage_key: UsageKey) -> str | None:
try:
course = get_course_by_id(usage_key.context_key)
return getattr(course, 'video_sharing_options', None)
- except Exception as err: # pylint: disable=broad-except
+ except Exception as err: # pylint: disable=broad-except # noqa: F841
log.exception(f"Error retrieving course for course ID: {usage_key.context_key}")
return None
diff --git a/openedx/core/djangoapps/video_config/tests/test_transcripts_utils.py b/openedx/core/djangoapps/video_config/tests/test_transcripts_utils.py
index a7c65efda8bb..6004a5cc143a 100644
--- a/openedx/core/djangoapps/video_config/tests/test_transcripts_utils.py
+++ b/openedx/core/djangoapps/video_config/tests/test_transcripts_utils.py
@@ -118,7 +118,7 @@ def test_get_transcript_link_from_youtube(self, language_code, mock_get):
mock_get.return_value = YoutubeVideoHTMLResponse.with_caption_track(language_code)
language_specific_caption_link = get_transcript_link_from_youtube(YOUTUBE_VIDEO_ID)
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
language_specific_caption_link,
{language_code: CAPTION_URL_UTF8_DECODED_TEMPLATE.format(language_code)}
)
@@ -132,7 +132,7 @@ def test_get_caption_no_caption(self, language_code, mock_get):
mock_get.return_value = YoutubeVideoHTMLResponse.with_caption_track(language_code)
english_language_caption_link = get_transcript_link_from_youtube(YOUTUBE_VIDEO_ID)
- self.assertIsNone(english_language_caption_link)
+ self.assertIsNone(english_language_caption_link) # noqa: PT009
@ mock.patch('requests.get')
def test_get_caption_malformed_caption_locator(self, mock_get):
@@ -143,4 +143,4 @@ def test_get_caption_malformed_caption_locator(self, mock_get):
mock_get.return_value = YoutubeVideoHTMLResponse.with_malformed_caption_track(language_code)
english_language_caption_link = get_transcript_link_from_youtube(YOUTUBE_VIDEO_ID)
- self.assertIsNone(english_language_caption_link)
+ self.assertIsNone(english_language_caption_link) # noqa: PT009
diff --git a/openedx/core/djangoapps/video_config/transcripts_utils.py b/openedx/core/djangoapps/video_config/transcripts_utils.py
index e6f747537fa8..c76a2b8b0377 100644
--- a/openedx/core/djangoapps/video_config/transcripts_utils.py
+++ b/openedx/core/djangoapps/video_config/transcripts_utils.py
@@ -69,7 +69,7 @@ def wrapper(*args, **kwds):
return func(*args, **kwds)
except (TranscriptsGenerationException, UnicodeDecodeError) as ex:
log.exception(str(ex))
- raise NotFoundError # lint-amnesty, pylint: disable=raise-missing-from
+ raise NotFoundError # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return wrapper
@@ -310,7 +310,7 @@ def generate_subs_from_source(speed_subs, subs_type, subs_filedata, block, langu
msg = _("Something wrong with SubRip transcripts file during parsing. Inner message is {error_message}").format(
error_message=str(ex)
)
- raise TranscriptsGenerationException(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise TranscriptsGenerationException(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not srt_subs_obj:
raise TranscriptsGenerationException(_("Something wrong with SubRip transcripts file during parsing."))
@@ -468,7 +468,7 @@ def youtube_speed_dict(item):
"""
yt_ids = [item.youtube_id_0_75, item.youtube_id_1_0, item.youtube_id_1_25, item.youtube_id_1_5]
yt_speeds = [0.75, 1.00, 1.25, 1.50]
- youtube_ids = {p[0]: p[1] for p in zip(yt_ids, yt_speeds) if p[0]}
+ youtube_ids = {p[0]: p[1] for p in zip(yt_ids, yt_speeds) if p[0]} # noqa: B905
return youtube_ids
@@ -491,7 +491,7 @@ def generate_sjson_for_all_speeds(block, user_filename, result_subs_dict, lang):
try:
srt_transcripts = contentstore().find(Transcript.asset_location(block.location, user_filename))
except NotFoundError as ex:
- raise TranscriptException(_("{exception_message}: Can't find uploaded transcripts: {user_filename}").format( # lint-amnesty, pylint: disable=raise-missing-from
+ raise TranscriptException(_("{exception_message}: Can't find uploaded transcripts: {user_filename}").format( # noqa: B904 # pylint: disable=raise-missing-from,line-too-long
exception_message=str(ex),
user_filename=user_filename
))
@@ -912,7 +912,7 @@ def get_transcript_from_contentstore(video, language, output_format, transcripts
continue
if transcript_content is None:
- raise NotFoundError('No transcript for `{lang}` language'.format(
+ raise NotFoundError('No transcript for `{lang}` language'.format( # noqa: UP032
lang=language
))
@@ -1090,7 +1090,7 @@ def resolve_language_code_to_transcript_code(transcripts, dest_lang):
"""
Attempts to match the requested dest lang with the existing transcript languages
"""
- sub, other_lang = transcripts["sub"], transcripts["transcripts"]
+ sub, other_lang = transcripts["sub"], transcripts["transcripts"] # noqa: F841
# lang code exists in list of other transcript languages as-is
if dest_lang in other_lang:
return dest_lang
diff --git a/openedx/core/djangoapps/video_pipeline/forms.py b/openedx/core/djangoapps/video_pipeline/forms.py
index 80eb041012d9..6f87b29a1e48 100644
--- a/openedx/core/djangoapps/video_pipeline/forms.py
+++ b/openedx/core/djangoapps/video_pipeline/forms.py
@@ -23,4 +23,4 @@ class VEMPipelineIntegrationAdminForm(forms.ModelForm):
"""
class Meta:
model = VEMPipelineIntegration
- fields = '__all__'
+ fields = '__all__' # noqa: DJ007
diff --git a/openedx/core/djangoapps/video_pipeline/models.py b/openedx/core/djangoapps/video_pipeline/models.py
index df118297f892..64617399d9fc 100644
--- a/openedx/core/djangoapps/video_pipeline/models.py
+++ b/openedx/core/djangoapps/video_pipeline/models.py
@@ -95,7 +95,7 @@ def feature_enabled(cls, course_id):
def __str__(self):
current_model = VideoUploadsEnabledByDefault.current()
- return "VideoUploadsEnabledByDefault: enabled {is_enabled}".format(
+ return "VideoUploadsEnabledByDefault: enabled {is_enabled}".format( # noqa: UP032
is_enabled=current_model.is_enabled()
)
@@ -124,7 +124,7 @@ def __str__(self):
if self.enabled:
not_en = ""
- return "Course '{course_key}': Video Uploads {not_enabled}Enabled by default.".format(
+ return "Course '{course_key}': Video Uploads {not_enabled}Enabled by default.".format( # noqa: UP032
course_key=str(self.course_id),
not_enabled=not_en
)
diff --git a/openedx/core/djangoapps/video_pipeline/tests/test_api.py b/openedx/core/djangoapps/video_pipeline/tests/test_api.py
index 35cc9eaf2998..917d5049d3fe 100644
--- a/openedx/core/djangoapps/video_pipeline/tests/test_api.py
+++ b/openedx/core/djangoapps/video_pipeline/tests/test_api.py
@@ -66,7 +66,7 @@ def test_update_transcription_service_credentials(self, credentials_payload, moc
error_response, is_updated = update_3rd_party_transcription_service_credentials(**credentials_payload)
# Making sure log.exception is not called.
- self.assertDictEqual(error_response, {})
+ self.assertDictEqual(error_response, {}) # noqa: PT009
assert not mock_logger.exception.called
assert is_updated
@@ -97,7 +97,7 @@ def test_update_transcription_service_credentials_exceptions(self, mock_client,
# Assert the results.
assert not is_updated
- self.assertDictEqual(error_response, json.loads(error_content))
+ self.assertDictEqual(error_response, json.loads(error_content)) # noqa: PT009
mock_logger.exception.assert_called_with(
'Unable to update transcript credentials -- org=%s, provider=%s, response=%s',
credentials_payload['org'],
diff --git a/openedx/core/djangoapps/waffle_utils/forms.py b/openedx/core/djangoapps/waffle_utils/forms.py
index 18592eddac7d..86a336201e6c 100644
--- a/openedx/core/djangoapps/waffle_utils/forms.py
+++ b/openedx/core/djangoapps/waffle_utils/forms.py
@@ -15,7 +15,7 @@ class WaffleFlagCourseOverrideAdminForm(forms.ModelForm):
"""
class Meta:
model = WaffleFlagCourseOverrideModel
- fields = '__all__'
+ fields = '__all__' # noqa: DJ007
def clean_course_id(self):
"""
@@ -42,7 +42,7 @@ class WaffleFlagOrgOverrideAdminForm(forms.ModelForm):
"""
class Meta:
model = WaffleFlagOrgOverrideModel
- fields = '__all__'
+ fields = '__all__' # noqa: DJ007
def clean_org(self):
"""
diff --git a/openedx/core/djangoapps/xblock/api.py b/openedx/core/djangoapps/xblock/api.py
index 9a9ee2bcbb68..0ab620db9ab3 100644
--- a/openedx/core/djangoapps/xblock/api.py
+++ b/openedx/core/djangoapps/xblock/api.py
@@ -8,17 +8,17 @@
Studio APIs cover use cases like adding/deleting/editing blocks.
"""
import logging
-import threading # pylint: disable=unused-import
-from datetime import datetime # pylint: disable=unused-import
+import threading # pylint: disable=unused-import # noqa: F401
+from datetime import datetime # pylint: disable=unused-import # noqa: F401
# pylint: disable=unused-import
-from enum import Enum
+from enum import Enum # noqa: F401
from django.core.exceptions import PermissionDenied
from django.urls import reverse
from django.utils.translation import gettext as _
from opaque_keys.edx.keys import UsageKeyV2
-from opaque_keys.edx.locator import LibraryUsageLocatorV2
+from opaque_keys.edx.locator import LibraryUsageLocatorV2 # noqa: F401
from openedx_content import api as content_api
from openedx_content.models_api import Component, ComponentVersion
from rest_framework.exceptions import NotFound
@@ -29,7 +29,7 @@
from openedx.core.djangoapps.xblock.apps import get_xblock_app_config
# Made available as part of this package's public API:
-from openedx.core.djangoapps.xblock.learning_context import LearningContext
+from openedx.core.djangoapps.xblock.learning_context import LearningContext # noqa: F401
from openedx.core.djangoapps.xblock.learning_context.manager import get_learning_context_impl
from openedx.core.djangoapps.xblock.runtime.openedx_content_runtime import (
OpenedXContentFieldData,
@@ -38,8 +38,8 @@
from openedx.core.types import User as UserType
from .data import CheckPerm, LatestVersion
-from .rest_api.url_converters import VersionConverter
-from .runtime.openedx_content_runtime import OpenedXContentRuntime
+from .rest_api.url_converters import VersionConverter # noqa: F401
+from .runtime.openedx_content_runtime import OpenedXContentRuntime # noqa: F811
from .utils import get_auto_latest_version, get_secure_token_for_xblock_handler, get_xblock_id_for_anonymous_user
# Implementation:
diff --git a/openedx/core/djangoapps/xblock/learning_context/__init__.py b/openedx/core/djangoapps/xblock/learning_context/__init__.py
index d4bad77ed934..b28484fbff67 100644
--- a/openedx/core/djangoapps/xblock/learning_context/__init__.py
+++ b/openedx/core/djangoapps/xblock/learning_context/__init__.py
@@ -2,4 +2,4 @@
A "Learning Context" is a course, a library, a program, or some other collection
of content where learning happens.
"""
-from .learning_context import LearningContext
+from .learning_context import LearningContext # noqa: F401
diff --git a/openedx/core/djangoapps/xblock/rest_api/views.py b/openedx/core/djangoapps/xblock/rest_api/views.py
index 484336861eee..97a519beecfa 100644
--- a/openedx/core/djangoapps/xblock/rest_api/views.py
+++ b/openedx/core/djangoapps/xblock/rest_api/views.py
@@ -125,7 +125,7 @@ def embed_block_view(request, usage_key: UsageKeyV2, view_name: str):
new_oa_manifest = {}
if oa_manifest_path.exists():
- with open(oa_manifest_path, "r") as f:
+ with open(oa_manifest_path, "r") as f: # noqa: UP015
oa_manifest = json.load(f)
new_oa_manifest = {
# When we add the RTL style, it automatically applies that style (right-to-left reading) regardless
diff --git a/openedx/core/djangoapps/xblock/runtime/openedx_content_runtime.py b/openedx/core/djangoapps/xblock/runtime/openedx_content_runtime.py
index 1d7f95e150f5..e943c85057ac 100644
--- a/openedx/core/djangoapps/xblock/runtime/openedx_content_runtime.py
+++ b/openedx/core/djangoapps/xblock/runtime/openedx_content_runtime.py
@@ -288,7 +288,7 @@ def save_block(self, block):
raise RuntimeError("You do not have permission to edit this XBlock")
serialized = serialize_modulestore_block_for_openedx_content(block)
- now = datetime.now(tz=timezone.utc)
+ now = datetime.now(tz=timezone.utc) # noqa: UP017
usage_key = block.scope_ids.usage_id
with atomic():
component = self._get_component_from_usage_key(usage_key)
@@ -454,7 +454,7 @@ def _lookup_asset_url(self, block: XBlock, asset_path: str) -> str | None:
# Retry with unquoted path. We don't always unquote because it would not
# be backwards-compatible, but we need to try both.
asset_path = unquote(asset_path)
- media = (
+ media = ( # noqa: F841
component_version
.componentversionmedia_set
.filter(media__has_file=True)
diff --git a/openedx/core/djangoapps/xblock/runtime/runtime.py b/openedx/core/djangoapps/xblock/runtime/runtime.py
index caa789a34dd6..f3544a6102d8 100644
--- a/openedx/core/djangoapps/xblock/runtime/runtime.py
+++ b/openedx/core/djangoapps/xblock/runtime/runtime.py
@@ -2,7 +2,7 @@
Common base classes for all new XBlock runtimes.
"""
import logging
-from typing import Callable, Protocol
+from typing import Callable, Protocol # noqa: UP035
from urllib.parse import urljoin # pylint: disable=import-error
import crum
@@ -371,7 +371,7 @@ def _init_field_data_for_block(self, block: XBlock) -> FieldData:
student_data_store = DictFieldData({})
elif self.user.is_anonymous:
# This is an anonymous (non-registered) user:
- assert isinstance(self.user_id, str) and self.user_id.startswith("anon")
+ assert isinstance(self.user_id, str) and self.user_id.startswith("anon") # noqa: PT018
kvs = EphemeralKeyValueStore()
student_data_store = KvsFieldData(kvs)
elif self.student_data_mode == StudentDataMode.Ephemeral:
diff --git a/openedx/core/djangoapps/xblock/tests/test_utils.py b/openedx/core/djangoapps/xblock/tests/test_utils.py
index d38b8b943ec6..0a7a2b0bfd56 100644
--- a/openedx/core/djangoapps/xblock/tests/test_utils.py
+++ b/openedx/core/djangoapps/xblock/tests/test_utils.py
@@ -24,13 +24,13 @@
"validation_xblock_handler_token_keys": None,
# A reference time that produces a token that will expire within the next day
# but not for a few hours.
- "reference_time": datetime.datetime(2021, 1, 28, 13, 26, 38, 787309, datetime.timezone.utc),
+ "reference_time": datetime.datetime(2021, 1, 28, 13, 26, 38, 787309, datetime.timezone.utc), # noqa: UP017
"validation_time_delta_s": 0,
}
@pytest.mark.parametrize(
- "param_delta,expected_validation",
+ "param_delta,expected_validation", # noqa: PT006
[
# Happy Path case with the above REFERENCE_PARAMS.
({}, True),
@@ -48,7 +48,7 @@
# Demonstrating maximum possible validity period is just below 4 days
# This passes because validation time is just below the cutoff point
(
- {"reference_time": datetime.datetime(2021, 1, 27, 0, 0, 20, tzinfo=datetime.timezone.utc),
+ {"reference_time": datetime.datetime(2021, 1, 27, 0, 0, 20, tzinfo=datetime.timezone.utc), # noqa: UP017
"validation_time_delta_s": (86400 * 4) - 21
},
True,
@@ -57,7 +57,7 @@
# Demonstrating maximum possible validity period is just below 4 days
# This does not pass because validation time is just above the cutoff point
(
- {"reference_time": datetime.datetime(2021, 1, 27, 0, 0, 20, tzinfo=datetime.timezone.utc),
+ {"reference_time": datetime.datetime(2021, 1, 27, 0, 0, 20, tzinfo=datetime.timezone.utc), # noqa: UP017
"validation_time_delta_s": (86400 * 4) - 19
},
False,
@@ -66,7 +66,7 @@
# Demonstrating minimum possible validity period is just above 2 days
# This passes because validation time is just below the cutoff point
(
- {"reference_time": datetime.datetime(2021, 1, 28, 23, 59, 40, tzinfo=datetime.timezone.utc),
+ {"reference_time": datetime.datetime(2021, 1, 28, 23, 59, 40, tzinfo=datetime.timezone.utc), # noqa: UP017
"validation_time_delta_s": (86400 * 2) + 19
},
True,
@@ -75,7 +75,7 @@
# Demonstrating minimum possible validity period is just above 2 days
# This fails because validation time is just above the cutoff point
(
- {"reference_time": datetime.datetime(2021, 1, 28, 23, 59, 40, tzinfo=datetime.timezone.utc),
+ {"reference_time": datetime.datetime(2021, 1, 28, 23, 59, 40, tzinfo=datetime.timezone.utc), # noqa: UP017
"validation_time_delta_s": (86400 * 2) + 21
},
False),
@@ -162,7 +162,7 @@ def test_private_get_secure_token_for_xblock_handler():
Confirms function behaviour has not changed and is giving the same token for same inputs
If these tokens change, this will invalidate some or all of the tokens handed out to learners
"""
- with freeze_time(datetime.datetime(2021, 1, 27, 0, 0, 0, tzinfo=datetime.timezone.utc)):
+ with freeze_time(datetime.datetime(2021, 1, 27, 0, 0, 0, tzinfo=datetime.timezone.utc)): # noqa: UP017
token_now = _get_secure_token_for_xblock_handler("12345", "some_block_key", 0, "some_hashing_key")
token_previous = _get_secure_token_for_xblock_handler("12345", "some_block_key", -1, "some_hashing_key")
assert token_now == "de8399a51fef6aa7584a"
diff --git a/openedx/core/djangoapps/zendesk_proxy/tests/test_v0_views.py b/openedx/core/djangoapps/zendesk_proxy/tests/test_v0_views.py
index 5bb0d5fc19f7..8cc6b168a8a6 100644
--- a/openedx/core/djangoapps/zendesk_proxy/tests/test_v0_views.py
+++ b/openedx/core/djangoapps/zendesk_proxy/tests/test_v0_views.py
@@ -45,7 +45,7 @@ def test_post(self):
self.assertHttpCreated(response)
(mock_args, mock_kwargs) = mock_post.call_args
assert mock_args == ('https://www.superrealurlsthataredefinitelynotfake.com/api/v2/tickets.json',)
- self.assertCountEqual(mock_kwargs.keys(), ['headers', 'data'])
+ self.assertCountEqual(mock_kwargs.keys(), ['headers', 'data']) # noqa: PT009
assert mock_kwargs['headers'] == {
'content-type': 'application/json', 'Authorization': 'Bearer abcdefghijklmnopqrstuvwxyz1234567890'
}
diff --git a/openedx/core/djangoapps/zendesk_proxy/tests/test_v1_views.py b/openedx/core/djangoapps/zendesk_proxy/tests/test_v1_views.py
index ed3a6cb2597b..9c2efe340fab 100644
--- a/openedx/core/djangoapps/zendesk_proxy/tests/test_v1_views.py
+++ b/openedx/core/djangoapps/zendesk_proxy/tests/test_v1_views.py
@@ -69,7 +69,7 @@ def test_post(self, user_activation_status):
self.assertHttpCreated(response)
(mock_args, mock_kwargs) = mock_post.call_args
assert mock_args == ('https://www.superrealurlsthataredefinitelynotfake.com/api/v2/tickets.json',)
- self.assertCountEqual(mock_kwargs.keys(), ['headers', 'data'])
+ self.assertCountEqual(mock_kwargs.keys(), ['headers', 'data']) # noqa: PT009
assert mock_kwargs['headers'] == {
'content-type': 'application/json', 'Authorization': 'Bearer abcdefghijklmnopqrstuvwxyz1234567890'
}
diff --git a/openedx/core/djangoapps/zendesk_proxy/utils.py b/openedx/core/djangoapps/zendesk_proxy/utils.py
index 9ddfa2874686..ccfa5eabb3af 100644
--- a/openedx/core/djangoapps/zendesk_proxy/utils.py
+++ b/openedx/core/djangoapps/zendesk_proxy/utils.py
@@ -99,7 +99,7 @@ def create_zendesk_ticket(
except (ValueError, KeyError):
log.error(
_std_error_message(
- "Got an unexpected response from zendesk api. Can't"
+ "Got an unexpected response from zendesk api. Can't" # noqa: UP032
" get the ticket number to add extra info. {}".format(additional_info),
response.content
)
diff --git a/openedx/core/djangolib/default_auth_classes.py b/openedx/core/djangolib/default_auth_classes.py
index 651bd79238a4..6ad01a302c01 100644
--- a/openedx/core/djangolib/default_auth_classes.py
+++ b/openedx/core/djangolib/default_auth_classes.py
@@ -28,7 +28,7 @@ def authenticate(self, request):
else:
set_custom_attribute('session_auth_result', 'n/a')
return user_and_auth
- except Exception as exception:
+ except Exception as exception: # noqa: F841
set_custom_attribute('session_auth_result', 'failure')
raise
diff --git a/openedx/core/djangolib/testing/utils.py b/openedx/core/djangolib/testing/utils.py
index 20003462064c..60b012607380 100644
--- a/openedx/core/djangolib/testing/utils.py
+++ b/openedx/core/djangolib/testing/utils.py
@@ -202,7 +202,7 @@ def is_unfiltered_query(query):
executed = len(filtered_queries)
assert executed == self.num, (
- '%d queries executed, %d expected\nCaptured queries were:\n%s' % (
+ '%d queries executed, %d expected\nCaptured queries were:\n%s' % ( # noqa: UP031
executed, self.num, '\n'.join(query['sql'] for query in filtered_queries)
)
)
diff --git a/openedx/core/djangolib/tests/test_js_utils.py b/openedx/core/djangolib/tests/test_js_utils.py
index e528ac35f206..ad2a29a33e9e 100644
--- a/openedx/core/djangolib/tests/test_js_utils.py
+++ b/openedx/core/djangolib/tests/test_js_utils.py
@@ -72,7 +72,7 @@ def test_js_escaped_string_escapes_unsafe_html(self):
"""
malicious_js_string = ""
- expected_escaped_string_for_js = str(
+ expected_escaped_string_for_js = str( # noqa: UP018
r"\u003C/script\u003E\u003Cscript\u003Ealert(\u0027hello, \u0027)\u003B\u003C/script\u003E"
)
escaped_string_for_js = js_escaped_string(malicious_js_string)
diff --git a/openedx/core/lib/api/authentication.py b/openedx/core/lib/api/authentication.py
index 04c6c53ba93c..86770f71fe5e 100644
--- a/openedx/core/lib/api/authentication.py
+++ b/openedx/core/lib/api/authentication.py
@@ -75,7 +75,7 @@ def authenticate_credentials(self, access_token):
try:
token = self.get_access_token(access_token)
except AuthenticationFailed as exc:
- raise AuthenticationFailed({ # lint-amnesty, pylint: disable=raise-missing-from
+ raise AuthenticationFailed({ # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
'error_code': OAUTH2_TOKEN_ERROR,
'developer_message': exc.detail
})
@@ -94,7 +94,7 @@ def authenticate_credentials(self, access_token):
user = token.user
has_application = dot_models.Application.objects.filter(user_id=user.id)
if not user.has_usable_password() and not has_application:
- msg = 'User disabled by admin: %s' % user.get_username()
+ msg = 'User disabled by admin: %s' % user.get_username() # noqa: UP031
raise AuthenticationFailed({
'error_code': OAUTH2_USER_DISABLED_ERROR,
'developer_message': msg})
@@ -102,7 +102,7 @@ def authenticate_credentials(self, access_token):
# 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: # lint-amnesty, pylint: disable=no-else-raise
set_custom_attribute("BearerAuthentication_user_active", False)
- msg = 'User inactive or deleted: %s' % user.get_username()
+ msg = 'User inactive or deleted: %s' % user.get_username() # noqa: UP031
raise AuthenticationFailed({
'error_code': OAUTH2_USER_NOT_ACTIVE_ERROR,
'developer_message': msg})
@@ -124,7 +124,7 @@ def authenticate_header(self, request):
Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response
"""
- return 'Bearer realm="%s"' % self.www_authenticate_realm
+ return 'Bearer realm="%s"' % self.www_authenticate_realm # noqa: UP031
class BearerAuthenticationAllowInactiveUser(BearerAuthentication):
diff --git a/openedx/core/lib/api/fields.py b/openedx/core/lib/api/fields.py
index 0f8e5ddf186d..78830e052dc8 100644
--- a/openedx/core/lib/api/fields.py
+++ b/openedx/core/lib/api/fields.py
@@ -13,7 +13,7 @@ class ExpandableField(Field): # lint-amnesty, pylint: disable=abstract-method
def __init__(self, **kwargs):
"""Sets up the ExpandableField with the collapsed and expanded versions of the serializer."""
- assert 'collapsed_serializer' in kwargs and 'expanded_serializer' in kwargs
+ assert 'collapsed_serializer' in kwargs and 'expanded_serializer' in kwargs # noqa: PT018
self.collapsed = kwargs.pop('collapsed_serializer')
self.expanded = kwargs.pop('expanded_serializer')
super().__init__(**kwargs)
@@ -47,7 +47,7 @@ def to_representation(self, value):
request = self.context.get('request', None)
assert request is not None, (
- "`%s` requires the request in the serializer context. "
+ "`%s` requires the request in the serializer context. " # noqa: UP031
"Add `context={'request': request}` when instantiating the serializer." % self.__class__.__name__
)
diff --git a/openedx/core/lib/api/permissions.py b/openedx/core/lib/api/permissions.py
index be999647532d..127c3c5d00ab 100644
--- a/openedx/core/lib/api/permissions.py
+++ b/openedx/core/lib/api/permissions.py
@@ -93,7 +93,7 @@ def has_permission(self, request, view):
try:
course_key = CourseKey.from_string(master_course_id)
except InvalidKeyError:
- raise Http404() # lint-amnesty, pylint: disable=raise-missing-from
+ raise Http404() # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return (hasattr(request, 'user') and
(CourseInstructorRole(course_key).has_user(request.user) or
CourseStaffRole(course_key).has_user(request.user)))
diff --git a/openedx/core/lib/api/test_utils.py b/openedx/core/lib/api/test_utils.py
index 6a647b485427..1c716092e40a 100644
--- a/openedx/core/lib/api/test_utils.py
+++ b/openedx/core/lib/api/test_utils.py
@@ -49,7 +49,7 @@ def assertAllowedMethods(self, uri, expected_methods):
allow_header = resp.get("Allow")
assert allow_header is not None
allowed_methods = re.split('[^A-Z]+', allow_header)
- self.assertCountEqual(allowed_methods, expected_methods)
+ self.assertCountEqual(allowed_methods, expected_methods) # noqa: PT009
def assertSelfReferential(self, obj):
"""Assert that accessing the "url" entry in the given object returns the same object"""
diff --git a/openedx/core/lib/api/tests/test_authentication.py b/openedx/core/lib/api/tests/test_authentication.py
index 6934fb96aa8c..8a53f3b2f92a 100644
--- a/openedx/core/lib/api/tests/test_authentication.py
+++ b/openedx/core/lib/api/tests/test_authentication.py
@@ -142,7 +142,7 @@ def test_get_form_passing_auth_with_dot(self):
def test_get_form_failing_auth_url_transport(self):
"""Ensure GETing form over OAuth with correct client credentials in query fails when DEBUG is False"""
query = urlencode({'access_token': self.dot_access_token.token})
- response = self.csrf_client.get(self.OAUTH2_BASE_TESTING_URL + '?%s' % query)
+ response = self.csrf_client.get(self.OAUTH2_BASE_TESTING_URL + '?%s' % query) # noqa: UP031
assert response.status_code == status.HTTP_401_UNAUTHORIZED
# This case is handled directly by DRF so no error_code is provided (yet).
diff --git a/openedx/core/lib/api/tests/test_fields.py b/openedx/core/lib/api/tests/test_fields.py
index f23756fb0e4b..b58cbce213e0 100644
--- a/openedx/core/lib/api/tests/test_fields.py
+++ b/openedx/core/lib/api/tests/test_fields.py
@@ -27,7 +27,7 @@ def setUp(self):
def test_to_representation_without_request(self):
""" Verify an AssertionError is raised if no request is passed as context to the field. """
self.field._context = {} # pylint:disable=protected-access
- self.assertRaises(AssertionError, self.field.to_representation, '/image.jpg')
+ self.assertRaises(AssertionError, self.field.to_representation, '/image.jpg') # noqa: PT027
@ddt.data(
'http://example.com',
diff --git a/openedx/core/lib/api/tests/test_parsers.py b/openedx/core/lib/api/tests/test_parsers.py
index f9af1e850c5d..12ed72e40c73 100644
--- a/openedx/core/lib/api/tests/test_parsers.py
+++ b/openedx/core/lib/api/tests/test_parsers.py
@@ -84,7 +84,7 @@ def test_parse_mismatched_filename_and_mimetype(self):
HTTP_CONTENT_DISPOSITION='attachment; filename="file.jpg"',
)
context = {'view': self.view, 'request': request}
- with pytest.raises(exceptions.ParseError) as err:
+ with pytest.raises(exceptions.ParseError) as err: # noqa: PT012
self.parser.parse(stream=BytesIO(b'abcdefgh'), media_type='image/png', parser_context=context)
assert 'developer_message' in err.detail
# lint-amnesty, pylint: disable=no-member
@@ -105,7 +105,7 @@ def test_no_acceptable_types(self):
HTTP_CONTENT_DISPOSITION='attachment; filename="file.png"',
)
context = {'view': view, 'request': request}
- with pytest.raises(exceptions.UnsupportedMediaType) as err:
+ with pytest.raises(exceptions.UnsupportedMediaType) as err: # noqa: PT012
self.parser.parse(stream=BytesIO(b'abcdefgh'), media_type='image/png', parser_context=context)
assert 'developer_message' in err.detail
# lint-amnesty, pylint: disable=no-member
diff --git a/openedx/core/lib/api/view_utils.py b/openedx/core/lib/api/view_utils.py
index d876e49ae579..ac8aac610ab8 100644
--- a/openedx/core/lib/api/view_utils.py
+++ b/openedx/core/lib/api/view_utils.py
@@ -291,7 +291,7 @@ def __getitem__(self, index):
self._data.append(next(self.iterable))
except StopIteration:
self._exhausted = True
- raise IndexError("Underlying sequence exhausted") # lint-amnesty, pylint: disable=raise-missing-from
+ raise IndexError("Underlying sequence exhausted") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
return self._data[index]
elif isinstance(index, slice):
@@ -324,12 +324,12 @@ def __getitem__(self, index):
def __repr__(self):
if self._exhausted:
- return "LazySequence({!r}, {!r})".format(
+ return "LazySequence({!r}, {!r})".format( # noqa: UP032
self._data,
self.est_len,
)
else:
- return "LazySequence(itertools.chain({!r}, {!r}), {!r})".format(
+ return "LazySequence(itertools.chain({!r}, {!r}), {!r})".format( # noqa: UP032
self._data,
self.iterable,
self.est_len,
diff --git a/openedx/core/lib/command_utils.py b/openedx/core/lib/command_utils.py
index dd9936f5dd65..c5cae3d2b125 100644
--- a/openedx/core/lib/command_utils.py
+++ b/openedx/core/lib/command_utils.py
@@ -46,4 +46,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(f'Invalid key specified: {str(error)}') # lint-amnesty, pylint: disable=raise-missing-from
+ raise CommandError(f'Invalid key specified: {str(error)}') # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
diff --git a/openedx/core/lib/courses.py b/openedx/core/lib/courses.py
index df806711e9fa..e0469bd3be70 100644
--- a/openedx/core/lib/courses.py
+++ b/openedx/core/lib/courses.py
@@ -83,7 +83,7 @@ def clean_course_id(model_form, is_required=True):
course_key = CourseKey.from_string(cleaned_id)
except InvalidKeyError:
msg = f'Course id invalid. Entered course id was: "{cleaned_id}".'
- raise forms.ValidationError(msg) # lint-amnesty, pylint: disable=raise-missing-from
+ raise forms.ValidationError(msg) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if not modulestore().has_course(course_key):
msg = f'Course not found. Entered course id was: "{str(course_key)}".'
diff --git a/openedx/core/lib/derived.py b/openedx/core/lib/derived.py
index 45ea0e218689..366573337471 100644
--- a/openedx/core/lib/derived.py
+++ b/openedx/core/lib/derived.py
@@ -11,13 +11,13 @@
import types
import typing as t
-Settings: t.TypeAlias = types.ModuleType
+Settings: t.TypeAlias = types.ModuleType # noqa: UP040
T = t.TypeVar('T')
-class Derived(t.Generic[T]):
+class Derived(t.Generic[T]): # noqa: UP046
"""
A temporary Django setting value, defined with a function which generates the setting's eventual value.
diff --git a/openedx/core/lib/edx_api_utils.py b/openedx/core/lib/edx_api_utils.py
index 90c45ce17eaa..0ec4eed9c98c 100644
--- a/openedx/core/lib/edx_api_utils.py
+++ b/openedx/core/lib/edx_api_utils.py
@@ -2,7 +2,7 @@
import logging
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union # noqa: UP035
from urllib.parse import urljoin
from django.core.cache import cache
@@ -28,15 +28,15 @@ def get_api_data(
resource: str,
api_client: "session",
base_api_url: str,
- resource_id: Optional[Union[int, str]] = None,
- querystring: Optional[Dict[Any, Any]] = None,
- cache_key: Optional[str] = None,
+ resource_id: Optional[Union[int, str]] = None, # noqa: UP007, UP045
+ querystring: Optional[Dict[Any, Any]] = None, # noqa: UP006, UP045
+ cache_key: Optional[str] = None, # noqa: UP045
many: bool = True,
traverse_pagination: bool = True,
- fields: Optional[List[Any]] = None,
+ fields: Optional[List[Any]] = None, # noqa: UP006, UP045
long_term_cache: bool = False,
raise_on_error: bool = False,
-) -> Union[List[Any], Dict[Any, Any]]:
+) -> Union[List[Any], Dict[Any, Any]]: # noqa: UP006, UP007
"""
GET data from an edX REST API endpoint using the API client.
diff --git a/openedx/core/lib/extract_archive.py b/openedx/core/lib/extract_archive.py
index e0175141d662..d3de59c2527f 100644
--- a/openedx/core/lib/extract_archive.py
+++ b/openedx/core/lib/extract_archive.py
@@ -10,7 +10,7 @@
from os.path import abspath, dirname, realpath
from os.path import join as joinpath
from tarfile import TarFile, TarInfo
-from typing import List, Union
+from typing import List, Union # noqa: UP035
from zipfile import ZipFile, ZipInfo
from django.conf import settings
@@ -64,7 +64,7 @@ def _check_tarinfo(finfo: TarInfo, base: str):
raise SuspiciousOperation("Dev file")
-def _checkmembers(members: Union[List[ZipInfo], List[TarInfo]], base: str):
+def _checkmembers(members: Union[List[ZipInfo], List[TarInfo]], base: str): # noqa: UP006, UP007
"""
Check that all elements of the archive file are safe.
"""
diff --git a/openedx/core/lib/gating/api.py b/openedx/core/lib/gating/api.py
index 24524ced3d30..42dfed6b9976 100644
--- a/openedx/core/lib/gating/api.py
+++ b/openedx/core/lib/gating/api.py
@@ -37,7 +37,7 @@ def _get_prerequisite_milestone(prereq_content_key):
Returns:
dict: Milestone dict
"""
- milestones = milestones_api.get_milestones("{usage_key}{qualifier}".format(
+ milestones = milestones_api.get_milestones("{usage_key}{qualifier}".format( # noqa: UP032
usage_key=prereq_content_key,
qualifier=GATING_NAMESPACE_QUALIFIER
))
@@ -72,7 +72,7 @@ def _validate_min_score(min_score):
try:
min_score = int(min_score)
except ValueError:
- raise GatingValidationError(message) # lint-amnesty, pylint: disable=raise-missing-from
+ raise GatingValidationError(message) # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if min_score < 0 or min_score > 100:
raise GatingValidationError(message)
@@ -184,7 +184,7 @@ def add_prerequisite(course_key, prereq_content_key):
milestone = milestones_api.add_milestone(
{
'name': _('Gating milestone for {usage_key}').format(usage_key=str(prereq_content_key)),
- 'namespace': "{usage_key}{qualifier}".format(
+ 'namespace': "{usage_key}{qualifier}".format( # noqa: UP032
usage_key=prereq_content_key,
qualifier=GATING_NAMESPACE_QUALIFIER
),
@@ -206,7 +206,7 @@ def remove_prerequisite(prereq_content_key):
Returns:
None
"""
- milestones = milestones_api.get_milestones("{usage_key}{qualifier}".format(
+ milestones = milestones_api.get_milestones("{usage_key}{qualifier}".format( # noqa: UP032
usage_key=prereq_content_key,
qualifier=GATING_NAMESPACE_QUALIFIER
))
diff --git a/openedx/core/lib/license/__init__.py b/openedx/core/lib/license/__init__.py
index e120a77eb61c..e36dd2a1176f 100644
--- a/openedx/core/lib/license/__init__.py
+++ b/openedx/core/lib/license/__init__.py
@@ -1,3 +1,3 @@
# lint-amnesty, pylint: disable=missing-module-docstring
-from .mixin import LicenseMixin
-from .wrapper import wrap_with_license
+from .mixin import LicenseMixin # noqa: F401
+from .wrapper import wrap_with_license # noqa: F401
diff --git a/openedx/core/lib/logsettings.py b/openedx/core/lib/logsettings.py
index ee78b26623ad..1b24224d757a 100644
--- a/openedx/core/lib/logsettings.py
+++ b/openedx/core/lib/logsettings.py
@@ -28,7 +28,7 @@ def get_logger_config(log_dir, # lint-amnesty, pylint: disable=unused-argument
local_loglevel = 'INFO'
hostname = platform.node().split(".")[0]
- syslog_format = ("[service_variant={service_variant}]"
+ syslog_format = ("[service_variant={service_variant}]" # noqa: UP032
"[%(name)s][env:{logging_env}] %(levelname)s "
"[{hostname} %(process)d] [user %(userid)s] [ip %(remoteip)s] [%(filename)s:%(lineno)d] "
"- %(message)s").format(service_variant=service_variant,
@@ -171,7 +171,7 @@ def get_docker_logger_config(log_dir='/var/tmp',
"""
hostname = platform.node().split(".")[0]
- syslog_format = (
+ syslog_format = ( # noqa: UP032
"[service_variant={service_variant}]"
"[%(name)s][env:{logging_env}] %(levelname)s "
"[{hostname} %(process)d] [%(filename)s:%(lineno)d] "
diff --git a/openedx/core/lib/safe_lxml/etree.py b/openedx/core/lib/safe_lxml/etree.py
index d6809403e3a6..8570a48cb649 100644
--- a/openedx/core/lib/safe_lxml/etree.py
+++ b/openedx/core/lib/safe_lxml/etree.py
@@ -14,11 +14,11 @@
from lxml.etree import XMLParser as _XMLParser
-from lxml.etree import * # lint-amnesty, pylint: disable=redefined-builtin
+from lxml.etree import * # lint-amnesty, pylint: disable=redefined-builtin # noqa: F403
# These private elements are used in some libraries to also defuse xml exploits for their own purposes.
# We need to re-expose them so that the libraries still work.
-from lxml.etree import _Comment, _Element, _ElementTree, _Entity, _ProcessingInstruction
-from .xmlparser import XML, fromstring, parse
+from lxml.etree import _Comment, _Element, _ElementTree, _Entity, _ProcessingInstruction # noqa: F401
+from .xmlparser import XML, fromstring, parse # noqa: F401
class XMLParser(_XMLParser): # pylint: disable=function-redefined
@@ -29,4 +29,4 @@ class XMLParser(_XMLParser): # pylint: disable=function-redefined
def __init__(self, *args, **kwargs):
if "resolve_entities" not in kwargs:
kwargs["resolve_entities"] = False
- super(XMLParser, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
+ super(XMLParser, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments # noqa: UP008
diff --git a/openedx/core/lib/safe_lxml/xmlparser.py b/openedx/core/lib/safe_lxml/xmlparser.py
index a463ff31477e..5512305d17a8 100644
--- a/openedx/core/lib/safe_lxml/xmlparser.py
+++ b/openedx/core/lib/safe_lxml/xmlparser.py
@@ -2,7 +2,7 @@
#
"""lxml.etree protection"""
-from __future__ import absolute_import, print_function
+from __future__ import absolute_import, print_function # noqa: UP010
import threading
@@ -41,12 +41,12 @@ def iterchildren(self, tag=None, reversed=False): # pylint: disable=redefined-b
def iter(self, tag=None, *tags): # pylint: disable=keyword-arg-before-vararg
"""Iterate over the element tree excluding blacklisted nodes."""
- iterator = super().iter(tag=tag, *tags)
+ iterator = super().iter(tag=tag, *tags) # noqa: B026
return self._filter(iterator)
def iterdescendants(self, tag=None, *tags): # pylint: disable=keyword-arg-before-vararg
"""Iterate over descendants while filtering out blacklisted nodes."""
- iterator = super().iterdescendants(tag=tag, *tags)
+ iterator = super().iterdescendants(tag=tag, *tags) # noqa: B026
return self._filter(iterator)
def itersiblings(self, tag=None, preceding=False):
diff --git a/openedx/core/lib/teams_config.py b/openedx/core/lib/teams_config.py
index 3dac37ccd904..1a9399b70419 100644
--- a/openedx/core/lib/teams_config.py
+++ b/openedx/core/lib/teams_config.py
@@ -178,7 +178,7 @@ def calc_max_team_size(self, teamset_id):
try:
teamset = self.teamsets_by_id[teamset_id]
except KeyError:
- raise ValueError(f"Team-set {teamset_id!r} does not exist.") # lint-amnesty, pylint: disable=raise-missing-from
+ raise ValueError(f"Team-set {teamset_id!r} does not exist.") # lint-amnesty, pylint: disable=raise-missing-from # noqa: B904
if teamset.teamset_type != TeamsetType.open:
return MANAGED_TEAM_MAX_TEAM_SIZE
if teamset.max_team_size:
diff --git a/openedx/core/lib/tests/assertions/events.py b/openedx/core/lib/tests/assertions/events.py
index 65d1fffdb3b0..a62f64db99f7 100644
--- a/openedx/core/lib/tests/assertions/events.py
+++ b/openedx/core/lib/tests/assertions/events.py
@@ -234,7 +234,7 @@ def compare_structs(expected, actual, should_strict_compare=None, path=None):
differences.extend(child_differences)
elif expected != actual:
- differences.append('{path}: {a} != {b} (expected != actual)'.format(
+ differences.append('{path}: {a} != {b} (expected != actual)'.format( # noqa: UP032
path=_path_to_string(path),
a=repr(expected),
b=repr(actual)
diff --git a/openedx/core/lib/tests/test_edx_api_utils.py b/openedx/core/lib/tests/test_edx_api_utils.py
index 68601caba0d6..725645408d9f 100644
--- a/openedx/core/lib/tests/test_edx_api_utils.py
+++ b/openedx/core/lib/tests/test_edx_api_utils.py
@@ -475,7 +475,7 @@ def test_data_retrieval_raise_on_error(self):
]
)
- with self.assertRaises(Exception):
+ with self.assertRaises(Exception): # noqa: B017, PT027
get_api_data(
catalog_integration,
"programs",
diff --git a/openedx/core/lib/tests/test_grade_utils.py b/openedx/core/lib/tests/test_grade_utils.py
index 9c319d5b475a..7ae8448c5984 100644
--- a/openedx/core/lib/tests/test_grade_utils.py
+++ b/openedx/core/lib/tests/test_grade_utils.py
@@ -61,5 +61,5 @@ def test_compare_scores_treat_undefined_as_zero(self):
(0.0, 0.0)
)
@ddt.unpack
- def test_round_away_from_zero(self, precise, expected_rounded_number, rounding_precision=0):
+ def test_round_away_from_zero(self, precise, expected_rounded_number, rounding_precision=0): # noqa: PT028
assert round_away_from_zero(precise, rounding_precision) == expected_rounded_number
diff --git a/openedx/core/lib/tests/test_jwt.py b/openedx/core/lib/tests/test_jwt.py
index ad2dd24d4328..c206e78e6cc3 100644
--- a/openedx/core/lib/tests/test_jwt.py
+++ b/openedx/core/lib/tests/test_jwt.py
@@ -33,7 +33,7 @@ def test_create_jwt(self):
token = create_jwt(test_user_id, test_timeout, {}, test_now)
decoded = unpack_and_verify(token)
- self.assertEqual(expected_full_token, decoded)
+ self.assertEqual(expected_full_token, decoded) # noqa: PT009
def test_create_jwt_with_claims(self):
token = create_jwt(test_user_id, test_timeout, test_claims, test_now)
@@ -42,7 +42,7 @@ def test_create_jwt_with_claims(self):
expected_token_with_claims.update(test_claims)
decoded = unpack_and_verify(token)
- self.assertEqual(expected_token_with_claims, decoded)
+ self.assertEqual(expected_token_with_claims, decoded) # noqa: PT009
def test_malformed_token(self):
token = create_jwt(test_user_id, test_timeout, test_claims, test_now)
@@ -51,7 +51,7 @@ def test_malformed_token(self):
expected_token_with_claims = expected_full_token.copy()
expected_token_with_claims.update(test_claims)
- with self.assertRaises(InvalidSignatureError):
+ with self.assertRaises(InvalidSignatureError): # noqa: PT027
unpack_and_verify(token)
@@ -65,7 +65,7 @@ def test_unpack_jwt(self):
token = create_jwt(test_user_id, test_timeout, {}, test_now)
decoded = unpack_jwt(token, test_user_id, test_now)
- self.assertEqual(expected_full_token, decoded)
+ self.assertEqual(expected_full_token, decoded) # noqa: PT009
def test_unpack_jwt_with_claims(self):
token = create_jwt(test_user_id, test_timeout, test_claims, test_now)
@@ -75,7 +75,7 @@ def test_unpack_jwt_with_claims(self):
decoded = unpack_jwt(token, test_user_id, test_now)
- self.assertEqual(expected_token_with_claims, decoded)
+ self.assertEqual(expected_token_with_claims, decoded) # noqa: PT009
def test_malformed_token(self):
token = create_jwt(test_user_id, test_timeout, test_claims, test_now)
@@ -84,19 +84,19 @@ def test_malformed_token(self):
expected_token_with_claims = expected_full_token.copy()
expected_token_with_claims.update(test_claims)
- with self.assertRaises(InvalidSignatureError):
+ with self.assertRaises(InvalidSignatureError): # noqa: PT027
unpack_jwt(token, test_user_id, test_now)
def test_unpack_token_with_invalid_user(self):
token = create_jwt(invalid_test_user_id, test_timeout, {}, test_now)
- with self.assertRaises(InvalidSignatureError):
+ with self.assertRaises(InvalidSignatureError): # noqa: PT027
unpack_jwt(token, test_user_id, test_now)
def test_unpack_expired_token(self):
token = create_jwt(test_user_id, test_timeout, {}, test_now)
- with self.assertRaises(ExpiredSignatureError):
+ with self.assertRaises(ExpiredSignatureError): # noqa: PT027
unpack_jwt(token, test_user_id, test_now + test_timeout + 1)
def test_missing_expired_lms_user_id(self):
@@ -104,7 +104,7 @@ def test_missing_expired_lms_user_id(self):
del payload['lms_user_id']
token = _encode_and_sign(payload)
- with self.assertRaises(MissingRequiredClaimError):
+ with self.assertRaises(MissingRequiredClaimError): # noqa: PT027
unpack_jwt(token, test_user_id, test_now)
def test_missing_expired_key(self):
@@ -112,5 +112,5 @@ def test_missing_expired_key(self):
del payload['exp']
token = _encode_and_sign(payload)
- with self.assertRaises(MissingRequiredClaimError):
+ with self.assertRaises(MissingRequiredClaimError): # noqa: PT027
unpack_jwt(token, test_user_id, test_now)
diff --git a/openedx/core/lib/tests/test_teams_config.py b/openedx/core/lib/tests/test_teams_config.py
index e82894b963b3..f7d7e6932ef9 100644
--- a/openedx/core/lib/tests/test_teams_config.py
+++ b/openedx/core/lib/tests/test_teams_config.py
@@ -185,7 +185,7 @@ def test_teams_config_round_trip(self, input_data, expected_output_data):
"""
teams_config = TeamsConfig(input_data)
actual_output_data = teams_config.cleaned_data
- self.assertDictEqual(actual_output_data, expected_output_data)
+ self.assertDictEqual(actual_output_data, expected_output_data) # noqa: PT009
@ddt.data(
(None, None, "open", DEFAULT_COURSE_RUN_MAX_TEAM_SIZE),
diff --git a/openedx/core/lib/tests/test_time_zone_utils.py b/openedx/core/lib/tests/test_time_zone_utils.py
index f10d08921e88..973a33e0350f 100644
--- a/openedx/core/lib/tests/test_time_zone_utils.py
+++ b/openedx/core/lib/tests/test_time_zone_utils.py
@@ -37,7 +37,7 @@ def _assert_time_zone_info_equal(self, display_tz_info, expected_name, expected_
"""
Asserts that all display_tz_info is equal to the expected inputs
"""
- assert display_tz_info['str'] == '{name} ({abbr}, UTC{offset})'.format(
+ assert display_tz_info['str'] == '{name} ({abbr}, UTC{offset})'.format( # noqa: UP032
name=expected_name, abbr=expected_abbr, offset=expected_offset
)
assert display_tz_info['abbr'] == expected_abbr
diff --git a/openedx/core/lib/tests/test_user_util.py b/openedx/core/lib/tests/test_user_util.py
index 5292a4120d22..214c5d016312 100644
--- a/openedx/core/lib/tests/test_user_util.py
+++ b/openedx/core/lib/tests/test_user_util.py
@@ -67,7 +67,7 @@ def test_unicode_username_to_hash():
assert len(retired_username.split('_')[-1]) == 40
-@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_THREE_SALTS,))
+@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_THREE_SALTS,)) # noqa: PT007
def test_correct_username_hash(salt_list):
"""
Verify that get_retired_username uses the current salt and returns the expected hash.
@@ -83,7 +83,7 @@ def test_correct_username_hash(salt_list):
assert retired_username == valid_retired_usernames[-1]
-@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_FIVE_SALTS,))
+@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_FIVE_SALTS,)) # noqa: PT007
def test_all_usernames_to_hash(salt_list):
username = 'ALearnerUserName'
retired_username_generator = user_util.get_all_retired_usernames(username, salt_list)
@@ -136,7 +136,7 @@ def test_unicode_email_to_hash():
assert len(retired_email.split('@')[0]) == len('retired_email_') + 40
-@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_THREE_SALTS,))
+@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_THREE_SALTS,)) # noqa: PT007
def test_correct_email_hash(salt_list):
"""
Verify that get_retired_email uses the current salt and returns the expected hash.
@@ -152,7 +152,7 @@ def test_correct_email_hash(salt_list):
assert retired_email == valid_retired_emails[-1]
-@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_FIVE_SALTS,))
+@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_FIVE_SALTS,)) # noqa: PT007
def test_all_emails_to_hash(salt_list):
email = 'a.learner@example.com'
retired_email_generator = user_util.get_all_retired_emails(email, salt_list)
@@ -206,7 +206,7 @@ def test_unicode_external_key_to_hash():
assert len(retired_external_key) == len('retired_external_key_') + 40
-@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_THREE_SALTS,))
+@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_THREE_SALTS,)) # noqa: PT007
def test_correct_external_key_hash(salt_list):
"""
Verify that get_retired_external_key uses the current salt and returns the expected hash.
@@ -223,7 +223,7 @@ def test_correct_external_key_hash(salt_list):
assert retired_email == valid_retired_external_keys[-1]
-@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_FIVE_SALTS,))
+@pytest.mark.parametrize('salt_list', (VALID_SALT_LIST_FIVE_SALTS,)) # noqa: PT007
def test_all_external_keys_to_hash(salt_list):
external_key = 'S34839GEF3'
retired_external_key_generator = user_util.get_all_retired_external_keys(external_key, salt_list)
diff --git a/openedx/core/lib/x_forwarded_for/middleware.py b/openedx/core/lib/x_forwarded_for/middleware.py
index cd208809820e..ed5a39541568 100644
--- a/openedx/core/lib/x_forwarded_for/middleware.py
+++ b/openedx/core/lib/x_forwarded_for/middleware.py
@@ -64,7 +64,7 @@ def process_request(self, request):
set_custom_attribute('ip_chain.safest_client_ip', safest_client_ip)
except BaseException:
- warnings.warn('Error while computing IP chain metrics')
+ warnings.warn('Error while computing IP chain metrics') # noqa: B028
# Older code for the Gunicorn 19.0 upgrade. Original docstring:
#
diff --git a/openedx/core/lib/xblock_pipeline/finder.py b/openedx/core/lib/xblock_pipeline/finder.py
index 31b9b9c501fc..4977c76f0a78 100644
--- a/openedx/core/lib/xblock_pipeline/finder.py
+++ b/openedx/core/lib/xblock_pipeline/finder.py
@@ -81,19 +81,19 @@ def get_accessed_time(self, name):
"""
Returns a URL to the package resource.
"""
- return datetime.fromtimestamp(os.path.getatime(self.path(name)), timezone.utc)
+ return datetime.fromtimestamp(os.path.getatime(self.path(name)), timezone.utc) # noqa: UP017
def get_created_time(self, name):
"""
Returns the created time of the package resource.
"""
- return datetime.fromtimestamp(os.path.getctime(self.path(name)), timezone.utc)
+ return datetime.fromtimestamp(os.path.getctime(self.path(name)), timezone.utc) # noqa: UP017
def get_modified_time(self, name):
"""
Returns the modified time of the resource.
"""
- return datetime.fromtimestamp(os.path.getmtime(self.path(name)), timezone.utc)
+ return datetime.fromtimestamp(os.path.getmtime(self.path(name)), timezone.utc) # noqa: UP017
def url(self, name):
"""
diff --git a/openedx/core/lib/xblock_serializer/api.py b/openedx/core/lib/xblock_serializer/api.py
index 6d0c1f78397c..7367310aaeb7 100644
--- a/openedx/core/lib/xblock_serializer/api.py
+++ b/openedx/core/lib/xblock_serializer/api.py
@@ -2,7 +2,7 @@
Public python API for serializing XBlocks to OLX
"""
# pylint: disable=unused-import
-from .block_serializer import StaticFile, XBlockSerializer
+from .block_serializer import StaticFile, XBlockSerializer # noqa: F401
def serialize_xblock_to_olx(block):
diff --git a/openedx/core/lib/xblock_serializer/test_api.py b/openedx/core/lib/xblock_serializer/test_api.py
index dac154d736da..d8703661693d 100644
--- a/openedx/core/lib/xblock_serializer/test_api.py
+++ b/openedx/core/lib/xblock_serializer/test_api.py
@@ -105,7 +105,7 @@ def setUpClass(cls):
def assertXmlEqual(self, xml_str_a: str, xml_str_b: str) -> None:
""" Assert that the given XML strings are equal, ignoring attribute order and some whitespace variations. """
- self.assertEqual(
+ self.assertEqual( # noqa: PT009
ElementTree.canonicalize(xml_str_a, strip_text=True),
ElementTree.canonicalize(xml_str_b, strip_text=True),
)
@@ -131,8 +131,8 @@ def test_html_with_static_asset(self):
]]>