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('
', html) - self.assertIn('
', html) + self.assertIn('
', html) # noqa: PT009 + self.assertIn('
', html) # noqa: PT009 def test_get_container_fragment(self): root_usage_key = self._create_vertical() @@ -214,18 +214,18 @@ def test_get_container_fragment(self): parent_usage_key=child_vertical_usage_key, category="problem", ) - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 # Get the preview HTML html, __ = self._get_container_preview(root_usage_key) # Verify that the Studio nesting wrapper has been added - self.assertIn("level-nesting", html) - self.assertIn('
', html) - self.assertIn('
', html) + self.assertIn("level-nesting", html) # noqa: PT009 + self.assertIn('
', html) # noqa: PT009 + self.assertIn('
', html) # noqa: PT009 # Verify that the Studio element wrapper has been added - self.assertIn("level-element", html) + self.assertIn("level-element", html) # noqa: PT009 def test_get_container_nested_container_fragment(self): """ @@ -235,23 +235,23 @@ def test_get_container_nested_container_fragment(self): root_usage_key = self._create_vertical() resp = self.create_xblock(parent_usage_key=root_usage_key, category="wrapper") - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 wrapper_usage_key = self.response_usage_key(resp) resp = self.create_xblock( parent_usage_key=wrapper_usage_key, category="problem", ) - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 # Get the preview HTML and verify the View -> link is present. html, __ = self._get_container_preview(root_usage_key) - self.assertIn("wrapper-xblock", html) - self.assertRegex( + self.assertIn("wrapper-xblock", html) # noqa: PT009 + self.assertRegex( # noqa: PT009 html, # The instance of the wrapper class will have an auto-generated ID. Allow any # characters after wrapper. - ( + ( # noqa: UP032 '"/container/{}" class="action-button xblock-view-action-button">' '\\s*View' ).format(re.escape(str(wrapper_usage_key))), @@ -269,7 +269,7 @@ def test_tag_count_in_container_fragment(self, mock_get_object_tag_counts): parent_usage_key=child_vertical_usage_key, category="problem", ) - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 usage_key = self.response_usage_key(resp) # Get the preview HTML with tags @@ -277,8 +277,8 @@ def test_tag_count_in_container_fragment(self, mock_get_object_tag_counts): str(usage_key): 13, } html, __ = self._get_container_preview(root_usage_key) - self.assertIn("wrapper-xblock", html) - self.assertIn('data-testid="tag-count-button"', html) + self.assertIn("wrapper-xblock", html) # noqa: PT009 + self.assertIn('data-testid="tag-count-button"', html) # noqa: PT009 def test_split_test(self): """ @@ -293,12 +293,12 @@ def test_split_test(self): parent_usage_key=split_test_usage_key, category="html", ) - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 resp = self.create_xblock( parent_usage_key=split_test_usage_key, category="html", ) - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 def test_split_test_edited(self): """ @@ -323,8 +323,8 @@ def test_split_test_edited(self): data={"metadata": {"user_partition_id": str(0)}}, ) html, __ = self._get_container_preview(split_test_usage_key) - self.assertIn("alpha", html) - self.assertIn("beta", html) + self.assertIn("alpha", html) # noqa: PT009 + self.assertIn("beta", html) # noqa: PT009 # Rename groups in group configuration GROUP_CONFIGURATION_JSON = { @@ -350,12 +350,12 @@ def test_split_test_edited(self): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 201) + self.assertEqual(response.status_code, 201) # noqa: PT009 html, __ = self._get_container_preview(split_test_usage_key) - self.assertNotIn("alpha", html) - self.assertNotIn("beta", html) - self.assertIn("New_NAME_A", html) - self.assertIn("New_NAME_B", html) + self.assertNotIn("alpha", html) # noqa: PT009 + self.assertNotIn("beta", html) # noqa: PT009 + self.assertIn("New_NAME_A", html) # noqa: PT009 + self.assertIn("New_NAME_B", html) # noqa: PT009 def test_valid_paging(self): """ @@ -376,8 +376,8 @@ def test_valid_paging(self): ) call_args = patched_get_preview_fragment.call_args[0] _, _, context = call_args - self.assertIn("paging", context) - self.assertEqual({"page_number": 0, "page_size": 2}, context["paging"]) + self.assertIn("paging", context) # noqa: PT009 + self.assertEqual({"page_number": 0, "page_size": 2}, context["paging"]) # noqa: PT009 @ddt.data([1, "invalid"], ["invalid", 2]) @ddt.unpack @@ -422,11 +422,11 @@ def test_get_user_partitions_and_groups(self): resp = self.create_xblock(category="vertical") usage_key = self.response_usage_key(resp) 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 # Check that the partition and group information was returned result = json.loads(resp.content.decode("utf-8")) - self.assertEqual( + self.assertEqual( # noqa: PT009 result["user_partitions"], [ { @@ -463,7 +463,7 @@ def test_get_user_partitions_and_groups(self): }, ], ) - self.assertEqual(result["group_access"], {}) + self.assertEqual(result["group_access"], {}) # noqa: PT009 @ddt.data("ancestorInfo", "") def test_ancestor_info(self, field_type): @@ -513,9 +513,9 @@ def assert_xblock_info(xblock, xblock_info): xblock (XBlock): An XBlock item. xblock_info (dict): A dict containing xblock information. """ - self.assertEqual(str(xblock.location), xblock_info["id"]) - self.assertEqual(xblock.display_name, xblock_info["display_name"]) - self.assertEqual(xblock.category, xblock_info["category"]) + self.assertEqual(str(xblock.location), xblock_info["id"]) # noqa: PT009 + self.assertEqual(xblock.display_name, xblock_info["display_name"]) # noqa: PT009 + self.assertEqual(xblock.category, xblock_info["category"]) # noqa: PT009 for usage_key in ( problem_usage_key, @@ -528,18 +528,18 @@ def assert_xblock_info(xblock, xblock_info): reverse_usage_url("xblock_handler", usage_key) + f"?fields={field_type}" ) response = self.client.get(url) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) if field_type == "ancestorInfo": - self.assertIn("ancestors", response) + self.assertIn("ancestors", response) # noqa: PT009 for ancestor_info in response["ancestors"]: parent_xblock = xblock.get_parent() assert_xblock_info(parent_xblock, ancestor_info) xblock = parent_xblock else: - self.assertNotIn("ancestors", response) + self.assertNotIn("ancestors", response) # noqa: PT009 xblock_info = get_block_info(xblock) - self.assertEqual(xblock_info, response) + self.assertEqual(xblock_info, response) # noqa: PT009 @ddt.ddt @@ -556,7 +556,7 @@ def test_delete_static_page(self): # Now delete it. There was a bug that the delete was failing (static tabs do not exist in draft modulestore). resp = self.client.delete(reverse_usage_url("xblock_handler", usage_key)) - self.assertEqual(resp.status_code, 204) + self.assertEqual(resp.status_code, 204) # noqa: PT009 class TestCreateItem(ItemTest): @@ -575,14 +575,14 @@ def test_create_nicely(self): # get the new item and check its category and display_name chap_usage_key = self.response_usage_key(resp) new_obj = self.get_item_from_modulestore(chap_usage_key) - self.assertEqual(new_obj.scope_ids.block_type, "chapter") - self.assertEqual(new_obj.display_name, display_name) - self.assertEqual(new_obj.location.org, self.course.location.org) - self.assertEqual(new_obj.location.course, self.course.location.course) + self.assertEqual(new_obj.scope_ids.block_type, "chapter") # noqa: PT009 + self.assertEqual(new_obj.display_name, display_name) # noqa: PT009 + self.assertEqual(new_obj.location.org, self.course.location.org) # noqa: PT009 + self.assertEqual(new_obj.location.course, self.course.location.course) # noqa: PT009 # get the course and ensure it now points to this one course = self.get_item_from_modulestore(self.usage_key) - self.assertIn(chap_usage_key, course.children) + self.assertIn(chap_usage_key, course.children) # noqa: PT009 def test_create_block_negative(self): """ @@ -590,14 +590,14 @@ def test_create_block_negative(self): """ # non-existent boilerplate: creates a default resp = self.create_xblock(category="problem") - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 def test_create_with_future_date(self): - self.assertEqual(self.course.start, datetime(2030, 1, 1, tzinfo=UTC)) + self.assertEqual(self.course.start, datetime(2030, 1, 1, tzinfo=UTC)) # noqa: PT009 resp = self.create_xblock(category="chapter") usage_key = self.response_usage_key(resp) obj = self.get_item_from_modulestore(usage_key) - self.assertEqual(obj.start, datetime(2030, 1, 1, tzinfo=UTC)) + self.assertEqual(obj.start, datetime(2030, 1, 1, tzinfo=UTC)) # noqa: PT009 def test_static_tabs_initialization(self): """ @@ -609,7 +609,7 @@ def test_static_tabs_initialization(self): # Check that its name is not None new_tab = self.get_item_from_modulestore(usage_key) - self.assertEqual(new_tab.display_name, "Empty") + self.assertEqual(new_tab.display_name, "Empty") # noqa: PT009 class DuplicateHelper: @@ -623,7 +623,7 @@ def _duplicate_and_verify( """Duplicates the source, parenting to supplied parent. Then does equality check.""" usage_key = self._duplicate_item(parent_usage_key, source_usage_key) # pylint: disable=no-member - self.assertTrue( + self.assertTrue( # noqa: PT009 self._check_equality( source_usage_key, usage_key, parent_usage_key, check_asides=check_asides ), @@ -651,16 +651,16 @@ def _check_equality( if check_asides: original_asides = original_item.runtime.get_asides(original_item) duplicated_asides = duplicated_item.runtime.get_asides(duplicated_item) - self.assertEqual(len(original_asides), 1) - self.assertEqual(len(duplicated_asides), 1) - self.assertEqual(original_asides[0].field11, duplicated_asides[0].field11) - self.assertEqual(original_asides[0].field12, duplicated_asides[0].field12) - self.assertNotEqual( + self.assertEqual(len(original_asides), 1) # noqa: PT009 + self.assertEqual(len(duplicated_asides), 1) # noqa: PT009 + self.assertEqual(original_asides[0].field11, duplicated_asides[0].field11) # noqa: PT009 + self.assertEqual(original_asides[0].field12, duplicated_asides[0].field12) # noqa: PT009 + self.assertNotEqual( # noqa: PT009 original_asides[0].field13, duplicated_asides[0].field13 ) - self.assertEqual(duplicated_asides[0].field13, "aside1_default_value3") + self.assertEqual(duplicated_asides[0].field13, "aside1_default_value3") # noqa: PT009 - self.assertNotEqual( + self.assertNotEqual( # noqa: PT009 str(original_item.location), str(duplicated_item.location), "Location of duplicate should be different from original", @@ -669,13 +669,13 @@ def _check_equality( # Parent will only be equal for root of duplicated structure, in the case # where an item is duplicated in-place. if parent_usage_key and str(original_item.parent) == str(parent_usage_key): - self.assertEqual( + self.assertEqual( # noqa: PT009 str(parent_usage_key), str(duplicated_item.parent), "Parent of duplicate should equal parent of source for root xblock when duplicated in-place", ) else: - self.assertNotEqual( + self.assertNotEqual( # noqa: PT009 str(original_item.parent), str(duplicated_item.parent), "Parent duplicate should be different from source", @@ -689,7 +689,7 @@ def _check_equality( # Children will also be duplicated, so for the purposes of testing equality, we will set # the children to the original after recursively checking the children. if original_item.has_children: - self.assertEqual( + self.assertEqual( # noqa: PT009 len(original_item.children), len(duplicated_item.children), "Duplicated item differs in number of children", @@ -719,11 +719,11 @@ def _verify_duplicate_display_name( if original_item.display_name is not None: return ( duplicated_item.display_name - == "Duplicate of '{display_name}'".format( + == "Duplicate of '{display_name}'".format( # noqa: UP032 display_name=original_item.display_name ) ) - return duplicated_item.display_name == "Duplicate of {display_name}".format( + return duplicated_item.display_name == "Duplicate of {display_name}".format( # noqa: UP032 display_name=original_item.category ) @@ -845,21 +845,21 @@ def verify_order(source_usage_key, parent_usage_key, source_position=None): parent = self.get_item_from_modulestore(parent_usage_key) children = parent.children if source_position is None: - self.assertNotIn( + self.assertNotIn( # noqa: PT009 source_usage_key, children, "source item not expected in children array", ) - self.assertEqual( + self.assertEqual( # noqa: PT009 children[len(children) - 1], usage_key, "duplicated item not at end" ) else: - self.assertEqual( + self.assertEqual( # noqa: PT009 children[source_position], source_usage_key, "source item at wrong position", ) - self.assertEqual( + self.assertEqual( # noqa: PT009 children[source_position + 1], usage_key, "duplicated item not ordered after source item", @@ -887,7 +887,7 @@ def verify_name( parent_usage_key, source_usage_key, display_name ) duplicated_item = self.get_item_from_modulestore(usage_key) - self.assertEqual(duplicated_item.display_name, expected_name) + self.assertEqual(duplicated_item.display_name, expected_name) # noqa: PT009 return usage_key # Uses default display_name of 'Text' from HTML component. @@ -918,7 +918,7 @@ def test_shallow_duplicate(self): BlockFactory(parent=source_chapter, category="html", display_name="Child") # Refresh. source_chapter = self.store.get_item(source_chapter.location) - self.assertEqual(len(source_chapter.get_children()), 1) + self.assertEqual(len(source_chapter.get_children()), 1) # noqa: PT009 destination_course = CourseFactory() destination_location = duplicate_block( parent_usage_key=destination_course.location, @@ -929,8 +929,8 @@ def test_shallow_duplicate(self): ) # Refresh here, too, just to be sure. destination_chapter = self.store.get_item(destination_location) - self.assertEqual(len(destination_chapter.get_children()), 0) - self.assertEqual(destination_chapter.display_name, "Source Chapter") + self.assertEqual(len(destination_chapter.get_children()), 0) # noqa: PT009 + self.assertEqual(destination_chapter.display_name, "Source Chapter") # noqa: PT009 def test_duplicate_library_content_block(self): # pylint: disable=too-many-statements """ @@ -1096,7 +1096,7 @@ def test_duplicate_tags(self): user=user, ) dupe_chapter = self.store.get_item(dupe_location) - self.assertEqual(len(dupe_chapter.get_children()), 1) + self.assertEqual(len(dupe_chapter.get_children()), 1) # noqa: PT009 dupe_block = dupe_chapter.get_children()[0] # Check that the duplicated blocks also duplicated tags @@ -1224,8 +1224,8 @@ def setup_and_verify_content_experiment(self, partition_id): split_test = self.get_item_from_modulestore(self.split_test_usage_key) # Initially, no user_partition_id is set, and the split_test has no children. - self.assertEqual(split_test.user_partition_id, -1) - self.assertEqual(len(split_test.children), 0) + self.assertEqual(split_test.user_partition_id, -1) # noqa: PT009 + self.assertEqual(len(split_test.children), 0) # noqa: PT009 # Set group configuration self.client.ajax_post( @@ -1233,8 +1233,8 @@ def setup_and_verify_content_experiment(self, partition_id): data={"metadata": {"user_partition_id": str(partition_id)}}, ) split_test = self.get_item_from_modulestore(self.split_test_usage_key) - self.assertEqual(split_test.user_partition_id, partition_id) - self.assertEqual( + self.assertEqual(split_test.user_partition_id, partition_id) # noqa: PT009 + self.assertEqual( # noqa: PT009 len(split_test.children), len(self.course.user_partitions[partition_id].groups), ) @@ -1279,24 +1279,24 @@ def assert_move_item(self, source_usage_key, target_usage_key, target_index=None response = self._move_component( source_usage_key, target_usage_key, target_index ) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) - self.assertEqual(response["move_source_locator"], str(source_usage_key)) - self.assertEqual(response["parent_locator"], str(target_usage_key)) - self.assertEqual(response["source_index"], expected_index) + self.assertEqual(response["move_source_locator"], str(source_usage_key)) # noqa: PT009 + self.assertEqual(response["parent_locator"], str(target_usage_key)) # noqa: PT009 + self.assertEqual(response["source_index"], expected_index) # noqa: PT009 # Verify parent referance has been changed now. new_parent_loc = self.store.get_parent_location(source_usage_key) source_item = self.get_item_from_modulestore(source_usage_key) - self.assertEqual(source_item.parent, new_parent_loc) - self.assertEqual(new_parent_loc, target_usage_key) - self.assertNotEqual(parent_loc, new_parent_loc) + self.assertEqual(source_item.parent, new_parent_loc) # noqa: PT009 + self.assertEqual(new_parent_loc, target_usage_key) # noqa: PT009 + self.assertNotEqual(parent_loc, new_parent_loc) # noqa: PT009 # Assert item is present in children list of target parent and not source parent target_parent = self.get_item_from_modulestore(target_usage_key) source_parent = self.get_item_from_modulestore(parent_loc) - self.assertIn(source_usage_key, target_parent.children) - self.assertNotIn(source_usage_key, source_parent.children) + self.assertIn(source_usage_key, target_parent.children) # noqa: PT009 + self.assertNotIn(source_usage_key, source_parent.children) # noqa: PT009 def test_move_component(self): """ @@ -1316,7 +1316,7 @@ def test_move_source_index(self): """ parent = self.get_item_from_modulestore(self.vert_usage_key) children = parent.get_children() - self.assertEqual(len(children), 3) + self.assertEqual(len(children), 3) # noqa: PT009 # Create a component within vert2. resp = self.create_xblock( @@ -1328,8 +1328,8 @@ def test_move_source_index(self): self.assert_move_item(html2_usage_key, self.vert_usage_key, 1) parent = self.get_item_from_modulestore(self.vert_usage_key) children = parent.get_children() - self.assertEqual(len(children), 4) - self.assertEqual(children[1].location, html2_usage_key) + self.assertEqual(len(children), 4) # noqa: PT009 + self.assertEqual(children[1].location, html2_usage_key) # noqa: PT009 def test_move_undo(self): """ @@ -1342,22 +1342,22 @@ def test_move_undo(self): # Move component and verify that response contains initial index response = self._move_component(self.html_usage_key, self.vert2_usage_key) response = json.loads(response.content.decode("utf-8")) - self.assertEqual(original_index, response["source_index"]) + self.assertEqual(original_index, response["source_index"]) # noqa: PT009 # Verify that new parent has the moved component at the last index. parent = self.get_item_from_modulestore(self.vert2_usage_key) - self.assertEqual(self.html_usage_key, parent.children[-1]) + self.assertEqual(self.html_usage_key, parent.children[-1]) # noqa: PT009 # Verify original and new index is different now. source_index = _get_source_index(self.html_usage_key, parent) - self.assertNotEqual(original_index, source_index) + self.assertNotEqual(original_index, source_index) # noqa: PT009 # Undo Move to the original index, use the source index fetched from the response. response = self._move_component( self.html_usage_key, self.vert_usage_key, response["source_index"] ) response = json.loads(response.content.decode("utf-8")) - self.assertEqual(original_index, response["source_index"]) + self.assertEqual(original_index, response["source_index"]) # noqa: PT009 def test_move_large_target_index(self): """ @@ -1368,17 +1368,17 @@ def test_move_large_target_index(self): response = self._move_component( self.html_usage_key, self.vert2_usage_key, parent_children_length + 10 ) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) expected_error = ( - "You can not move {usage_key} at an invalid index ({target_index}).".format( + "You can not move {usage_key} at an invalid index ({target_index}).".format( # noqa: UP032 usage_key=self.html_usage_key, target_index=parent_children_length + 10 ) ) - self.assertEqual(expected_error, response["error"]) + self.assertEqual(expected_error, response["error"]) # noqa: PT009 new_parent_loc = self.store.get_parent_location(self.html_usage_key) - self.assertEqual(new_parent_loc, self.vert_usage_key) + self.assertEqual(new_parent_loc, self.vert_usage_key) # noqa: PT009 def test_invalid_move(self): """ @@ -1386,31 +1386,31 @@ def test_invalid_move(self): """ parent_loc = self.store.get_parent_location(self.html_usage_key) response = self._move_component(self.html_usage_key, self.seq_usage_key) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) - expected_error = "You can not move {source_type} into {target_type}.".format( + expected_error = "You can not move {source_type} into {target_type}.".format( # noqa: UP032 source_type=self.html_usage_key.block_type, target_type=self.seq_usage_key.block_type, ) - self.assertEqual(expected_error, response["error"]) + self.assertEqual(expected_error, response["error"]) # noqa: PT009 new_parent_loc = self.store.get_parent_location(self.html_usage_key) - self.assertEqual(new_parent_loc, parent_loc) + self.assertEqual(new_parent_loc, parent_loc) # noqa: PT009 def test_move_current_parent(self): """ Test that a component can not be moved to it's current parent. """ parent_loc = self.store.get_parent_location(self.html_usage_key) - self.assertEqual(parent_loc, self.vert_usage_key) + self.assertEqual(parent_loc, self.vert_usage_key) # noqa: PT009 response = self._move_component(self.html_usage_key, self.vert_usage_key) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) - self.assertEqual( + self.assertEqual( # noqa: PT009 response["error"], "Item is already present in target location." ) - self.assertEqual( + self.assertEqual( # noqa: PT009 self.store.get_parent_location(self.html_usage_key), parent_loc ) @@ -1425,15 +1425,15 @@ def test_can_not_move_into_itself(self): ) library_content_usage_key = self.response_usage_key(library_content) parent_loc = self.store.get_parent_location(library_content_usage_key) - self.assertEqual(parent_loc, self.vert_usage_key) + self.assertEqual(parent_loc, self.vert_usage_key) # noqa: PT009 response = self._move_component( library_content_usage_key, library_content_usage_key ) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) - self.assertEqual(response["error"], "You can not move an item into itself.") - self.assertEqual( + self.assertEqual(response["error"], "You can not move an item into itself.") # noqa: PT009 + self.assertEqual( # noqa: PT009 self.store.get_parent_location(self.html_usage_key), parent_loc ) @@ -1448,7 +1448,7 @@ def test_move_library_content(self): ) library_content_usage_key = self.response_usage_key(library_content) parent_loc = self.store.get_parent_location(library_content_usage_key) - self.assertEqual(parent_loc, self.vert_usage_key) + self.assertEqual(parent_loc, self.vert_usage_key) # noqa: PT009 self.assert_move_item(library_content_usage_key, self.vert2_usage_key) def test_move_into_library_content(self): @@ -1502,14 +1502,14 @@ def test_can_not_move_into_content_experiment_level(self): """ self.setup_and_verify_content_experiment(0) response = self._move_component(self.html_usage_key, self.split_test_usage_key) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) - self.assertEqual( + self.assertEqual( # noqa: PT009 response["error"], "You can not move an item directly into content experiment.", ) - self.assertEqual( + self.assertEqual( # noqa: PT009 self.store.get_parent_location(self.html_usage_key), self.vert_usage_key ) @@ -1524,13 +1524,13 @@ def test_can_not_move_content_experiment_into_its_children(self): response = self._move_component( self.split_test_usage_key, child_vert_usage_key ) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) - self.assertEqual( + self.assertEqual( # noqa: PT009 response["error"], "You can not move an item into it's child." ) - self.assertEqual( + self.assertEqual( # noqa: PT009 self.store.get_parent_location(self.split_test_usage_key), self.vert_usage_key, ) @@ -1550,11 +1550,11 @@ def test_can_not_move_content_experiment_into_its_children(self): response = self._move_component( self.split_test_usage_key, child_split_test.children[0] ) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) - self.assertEqual(response["error"], "You can not move an item into it's child.") - self.assertEqual( + self.assertEqual(response["error"], "You can not move an item into it's child.") # noqa: PT009 + self.assertEqual( # noqa: PT009 self.store.get_parent_location(self.split_test_usage_key), self.vert_usage_key, ) @@ -1568,20 +1568,20 @@ def test_move_invalid_source_index(self): response = self._move_component( self.html_usage_key, self.vert2_usage_key, target_index ) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) error = f"You must provide target_index ({target_index}) as an integer." - self.assertEqual(response["error"], error) + self.assertEqual(response["error"], error) # noqa: PT009 new_parent_loc = self.store.get_parent_location(self.html_usage_key) - self.assertEqual(new_parent_loc, parent_loc) + self.assertEqual(new_parent_loc, parent_loc) # noqa: PT009 def test_move_no_target_locator(self): """ Test move an item without specifying the target location. """ data = {"move_source_locator": str(self.html_usage_key)} - with self.assertRaises(InvalidKeyError): + with self.assertRaises(InvalidKeyError): # noqa: PT027 self.client.patch( reverse("xblock_handler"), json.dumps(data), @@ -1593,9 +1593,9 @@ def test_no_move_source_locator(self): Test patch request without providing a move source locator. """ response = self.client.patch(reverse("xblock_handler")) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 response = json.loads(response.content.decode("utf-8")) - self.assertEqual( + self.assertEqual( # noqa: PT009 response["error"], "Patch request did not recognise any parameters to handle.", ) @@ -1606,8 +1606,8 @@ def _verify_validation_message( """ Verify that the validation message has the expected validation message and type. """ - self.assertEqual(message.text, expected_message) - self.assertEqual(message.type, expected_message_type) + self.assertEqual(message.text, expected_message) # noqa: PT009 + self.assertEqual(message.type, expected_message_type) # noqa: PT009 def test_move_component_nonsensical_access_restriction_validation(self): """ @@ -1642,14 +1642,14 @@ def test_move_component_nonsensical_access_restriction_validation(self): # Verify that there is no warning when html is in a non contradicting unit validation = html.validate() - self.assertEqual(len(validation.messages), 0) + self.assertEqual(len(validation.messages), 0) # noqa: PT009 # Now move it and confirm that the html component has been moved into vertical 2 self.assert_move_item(self.html_usage_key, self.vert2_usage_key) html.parent = self.vert2_usage_key html = self.store.update_item(html, self.user.id) validation = html.validate() - self.assertEqual(len(validation.messages), 1) + self.assertEqual(len(validation.messages), 1) # noqa: PT009 self._verify_validation_message( validation.messages[0], NONSENSICAL_ACCESS_RESTRICTION, @@ -1661,7 +1661,7 @@ def test_move_component_nonsensical_access_restriction_validation(self): html.parent = self.vert_usage_key html = self.store.update_item(html, self.user.id) validation = html.validate() - self.assertEqual(len(validation.messages), 0) + self.assertEqual(len(validation.messages), 0) # noqa: PT009 @patch("cms.djangoapps.contentstore.xblock_storage_handlers.view_handlers.log") def test_move_logging(self, mock_logger): @@ -1691,7 +1691,7 @@ def test_move_and_discard_changes(self): old_parent_loc = self.store.get_parent_location(self.html_usage_key) # Check that old_parent_loc is not yet published. - self.assertFalse( + self.assertFalse( # noqa: PT009 self.store.has_item( old_parent_loc, revision=ModuleStoreEnum.RevisionOption.published_only ) @@ -1704,18 +1704,18 @@ def test_move_and_discard_changes(self): ) # Check that old_parent_loc is now published. - self.assertTrue( + self.assertTrue( # noqa: PT009 self.store.has_item( old_parent_loc, revision=ModuleStoreEnum.RevisionOption.published_only ) ) - self.assertFalse(self.store.has_changes(self.store.get_item(old_parent_loc))) + self.assertFalse(self.store.has_changes(self.store.get_item(old_parent_loc))) # noqa: PT009 # Move component html_usage_key in vert2_usage_key self.assert_move_item(self.html_usage_key, self.vert2_usage_key) # Check old_parent_loc becomes in draft mode now. - self.assertTrue(self.store.has_changes(self.store.get_item(old_parent_loc))) + self.assertTrue(self.store.has_changes(self.store.get_item(old_parent_loc))) # noqa: PT009 # Now discard changes in old_parent_loc self.client.ajax_post( @@ -1724,25 +1724,25 @@ def test_move_and_discard_changes(self): ) # Check that old_parent_loc now is reverted to publish. Changes discarded, html_usage_key moved back. - self.assertTrue( + self.assertTrue( # noqa: PT009 self.store.has_item( old_parent_loc, revision=ModuleStoreEnum.RevisionOption.published_only ) ) - self.assertFalse(self.store.has_changes(self.store.get_item(old_parent_loc))) + self.assertFalse(self.store.has_changes(self.store.get_item(old_parent_loc))) # noqa: PT009 # Now source item should be back in the old parent. source_item = self.get_item_from_modulestore(self.html_usage_key) - self.assertEqual(source_item.parent, old_parent_loc) - self.assertEqual( + self.assertEqual(source_item.parent, old_parent_loc) # noqa: PT009 + self.assertEqual( # noqa: PT009 self.store.get_parent_location(self.html_usage_key), source_item.parent ) # Also, check that item is not present in target parent but in source parent target_parent = self.get_item_from_modulestore(self.vert2_usage_key) source_parent = self.get_item_from_modulestore(old_parent_loc) - self.assertIn(self.html_usage_key, source_parent.children) - self.assertNotIn(self.html_usage_key, target_parent.children) + self.assertIn(self.html_usage_key, source_parent.children) # noqa: PT009 + self.assertNotIn(self.html_usage_key, target_parent.children) # noqa: PT009 def test_move_item_not_found(self): """ @@ -1756,7 +1756,7 @@ def test_move_item_not_found(self): ), "parent_locator": str(self.vert2_usage_key), } - with self.assertRaises(ItemNotFoundError): + with self.assertRaises(ItemNotFoundError): # noqa: PT027 self.client.patch( reverse("xblock_handler"), json.dumps(data), @@ -1821,9 +1821,9 @@ def create_aside(usage_key, block_type): scope_ids=ScopeIds("user", block_type, def_id, usage_id), runtime=runtime, ) - aside.field11 = "%s_new_value11" % block_type - aside.field12 = "%s_new_value12" % block_type - aside.field13 = "%s_new_value13" % block_type + aside.field11 = "%s_new_value11" % block_type # noqa: UP031 + aside.field12 = "%s_new_value12" % block_type # noqa: UP031 + aside.field13 = "%s_new_value13" % block_type # noqa: UP031 self.store.update_item(item, self.user.id, asides=[aside]) @@ -1896,30 +1896,30 @@ def test_delete_field(self): self.problem_update_url, data={"metadata": {"rerandomize": "onreset"}} ) problem = self.get_item_from_modulestore(self.problem_usage_key) - self.assertEqual(problem.rerandomize, 'onreset') + self.assertEqual(problem.rerandomize, 'onreset') # noqa: PT009 self.client.ajax_post( self.problem_update_url, data={"metadata": {"rerandomize": None}} ) problem = self.get_item_from_modulestore(self.problem_usage_key) - self.assertEqual(problem.rerandomize, 'never') + self.assertEqual(problem.rerandomize, 'never') # noqa: PT009 def test_date_fields(self): """ Test setting due & start dates on sequential """ sequential = self.get_item_from_modulestore(self.seq_usage_key) - self.assertIsNone(sequential.due) + self.assertIsNone(sequential.due) # noqa: PT009 self.client.ajax_post( self.seq_update_url, data={"metadata": {"due": "2010-11-22T04:00Z"}} ) sequential = self.get_item_from_modulestore(self.seq_usage_key) - self.assertEqual(sequential.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC)) + self.assertEqual(sequential.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC)) # noqa: PT009 self.client.ajax_post( self.seq_update_url, data={"metadata": {"start": "2010-09-12T14:00Z"}} ) sequential = self.get_item_from_modulestore(self.seq_usage_key) - self.assertEqual(sequential.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC)) - self.assertEqual(sequential.start, datetime(2010, 9, 12, 14, 0, tzinfo=UTC)) + self.assertEqual(sequential.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC)) # noqa: PT009 + self.assertEqual(sequential.start, datetime(2010, 9, 12, 14, 0, tzinfo=UTC)) # noqa: PT009 @ddt.data( "1000-01-01T00:00Z", @@ -1941,8 +1941,8 @@ def test_xblock_due_date_validity(self, date): user=self.user, ) # Both display and actual value should be None - self.assertEqual(xblock_info["due_date"], "") - self.assertIsNone(xblock_info["due"]) + self.assertEqual(xblock_info["due_date"], "") # noqa: PT009 + self.assertIsNone(xblock_info["due"]) # noqa: PT009 def test_update_generic_fields(self): new_display_name = "New Display Name" @@ -1957,8 +1957,8 @@ def test_update_generic_fields(self): }, ) problem = self.get_item_from_modulestore(self.problem_usage_key) - self.assertEqual(problem.display_name, new_display_name) - self.assertEqual(problem.max_attempts, new_max_attempts) + self.assertEqual(problem.display_name, new_display_name) # noqa: PT009 + self.assertEqual(problem.max_attempts, new_max_attempts) # noqa: PT009 def test_delete_child(self): """ @@ -1971,19 +1971,19 @@ def test_delete_child(self): chapter2_usage_key = self.response_usage_key(resp_2) course = self.get_item_from_modulestore(self.usage_key) - self.assertIn(chapter1_usage_key, course.children) - self.assertIn(chapter2_usage_key, course.children) + self.assertIn(chapter1_usage_key, course.children) # noqa: PT009 + self.assertIn(chapter2_usage_key, course.children) # noqa: PT009 # Remove one child from the course. resp = self.client.delete( reverse_usage_url("xblock_handler", chapter1_usage_key) ) - self.assertEqual(resp.status_code, 204) + self.assertEqual(resp.status_code, 204) # noqa: PT009 # Verify that the child is removed. course = self.get_item_from_modulestore(self.usage_key) - self.assertNotIn(chapter1_usage_key, course.children) - self.assertIn(chapter2_usage_key, course.children) + self.assertNotIn(chapter1_usage_key, course.children) # noqa: PT009 + self.assertIn(chapter2_usage_key, course.children) # noqa: PT009 def test_reorder_children(self): """ @@ -2004,8 +2004,8 @@ def test_reorder_children(self): # Children must be on the sequential to reproduce the original bug, # as it is important that the parent (sequential) NOT be in the draft store. children = self.get_item_from_modulestore(self.seq_usage_key).children - self.assertEqual(unit1_usage_key, children[1]) - self.assertEqual(unit2_usage_key, children[2]) + self.assertEqual(unit1_usage_key, children[1]) # noqa: PT009 + self.assertEqual(unit2_usage_key, children[2]) # noqa: PT009 resp = self.client.ajax_post( self.seq_update_url, @@ -2017,12 +2017,12 @@ def test_reorder_children(self): ] }, ) - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 children = self.get_item_from_modulestore(self.seq_usage_key).children - self.assertEqual(self.problem_usage_key, children[0]) - self.assertEqual(unit1_usage_key, children[2]) - self.assertEqual(unit2_usage_key, children[1]) + self.assertEqual(self.problem_usage_key, children[0]) # noqa: PT009 + self.assertEqual(unit1_usage_key, children[2]) # noqa: PT009 + self.assertEqual(unit2_usage_key, children[1]) # noqa: PT009 def test_move_parented_child(self): """ @@ -2047,14 +2047,14 @@ def test_move_parented_child(self): resp = self.client.ajax_post( self.seq2_update_url, data={"children": [str(unit_1_key), str(unit_2_key)]} ) - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 # verify children - self.assertListEqual( + self.assertListEqual( # noqa: PT009 self.get_item_from_modulestore(self.seq2_usage_key).children, [unit_1_key, unit_2_key], ) - self.assertListEqual( + self.assertListEqual( # noqa: PT009 self.get_item_from_modulestore(self.seq_usage_key).children, [self.problem_usage_key], # problem child created in setUp ) @@ -2076,7 +2076,7 @@ def test_move_orphaned_child_error(self): ) # verify children - self.assertListEqual( + self.assertListEqual( # noqa: PT009 self.get_item_from_modulestore(self.seq2_usage_key).children, [] ) @@ -2108,7 +2108,7 @@ def test_move_child_creates_orphan_error(self): ) # verify children - self.assertListEqual( + self.assertListEqual( # noqa: PT009 self.get_item_from_modulestore(self.seq2_usage_key).children, [unit_1_key, unit_2_key], ) @@ -2125,20 +2125,20 @@ def _verify_published_with_no_draft(self, location): """ Verifies the item with given location has a published version and no draft (unpublished changes). """ - self.assertTrue(self._is_location_published(location)) - self.assertFalse(modulestore().has_changes(modulestore().get_item(location))) + self.assertTrue(self._is_location_published(location)) # noqa: PT009 + self.assertFalse(modulestore().has_changes(modulestore().get_item(location))) # noqa: PT009 def _verify_published_with_draft(self, location): """ Verifies the item with given location has a published version and also a draft version (unpublished changes). """ - self.assertTrue(self._is_location_published(location)) - self.assertTrue(modulestore().has_changes(modulestore().get_item(location))) + self.assertTrue(self._is_location_published(location)) # noqa: PT009 + self.assertTrue(modulestore().has_changes(modulestore().get_item(location))) # noqa: PT009 def test_make_public(self): """Test making a private problem public (publishing it).""" # When the problem is first created, it is only in draft (because of its category). - self.assertFalse(self._is_location_published(self.problem_usage_key)) + self.assertFalse(self._is_location_published(self.problem_usage_key)) # noqa: PT009 self.client.ajax_post(self.problem_update_url, data={"publish": "make_public"}) self._verify_published_with_no_draft(self.problem_usage_key) @@ -2157,14 +2157,14 @@ def test_revert_to_published(self): self.problem_usage_key, revision=ModuleStoreEnum.RevisionOption.published_only, ) - self.assertIsNone(published.due) + self.assertIsNone(published.due) # noqa: PT009 def test_republish(self): """Test republishing an item.""" new_display_name = "New Display Name" # When the problem is first created, it is only in draft (because of its category). - self.assertFalse(self._is_location_published(self.problem_usage_key)) + self.assertFalse(self._is_location_published(self.problem_usage_key)) # noqa: PT009 # Republishing when only in draft will update the draft but not cause a public item to be created. self.client.ajax_post( @@ -2174,9 +2174,9 @@ def test_republish(self): "metadata": {"display_name": new_display_name}, }, ) - self.assertFalse(self._is_location_published(self.problem_usage_key)) + self.assertFalse(self._is_location_published(self.problem_usage_key)) # noqa: PT009 draft = self.get_item_from_modulestore(self.problem_usage_key) - self.assertEqual(draft.display_name, new_display_name) + self.assertEqual(draft.display_name, new_display_name) # noqa: PT009 # Publish the item self.client.ajax_post(self.problem_update_url, data={"publish": "make_public"}) @@ -2195,7 +2195,7 @@ def test_republish(self): self.problem_usage_key, revision=ModuleStoreEnum.RevisionOption.published_only, ) - self.assertEqual(published.display_name, new_display_name_2) + self.assertEqual(published.display_name, new_display_name_2) # noqa: PT009 def test_direct_only_categories_not_republished(self): """Verify that republish is ignored for items in DIRECT_ONLY_CATEGORIES""" @@ -2234,13 +2234,13 @@ def _make_draft_content_different_from_published(self): self.problem_update_url, data={"metadata": {"due": "2077-10-10T04:00Z"}} ) updated_draft = self.get_item_from_modulestore(self.problem_usage_key) - self.assertEqual(updated_draft.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC)) - self.assertIsNone(published.due) + self.assertEqual(updated_draft.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC)) # noqa: PT009 + self.assertIsNone(published.due) # noqa: PT009 # Fetch the published version again to make sure the due date is still unset. published = modulestore().get_item( published.location, revision=ModuleStoreEnum.RevisionOption.published_only ) - self.assertIsNone(published.due) + self.assertIsNone(published.due) # noqa: PT009 def test_make_public_with_update(self): """Update a problem and make it public at the same time.""" @@ -2249,7 +2249,7 @@ def test_make_public_with_update(self): data={"metadata": {"due": "2077-10-10T04:00Z"}, "publish": "make_public"}, ) published = self.get_item_from_modulestore(self.problem_usage_key) - self.assertEqual(published.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC)) + self.assertEqual(published.due, datetime(2077, 10, 10, 4, 0, tzinfo=UTC)) # noqa: PT009 def test_published_and_draft_contents_with_update(self): """Create a draft and publish it then modify the draft and check that published content is not modified""" @@ -2274,30 +2274,30 @@ def test_published_and_draft_contents_with_update(self): # Both published and draft content should be different draft = self.get_item_from_modulestore(self.problem_usage_key) - self.assertNotEqual(draft.data, published.data) + self.assertNotEqual(draft.data, published.data) # noqa: PT009 # Get problem by 'xblock_handler' view_url = reverse_usage_url( "xblock_view_handler", self.problem_usage_key, {"view_name": STUDENT_VIEW} ) resp = self.client.get(view_url, HTTP_ACCEPT="application/json") - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 # Activate the editing view view_url = reverse_usage_url( "xblock_view_handler", self.problem_usage_key, {"view_name": STUDIO_VIEW} ) resp = self.client.get(view_url, HTTP_ACCEPT="application/json") - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 # Both published and draft content should still be different draft = self.get_item_from_modulestore(self.problem_usage_key) - self.assertNotEqual(draft.data, published.data) + self.assertNotEqual(draft.data, published.data) # noqa: PT009 # Fetch the published version again to make sure the data is correct. published = modulestore().get_item( published.location, revision=ModuleStoreEnum.RevisionOption.published_only ) - self.assertNotEqual(draft.data, published.data) + self.assertNotEqual(draft.data, published.data) # noqa: PT009 def test_publish_states_of_nested_xblocks(self): """Test publishing of a unit page containing a nested xblock""" @@ -2315,12 +2315,12 @@ def test_publish_states_of_nested_xblocks(self): # The unit and its children should be private initially unit_update_url = reverse_usage_url("xblock_handler", unit_usage_key) - self.assertFalse(self._is_location_published(unit_usage_key)) - self.assertFalse(self._is_location_published(html_usage_key)) + self.assertFalse(self._is_location_published(unit_usage_key)) # noqa: PT009 + self.assertFalse(self._is_location_published(html_usage_key)) # noqa: PT009 # Make the unit public and verify that the problem is also made public resp = self.client.ajax_post(unit_update_url, data={"publish": "make_public"}) - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 self._verify_published_with_no_draft(unit_usage_key) self._verify_published_with_no_draft(html_usage_key) @@ -2344,10 +2344,10 @@ def test_field_value_errors(self): }, }, ) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 parsed = json.loads(response.content.decode("utf-8")) - self.assertIn("error", parsed) - self.assertIn( + self.assertIn("error", parsed) # noqa: PT009 + self.assertIn( # noqa: PT009 "Incorrect RelativeTime value", parsed["error"] ) # See xmodule/fields.py @@ -2428,7 +2428,7 @@ def _update_partition_id(self, partition_id): # Verify the partition_id was saved. split_test = self.get_item_from_modulestore(self.split_test_usage_key) - self.assertEqual(partition_id, split_test.user_partition_id) + self.assertEqual(partition_id, split_test.user_partition_id) # noqa: PT009 return split_test def _assert_children(self, expected_number): @@ -2436,7 +2436,7 @@ def _assert_children(self, expected_number): Verifies the number of children of the split_test instance. """ split_test = self.get_item_from_modulestore(self.split_test_usage_key) - self.assertEqual(expected_number, len(split_test.children)) + self.assertEqual(expected_number, len(split_test.children)) # noqa: PT009 return split_test def test_create_groups(self): @@ -2446,32 +2446,32 @@ def test_create_groups(self): """ split_test = self.get_item_from_modulestore(self.split_test_usage_key) # Initially, no user_partition_id is set, and the split_test has no children. - self.assertEqual(-1, split_test.user_partition_id) - self.assertEqual(0, len(split_test.children)) + self.assertEqual(-1, split_test.user_partition_id) # noqa: PT009 + self.assertEqual(0, len(split_test.children)) # noqa: PT009 # Set the user_partition_id to match the first user_partition. split_test = self._update_partition_id(self.first_user_partition.id) # Verify that child verticals have been set to match the groups - self.assertEqual(2, len(split_test.children)) + self.assertEqual(2, len(split_test.children)) # noqa: PT009 vertical_0 = self.get_item_from_modulestore(split_test.children[0]) vertical_1 = self.get_item_from_modulestore(split_test.children[1]) - self.assertEqual("vertical", vertical_0.category) - self.assertEqual("vertical", vertical_1.category) - self.assertEqual( + self.assertEqual("vertical", vertical_0.category) # noqa: PT009 + self.assertEqual("vertical", vertical_1.category) # noqa: PT009 + self.assertEqual( # noqa: PT009 "Group ID " + str(MINIMUM_UNUSED_PARTITION_ID + 1), vertical_0.display_name ) - self.assertEqual( + self.assertEqual( # noqa: PT009 "Group ID " + str(MINIMUM_UNUSED_PARTITION_ID + 2), vertical_1.display_name ) # Verify that the group_id_to_child mapping is correct. - self.assertEqual(2, len(split_test.group_id_to_child)) - self.assertEqual( + self.assertEqual(2, len(split_test.group_id_to_child)) # noqa: PT009 + self.assertEqual( # noqa: PT009 vertical_0.location, split_test.group_id_to_child[str(self.first_user_partition_group_1.id)], ) - self.assertEqual( + self.assertEqual( # noqa: PT009 vertical_1.location, split_test.group_id_to_child[str(self.first_user_partition_group_2.id)], ) @@ -2482,12 +2482,12 @@ def test_split_xblock_info_group_name(self): """ split_test = self.get_item_from_modulestore(self.split_test_usage_key) # Initially, no user_partition_id is set, and the split_test has no children. - self.assertEqual(split_test.user_partition_id, -1) - self.assertEqual(len(split_test.children), 0) + self.assertEqual(split_test.user_partition_id, -1) # noqa: PT009 + self.assertEqual(len(split_test.children), 0) # noqa: PT009 # Set the user_partition_id to match the first user_partition. split_test = self._update_partition_id(self.first_user_partition.id) # Verify that child verticals have been set to match the groups - self.assertEqual(len(split_test.children), 2) + self.assertEqual(len(split_test.children), 2) # noqa: PT009 # Get xblock outline xblock_info = create_xblock_info( @@ -2498,10 +2498,10 @@ def test_split_xblock_info_group_name(self): course=self.course, user=self.request.user, ) - self.assertEqual( + self.assertEqual( # noqa: PT009 xblock_info["child_info"]["children"][0]["display_name"], "alpha" ) - self.assertEqual( + self.assertEqual( # noqa: PT009 xblock_info["child_info"]["children"][1]["display_name"], "beta" ) @@ -2512,36 +2512,36 @@ def test_change_user_partition_id(self): """ # Set to first group configuration. split_test = self._update_partition_id(self.first_user_partition.id) - self.assertEqual(2, len(split_test.children)) + self.assertEqual(2, len(split_test.children)) # noqa: PT009 initial_vertical_0_location = split_test.children[0] initial_vertical_1_location = split_test.children[1] # Set to second group configuration split_test = self._update_partition_id(self.second_user_partition.id) # We don't remove existing children. - self.assertEqual(5, len(split_test.children)) - self.assertEqual(initial_vertical_0_location, split_test.children[0]) - self.assertEqual(initial_vertical_1_location, split_test.children[1]) + self.assertEqual(5, len(split_test.children)) # noqa: PT009 + self.assertEqual(initial_vertical_0_location, split_test.children[0]) # noqa: PT009 + self.assertEqual(initial_vertical_1_location, split_test.children[1]) # noqa: PT009 vertical_0 = self.get_item_from_modulestore(split_test.children[2]) vertical_1 = self.get_item_from_modulestore(split_test.children[3]) vertical_2 = self.get_item_from_modulestore(split_test.children[4]) # Verify that the group_id_to child mapping is correct. - self.assertEqual(3, len(split_test.group_id_to_child)) - self.assertEqual( + self.assertEqual(3, len(split_test.group_id_to_child)) # noqa: PT009 + self.assertEqual( # noqa: PT009 vertical_0.location, split_test.group_id_to_child[str(self.second_user_partition_group_1.id)], ) - self.assertEqual( + self.assertEqual( # noqa: PT009 vertical_1.location, split_test.group_id_to_child[str(self.second_user_partition_group_2.id)], ) - self.assertEqual( + self.assertEqual( # noqa: PT009 vertical_2.location, split_test.group_id_to_child[str(self.second_user_partition_group_3.id)], ) - self.assertNotEqual(initial_vertical_0_location, vertical_0.location) - self.assertNotEqual(initial_vertical_1_location, vertical_1.location) + self.assertNotEqual(initial_vertical_0_location, vertical_0.location) # noqa: PT009 + self.assertNotEqual(initial_vertical_1_location, vertical_1.location) # noqa: PT009 def test_change_same_user_partition_id(self): """ @@ -2549,13 +2549,13 @@ def test_change_same_user_partition_id(self): """ # Set to first group configuration. split_test = self._update_partition_id(self.first_user_partition.id) - self.assertEqual(2, len(split_test.children)) + self.assertEqual(2, len(split_test.children)) # noqa: PT009 initial_group_id_to_child = split_test.group_id_to_child # Set again to first group configuration. split_test = self._update_partition_id(self.first_user_partition.id) - self.assertEqual(2, len(split_test.children)) - self.assertEqual(initial_group_id_to_child, split_test.group_id_to_child) + self.assertEqual(2, len(split_test.children)) # noqa: PT009 + self.assertEqual(initial_group_id_to_child, split_test.group_id_to_child) # noqa: PT009 def test_change_non_existent_user_partition_id(self): """ @@ -2565,13 +2565,13 @@ def test_change_non_existent_user_partition_id(self): """ # Set to first group configuration. split_test = self._update_partition_id(self.first_user_partition.id) - self.assertEqual(2, len(split_test.children)) + self.assertEqual(2, len(split_test.children)) # noqa: PT009 initial_group_id_to_child = split_test.group_id_to_child # Set to an group configuration that doesn't exist. split_test = self._update_partition_id(-50) - self.assertEqual(2, len(split_test.children)) - self.assertEqual(initial_group_id_to_child, split_test.group_id_to_child) + self.assertEqual(2, len(split_test.children)) # noqa: PT009 + self.assertEqual(initial_group_id_to_child, split_test.group_id_to_child) # noqa: PT009 def test_add_groups(self): """ @@ -2602,7 +2602,7 @@ def test_add_groups(self): # group_id_to_child and children have not changed yet. split_test = self._assert_children(2) group_id_to_child = split_test.group_id_to_child.copy() - self.assertEqual(2, len(group_id_to_child)) + self.assertEqual(2, len(group_id_to_child)) # noqa: PT009 # SplitModuleStoreRuntime is used in tests. # SplitModuleStoreRuntime doesn't have user service, that's needed for @@ -2614,14 +2614,14 @@ def test_add_groups(self): # Call add_missing_groups method to add the missing group. split_test.add_missing_groups(self.request) split_test = self._assert_children(3) - self.assertNotEqual(group_id_to_child, split_test.group_id_to_child) + self.assertNotEqual(group_id_to_child, split_test.group_id_to_child) # noqa: PT009 group_id_to_child = split_test.group_id_to_child - self.assertEqual(split_test.children[2], group_id_to_child[new_group_id]) + self.assertEqual(split_test.children[2], group_id_to_child[new_group_id]) # noqa: PT009 # Call add_missing_groups again -- it should be a no-op. split_test.add_missing_groups(self.request) split_test = self._assert_children(3) - self.assertEqual(group_id_to_child, split_test.group_id_to_child) + self.assertEqual(group_id_to_child, split_test.group_id_to_child) # noqa: PT009 @ddt.ddt @@ -2657,7 +2657,7 @@ def setUp(self): def test_invalid_handler(self): self.block.handle.side_effect = NoSuchHandlerError - with self.assertRaises(Http404): + with self.assertRaises(Http404): # noqa: PT027 component_handler(self.request, self.usage_key_string, "invalid_handler") @ddt.data("GET", "POST", "PUT", "DELETE") @@ -2665,7 +2665,7 @@ def test_request_method(self, method): def check_handler( handler, request, suffix ): # lint-amnesty, pylint: disable=unused-argument - self.assertEqual(request.method, method) + self.assertEqual(request.method, method) # noqa: PT009 return Response() self.block.handle = check_handler @@ -2685,7 +2685,7 @@ def create_response( self.block.handle = create_response - self.assertEqual( + self.assertEqual( # noqa: PT009 component_handler( self.request, self.usage_key_string, "dummy_handler" ).status_code, @@ -2875,19 +2875,19 @@ def test_basic_components(self): self._verify_basic_component_display_name("discussion", "Discussion") self._verify_basic_component_display_name("video", "Video") self._verify_basic_component_display_name("openassessment", "Open Response") - self.assertGreater(len(self.get_templates_of_type("library")), 0) - self.assertGreater(len(self.get_templates_of_type("html")), 0) - self.assertGreater(len(self.get_templates_of_type("problem")), 0) + self.assertGreater(len(self.get_templates_of_type("library")), 0) # noqa: PT009 + self.assertGreater(len(self.get_templates_of_type("html")), 0) # noqa: PT009 + self.assertGreater(len(self.get_templates_of_type("problem")), 0) # noqa: PT009 # Check for default advanced modules advanced_templates = self.get_templates_of_type("advanced") advanced_module_keys = [t['category'] for t in advanced_templates] - self.assertCountEqual(advanced_module_keys, DEFAULT_ADVANCED_MODULES) + self.assertCountEqual(advanced_module_keys, DEFAULT_ADVANCED_MODULES) # noqa: PT009 # Now fully disable video through XBlockConfiguration XBlockConfiguration.objects.create(name="video", enabled=False) self.templates = get_component_templates(self.course) - self.assertIsNone(self.get_templates_of_type("video")) + self.assertIsNone(self.get_templates_of_type("video")) # noqa: PT009 def test_basic_components_support_levels(self): """ @@ -2896,7 +2896,7 @@ def test_basic_components_support_levels(self): XBlockStudioConfigurationFlag.objects.create(enabled=True) self.templates = get_component_templates(self.course) self._verify_basic_component("discussion", "Discussion", "ps") - self.assertEqual([], self.get_templates_of_type("video")) + self.assertEqual([], self.get_templates_of_type("video")) # noqa: PT009 supported_problem_templates = [ { "boilerplate_name": None, @@ -2907,7 +2907,7 @@ def test_basic_components_support_levels(self): "tab": "advanced", } ] - self.assertEqual( + self.assertEqual( # noqa: PT009 supported_problem_templates, self.get_templates_of_type("problem") ) @@ -2918,7 +2918,7 @@ def test_basic_components_support_levels(self): # Now fully disable video through XBlockConfiguration XBlockConfiguration.objects.create(name="video", enabled=False) self.templates = get_component_templates(self.course) - self.assertIsNone(self.get_templates_of_type("video")) + self.assertIsNone(self.get_templates_of_type("video")) # noqa: PT009 def test_advanced_components(self): """ @@ -2928,11 +2928,11 @@ def test_advanced_components(self): EXPECTED_ADVANCED_MODULES_LENGTH = len(DEFAULT_ADVANCED_MODULES) + 1 self.templates = get_component_templates(self.course) advanced_templates = self.get_templates_of_type("advanced") - self.assertEqual(len(advanced_templates), EXPECTED_ADVANCED_MODULES_LENGTH) + self.assertEqual(len(advanced_templates), EXPECTED_ADVANCED_MODULES_LENGTH) # noqa: PT009 done_template = advanced_templates[0] - self.assertEqual(done_template.get("category"), "done") - self.assertEqual(done_template.get("display_name"), "Completion") - self.assertIsNone(done_template.get("boilerplate_name", None)) + self.assertEqual(done_template.get("category"), "done") # noqa: PT009 + self.assertEqual(done_template.get("display_name"), "Completion") # noqa: PT009 + self.assertIsNone(done_template.get("boilerplate_name", None)) # noqa: PT009 # Verify that components are not added twice self.course.advanced_modules.append("video") @@ -2944,18 +2944,18 @@ def test_advanced_components(self): self.templates = get_component_templates(self.course) advanced_templates = self.get_templates_of_type("advanced") - self.assertEqual(len(advanced_templates), EXPECTED_ADVANCED_MODULES_LENGTH) + self.assertEqual(len(advanced_templates), EXPECTED_ADVANCED_MODULES_LENGTH) # noqa: PT009 only_template = advanced_templates[0] - self.assertNotEqual(only_template.get("category"), "video") - self.assertNotEqual(only_template.get("category"), "drag-and-drop-v2") - self.assertNotEqual(only_template.get("category"), "poll") - self.assertNotEqual(only_template.get("category"), "google-document") - self.assertNotEqual(only_template.get("category"), "survey") + self.assertNotEqual(only_template.get("category"), "video") # noqa: PT009 + self.assertNotEqual(only_template.get("category"), "drag-and-drop-v2") # noqa: PT009 + self.assertNotEqual(only_template.get("category"), "poll") # noqa: PT009 + self.assertNotEqual(only_template.get("category"), "google-document") # noqa: PT009 + self.assertNotEqual(only_template.get("category"), "survey") # noqa: PT009 # Now fully disable done through XBlockConfiguration XBlockConfiguration.objects.create(name="done", enabled=False) self.templates = get_component_templates(self.course) - self.assertTrue((not any(item.get("category") == "done" for item in self.get_templates_of_type("advanced")))) + self.assertTrue((not any(item.get("category") == "done" for item in self.get_templates_of_type("advanced")))) # noqa: PT009, UP034 # pylint: disable=line-too-long def test_deprecated_no_advance_component_button(self): """ @@ -2973,7 +2973,7 @@ def test_deprecated_no_advance_component_button(self): self.course.advanced_modules.extend(["poll", "survey"]) templates = get_component_templates(self.course) button_names = [template["display_name"] for template in templates] - self.assertNotIn("Advanced", button_names) + self.assertNotIn("Advanced", button_names) # noqa: PT009 def test_cannot_create_deprecated_problems(self): """ @@ -3024,18 +3024,18 @@ def verify_staffgradedxblock_present(support_level): Helper method to verify that staffgradedxblock template is present """ sgp = get_xblock_problem("Staff Graded Points") - self.assertIsNotNone(sgp) - self.assertEqual(sgp.get("category"), "staffgradedxblock") - self.assertEqual(sgp.get("support_level"), support_level) + self.assertIsNotNone(sgp) # noqa: PT009 + self.assertEqual(sgp.get("category"), "staffgradedxblock") # noqa: PT009 + self.assertEqual(sgp.get("support_level"), support_level) # noqa: PT009 def verify_dndv2_present(support_level): """ Helper method to verify that DnDv2 template is present """ dndv2 = get_xblock_problem("Drag and Drop") - self.assertIsNotNone(dndv2) - self.assertEqual(dndv2.get("category"), "drag-and-drop-v2") - self.assertEqual(dndv2.get("support_level"), support_level) + self.assertIsNotNone(dndv2) # noqa: PT009 + self.assertEqual(dndv2.get("category"), "drag-and-drop-v2") # noqa: PT009 + self.assertEqual(dndv2.get("support_level"), support_level) # noqa: PT009 verify_dndv2_present(True) verify_staffgradedxblock_present(True) @@ -3043,8 +3043,8 @@ def verify_dndv2_present(support_level): # Now enable XBlockStudioConfigurationFlag. The staffgradedxblock block is marked # unsupported, so will no longer show up, but DnDv2 will continue to appear. XBlockStudioConfigurationFlag.objects.create(enabled=True) - self.assertIsNone(get_xblock_problem("Staff Graded Points")) - self.assertIsNotNone(get_xblock_problem("Drag and Drop")) + self.assertIsNone(get_xblock_problem("Staff Graded Points")) # noqa: PT009 + self.assertIsNotNone(get_xblock_problem("Drag and Drop")) # noqa: PT009 # Now allow unsupported components. self.course.allow_unsupported_xblocks = True @@ -3054,8 +3054,8 @@ def verify_dndv2_present(support_level): # Now disable the blocks completely through XBlockConfiguration XBlockConfiguration.objects.create(name="staffgradedxblock", enabled=False) XBlockConfiguration.objects.create(name="drag-and-drop-v2", enabled=False) - self.assertIsNone(get_xblock_problem("Staff Graded Points")) - self.assertIsNone(get_xblock_problem("Drag and Drop")) + self.assertIsNone(get_xblock_problem("Staff Graded Points")) # noqa: PT009 + self.assertIsNone(get_xblock_problem("Drag and Drop")) # noqa: PT009 def test_discussion_button_present_no_provider(self): """ @@ -3101,16 +3101,16 @@ def _verify_advanced_xblocks(self, expected_xblocks, expected_support_levels): """ templates = get_component_templates(self.course) button_names = [template["display_name"] for template in templates] - self.assertIn("Advanced", button_names) - self.assertEqual(len(templates[-1]["templates"]), len(expected_xblocks)) + self.assertIn("Advanced", button_names) # noqa: PT009 + self.assertEqual(len(templates[-1]["templates"]), len(expected_xblocks)) # noqa: PT009 template_display_names = [ template["display_name"] for template in templates[-1]["templates"] ] - self.assertEqual(template_display_names, expected_xblocks) + self.assertEqual(template_display_names, expected_xblocks) # noqa: PT009 template_support_levels = [ template["support_level"] for template in templates[-1]["templates"] ] - self.assertEqual(template_support_levels, expected_support_levels) + self.assertEqual(template_support_levels, expected_support_levels) # noqa: PT009 def _verify_basic_component( self, component_type, display_name, support_level=True, no_of_templates=1 @@ -3119,16 +3119,16 @@ def _verify_basic_component( Verify the display name and support level of basic components (that have no boilerplates). """ templates = self.get_templates_of_type(component_type) - self.assertEqual(no_of_templates, len(templates)) - self.assertEqual(display_name, templates[0]["display_name"]) - self.assertEqual(support_level, templates[0]["support_level"]) + self.assertEqual(no_of_templates, len(templates)) # noqa: PT009 + self.assertEqual(display_name, templates[0]["display_name"]) # noqa: PT009 + self.assertEqual(support_level, templates[0]["support_level"]) # noqa: PT009 def _verify_basic_component_display_name(self, component_type, display_name): """ Verify the display name of basic components. """ component_display_name = self.get_display_name_of_type(component_type) - self.assertEqual(display_name, component_display_name) + self.assertEqual(display_name, component_display_name) # noqa: PT009 @ddt.ddt @@ -3208,11 +3208,11 @@ def test_entrance_exam_chapter_xblock_info(self): ) # entrance exam chapter should not be deletable, draggable and childAddable. actions = xblock_info["actions"] - self.assertEqual(actions["deletable"], False) - self.assertEqual(actions["draggable"], False) - self.assertEqual(actions["childAddable"], False) - self.assertEqual(xblock_info["display_name"], "Entrance Exam") - self.assertIsNone(xblock_info.get("is_header_visible", None)) + self.assertEqual(actions["deletable"], False) # noqa: PT009 + self.assertEqual(actions["draggable"], False) # noqa: PT009 + self.assertEqual(actions["childAddable"], False) # noqa: PT009 + self.assertEqual(xblock_info["display_name"], "Entrance Exam") # noqa: PT009 + self.assertIsNone(xblock_info.get("is_header_visible", None)) # noqa: PT009 def test_none_entrance_exam_chapter_xblock_info(self): chapter = BlockFactory.create( @@ -3230,11 +3230,11 @@ def test_none_entrance_exam_chapter_xblock_info(self): # chapter should be deletable, draggable and childAddable if not an entrance exam. actions = xblock_info["actions"] - self.assertEqual(actions["deletable"], True) - self.assertEqual(actions["draggable"], True) - self.assertEqual(actions["childAddable"], True) + self.assertEqual(actions["deletable"], True) # noqa: PT009 + self.assertEqual(actions["draggable"], True) # noqa: PT009 + self.assertEqual(actions["childAddable"], True) # noqa: PT009 # chapter xblock info should not contains the key of 'is_header_visible'. - self.assertIsNone(xblock_info.get("is_header_visible", None)) + self.assertIsNone(xblock_info.get("is_header_visible", None)) # noqa: PT009 def test_entrance_exam_sequential_xblock_info(self): chapter = BlockFactory.create( @@ -3258,8 +3258,8 @@ def test_entrance_exam_sequential_xblock_info(self): subsection, include_child_info=True, include_children_predicate=ALWAYS ) # in case of entrance exam subsection, header should be hidden. - self.assertEqual(xblock_info["is_header_visible"], False) - self.assertEqual(xblock_info["display_name"], "Subsection - Entrance Exam") + self.assertEqual(xblock_info["is_header_visible"], False) # noqa: PT009 + self.assertEqual(xblock_info["display_name"], "Subsection - Entrance Exam") # noqa: PT009 def test_none_entrance_exam_sequential_xblock_info(self): subsection = BlockFactory.create( @@ -3276,7 +3276,7 @@ def test_none_entrance_exam_sequential_xblock_info(self): parent_xblock=self.chapter, ) # sequential xblock info should not contains the key of 'is_header_visible'. - self.assertIsNone(xblock_info.get("is_header_visible", None)) + self.assertIsNone(xblock_info.get("is_header_visible", None)) # noqa: PT009 def test_chapter_xblock_info(self): chapter = modulestore().get_item(self.chapter.location) @@ -3335,13 +3335,13 @@ def test_validate_start_date(self): user=self.user ) - self.assertEqual(xblock_info['start'], DEFAULT_START_DATE.strftime('%Y-%m-%dT%H:%M:%SZ')) + self.assertEqual(xblock_info['start'], DEFAULT_START_DATE.strftime('%Y-%m-%dT%H:%M:%SZ')) # noqa: PT009 def test_highlights_enabled(self): self.course.highlights_enabled_for_messaging = True self.store.update_item(self.course, None) course_xblock_info = create_xblock_info(self.course) - self.assertTrue(course_xblock_info["highlights_enabled_for_messaging"]) + self.assertTrue(course_xblock_info["highlights_enabled_for_messaging"]) # noqa: PT009 def test_xblock_public_video_sharing_enabled(self): """ @@ -3351,8 +3351,8 @@ def test_xblock_public_video_sharing_enabled(self): with patch.object(PUBLIC_VIDEO_SHARE, "is_enabled", return_value=True): self.store.update_item(self.course, None) course_xblock_info = create_xblock_info(self.course) - self.assertTrue(course_xblock_info["video_sharing_enabled"]) - self.assertEqual(course_xblock_info["video_sharing_options"], "all-on") + self.assertTrue(course_xblock_info["video_sharing_enabled"]) # noqa: PT009 + self.assertEqual(course_xblock_info["video_sharing_options"], "all-on") # noqa: PT009 def test_xblock_public_video_sharing_disabled(self): """ @@ -3362,8 +3362,8 @@ def test_xblock_public_video_sharing_disabled(self): with patch.object(PUBLIC_VIDEO_SHARE, "is_enabled", return_value=False): self.store.update_item(self.course, None) course_xblock_info = create_xblock_info(self.course) - self.assertNotIn("video_sharing_enabled", course_xblock_info) - self.assertNotIn("video_sharing_options", course_xblock_info) + self.assertNotIn("video_sharing_enabled", course_xblock_info) # noqa: PT009 + self.assertNotIn("video_sharing_options", course_xblock_info) # noqa: PT009 def validate_course_xblock_info( self, xblock_info, has_child_info=True, course_outline=False @@ -3371,11 +3371,11 @@ def validate_course_xblock_info( """ Validate that the xblock info is correct for the test course. """ - self.assertEqual(xblock_info["category"], "course") - self.assertEqual(xblock_info["id"], str(self.course.location)) - self.assertEqual(xblock_info["display_name"], self.course.display_name) - self.assertTrue(xblock_info["published"]) - self.assertFalse(xblock_info["highlights_enabled_for_messaging"]) + self.assertEqual(xblock_info["category"], "course") # noqa: PT009 + self.assertEqual(xblock_info["id"], str(self.course.location)) # noqa: PT009 + self.assertEqual(xblock_info["display_name"], self.course.display_name) # noqa: PT009 + self.assertTrue(xblock_info["published"]) # noqa: PT009 + self.assertFalse(xblock_info["highlights_enabled_for_messaging"]) # noqa: PT009 # Finally, validate the entire response for consistency self.validate_xblock_info_consistency( @@ -3386,21 +3386,21 @@ def validate_chapter_xblock_info(self, xblock_info, has_child_info=True): """ Validate that the xblock info is correct for the test chapter. """ - self.assertEqual(xblock_info["category"], "chapter") - self.assertEqual(xblock_info["id"], str(self.chapter.location)) - self.assertEqual(xblock_info["display_name"], "Week 1") - self.assertTrue(xblock_info["published"]) - self.assertIsNone(xblock_info.get("edited_by", None)) - self.assertEqual( + self.assertEqual(xblock_info["category"], "chapter") # noqa: PT009 + self.assertEqual(xblock_info["id"], str(self.chapter.location)) # noqa: PT009 + self.assertEqual(xblock_info["display_name"], "Week 1") # noqa: PT009 + self.assertTrue(xblock_info["published"]) # noqa: PT009 + self.assertIsNone(xblock_info.get("edited_by", None)) # noqa: PT009 + self.assertEqual( # noqa: PT009 xblock_info["course_graders"], ["Homework", "Lab", "Midterm Exam", "Final Exam"], ) - self.assertEqual(xblock_info["start"], "2030-01-01T00:00:00Z") - self.assertEqual(xblock_info["graded"], False) - self.assertEqual(xblock_info["due"], None) - self.assertEqual(xblock_info["format"], None) - self.assertEqual(xblock_info["highlights"], self.chapter.highlights) - self.assertTrue(xblock_info["highlights_enabled"]) + self.assertEqual(xblock_info["start"], "2030-01-01T00:00:00Z") # noqa: PT009 + self.assertEqual(xblock_info["graded"], False) # noqa: PT009 + self.assertEqual(xblock_info["due"], None) # noqa: PT009 + self.assertEqual(xblock_info["format"], None) # noqa: PT009 + self.assertEqual(xblock_info["highlights"], self.chapter.highlights) # noqa: PT009 + self.assertTrue(xblock_info["highlights_enabled"]) # noqa: PT009 # Finally, validate the entire response for consistency self.validate_xblock_info_consistency( @@ -3411,11 +3411,11 @@ def validate_sequential_xblock_info(self, xblock_info, has_child_info=True): """ Validate that the xblock info is correct for the test sequential. """ - self.assertEqual(xblock_info["category"], "sequential") - self.assertEqual(xblock_info["id"], str(self.sequential.location)) - self.assertEqual(xblock_info["display_name"], "Lesson 1") - self.assertTrue(xblock_info["published"]) - self.assertIsNone(xblock_info.get("edited_by", None)) + self.assertEqual(xblock_info["category"], "sequential") # noqa: PT009 + self.assertEqual(xblock_info["id"], str(self.sequential.location)) # noqa: PT009 + self.assertEqual(xblock_info["display_name"], "Lesson 1") # noqa: PT009 + self.assertTrue(xblock_info["published"]) # noqa: PT009 + self.assertIsNone(xblock_info.get("edited_by", None)) # noqa: PT009 # Finally, validate the entire response for consistency self.validate_xblock_info_consistency( @@ -3426,17 +3426,17 @@ def validate_vertical_xblock_info(self, xblock_info): """ Validate that the xblock info is correct for the test vertical. """ - self.assertEqual(xblock_info["category"], "vertical") - self.assertEqual(xblock_info["id"], str(self.vertical.location)) - self.assertEqual(xblock_info["display_name"], "Unit 1") - self.assertTrue(xblock_info["published"]) - self.assertEqual(xblock_info["edited_by"], "testuser") + self.assertEqual(xblock_info["category"], "vertical") # noqa: PT009 + self.assertEqual(xblock_info["id"], str(self.vertical.location)) # noqa: PT009 + self.assertEqual(xblock_info["display_name"], "Unit 1") # noqa: PT009 + self.assertTrue(xblock_info["published"]) # noqa: PT009 + self.assertEqual(xblock_info["edited_by"], "testuser") # noqa: PT009 # Validate that the correct ancestor info has been included ancestor_info = xblock_info.get("ancestor_info", None) - self.assertIsNotNone(ancestor_info) + self.assertIsNotNone(ancestor_info) # noqa: PT009 ancestors = ancestor_info["ancestors"] - self.assertEqual(len(ancestors), 3) + self.assertEqual(len(ancestors), 3) # noqa: PT009 self.validate_sequential_xblock_info(ancestors[0], has_child_info=True) self.validate_chapter_xblock_info(ancestors[1], has_child_info=False) self.validate_course_xblock_info(ancestors[2], has_child_info=False) @@ -3450,11 +3450,11 @@ def validate_component_xblock_info(self, xblock_info): """ Validate that the xblock info is correct for the test component. """ - self.assertEqual(xblock_info["category"], "video") - self.assertEqual(xblock_info["id"], str(self.video.location)) - self.assertEqual(xblock_info["display_name"], "My Video") - self.assertTrue(xblock_info["published"]) - self.assertIsNone(xblock_info.get("edited_by", None)) + self.assertEqual(xblock_info["category"], "video") # noqa: PT009 + self.assertEqual(xblock_info["id"], str(self.video.location)) # noqa: PT009 + self.assertEqual(xblock_info["display_name"], "My Video") # noqa: PT009 + self.assertTrue(xblock_info["published"]) # noqa: PT009 + self.assertIsNone(xblock_info.get("edited_by", None)) # noqa: PT009 # Finally, validate the entire response for consistency self.validate_xblock_info_consistency(xblock_info) @@ -3469,12 +3469,12 @@ def validate_xblock_info_consistency( """ Validate that the xblock info is internally consistent. """ - self.assertIsNotNone(xblock_info["display_name"]) - self.assertIsNotNone(xblock_info["id"]) - self.assertIsNotNone(xblock_info["category"]) - self.assertTrue(xblock_info["published"]) + self.assertIsNotNone(xblock_info["display_name"]) # noqa: PT009 + self.assertIsNotNone(xblock_info["id"]) # noqa: PT009 + self.assertIsNotNone(xblock_info["category"]) # noqa: PT009 + self.assertTrue(xblock_info["published"]) # noqa: PT009 if has_ancestor_info: - self.assertIsNotNone(xblock_info.get("ancestor_info", None)) + self.assertIsNotNone(xblock_info.get("ancestor_info", None)) # noqa: PT009 ancestors = xblock_info["ancestor_info"]["ancestors"] for ancestor in xblock_info["ancestor_info"]["ancestors"]: self.validate_xblock_info_consistency( @@ -3485,9 +3485,9 @@ def validate_xblock_info_consistency( course_outline=course_outline, ) else: - self.assertIsNone(xblock_info.get("ancestor_info", None)) + self.assertIsNone(xblock_info.get("ancestor_info", None)) # noqa: PT009 if has_child_info: - self.assertIsNotNone(xblock_info.get("child_info", None)) + self.assertIsNotNone(xblock_info.get("child_info", None)) # noqa: PT009 if xblock_info["child_info"].get("children", None): for child_response in xblock_info["child_info"]["children"]: self.validate_xblock_info_consistency( @@ -3498,7 +3498,7 @@ def validate_xblock_info_consistency( course_outline=course_outline, ) else: - self.assertIsNone(xblock_info.get("child_info", None)) + self.assertIsNone(xblock_info.get("child_info", None)) # noqa: PT009 @patch.dict("django.conf.settings.FEATURES", {"ENABLE_SPECIAL_EXAMS": True}) @@ -3557,7 +3557,7 @@ def test_proctoring_is_enabled_for_course(self): def test_special_exam_xblock_info( self, mock_get_exam_by_content_id, - _mock_does_backend_support_onboarding, + _mock_does_backend_support_onboarding, # noqa: PT019 mock_get_exam_configuration_dashboard_url, ): sequential = BlockFactory.create( @@ -3602,7 +3602,7 @@ def test_special_exam_xblock_info( def test_show_review_rules_xblock_info( self, mock_get_exam_by_content_id, - _mock_does_backend_support_onboarding, + _mock_does_backend_support_onboarding, # noqa: PT019 mock_get_exam_configuration_dashboard_url, ): # Set course.proctoring_provider to test_proctoring_provider @@ -3642,7 +3642,7 @@ def test_proctoring_values_correct_depending_on_lti_external( expected_proctoring_link, mock_get_exam_by_content_id, mock_does_backend_support_onboarding, - _mock_get_exam_configuration_dashboard_url, + _mock_get_exam_configuration_dashboard_url, # noqa: PT019 ): sequential = BlockFactory.create( parent_location=self.chapter.location, @@ -3684,8 +3684,8 @@ def test_xblock_was_ever_linked_to_external_exam( external_id, expected_value, mock_get_exam_by_content_id, - _mock_does_backend_support_onboarding_patch, - _mock_get_exam_configuration_dashboard_url, + _mock_does_backend_support_onboarding_patch, # noqa: PT019 + _mock_get_exam_configuration_dashboard_url, # noqa: PT019 ): sequential = BlockFactory.create( parent_location=self.chapter.location, @@ -3712,8 +3712,8 @@ def test_xblock_was_ever_linked_to_external_exam( def test_xblock_was_never_linked_to_external_exam( self, mock_get_exam_by_content_id, - _mock_does_backend_support_onboarding_patch, - _mock_get_exam_configuration_dashboard_url, + _mock_does_backend_support_onboarding_patch, # noqa: PT019 + _mock_get_exam_configuration_dashboard_url, # noqa: PT019 ): sequential = BlockFactory.create( parent_location=self.chapter.location, @@ -3739,7 +3739,7 @@ def test_xblock_was_never_linked_to_external_exam( def test_special_exam_xblock_info_get_dashboard_error( self, mock_get_exam_by_content_id, - _mock_does_backend_support_onboarding, + _mock_does_backend_support_onboarding, # noqa: PT019 mock_get_exam_configuration_dashboard_url, ): sequential = BlockFactory.create( @@ -3804,7 +3804,7 @@ def test_lib_xblock_info(self): html_block = modulestore().get_item(self.top_level_html.location) xblock_info = create_xblock_info(html_block) self.validate_component_xblock_info(xblock_info, html_block) - self.assertIsNone(xblock_info.get("child_info", None)) + self.assertIsNone(xblock_info.get("child_info", None)) # noqa: PT009 def test_lib_child_xblock_info(self): html_block = modulestore().get_item(self.child_html.location) @@ -3812,24 +3812,24 @@ def test_lib_child_xblock_info(self): html_block, include_ancestor_info=True, include_child_info=True ) self.validate_component_xblock_info(xblock_info, html_block) - self.assertIsNone(xblock_info.get("child_info", None)) + self.assertIsNone(xblock_info.get("child_info", None)) # noqa: PT009 ancestors = xblock_info["ancestor_info"]["ancestors"] - self.assertEqual(len(ancestors), 2) - self.assertEqual(ancestors[0]["category"], "vertical") - self.assertEqual(ancestors[0]["id"], str(self.vertical.location)) - self.assertEqual(ancestors[1]["category"], "library") + self.assertEqual(len(ancestors), 2) # noqa: PT009 + self.assertEqual(ancestors[0]["category"], "vertical") # noqa: PT009 + self.assertEqual(ancestors[0]["id"], str(self.vertical.location)) # noqa: PT009 + self.assertEqual(ancestors[1]["category"], "library") # noqa: PT009 def validate_component_xblock_info(self, xblock_info, original_block): """ Validate that the xblock info is correct for the test component. """ - self.assertEqual(xblock_info["category"], original_block.category) - self.assertEqual(xblock_info["id"], str(original_block.location)) - self.assertEqual(xblock_info["display_name"], original_block.display_name) - self.assertIsNone(xblock_info.get("has_changes", None)) - self.assertIsNone(xblock_info.get("published", None)) - self.assertIsNone(xblock_info.get("published_on", None)) - self.assertIsNone(xblock_info.get("graders", None)) + self.assertEqual(xblock_info["category"], original_block.category) # noqa: PT009 + self.assertEqual(xblock_info["id"], str(original_block.location)) # noqa: PT009 + self.assertEqual(xblock_info["display_name"], original_block.display_name) # noqa: PT009 + self.assertIsNone(xblock_info.get("has_changes", None)) # noqa: PT009 + self.assertIsNone(xblock_info.get("published", None)) # noqa: PT009 + self.assertIsNone(xblock_info.get("published_on", None)) # noqa: PT009 + self.assertIsNone(xblock_info.get("graders", None)) # noqa: PT009 class TestLibraryXBlockCreation(ItemTest): @@ -3846,9 +3846,9 @@ def test_add_xblock(self): parent_usage_key=lib.location, display_name="Test", category="html" ) lib = self.store.get_library(lib.location.library_key) - self.assertTrue(lib.children) + self.assertTrue(lib.children) # noqa: PT009 xblock_locator = lib.children[0] - self.assertEqual(self.store.get_item(xblock_locator).display_name, "Test") + self.assertEqual(self.store.get_item(xblock_locator).display_name, "Test") # noqa: PT009 def test_no_add_discussion(self): """ @@ -3858,9 +3858,9 @@ def test_no_add_discussion(self): response = self.create_xblock( parent_usage_key=lib.location, display_name="Test", category="discussion" ) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 lib = self.store.get_library(lib.location.library_key) - self.assertFalse(lib.children) + self.assertFalse(lib.children) # noqa: PT009 def test_no_add_advanced(self): lib = LibraryFactory.create() @@ -3869,9 +3869,9 @@ def test_no_add_advanced(self): response = self.create_xblock( parent_usage_key=lib.location, display_name="Test", category="lti" ) - self.assertEqual(response.status_code, 400) + self.assertEqual(response.status_code, 400) # noqa: PT009 lib = self.store.get_library(lib.location.library_key) - self.assertFalse(lib.children) + self.assertFalse(lib.children) # noqa: PT009 @ddt.ddt @@ -3907,7 +3907,7 @@ def _get_child_xblock_info(self, xblock_info, index): Returns the child xblock info at the specified index. """ children = xblock_info["child_info"]["children"] - self.assertGreater(len(children), index) + self.assertGreater(len(children), index) # noqa: PT009 return children[index] def _get_xblock_info(self, location): @@ -3980,9 +3980,9 @@ def _verify_xblock_info_state( ) else: if should_equal: - self.assertEqual(xblock_info[xblock_info_field], expected_state) + self.assertEqual(xblock_info[xblock_info_field], expected_state) # noqa: PT009 else: - self.assertNotEqual(xblock_info[xblock_info_field], expected_state) + self.assertNotEqual(xblock_info[xblock_info_field], expected_state) # noqa: PT009 def _verify_has_staff_only_message(self, xblock_info, expected_state, path=None): """ @@ -4162,7 +4162,7 @@ def test_staff_only_section(self): vertical_info = self._get_xblock_info(vertical.location) add_container_page_publishing_info(vertical, vertical_info) - self.assertEqual( + self.assertEqual( # noqa: PT009 _xblock_type_and_display_name(chapter), vertical_info["staff_lock_from"] ) @@ -4213,7 +4213,7 @@ def test_staff_only_subsection(self): vertical_info = self._get_xblock_info(vertical.location) add_container_page_publishing_info(vertical, vertical_info) - self.assertEqual( + self.assertEqual( # noqa: PT009 _xblock_type_and_display_name(sequential), vertical_info["staff_lock_from"] ) @@ -4265,7 +4265,7 @@ def test_staff_only_unit(self): vertical_info = self._get_xblock_info(vertical.location) add_container_page_publishing_info(vertical, vertical_info) - self.assertEqual( + self.assertEqual( # noqa: PT009 _xblock_type_and_display_name(vertical), vertical_info["staff_lock_from"] ) @@ -4359,12 +4359,12 @@ def test_self_paced_item_visibility_state(self): # Check that chapter has scheduled state xblock_info = self._get_xblock_info(chapter.location) self._verify_visibility_state(xblock_info, VisibilityState.ready) - self.assertFalse(course.self_paced) + self.assertFalse(course.self_paced) # noqa: PT009 # Change course pacing to self paced course.self_paced = True self.store.update_item(course, self.user.id) - self.assertTrue(course.self_paced) + self.assertTrue(course.self_paced) # noqa: PT009 # Check that in self paced course content has live state now xblock_info = self._get_xblock_info(chapter.location) @@ -4417,13 +4417,13 @@ def create_source_block(self, course): # quick sanity checks source_block = self.store.get_item(source_block.location) - self.assertEqual(source_block.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC)) - self.assertEqual(source_block.display_name, "Source Block") - self.assertEqual( + self.assertEqual(source_block.due, datetime(2010, 11, 22, 4, 0, tzinfo=UTC)) # noqa: PT009 + self.assertEqual(source_block.display_name, "Source Block") # noqa: PT009 + self.assertEqual( # noqa: PT009 source_block.runtime.get_asides(source_block)[0].field11, "html_new_value1" ) - self.assertEqual(source_block.data, "
test
") - self.assertEqual(source_block.items, ["test", "beep"]) + self.assertEqual(source_block.data, "
test
") # noqa: PT009 + self.assertEqual(source_block.items, ["test", "beep"]) # noqa: PT009 return source_block @@ -4432,12 +4432,12 @@ def check_updated(self, source_block, destination_key): Check that the destination block has been updated to match our source block. """ revised = self.store.get_item(destination_key) - self.assertEqual(source_block.display_name, revised.display_name) - self.assertEqual(source_block.due, revised.due) - self.assertEqual(revised.data, source_block.data) - self.assertEqual(revised.items, source_block.items) + self.assertEqual(source_block.display_name, revised.display_name) # noqa: PT009 + self.assertEqual(source_block.due, revised.due) # noqa: PT009 + self.assertEqual(revised.data, source_block.data) # noqa: PT009 + self.assertEqual(revised.items, source_block.items) # noqa: PT009 - self.assertEqual( + self.assertEqual( # noqa: PT009 revised.runtime.get_asides(revised)[0].field11, source_block.runtime.get_asides(source_block)[0].field11, ) @@ -4535,15 +4535,15 @@ def _create_block(self, parent, category, display_name, **kwargs): def test_xblock_edit_view(self): url = reverse_usage_url("xblock_edit_handler", self.video.location) resp = self.client.get_html(url) - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 html_content = resp.content.decode(resp.charset) - self.assertIn("var decodedActionName = 'edit';", html_content) + self.assertIn("var decodedActionName = 'edit';", html_content) # noqa: PT009 def test_xblock_edit_view_contains_resources(self): url = reverse_usage_url("xblock_edit_handler", self.video.location) resp = self.client.get(url) - self.assertEqual(resp.status_code, 200) + self.assertEqual(resp.status_code, 200) # noqa: PT009 html_content = resp.content.decode(resp.charset) soup = BeautifulSoup(html_content, "html.parser") @@ -4551,5 +4551,5 @@ def test_xblock_edit_view_contains_resources(self): resource_links = [link["href"] for link in soup.find_all("link", {"rel": "stylesheet"})] script_sources = [script["src"] for script in soup.find_all("script") if script.get("src")] - self.assertGreater(len(resource_links), 0, f"No CSS resources found in HTML. Found: {resource_links}") - self.assertGreater(len(script_sources), 0, f"No JS resources found in HTML. Found: {script_sources}") + self.assertGreater(len(resource_links), 0, f"No CSS resources found in HTML. Found: {resource_links}") # noqa: PT009 # pylint: disable=line-too-long + self.assertGreater(len(script_sources), 0, f"No JS resources found in HTML. Found: {script_sources}") # noqa: PT009 # pylint: disable=line-too-long diff --git a/cms/djangoapps/contentstore/views/tests/test_certificates.py b/cms/djangoapps/contentstore/views/tests/test_certificates.py index dfbad798f6f4..bd3f2b1b7e54 100644 --- a/cms/djangoapps/contentstore/views/tests/test_certificates.py +++ b/cms/djangoapps/contentstore/views/tests/test_certificates.py @@ -143,10 +143,10 @@ def test_required_fields_are_absent(self): HTTP_X_REQUESTED_WITH="XMLHttpRequest" ) - self.assertEqual(response.status_code, 400) - self.assertNotIn("Location", response) + self.assertEqual(response.status_code, 400) # noqa: PT009 + self.assertNotIn("Location", response) # noqa: PT009 content = json.loads(response.content.decode('utf-8')) - self.assertIn("error", content) + self.assertIn("error", content) # noqa: PT009 def test_invalid_json(self): """ @@ -164,10 +164,10 @@ def test_invalid_json(self): HTTP_X_REQUESTED_WITH="XMLHttpRequest" ) - self.assertEqual(response.status_code, 400) - self.assertNotIn("Location", response) + self.assertEqual(response.status_code, 400) # noqa: PT009 + self.assertNotIn("Location", response) # noqa: PT009 content = json.loads(response.content.decode('utf-8')) - self.assertTrue("error" in content or "detail" in content) + self.assertTrue("error" in content or "detail" in content) # noqa: PT009 def test_certificate_data_validation(self): #Test certificate schema version @@ -177,10 +177,10 @@ def test_certificate_data_validation(self): 'description': 'Test description' } - with self.assertRaises(Exception) as context: + with self.assertRaises(Exception) as context: # noqa: PT027 CertificateManager.validate(json_data_1) - self.assertIn( + self.assertIn( # noqa: PT009 "Unsupported certificate schema version: 100. Expected version: 1.", str(context.exception) ) @@ -191,10 +191,10 @@ def test_certificate_data_validation(self): 'description': 'Test description' } - with self.assertRaises(Exception) as context: + with self.assertRaises(Exception) as context: # noqa: PT027 CertificateManager.validate(json_data_2) - self.assertIn('must have name of the certificate', str(context.exception)) + self.assertIn('must have name of the certificate', str(context.exception)) # noqa: PT009 @ddt.ddt @@ -235,11 +235,11 @@ def test_can_create_certificate(self): data=CERTIFICATE_JSON ) - self.assertEqual(response.status_code, 201) - self.assertIn("Location", response) + self.assertEqual(response.status_code, 201) # noqa: PT009 + self.assertIn("Location", response) # noqa: PT009 content = json.loads(response.content.decode('utf-8')) certificate_id = content.pop("id") - self.assertEqual(content, expected) + self.assertEqual(content, expected) # noqa: PT009 self.assert_event_emitted( 'edx.certificate.configuration.created', course_id=str(self.course.id), @@ -257,7 +257,7 @@ def test_cannot_create_certificate_if_user_has_no_write_permissions(self): data=CERTIFICATE_JSON ) - self.assertEqual(response.status_code, 403) + self.assertEqual(response.status_code, 403) # noqa: PT009 @override_settings(LMS_BASE=None) def test_no_lms_base_for_certificate_web_view_link(self): @@ -265,7 +265,7 @@ def test_no_lms_base_for_certificate_web_view_link(self): course_key=self.course.id, mode='honor' ) - self.assertEqual(test_link, None) + self.assertEqual(test_link, None) # noqa: PT009 @override_settings(LMS_BASE="lms_base_url") def test_lms_link_for_certificate_web_view(self): @@ -275,7 +275,7 @@ def test_lms_link_for_certificate_web_view(self): course_key=self.course.id, mode='honor' ) - self.assertEqual(link, test_url) + self.assertEqual(link, test_url) # noqa: PT009 @override_waffle_flag(toggles.LEGACY_STUDIO_CERTIFICATES, True) @mock.patch.dict('django.conf.settings.FEATURES', {'CERTIFICATES_HTML_VIEW': True}) @@ -289,7 +289,7 @@ def test_certificate_info_in_response(self): data=CERTIFICATE_JSON_WITH_SIGNATORIES ) - self.assertEqual(response.status_code, 201) + self.assertEqual(response.status_code, 201) # noqa: PT009 # in html response result = self.client.get_html(self._url()) @@ -299,10 +299,10 @@ def test_certificate_info_in_response(self): # in JSON response response = self.client.get_json(self._url()) data = json.loads(response.content.decode('utf-8')) - self.assertEqual(len(data), 1) - self.assertEqual(data[0]['name'], 'Test certificate') - self.assertEqual(data[0]['description'], 'Test description') - self.assertEqual(data[0]['version'], CERTIFICATE_SCHEMA_VERSION) + self.assertEqual(len(data), 1) # noqa: PT009 + self.assertEqual(data[0]['name'], 'Test certificate') # noqa: PT009 + self.assertEqual(data[0]['description'], 'Test description') # noqa: PT009 + self.assertEqual(data[0]['version'], CERTIFICATE_SCHEMA_VERSION) # noqa: PT009 @mock.patch.dict('django.conf.settings.FEATURES', {'CERTIFICATES_HTML_VIEW': True}) @override_waffle_flag(toggles.LEGACY_STUDIO_CERTIFICATES, True) @@ -315,7 +315,7 @@ def test_certificate_info_not_in_response(self): data=CERTIFICATE_JSON_WITH_SIGNATORIES ) - self.assertEqual(response.status_code, 201) + self.assertEqual(response.status_code, 201) # noqa: PT009 # in html response result = self.client.get_html(self._url()) @@ -329,14 +329,14 @@ def test_unsupported_http_accept_header(self): self._url(), HTTP_ACCEPT="text/plain", ) - self.assertEqual(response.status_code, 406) + self.assertEqual(response.status_code, 406) # noqa: PT009 def test_certificate_unsupported_method(self): """ Unit Test: test_certificate_unsupported_method """ resp = self.client.put(self._url()) - self.assertEqual(resp.status_code, 405) + self.assertEqual(resp.status_code, 405) # noqa: PT009 def test_not_permitted(self): """ @@ -360,7 +360,7 @@ def test_audit_course_mode_is_skipped(self): response = self.client.get_html( self._url(), ) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) # noqa: PT009 self.assertContains(response, 'verified') self.assertNotContains(response, 'audit') @@ -373,7 +373,7 @@ def test_audit_only_disables_cert(self): response = self.client.get_html( self._url(), ) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) # noqa: PT009 self.assertContains(response, 'This course does not use a mode that offers certificates.') self.assertNotContains(response, 'This module is not enabled.') self.assertNotContains(response, 'Loading') @@ -395,7 +395,7 @@ def test_non_audit_enables_cert(self, slugs): response = self.client.get_html( self._url(), ) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) # noqa: PT009 self.assertNotContains(response, 'This course does not use a mode that offers certificates.') self.assertNotContains(response, 'This module is not enabled.') self.assertContains(response, 'Loading') @@ -423,7 +423,7 @@ def test_assign_unique_identifier_to_certificates(self): new_certificate = json.loads(response.content.decode('utf-8')) for prev_certificate in self.course.certificates['certificates']: - self.assertNotEqual(new_certificate.get('id'), prev_certificate.get('id')) + self.assertNotEqual(new_certificate.get('id'), prev_certificate.get('id')) # noqa: PT009 @ddt.ddt @@ -476,7 +476,7 @@ def test_can_create_new_certificate_if_it_does_not_exist(self): HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) content = json.loads(response.content.decode('utf-8')) - self.assertEqual(content, expected) + self.assertEqual(content, expected) # noqa: PT009 self.assert_event_emitted( 'edx.certificate.configuration.created', course_id=str(self.course.id), @@ -508,7 +508,7 @@ def test_can_edit_certificate(self): HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) content = json.loads(response.content.decode('utf-8')) - self.assertEqual(content, expected) + self.assertEqual(content, expected) # noqa: PT009 self.assert_event_emitted( 'edx.certificate.configuration.modified', course_id=str(self.course.id), @@ -518,9 +518,9 @@ def test_can_edit_certificate(self): # Verify that certificate is properly updated in the course. course_certificates = self.course.certificates['certificates'] - self.assertEqual(len(course_certificates), 2) - self.assertEqual(course_certificates[1].get('name'), 'New test certificate') - self.assertEqual(course_certificates[1].get('description'), 'New test description') + self.assertEqual(len(course_certificates), 2) # noqa: PT009 + self.assertEqual(course_certificates[1].get('name'), 'New test certificate') # noqa: PT009 + self.assertEqual(course_certificates[1].get('description'), 'New test description') # noqa: PT009 def test_can_edit_certificate_without_is_active(self): """ @@ -557,9 +557,9 @@ def test_can_edit_certificate_without_is_active(self): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 201) + self.assertEqual(response.status_code, 201) # noqa: PT009 content = json.loads(response.content.decode('utf-8')) - self.assertEqual(content, expected) + self.assertEqual(content, expected) # noqa: PT009 @ddt.data(C4X_SIGNATORY_PATH, SIGNATORY_PATH) def test_can_delete_certificate_with_signatories(self, signatory_path): @@ -573,7 +573,7 @@ def test_can_delete_certificate_with_signatories(self, signatory_path): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 204) + self.assertEqual(response.status_code, 204) # noqa: PT009 self.assert_event_emitted( 'edx.certificate.configuration.deleted', course_id=str(self.course.id), @@ -582,9 +582,9 @@ def test_can_delete_certificate_with_signatories(self, signatory_path): self.reload_course() # Verify that certificates are properly updated in the course. certificates = self.course.certificates['certificates'] - self.assertEqual(len(certificates), 1) - self.assertEqual(certificates[0].get('name'), 'Name 0') - self.assertEqual(certificates[0].get('description'), 'Description 0') + self.assertEqual(len(certificates), 1) # noqa: PT009 + self.assertEqual(certificates[0].get('name'), 'Name 0') # noqa: PT009 + self.assertEqual(certificates[0].get('description'), 'Description 0') # noqa: PT009 def test_can_delete_certificate_with_slash_prefix_signatory(self): """ @@ -597,7 +597,7 @@ def test_can_delete_certificate_with_slash_prefix_signatory(self): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 204) + self.assertEqual(response.status_code, 204) # noqa: PT009 self.assert_event_emitted( 'edx.certificate.configuration.deleted', course_id=str(self.course.id), @@ -606,9 +606,9 @@ def test_can_delete_certificate_with_slash_prefix_signatory(self): self.reload_course() # Verify that certificates are properly updated in the course. certificates = self.course.certificates['certificates'] - self.assertEqual(len(certificates), 1) - self.assertEqual(certificates[0].get('name'), 'Name 0') - self.assertEqual(certificates[0].get('description'), 'Description 0') + self.assertEqual(len(certificates), 1) # noqa: PT009 + self.assertEqual(certificates[0].get('name'), 'Name 0') # noqa: PT009 + self.assertEqual(certificates[0].get('description'), 'Description 0') # noqa: PT009 @ddt.data("not_a_valid_asset_key{}.png", "/not_a_valid_asset_key{}.png") def test_can_delete_certificate_with_invalid_signatory(self, signatory_path): @@ -622,7 +622,7 @@ def test_can_delete_certificate_with_invalid_signatory(self, signatory_path): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 204) + self.assertEqual(response.status_code, 204) # noqa: PT009 self.assert_event_emitted( 'edx.certificate.configuration.deleted', course_id=str(self.course.id), @@ -631,9 +631,9 @@ def test_can_delete_certificate_with_invalid_signatory(self, signatory_path): self.reload_course() # Verify that certificates are properly updated in the course. certificates = self.course.certificates['certificates'] - self.assertEqual(len(certificates), 1) - self.assertEqual(certificates[0].get('name'), 'Name 0') - self.assertEqual(certificates[0].get('description'), 'Description 0') + self.assertEqual(len(certificates), 1) # noqa: PT009 + self.assertEqual(certificates[0].get('name'), 'Name 0') # noqa: PT009 + self.assertEqual(certificates[0].get('description'), 'Description 0') # noqa: PT009 @ddt.data(C4X_SIGNATORY_PATH, SIGNATORY_PATH) def test_delete_certificate_without_write_permissions(self, signatory_path): @@ -649,7 +649,7 @@ def test_delete_certificate_without_write_permissions(self, signatory_path): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 403) + self.assertEqual(response.status_code, 403) # noqa: PT009 @ddt.data(C4X_SIGNATORY_PATH, SIGNATORY_PATH) def test_delete_certificate_without_global_staff_permissions(self, signatory_path): @@ -667,7 +667,7 @@ def test_delete_certificate_without_global_staff_permissions(self, signatory_pat HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 403) + self.assertEqual(response.status_code, 403) # noqa: PT009 @ddt.data(C4X_SIGNATORY_PATH, SIGNATORY_PATH) def test_update_active_certificate_without_global_staff_permissions(self, signatory_path): @@ -696,7 +696,7 @@ def test_update_active_certificate_without_global_staff_permissions(self, signat HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 403) + self.assertEqual(response.status_code, 403) # noqa: PT009 def test_delete_non_existing_certificate(self): """ @@ -709,7 +709,7 @@ def test_delete_non_existing_certificate(self): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 404) + self.assertEqual(response.status_code, 404) # noqa: PT009 @ddt.data(C4X_SIGNATORY_PATH, SIGNATORY_PATH) def test_can_delete_signatory(self, signatory_path): @@ -721,7 +721,7 @@ def test_can_delete_signatory(self, signatory_path): signatory = certificates[1].get("signatories")[1] image_asset_location = AssetKey.from_string(signatory['signature_image_path']) content = contentstore().find(image_asset_location) - self.assertIsNotNone(content) + self.assertIsNotNone(content) # noqa: PT009 test_url = f'{self._url(cid=1)}/signatories/1' response = self.client.delete( test_url, @@ -729,14 +729,14 @@ def test_can_delete_signatory(self, signatory_path): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 204) + self.assertEqual(response.status_code, 204) # noqa: PT009 self.reload_course() # Verify that certificates are properly updated in the course. certificates = self.course.certificates['certificates'] - self.assertEqual(len(certificates[1].get("signatories")), 2) + self.assertEqual(len(certificates[1].get("signatories")), 2) # noqa: PT009 # make sure signatory signature image is deleted too - self.assertRaises(NotFoundError, contentstore().find, image_asset_location) + self.assertRaises(NotFoundError, contentstore().find, image_asset_location) # noqa: PT027 @ddt.data(C4X_SIGNATORY_PATH, SIGNATORY_PATH) def test_deleting_signatory_without_signature(self, signatory_path): @@ -751,7 +751,7 @@ def test_deleting_signatory_without_signature(self, signatory_path): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 204) + self.assertEqual(response.status_code, 204) # noqa: PT009 def test_delete_signatory_non_existing_certificate(self): """ @@ -765,7 +765,7 @@ def test_delete_signatory_non_existing_certificate(self): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 404) + self.assertEqual(response.status_code, 404) # noqa: PT009 @ddt.data(C4X_SIGNATORY_PATH, SIGNATORY_PATH) def test_certificate_activation_success(self, signatory_path): @@ -786,10 +786,10 @@ def test_certificate_activation_success(self, signatory_path): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest" ) - self.assertEqual(response.status_code, 200) + self.assertEqual(response.status_code, 200) # noqa: PT009 course = self.store.get_course(self.course.id) certificates = course.certificates['certificates'] - self.assertEqual(certificates[0].get('is_active'), is_active) + self.assertEqual(certificates[0].get('is_active'), is_active) # noqa: PT009 cert_event_type = 'activated' if is_active else 'deactivated' self.assert_event_emitted( '.'.join(['edx.certificate.configuration', cert_event_type]), @@ -814,7 +814,7 @@ def test_certificate_activation_without_write_permissions(self, activate, signat HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest" ) - self.assertEqual(response.status_code, 403) + self.assertEqual(response.status_code, 403) # noqa: PT009 @ddt.data(C4X_SIGNATORY_PATH, SIGNATORY_PATH) def test_certificate_activation_failure(self, signatory_path): @@ -833,7 +833,7 @@ def test_certificate_activation_failure(self, signatory_path): HTTP_ACCEPT="application/json", HTTP_X_REQUESTED_WITH="XMLHttpRequest", ) - self.assertEqual(response.status_code, 403) + self.assertEqual(response.status_code, 403) # noqa: PT009 course = self.store.get_course(self.course.id) certificates = course.certificates['certificates'] - self.assertEqual(certificates[0].get('is_active'), False) + self.assertEqual(certificates[0].get('is_active'), False) # noqa: PT009 diff --git a/cms/djangoapps/contentstore/views/tests/test_clipboard_paste.py b/cms/djangoapps/contentstore/views/tests/test_clipboard_paste.py index acbc8a9b497a..8b7ba2225f44 100644 --- a/cms/djangoapps/contentstore/views/tests/test_clipboard_paste.py +++ b/cms/djangoapps/contentstore/views/tests/test_clipboard_paste.py @@ -622,7 +622,7 @@ def setup_library(cls): Creates and returns a legacy content library with 1 problem """ library = LibraryFactory.create(display_name='Library') - lib_block = BlockFactory.create( + lib_block = BlockFactory.create( # noqa: F841 parent_location=library.usage_key, category="problem", display_name="MCQ", diff --git a/cms/djangoapps/contentstore/views/tests/test_container_page.py b/cms/djangoapps/contentstore/views/tests/test_container_page.py index 5c27aea44c30..ee804f10cb7f 100644 --- a/cms/djangoapps/contentstore/views/tests/test_container_page.py +++ b/cms/djangoapps/contentstore/views/tests/test_container_page.py @@ -69,7 +69,7 @@ def test_container_html(self): self._test_html_content( self.child_container, expected_section_tag=( - '