diff --git a/lms/djangoapps/courseware/management/commands/tests/test_dump_course.py b/lms/djangoapps/courseware/management/commands/tests/test_dump_course.py index cc341f3b24316f5b59e268003f281f9c477e8be6..4e02eeba46d254f18e1f94cf2ef7ef233cb9fa3f 100644 --- a/lms/djangoapps/courseware/management/commands/tests/test_dump_course.py +++ b/lms/djangoapps/courseware/management/commands/tests/test_dump_course.py @@ -90,7 +90,7 @@ class CommandsTestBase(SharedModuleStoreTestCase): dumped_courses = output.strip().split('\n') course_ids = {text_type(course_id) for course_id in self.loaded_courses} dumped_ids = set(dumped_courses) - self.assertEqual(course_ids, dumped_ids) + assert course_ids == dumped_ids def test_correct_course_structure_metadata(self): course_id = text_type(self.test_course_key) @@ -103,7 +103,7 @@ class CommandsTestBase(SharedModuleStoreTestCase): self.fail(exception) dump = json.loads(output) - self.assertGreater(len(list(dump.values())), 0) + assert len(list(dump.values())) > 0 def test_dump_course_structure(self): args = [text_type(self.test_course_key)] @@ -115,23 +115,23 @@ class CommandsTestBase(SharedModuleStoreTestCase): # check that all elements in the course structure have metadata, # but not inherited metadata: for element in six.itervalues(dump): - self.assertIn('metadata', element) - self.assertIn('children', element) - self.assertIn('category', element) - self.assertNotIn('inherited_metadata', element) + assert 'metadata' in element + assert 'children' in element + assert 'category' in element + assert 'inherited_metadata' not in element # Check a few elements in the course dump test_course_key = self.test_course_key parent_id = text_type(test_course_key.make_usage_key('chapter', 'Overview')) - self.assertEqual(dump[parent_id]['category'], 'chapter') - self.assertEqual(len(dump[parent_id]['children']), 3) + assert dump[parent_id]['category'] == 'chapter' + assert len(dump[parent_id]['children']) == 3 child_id = dump[parent_id]['children'][1] - self.assertEqual(dump[child_id]['category'], 'videosequence') - self.assertEqual(len(dump[child_id]['children']), 2) + assert dump[child_id]['category'] == 'videosequence' + assert len(dump[child_id]['children']) == 2 video_id = text_type(test_course_key.make_usage_key('video', 'Welcome')) - self.assertEqual(dump[video_id]['category'], 'video') + assert dump[video_id]['category'] == 'video' video_metadata = dump[video_id]['metadata'] video_metadata.pop('edx_video_id', None) six.assertCountEqual( @@ -139,11 +139,11 @@ class CommandsTestBase(SharedModuleStoreTestCase): list(video_metadata.keys()), ['youtube_id_0_75', 'youtube_id_1_0', 'youtube_id_1_25', 'youtube_id_1_5'] ) - self.assertIn('youtube_id_1_0', dump[video_id]['metadata']) + assert 'youtube_id_1_0' in dump[video_id]['metadata'] # Check if there are the right number of elements - self.assertEqual(len(dump), 17) + assert len(dump) == 17 def test_dump_inherited_course_structure(self): args = [text_type(self.test_course_key)] @@ -153,12 +153,12 @@ class CommandsTestBase(SharedModuleStoreTestCase): # check that all elements in the course structure have inherited metadata, # and that it contains a particular value as well: for element in six.itervalues(dump): - self.assertIn('metadata', element) - self.assertIn('children', element) - self.assertIn('category', element) - self.assertIn('inherited_metadata', element) + assert 'metadata' in element + assert 'children' in element + assert 'category' in element + assert 'inherited_metadata' in element # ... but does not contain inherited metadata containing a default value: - self.assertNotIn('due', element['inherited_metadata']) + assert 'due' not in element['inherited_metadata'] def test_dump_inherited_course_structure_with_defaults(self): args = [text_type(self.test_course_key)] @@ -168,25 +168,25 @@ class CommandsTestBase(SharedModuleStoreTestCase): # check that all elements in the course structure have inherited metadata, # and that it contains a particular value as well: for element in six.itervalues(dump): - self.assertIn('metadata', element) - self.assertIn('children', element) - self.assertIn('category', element) - self.assertIn('inherited_metadata', element) + assert 'metadata' in element + assert 'children' in element + assert 'category' in element + assert 'inherited_metadata' in element # ... and contains inherited metadata containing a default value: - self.assertIsNone(element['inherited_metadata']['due']) + assert element['inherited_metadata']['due'] is None def test_export_discussion_ids(self): output = self.call_command('dump_course_structure', text_type(self.course.id)) dump = json.loads(output) dumped_id = dump[text_type(self.discussion.location)]['metadata']['discussion_id'] - self.assertEqual(dumped_id, self.discussion.discussion_id) + assert dumped_id == self.discussion.discussion_id def test_export_discussion_id_custom_id(self): output = self.call_command('dump_course_structure', text_type(self.test_course_key)) dump = json.loads(output) discussion_key = text_type(self.test_course_key.make_usage_key('discussion', 'custom_id')) dumped_id = dump[text_type(discussion_key)]['metadata']['discussion_id'] - self.assertEqual(dumped_id, "custom") + assert dumped_id == 'custom' def check_export_file(self, tar_file): # pylint: disable=missing-function-docstring names = tar_file.getnames() diff --git a/lms/djangoapps/courseware/tests/helpers.py b/lms/djangoapps/courseware/tests/helpers.py index e4f56b36c8a72caa74383419ec077fa99d07de41..dc0ab1fd4198b3107489a7672bbda752a3750ef2 100644 --- a/lms/djangoapps/courseware/tests/helpers.py +++ b/lms/djangoapps/courseware/tests/helpers.py @@ -129,7 +129,7 @@ class BaseTestXmodule(ModuleStoreTestCase): for user in self.users ] - self.assertTrue(all(self.login_statuses)) + assert all(self.login_statuses) def setUp(self): super(BaseTestXmodule, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments @@ -185,23 +185,16 @@ class LoginEnrollmentTestCase(TestCase): """ make_request = getattr(self.client, method.lower()) response = make_request(url, **kwargs) - self.assertEqual( - response.status_code, status_code, - u"{method} request to {url} returned status code {actual}, " - u"expected status code {expected}".format( - method=method, url=url, - actual=response.status_code, expected=status_code - ) - ) + assert response.status_code == status_code, u'{method} request to {url} returned status code {actual}, expected status code {expected}'.format(method=method, url=url, actual=response.status_code, expected=status_code) # pylint: disable=line-too-long return response def assert_account_activated(self, url, method="GET", **kwargs): # lint-amnesty, pylint: disable=missing-function-docstring make_request = getattr(self.client, method.lower()) response = make_request(url, **kwargs) message_list = list(messages.get_messages(response.wsgi_request)) - self.assertEqual(len(message_list), 1) - self.assertIn("success", message_list[0].tags) - self.assertIn("You have activated your account.", message_list[0].message) + assert len(message_list) == 1 + assert 'success' in message_list[0].tags + assert 'You have activated your account.' in message_list[0].message # ============ User creation and login ============== @@ -211,7 +204,7 @@ class LoginEnrollmentTestCase(TestCase): """ resp = self.client.post(reverse('user_api_login_session'), {'email': email, 'password': password}) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 def logout(self): """ @@ -236,7 +229,7 @@ class LoginEnrollmentTestCase(TestCase): self.assert_request_status_code(200, url, method="POST", data=request_data) # Check both that the user is created, and inactive user = User.objects.get(email=email) - self.assertFalse(user.is_active) + assert not user.is_active return user def activate_user(self, email): @@ -250,7 +243,7 @@ class LoginEnrollmentTestCase(TestCase): self.assert_account_activated(url) # Now make sure that the user is now actually activated user = User.objects.get(email=email) - self.assertTrue(user.is_active) + assert user.is_active # And return the user we fetched. return user @@ -269,7 +262,7 @@ class LoginEnrollmentTestCase(TestCase): }) result = resp.status_code == 200 if verify: - self.assertTrue(result) + assert result return result def unenroll(self, course): @@ -303,8 +296,8 @@ class CourseAccessTestMixin(TestCase): action (str): type of access to test. course (CourseDescriptor): a course. """ - self.assertTrue(has_access(user, action, course)) - self.assertTrue(has_access(user, action, CourseOverview.get_from_id(course.id))) + assert has_access(user, action, course) + assert has_access(user, action, CourseOverview.get_from_id(course.id)) def assertCannotAccessCourse(self, user, action, course): """ @@ -324,8 +317,8 @@ class CourseAccessTestMixin(TestCase): them into one method with a boolean flag?), but it makes reading stack traces of failed tests easier to understand at a glance. """ - self.assertFalse(has_access(user, action, course)) - self.assertFalse(has_access(user, action, CourseOverview.get_from_id(course.id))) + assert not has_access(user, action, course) + assert not has_access(user, action, CourseOverview.get_from_id(course.id)) class MasqueradeMixin: @@ -369,8 +362,8 @@ class MasqueradeMixin: }), 'application/json' ) - self.assertEqual(response.status_code, 200) - self.assertTrue(response.json()['success'], response.json().get('error')) + assert response.status_code == 200 + assert response.json()['success'], response.json().get('error') return response diff --git a/lms/djangoapps/courseware/tests/test_about.py b/lms/djangoapps/courseware/tests/test_about.py index 05ca31def52d5ab48b57982e345b60da1c5acef8..fa51481d7799f976850ca2624ca076adbe18fd90 100644 --- a/lms/djangoapps/courseware/tests/test_about.py +++ b/lms/djangoapps/courseware/tests/test_about.py @@ -132,7 +132,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra url = reverse('about_course', args=[text_type(self.course_without_about.id)]) resp = self.client.get(url) - self.assertEqual(resp.status_code, 404) + assert resp.status_code == 404 @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) def test_logged_in_marketing(self): @@ -140,12 +140,12 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) # should be redirected - self.assertEqual(resp.status_code, 302) + assert resp.status_code == 302 # follow this time, and check we're redirected to the course home page resp = self.client.get(url, follow=True) target_url = resp.redirect_chain[-1][0] course_home_url = reverse('openedx.course_experience.course_home', args=[text_type(self.course.id)]) - self.assertTrue(target_url.endswith(course_home_url)) + assert target_url.endswith(course_home_url) @patch.dict(settings.FEATURES, {'ENABLE_COURSE_HOME_REDIRECT': False}) @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) @@ -180,12 +180,10 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra self.setup_user() url = reverse('about_course', args=[text_type(course.id)]) resp = self.client.get(url) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 pre_requisite_courses = get_prerequisite_courses_display(course) pre_requisite_course_about_url = reverse('about_course', args=[text_type(pre_requisite_courses[0]['key'])]) - self.assertIn(u"<span class=\"important-dates-item-text pre-requisite\"><a href=\"{}\">{}</a></span>" - .format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']), - resp.content.decode(resp.charset).strip('\n')) + assert u'<span class="important-dates-item-text pre-requisite"><a href="{}">{}</a></span>'.format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']) in resp.content.decode(resp.charset).strip('\n') # pylint: disable=line-too-long @patch.dict(settings.FEATURES, {'ENABLE_PREREQUISITE_COURSES': True}) def test_about_page_unfulfilled_prereqs(self): @@ -216,16 +214,14 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra url = reverse('about_course', args=[text_type(course.id)]) resp = self.client.get(url) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 pre_requisite_courses = get_prerequisite_courses_display(course) pre_requisite_course_about_url = reverse('about_course', args=[text_type(pre_requisite_courses[0]['key'])]) - self.assertIn(u"<span class=\"important-dates-item-text pre-requisite\"><a href=\"{}\">{}</a></span>" - .format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']), - resp.content.decode(resp.charset).strip('\n')) + assert u'<span class="important-dates-item-text pre-requisite"><a href="{}">{}</a></span>'.format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']) in resp.content.decode(resp.charset).strip('\n') # pylint: disable=line-too-long url = reverse('about_course', args=[six.text_type(pre_requisite_course.id)]) resp = self.client.get(url) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 @ddt.data( [COURSE_VISIBILITY_PRIVATE], @@ -332,7 +328,7 @@ class AboutWithCappedEnrollmentsTestCase(LoginEnrollmentTestCase, SharedModuleSt # Try to enroll as well result = self.enroll(self.course) - self.assertFalse(result) + assert not result # Check that registration button is not present self.assertNotContains(resp, REG_STR) diff --git a/lms/djangoapps/courseware/tests/test_access.py b/lms/djangoapps/courseware/tests/test_access.py index 37a9e749142bd2433da21032d56fae3199198c94..a00333a3d70a7e7c4c09c10a76caef7172ccc171 100644 --- a/lms/djangoapps/courseware/tests/test_access.py +++ b/lms/djangoapps/courseware/tests/test_access.py @@ -7,6 +7,7 @@ Test the access control framework import datetime import itertools +import pytest import ddt import pytz import six @@ -116,11 +117,11 @@ class CoachAccessTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase) ccx_locator = self.make_ccx() # user have access as coach on ccx - self.assertTrue(access.has_ccx_coach_role(self.coach, ccx_locator)) + assert access.has_ccx_coach_role(self.coach, ccx_locator) # user dont have access as coach on ccx self.setup_user() - self.assertFalse(access.has_ccx_coach_role(self.user, ccx_locator)) + assert not access.has_ccx_coach_role(self.user, ccx_locator) def test_ccx_coach_has_staff_role(self): """ @@ -129,15 +130,15 @@ class CoachAccessTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase) ccx_locator = self.make_ccx() # coach user has access as staff on ccx - self.assertTrue(access.has_access(self.coach, 'staff', ccx_locator)) + assert access.has_access(self.coach, 'staff', ccx_locator) # basic user doesn't have staff access on ccx.. self.setup_user() - self.assertFalse(access.has_access(self.user, 'staff', ccx_locator)) + assert not access.has_access(self.user, 'staff', ccx_locator) # until we give her a staff role. CourseStaffRole(ccx_locator).add_users(self.user) - self.assertTrue(access.has_access(self.user, 'staff', ccx_locator)) + assert access.has_access(self.user, 'staff', ccx_locator) def test_access_student_progress_ccx(self): """ @@ -151,12 +152,12 @@ class CoachAccessTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase) # Test for access of a coach resp = self.client.get(reverse('student_progress', args=[six.text_type(ccx_locator), student.id])) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 # Assert access of a student self.client.login(username=student.username, password='test') resp = self.client.get(reverse('student_progress', args=[six.text_type(ccx_locator), self.coach.id])) - self.assertEqual(resp.status_code, 404) + assert resp.status_code == 404 @ddt.ddt @@ -187,15 +188,13 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes def verify_access(self, mock_unit, student_should_have_access, expected_error_type=None): """ Verify the expected result from _has_access_descriptor """ response = access._has_access_descriptor(self.anonymous_user, 'load', mock_unit, course_key=self.course.id) - self.assertEqual(student_should_have_access, bool(response)) + assert student_should_have_access == bool(response) if expected_error_type is not None: - self.assertIsInstance(response, expected_error_type) - self.assertIsNotNone(response.to_json()['error_code']) + assert isinstance(response, expected_error_type) + assert response.to_json()['error_code'] is not None - self.assertTrue( - access._has_access_descriptor(self.course_staff, 'load', mock_unit, course_key=self.course.id) - ) + assert access._has_access_descriptor(self.course_staff, 'load', mock_unit, course_key=self.course.id) def test_has_staff_access_to_preview_mode(self): """ @@ -205,9 +204,9 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes CourseEnrollmentFactory(user=self.student, course_id=self.course.id) for user in [self.global_staff, self.course_staff, self.course_instructor]: - self.assertTrue(access.has_staff_access_to_preview_mode(user, course_key)) + assert access.has_staff_access_to_preview_mode(user, course_key) - self.assertFalse(access.has_staff_access_to_preview_mode(self.student, course_key)) + assert not access.has_staff_access_to_preview_mode(self.student, course_key) # we don't want to restrict a staff user, masquerading as student, # to access preview mode. @@ -218,7 +217,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes with patch('lms.djangoapps.courseware.access.is_masquerading_as_student') as mock_masquerade: mock_masquerade.return_value = True for user in [self.global_staff, self.course_staff, self.course_instructor, self.student]: - self.assertTrue(access.has_staff_access_to_preview_mode(user, course_key)) + assert access.has_staff_access_to_preview_mode(user, course_key) def test_administrative_accesses_to_course_for_user(self): """ @@ -231,9 +230,9 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes # Order matters here, for example `True` at first index in tuple essentially means # given user is a global staff. for count, user in enumerate([self.global_staff, self.course_staff, self.course_instructor]): - self.assertTrue(access.administrative_accesses_to_course_for_user(user, course_key)[count]) + assert access.administrative_accesses_to_course_for_user(user, course_key)[count] - self.assertFalse(any(access.administrative_accesses_to_course_for_user(self.student, course_key))) + assert not any(access.administrative_accesses_to_course_for_user(self.student, course_key)) def test_student_has_access(self): """ @@ -254,35 +253,29 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes with patch('lms.djangoapps.courseware.access.in_preview_mode') as mock_preview: mock_preview.return_value = False for obj in modules: - self.assertTrue(bool(access.has_access(self.student, 'load', obj, course_key=self.course.id))) + assert bool(access.has_access(self.student, 'load', obj, course_key=self.course.id)) with patch('lms.djangoapps.courseware.access.in_preview_mode') as mock_preview: mock_preview.return_value = True for obj in modules: - self.assertFalse(bool(access.has_access(self.student, 'load', obj, course_key=self.course.id))) + assert not bool(access.has_access(self.student, 'load', obj, course_key=self.course.id)) @patch('lms.djangoapps.courseware.access.in_preview_mode', Mock(return_value=True)) def test_has_access_with_preview_mode(self): """ Tests particular user's can access content via has_access in preview mode. """ - self.assertTrue(bool(access.has_access(self.global_staff, 'staff', self.course, course_key=self.course.id))) - self.assertTrue(bool(access.has_access(self.course_staff, 'staff', self.course, course_key=self.course.id))) - self.assertTrue(bool(access.has_access( - self.course_instructor, 'staff', self.course, course_key=self.course.id - ))) - self.assertFalse(bool(access.has_access(self.student, 'staff', self.course, course_key=self.course.id))) - self.assertFalse(bool(access.has_access(self.student, 'load', self.course, course_key=self.course.id))) + assert bool(access.has_access(self.global_staff, 'staff', self.course, course_key=self.course.id)) + assert bool(access.has_access(self.course_staff, 'staff', self.course, course_key=self.course.id)) + assert bool(access.has_access(self.course_instructor, 'staff', self.course, course_key=self.course.id)) + assert not bool(access.has_access(self.student, 'staff', self.course, course_key=self.course.id)) + assert not bool(access.has_access(self.student, 'load', self.course, course_key=self.course.id)) # When masquerading is true, user should not be able to access staff content with patch('lms.djangoapps.courseware.access.is_masquerading_as_student') as mock_masquerade: mock_masquerade.return_value = True - self.assertFalse( - bool(access.has_access(self.global_staff, 'staff', self.course, course_key=self.course.id)) - ) - self.assertFalse( - bool(access.has_access(self.student, 'staff', self.course, course_key=self.course.id)) - ) + assert not bool(access.has_access(self.global_staff, 'staff', self.course, course_key=self.course.id)) + assert not bool(access.has_access(self.student, 'staff', self.course, course_key=self.course.id)) @patch('lms.djangoapps.courseware.access_utils.in_preview_mode', Mock(return_value=True)) def test_has_access_in_preview_mode_with_group(self): @@ -310,86 +303,54 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes # User should not be able to preview when masquerading as student (and not in the group above). with patch('lms.djangoapps.courseware.access.get_user_role') as mock_user_role: mock_user_role.return_value = 'student' - self.assertFalse( - bool(access.has_access(self.global_staff, 'load', chapter, course_key=self.course.id)) - ) + assert not bool(access.has_access(self.global_staff, 'load', chapter, course_key=self.course.id)) # Should be able to preview when in staff or instructor role. for mocked_role in ['staff', 'instructor']: with patch('lms.djangoapps.courseware.access.get_user_role') as mock_user_role: mock_user_role.return_value = mocked_role - self.assertTrue( - bool(access.has_access(self.global_staff, 'load', chapter, course_key=self.course.id)) - ) + assert bool(access.has_access(self.global_staff, 'load', chapter, course_key=self.course.id)) # Now install masquerade group and set staff as a member of that. - self.assertEqual(200, masquerade_as_group_member(self.global_staff, self.course, partition_id, group_0_id)) + assert 200 == masquerade_as_group_member(self.global_staff, self.course, partition_id, group_0_id) # Can load the chapter since user is in the group. - self.assertTrue( - bool(access.has_access(self.global_staff, 'load', chapter, course_key=self.course.id)) - ) + assert bool(access.has_access(self.global_staff, 'load', chapter, course_key=self.course.id)) # Move the user to be a part of the second group. - self.assertEqual(200, masquerade_as_group_member(self.global_staff, self.course, partition_id, group_1_id)) + assert 200 == masquerade_as_group_member(self.global_staff, self.course, partition_id, group_1_id) # Cannot load the chapter since user is in a different group. - self.assertFalse( - bool(access.has_access(self.global_staff, 'load', chapter, course_key=self.course.id)) - ) + assert not bool(access.has_access(self.global_staff, 'load', chapter, course_key=self.course.id)) def test_has_access_to_course(self): - self.assertFalse(access._has_access_to_course( - None, 'staff', self.course.id - )) - - self.assertFalse(access._has_access_to_course( - self.anonymous_user, 'staff', self.course.id - )) - self.assertFalse(access._has_access_to_course( - self.anonymous_user, 'instructor', self.course.id - )) - - self.assertTrue(access._has_access_to_course( - self.global_staff, 'staff', self.course.id - )) - self.assertTrue(access._has_access_to_course( - self.global_staff, 'instructor', self.course.id - )) + assert not access._has_access_to_course(None, 'staff', self.course.id) + + assert not access._has_access_to_course(self.anonymous_user, 'staff', self.course.id) + assert not access._has_access_to_course(self.anonymous_user, 'instructor', self.course.id) + + assert access._has_access_to_course(self.global_staff, 'staff', self.course.id) + assert access._has_access_to_course(self.global_staff, 'instructor', self.course.id) # A user has staff access if they are in the staff group - self.assertTrue(access._has_access_to_course( - self.course_staff, 'staff', self.course.id - )) - self.assertFalse(access._has_access_to_course( - self.course_staff, 'instructor', self.course.id - )) + assert access._has_access_to_course(self.course_staff, 'staff', self.course.id) + assert not access._has_access_to_course(self.course_staff, 'instructor', self.course.id) # A user has staff and instructor access if they are in the instructor group - self.assertTrue(access._has_access_to_course( - self.course_instructor, 'staff', self.course.id - )) - self.assertTrue(access._has_access_to_course( - self.course_instructor, 'instructor', self.course.id - )) + assert access._has_access_to_course(self.course_instructor, 'staff', self.course.id) + assert access._has_access_to_course(self.course_instructor, 'instructor', self.course.id) # A user does not have staff or instructor access if they are # not in either the staff or the the instructor group - self.assertFalse(access._has_access_to_course( - self.student, 'staff', self.course.id - )) - self.assertFalse(access._has_access_to_course( - self.student, 'instructor', self.course.id - )) + assert not access._has_access_to_course(self.student, 'staff', self.course.id) + assert not access._has_access_to_course(self.student, 'instructor', self.course.id) - self.assertFalse(access._has_access_to_course( - self.student, 'not_staff_or_instructor', self.course.id - )) + assert not access._has_access_to_course(self.student, 'not_staff_or_instructor', self.course.id) def test__has_access_string(self): user = Mock(is_staff=True) - self.assertFalse(access._has_access_string(user, 'staff', 'not_global')) + assert not access._has_access_string(user, 'staff', 'not_global') user._has_global_staff_access.return_value = True - self.assertTrue(access._has_access_string(user, 'staff', 'global')) + assert access._has_access_string(user, 'staff', 'global') self.assertRaises(ValueError, access._has_access_string, user, 'not_staff', 'global') @@ -407,12 +368,9 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes (self.course_staff, expected_staff), (self.course_instructor, expected_instructor) ): - self.assertEqual( - bool(access._has_access_error_desc(user, action, descriptor, self.course.id)), - expected_response - ) + assert bool(access._has_access_error_desc(user, action, descriptor, self.course.id)) == expected_response - with self.assertRaises(ValueError): + with pytest.raises(ValueError): access._has_access_error_desc(self.course_instructor, 'not_load_or_staff', descriptor, self.course.id) def test__has_access_descriptor(self): @@ -423,9 +381,9 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes descriptor.merged_group_access = {} # Always returns true because DISABLE_START_DATES is set in test.py - self.assertTrue(access._has_access_descriptor(user, 'load', descriptor)) - self.assertTrue(access._has_access_descriptor(user, 'instructor', descriptor)) - with self.assertRaises(ValueError): + assert access._has_access_descriptor(user, 'load', descriptor) + assert access._has_access_descriptor(user, 'instructor', descriptor) + with pytest.raises(ValueError): access._has_access_descriptor(user, 'not_load_or_staff', descriptor) @ddt.data( @@ -459,8 +417,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes mock_unit.visible_to_staff_only = False mock_unit.merged_group_access = {} - self.assertTrue(bool(access._has_access_descriptor( - self.beta_user, 'load', mock_unit, course_key=self.course.id))) + assert bool(access._has_access_descriptor(self.beta_user, 'load', mock_unit, course_key=self.course.id)) @ddt.data(None, YESTERDAY, TOMORROW) @patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) @@ -513,11 +470,11 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes id=CourseLocator('edX', 'test', '2012_Fall'), enrollment_domain='' ) CourseEnrollmentAllowedFactory(email=user.email, course_id=course.id) - self.assertTrue(access._has_access_course(user, 'enroll', course)) + assert access._has_access_course(user, 'enroll', course) # Staff can always enroll even outside the open enrollment period user = StaffFactory.create(course_key=course.id) - self.assertTrue(access._has_access_course(user, 'enroll', course)) + assert access._has_access_course(user, 'enroll', course) # Non-staff cannot enroll if it is between the start and end dates and invitation only # and not specifically allowed @@ -527,7 +484,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes invitation_only=True ) user = UserFactory.create() - self.assertFalse(access._has_access_course(user, 'enroll', course)) + assert not access._has_access_course(user, 'enroll', course) # Non-staff can enroll if it is between the start and end dates and not invitation only course = Mock( @@ -535,7 +492,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes id=CourseLocator('edX', 'test', '2012_Fall'), enrollment_domain='', invitation_only=False ) - self.assertTrue(access._has_access_course(user, 'enroll', course)) + assert access._has_access_course(user, 'enroll', course) # Non-staff cannot enroll outside the open enrollment period if not specifically allowed course = Mock( @@ -543,7 +500,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes id=CourseLocator('edX', 'test', '2012_Fall'), enrollment_domain='', invitation_only=False ) - self.assertFalse(access._has_access_course(user, 'enroll', course)) + assert not access._has_access_course(user, 'enroll', course) def test__user_passed_as_none(self): """Ensure has_access handles a user being passed as null""" @@ -561,30 +518,30 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes id=course_id, catalog_visibility=CATALOG_VISIBILITY_CATALOG_AND_ABOUT ) - self.assertTrue(access._has_access_course(user, 'see_in_catalog', course)) - self.assertTrue(access._has_access_course(user, 'see_about_page', course)) - self.assertTrue(access._has_access_course(staff, 'see_in_catalog', course)) - self.assertTrue(access._has_access_course(staff, 'see_about_page', course)) + assert access._has_access_course(user, 'see_in_catalog', course) + assert access._has_access_course(user, 'see_about_page', course) + assert access._has_access_course(staff, 'see_in_catalog', course) + assert access._has_access_course(staff, 'see_about_page', course) # Now set visibility to just about page course = Mock( id=CourseLocator('edX', 'test', '2012_Fall'), catalog_visibility=CATALOG_VISIBILITY_ABOUT ) - self.assertFalse(access._has_access_course(user, 'see_in_catalog', course)) - self.assertTrue(access._has_access_course(user, 'see_about_page', course)) - self.assertTrue(access._has_access_course(staff, 'see_in_catalog', course)) - self.assertTrue(access._has_access_course(staff, 'see_about_page', course)) + assert not access._has_access_course(user, 'see_in_catalog', course) + assert access._has_access_course(user, 'see_about_page', course) + assert access._has_access_course(staff, 'see_in_catalog', course) + assert access._has_access_course(staff, 'see_about_page', course) # Now set visibility to none, which means neither in catalog nor about pages course = Mock( id=CourseLocator('edX', 'test', '2012_Fall'), catalog_visibility=CATALOG_VISIBILITY_NONE ) - self.assertFalse(access._has_access_course(user, 'see_in_catalog', course)) - self.assertFalse(access._has_access_course(user, 'see_about_page', course)) - self.assertTrue(access._has_access_course(staff, 'see_in_catalog', course)) - self.assertTrue(access._has_access_course(staff, 'see_about_page', course)) + assert not access._has_access_course(user, 'see_in_catalog', course) + assert not access._has_access_course(user, 'see_about_page', course) + assert access._has_access_course(staff, 'see_in_catalog', course) + assert access._has_access_course(staff, 'see_about_page', course) @patch.dict("django.conf.settings.FEATURES", {'ENABLE_PREREQUISITE_COURSES': True, 'MILESTONES_APP': True}) def test_access_on_course_with_pre_requisites(self): @@ -606,15 +563,15 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes # user should not be able to load course even if enrolled CourseEnrollmentFactory(user=user, course_id=course.id) response = access._has_access_course(user, 'load', course) - self.assertFalse(response) - self.assertIsInstance(response, access_response.MilestoneAccessError) + assert not response + assert isinstance(response, access_response.MilestoneAccessError) # Staff can always access course staff = StaffFactory.create(course_key=course.id) - self.assertTrue(access._has_access_course(staff, 'load', course)) + assert access._has_access_course(staff, 'load', course) # User should be able access after completing required course fulfill_course_milestone(pre_requisite_course.id, user) - self.assertTrue(access._has_access_course(user, 'load', course)) + assert access._has_access_course(user, 'load', course) @ddt.data( (True, True, True), @@ -629,11 +586,8 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes descriptor.visible_to_staff_only = False descriptor.mobile_available = mobile_available - self.assertEqual( - bool(access._has_access_course(self.student, 'load_mobile', descriptor)), - student_expected - ) - self.assertEqual(bool(access._has_access_course(self.staff, 'load_mobile', descriptor)), staff_expected) + assert bool(access._has_access_course(self.student, 'load_mobile', descriptor)) == student_expected + assert bool(access._has_access_course(self.staff, 'load_mobile', descriptor)) == staff_expected @patch.dict("django.conf.settings.FEATURES", {'ENABLE_PREREQUISITE_COURSES': True, 'MILESTONES_APP': True}) def test_courseware_page_unfulfilled_prereqs(self): @@ -670,11 +624,11 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes 'dashboard' ) ) - self.assertEqual(response.status_code, 302) + assert response.status_code == 302 fulfill_course_milestone(pre_requisite_course.id, user) response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 class UserRoleTestCase(TestCase): @@ -701,36 +655,21 @@ class UserRoleTestCase(TestCase): def test_user_role_staff(self): """Ensure that user role is student for staff masqueraded as student.""" - self.assertEqual( - 'staff', - access.get_user_role(self.course_staff, self.course_key) - ) + assert 'staff' == access.get_user_role(self.course_staff, self.course_key) # Masquerade staff self._install_masquerade(self.course_staff) - self.assertEqual( - 'student', - access.get_user_role(self.course_staff, self.course_key) - ) + assert 'student' == access.get_user_role(self.course_staff, self.course_key) def test_user_role_instructor(self): """Ensure that user role is student for instructor masqueraded as student.""" - self.assertEqual( - 'instructor', - access.get_user_role(self.course_instructor, self.course_key) - ) + assert 'instructor' == access.get_user_role(self.course_instructor, self.course_key) # Masquerade instructor self._install_masquerade(self.course_instructor) - self.assertEqual( - 'student', - access.get_user_role(self.course_instructor, self.course_key) - ) + assert 'student' == access.get_user_role(self.course_instructor, self.course_key) def test_user_role_anonymous(self): """Ensure that user role is student for anonymous user.""" - self.assertEqual( - 'student', - access.get_user_role(self.anonymous_user, self.course_key) - ) + assert 'student' == access.get_user_role(self.anonymous_user, self.course_key) @ddt.ddt @@ -806,10 +745,8 @@ class CourseOverviewAccessTestCase(ModuleStoreTestCase): course = getattr(self, course_attr_name) course_overview = CourseOverview.get_from_id(course.id) - self.assertEqual( - bool(access.has_access(user, action, course, course_key=course.id)), - bool(access.has_access(user, action, course_overview, course_key=course.id)) - ) + assert bool(access.has_access(user, action, course, course_key=course.id)) ==\ + bool(access.has_access(user, action, course_overview, course_key=course.id)) def test_course_overview_unsupported_action(self): """ @@ -817,7 +754,7 @@ class CourseOverviewAccessTestCase(ModuleStoreTestCase): ValueError. """ overview = CourseOverview.get_from_id(self.course_default.id) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): access.has_access(self.user, '_non_existent_action', overview) @ddt.data( diff --git a/lms/djangoapps/courseware/tests/test_comprehensive_theming.py b/lms/djangoapps/courseware/tests/test_comprehensive_theming.py index 7d26a3d630a4db167725b732b73e6dbbc57b1e8d..a5ced9d9d65137e03c03c9341c96c02156608a57 100644 --- a/lms/djangoapps/courseware/tests/test_comprehensive_theming.py +++ b/lms/djangoapps/courseware/tests/test_comprehensive_theming.py @@ -28,7 +28,7 @@ class TestComprehensiveTheming(TestCase): asserts presence of the content from header.html and footer.html """ resp = self.client.get('/') - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 # This string comes from footer.html self.assertContains(resp, "super-ugly") @@ -54,7 +54,7 @@ class TestComprehensiveTheming(TestCase): def do_the_test(self): """A function to do the work so we can use the decorator.""" resp = self.client.get('/') - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 self.assertContains(resp, "TEMPORARY THEME") do_the_test(self) @@ -63,19 +63,19 @@ class TestComprehensiveTheming(TestCase): def test_default_logo_image(self): result = staticfiles.finders.find('images/logo.png') - self.assertEqual(result, settings.REPO_ROOT / 'lms/static/images/logo.png') + assert result == (settings.REPO_ROOT / 'lms/static/images/logo.png') @with_comprehensive_theme('red-theme') def test_overridden_logo_image(self): result = staticfiles.finders.find('red-theme/images/logo.png') - self.assertEqual(result, settings.REPO_ROOT / 'themes/red-theme/lms/static/images/logo.png') + assert result == (settings.REPO_ROOT / 'themes/red-theme/lms/static/images/logo.png') def test_default_favicon(self): """ Test default favicon is served if no theme is applied """ result = staticfiles.finders.find('images/favicon.ico') - self.assertEqual(result, settings.REPO_ROOT / 'lms/static/images/favicon.ico') + assert result == (settings.REPO_ROOT / 'lms/static/images/favicon.ico') @with_comprehensive_theme('red-theme') def test_overridden_favicon(self): @@ -83,4 +83,4 @@ class TestComprehensiveTheming(TestCase): Test comprehensive theme override on favicon image. """ result = staticfiles.finders.find('red-theme/images/favicon.ico') - self.assertEqual(result, settings.REPO_ROOT / 'themes/red-theme/lms/static/images/favicon.ico') + assert result == (settings.REPO_ROOT / 'themes/red-theme/lms/static/images/favicon.ico') diff --git a/lms/djangoapps/courseware/tests/test_context_processor.py b/lms/djangoapps/courseware/tests/test_context_processor.py index 1c71fd7ec756e209d238673e23d06b60e7ca12d5..31373c2f0f5406e5f8d4924b81849c8fe996016d 100644 --- a/lms/djangoapps/courseware/tests/test_context_processor.py +++ b/lms/djangoapps/courseware/tests/test_context_processor.py @@ -27,19 +27,19 @@ class UserPrefContextProcessorUnitTest(ModuleStoreTestCase): def test_anonymous_user(self): self.request.user = AnonymousUser() context = user_timezone_locale_prefs(self.request) - self.assertIsNone(context['user_timezone']) - self.assertIsNone(context['user_language']) + assert context['user_timezone'] is None + assert context['user_language'] is None def test_no_timezone_preference(self): set_user_preference(self.user, 'pref-lang', 'en') context = user_timezone_locale_prefs(self.request) - self.assertIsNone(context['user_timezone']) - self.assertIsNotNone(context['user_language']) - self.assertEqual(context['user_language'], 'en') + assert context['user_timezone'] is None + assert context['user_language'] is not None + assert context['user_language'] == 'en' def test_no_language_preference(self): set_user_preference(self.user, 'time_zone', 'Asia/Tokyo') context = user_timezone_locale_prefs(self.request) - self.assertIsNone(context['user_language']) - self.assertIsNotNone(context['user_timezone']) - self.assertEqual(context['user_timezone'], 'Asia/Tokyo') + assert context['user_language'] is None + assert context['user_timezone'] is not None + assert context['user_timezone'] == 'Asia/Tokyo' diff --git a/lms/djangoapps/courseware/tests/test_course_info.py b/lms/djangoapps/courseware/tests/test_course_info.py index 071de1d86007cb6d8ab81dab2eb4f3946bfa50ca..77c3f9deeab45624fb531c000ca9da1f9328ae10 100644 --- a/lms/djangoapps/courseware/tests/test_course_info.py +++ b/lms/djangoapps/courseware/tests/test_course_info.py @@ -69,7 +69,7 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, self.enroll(self.course) url = reverse('info', args=[text_type(self.course.id)]) resp = self.client.get(url) - self.assertNotIn(b"You are not currently enrolled in this course", resp.content) + assert b'You are not currently enrolled in this course' not in resp.content # TODO: LEARNER-611: If this is only tested under Course Info, does this need to move? @mock.patch('openedx.features.enterprise_support.api.enterprise_customer_for_request') @@ -92,8 +92,8 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, def test_anonymous_user(self): url = reverse('info', args=[text_type(self.course.id)]) resp = self.client.get(url) - self.assertEqual(resp.status_code, 200) - self.assertNotIn(b"OOGIE BLOOGIE", resp.content) + assert resp.status_code == 200 + assert b'OOGIE BLOOGIE' not in resp.content def test_logged_in_not_enrolled(self): self.setup_user() @@ -107,7 +107,7 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, enrollment_exists = CourseEnrollment.objects.filter( user=self.user, course_id=self.course.id ).exists() - self.assertFalse(enrollment_exists) + assert not enrollment_exists @mock.patch.dict(settings.FEATURES, {'DISABLE_START_DATES': False}) def test_non_live_course(self): @@ -152,7 +152,7 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, self.setup_user() url = reverse('info', args=['not/a/course']) response = self.client.get(url) - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 @override_waffle_flag(DISABLE_UNIFIED_COURSE_TAB_FLAG, active=True) @@ -178,7 +178,7 @@ class CourseInfoLastAccessedTestCase(LoginEnrollmentTestCase, ModuleStoreTestCas url = reverse('info', args=(six.text_type(self.course.id),)) response = self.client.get(url) content = pq(response.content) - self.assertEqual(content('.page-header-secondary a').length, 0) + assert content('.page-header-secondary a').length == 0 def get_resume_course_url(self, course_info_url): """ @@ -210,17 +210,17 @@ class CourseInfoLastAccessedTestCase(LoginEnrollmentTestCase, ModuleStoreTestCas # Assuring a non-authenticated user cannot see the resume course button. resume_course_url = self.get_resume_course_url(info_url) - self.assertEqual(resume_course_url, None) + assert resume_course_url is None # Assuring an unenrolled user cannot see the resume course button. self.setup_user() resume_course_url = self.get_resume_course_url(info_url) - self.assertEqual(resume_course_url, None) + assert resume_course_url is None # Assuring an enrolled user can see the resume course button. self.enroll(self.course) resume_course_url = self.get_resume_course_url(info_url) - self.assertEqual(resume_course_url, section_url) + assert resume_course_url == section_url @override_waffle_flag(DISABLE_UNIFIED_COURSE_TAB_FLAG, active=True) @@ -298,21 +298,12 @@ class CourseInfoTitleTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase): content = pq(response.content) - self.assertEqual( - expected_title, - content('.page-title').contents()[0].strip(), - ) + assert expected_title == content('.page-title').contents()[0].strip() if expected_subtitle is None: - self.assertEqual( - [], - content('.page-subtitle'), - ) + assert [] == content('.page-subtitle') else: - self.assertEqual( - expected_subtitle, - content('.page-subtitle').contents()[0].strip(), - ) + assert expected_subtitle == content('.page-subtitle').contents()[0].strip() @override_waffle_flag(DISABLE_UNIFIED_COURSE_TAB_FLAG, active=True) @@ -428,7 +419,7 @@ class SelfPacedCourseInfoTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest with check_mongo_calls(mongo_queries): with mock.patch("openedx.core.djangoapps.theming.helpers.get_current_site", return_value=None): resp = self.client.get(url) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 def test_num_queries_instructor_paced(self): # TODO: decrease query count as part of REVO-28 diff --git a/lms/djangoapps/courseware/tests/test_course_survey.py b/lms/djangoapps/courseware/tests/test_course_survey.py index a0c2d4fbc910bef30bbff2715bfaf2e2a0792eed..c057c1a0b2a869616ded9a9dd554892d0f506a79 100644 --- a/lms/djangoapps/courseware/tests/test_course_survey.py +++ b/lms/djangoapps/courseware/tests/test_course_survey.py @@ -101,7 +101,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe kwargs={'course_id': six.text_type(course.id)} ) ) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 def test_visiting_course_without_survey(self): """ @@ -128,7 +128,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe kwargs={'course_id': six.text_type(self.course.id)} ) ) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 def test_visiting_course_with_existing_answers(self): """ @@ -138,7 +138,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe self.postback_url, self.student_answers ) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 self._assert_no_redirect(self.course) @@ -154,7 +154,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe ) ) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 expected = u'<input type="hidden" name="course_id" value="{course_id}" />'.format( course_id=six.text_type(self.course.id) ) @@ -175,7 +175,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe self.postback_url, answers ) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 self._assert_no_redirect(self.course) @@ -186,7 +186,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe ) for answer_obj in answer_objs: - self.assertEqual(answer_obj.course_key, self.course.id) + assert answer_obj.course_key == self.course.id def test_visiting_course_with_bogus_survey(self): """ diff --git a/lms/djangoapps/courseware/tests/test_course_tools.py b/lms/djangoapps/courseware/tests/test_course_tools.py index a605dae8eff4af9d156eb47a66af152bcd3da84c..d726bcd7fb7fcd56893574a00df528b7ac6c78b0 100644 --- a/lms/djangoapps/courseware/tests/test_course_tools.py +++ b/lms/djangoapps/courseware/tests/test_course_tools.py @@ -67,42 +67,42 @@ class VerifiedUpgradeToolTest(SharedModuleStoreTestCase): # lint-amnesty, pylin self.request.user = self.enrollment.user def test_tool_visible(self): - self.assertTrue(VerifiedUpgradeTool().is_enabled(self.request, self.course.id)) + assert VerifiedUpgradeTool().is_enabled(self.request, self.course.id) def test_not_visible_when_no_enrollment_exists(self): self.enrollment.delete() request = RequestFactory().request() request.user = UserFactory() - self.assertFalse(VerifiedUpgradeTool().is_enabled(self.request, self.course.id)) + assert not VerifiedUpgradeTool().is_enabled(self.request, self.course.id) def test_not_visible_when_using_deadline_from_course_mode(self): DynamicUpgradeDeadlineConfiguration.objects.create(enabled=False) - self.assertFalse(VerifiedUpgradeTool().is_enabled(self.request, self.course.id)) + assert not VerifiedUpgradeTool().is_enabled(self.request, self.course.id) def test_not_visible_when_enrollment_is_inactive(self): self.enrollment.is_active = False self.enrollment.save() - self.assertFalse(VerifiedUpgradeTool().is_enabled(self.request, self.course.id)) + assert not VerifiedUpgradeTool().is_enabled(self.request, self.course.id) def test_not_visible_when_already_verified(self): self.enrollment.mode = CourseMode.VERIFIED self.enrollment.save() - self.assertFalse(VerifiedUpgradeTool().is_enabled(self.request, self.course.id)) + assert not VerifiedUpgradeTool().is_enabled(self.request, self.course.id) def test_not_visible_when_no_verified_track(self): self.course_verified_mode.delete() - self.assertFalse(VerifiedUpgradeTool().is_enabled(self.request, self.course.id)) + assert not VerifiedUpgradeTool().is_enabled(self.request, self.course.id) def test_not_visible_when_course_deadline_has_passed(self): self.course_verified_mode.expiration_datetime = self.now - datetime.timedelta(days=1) self.course_verified_mode.save() - self.assertFalse(VerifiedUpgradeTool().is_enabled(self.request, self.course.id)) + assert not VerifiedUpgradeTool().is_enabled(self.request, self.course.id) def test_not_visible_when_course_mode_has_no_deadline(self): self.course_verified_mode.expiration_datetime = None self.course_verified_mode.save() - self.assertFalse(VerifiedUpgradeTool().is_enabled(self.request, self.course.id)) + assert not VerifiedUpgradeTool().is_enabled(self.request, self.course.id) class FinancialAssistanceToolTest(SharedModuleStoreTestCase): @@ -164,38 +164,38 @@ class FinancialAssistanceToolTest(SharedModuleStoreTestCase): def test_tool_visible_logged_in(self): self.course_financial_mode.save() - self.assertTrue(FinancialAssistanceTool().is_enabled(self.request, self.course.id)) + assert FinancialAssistanceTool().is_enabled(self.request, self.course.id) def test_tool_not_visible_when_not_eligible(self): self.course_overview.eligible_for_financial_aid = False self.course_overview.save() - self.assertFalse(FinancialAssistanceTool().is_enabled(self.request, self.course_overview.id)) + assert not FinancialAssistanceTool().is_enabled(self.request, self.course_overview.id) def test_tool_not_visible_when_user_not_enrolled(self): self.course_financial_mode.save() self.request.user = None - self.assertFalse(FinancialAssistanceTool().is_enabled(self.request, self.course.id)) + assert not FinancialAssistanceTool().is_enabled(self.request, self.course.id) # mock the response from get_enrollment to use enrollment with course_upgrade_deadline in the past @patch('lms.djangoapps.courseware.course_tools.CourseEnrollment.get_enrollment') def test_not_visible_when_upgrade_deadline_has_passed(self, get_enrollment_mock): get_enrollment_mock.return_value = self.enrollment_deadline_past - self.assertFalse(FinancialAssistanceTool().is_enabled(self.request, self.course.id)) + assert not FinancialAssistanceTool().is_enabled(self.request, self.course.id) # mock the response from get_enrollment to use enrollment with no course_upgrade_deadline @patch('lms.djangoapps.courseware.course_tools.CourseEnrollment.get_enrollment') def test_not_visible_when_no_upgrade_deadline(self, get_enrollment_mock): get_enrollment_mock.return_value = self.enrollment_deadline_missing - self.assertFalse(FinancialAssistanceTool().is_enabled(self.request, self.course.id)) + assert not FinancialAssistanceTool().is_enabled(self.request, self.course.id) def test_tool_not_visible_when_end_date_passed(self): self.course_overview.end_date = self.now - datetime.timedelta(days=30) self.course_overview.save() - self.assertFalse(FinancialAssistanceTool().is_enabled(self.request, self.course_overview.id)) + assert not FinancialAssistanceTool().is_enabled(self.request, self.course_overview.id) # mock the response from get_enrollment to use enrollment where learner upgraded @patch('lms.djangoapps.courseware.course_tools.CourseEnrollment.get_enrollment') def test_tool_not_visible_when_already_upgraded(self, get_enrollment_mock): self.course_financial_mode.save() get_enrollment_mock.return_value = self.enrollment_upgraded - self.assertFalse(FinancialAssistanceTool().is_enabled(self.request, self.course.id)) + assert not FinancialAssistanceTool().is_enabled(self.request, self.course.id) diff --git a/lms/djangoapps/courseware/tests/test_courses.py b/lms/djangoapps/courseware/tests/test_courses.py index fbce5d1d1b08657f3354251a3a2c4bbfd58b93ca..f177aeacaee41e64f58cb2d13510a4be49d530ef 100644 --- a/lms/djangoapps/courseware/tests/test_courses.py +++ b/lms/djangoapps/courseware/tests/test_courses.py @@ -7,6 +7,7 @@ Tests for course access import datetime import itertools +import pytest import ddt import mock import pytz @@ -75,9 +76,9 @@ class CoursesTest(ModuleStoreTestCase): ) cms_url = u"//{}/course/{}".format(CMS_BASE_TEST, six.text_type(self.course.id)) - self.assertEqual(cms_url, get_cms_course_link(self.course)) + assert cms_url == get_cms_course_link(self.course) cms_url = u"//{}/course/{}".format(CMS_BASE_TEST, six.text_type(self.course.location)) - self.assertEqual(cms_url, get_cms_block_link(self.course, 'course')) + assert cms_url == get_cms_block_link(self.course, 'course') @ddt.data(GET_COURSE_WITH_ACCESS, GET_COURSE_OVERVIEW_WITH_ACCESS) def test_get_course_func_with_access_error(self, course_access_func_name): @@ -85,11 +86,11 @@ class CoursesTest(ModuleStoreTestCase): user = UserFactory.create() course = CourseFactory.create(visible_to_staff_only=True) - with self.assertRaises(CoursewareAccessException) as error: + with pytest.raises(CoursewareAccessException) as error: course_access_func(user, 'load', course.id) - self.assertEqual(text_type(error.exception), "Course not found.") - self.assertEqual(error.exception.access_response.error_code, "not_visible_to_user") - self.assertFalse(error.exception.access_response.has_access) + assert text_type(error.value) == 'Course not found.' + assert error.value.access_response.error_code == 'not_visible_to_user' + assert not error.value.access_response.has_access @ddt.data( (GET_COURSE_WITH_ACCESS, 1), @@ -125,18 +126,14 @@ class CoursesTest(ModuleStoreTestCase): primary_course = CourseFactory.create(org=primary, emit_signals=True) alternate_course = CourseFactory.create(org=alternate, emit_signals=True) - self.assertNotEqual(primary_course.org, alternate_course.org) + assert primary_course.org != alternate_course.org unfiltered_courses = get_courses(user) for org in [primary_course.org, alternate_course.org]: - self.assertTrue( - any(course.org == org for course in unfiltered_courses) - ) + assert any(((course.org == org) for course in unfiltered_courses)) filtered_courses = get_courses(user, org=primary) - self.assertTrue( - all(course.org == primary_course.org for course in filtered_courses) - ) + assert all(((course.org == primary_course.org) for course in filtered_courses)) with mock.patch( 'openedx.core.djangoapps.site_configuration.helpers.get_value', @@ -146,13 +143,11 @@ class CoursesTest(ModuleStoreTestCase): # Request filtering for an org distinct from the designated org. no_courses = get_courses(user, org=primary) - self.assertEqual(list(no_courses), []) + assert list(no_courses) == [] # Request filtering for an org matching the designated org. site_courses = get_courses(user, org=alternate) - self.assertTrue( - all(course.org == alternate_course.org for course in site_courses) - ) + assert all(((course.org == alternate_course.org) for course in site_courses)) def test_get_courses_with_filter(self): """ @@ -169,32 +164,25 @@ class CoursesTest(ModuleStoreTestCase): (dict(mobile_available=False), {non_mobile_course.id}), ) for filter_, expected_courses in test_cases: - self.assertEqual( - { - course.id - for course in - get_courses(user, filter_=filter_) - }, - expected_courses, - u"testing get_courses with filter_={}".format(filter_), - ) + assert {course.id for course in get_courses(user, filter_=filter_)} ==\ + expected_courses, u'testing get_courses with filter_={}'.format(filter_) def test_get_current_child(self): mock_xmodule = mock.MagicMock() - self.assertIsNone(get_current_child(mock_xmodule)) + assert get_current_child(mock_xmodule) is None mock_xmodule.position = -1 mock_xmodule.get_display_items.return_value = ['one', 'two', 'three'] - self.assertEqual(get_current_child(mock_xmodule), 'one') + assert get_current_child(mock_xmodule) == 'one' mock_xmodule.position = 2 - self.assertEqual(get_current_child(mock_xmodule), 'two') - self.assertEqual(get_current_child(mock_xmodule, requested_child='first'), 'one') - self.assertEqual(get_current_child(mock_xmodule, requested_child='last'), 'three') + assert get_current_child(mock_xmodule) == 'two' + assert get_current_child(mock_xmodule, requested_child='first') == 'one' + assert get_current_child(mock_xmodule, requested_child='last') == 'three' mock_xmodule.position = 3 mock_xmodule.get_display_items.return_value = [] - self.assertIsNone(get_current_child(mock_xmodule)) + assert get_current_child(mock_xmodule) is None class ModuleStoreBranchSettingTest(ModuleStoreTestCase): @@ -208,7 +196,7 @@ class ModuleStoreBranchSettingTest(ModuleStoreTestCase): MODULESTORE_BRANCH='fake_default_branch', ) def test_default_modulestore_preview_mapping(self): - self.assertEqual(_get_modulestore_branch_setting(), ModuleStoreEnum.Branch.draft_preferred) + assert _get_modulestore_branch_setting() == ModuleStoreEnum.Branch.draft_preferred @mock.patch( 'xmodule.modulestore.django.get_current_request_hostname', @@ -219,7 +207,7 @@ class ModuleStoreBranchSettingTest(ModuleStoreTestCase): MODULESTORE_BRANCH='fake_default_branch', ) def test_default_modulestore_branch_mapping(self): - self.assertEqual(_get_modulestore_branch_setting(), 'fake_default_branch') + assert _get_modulestore_branch_setting() == 'fake_default_branch' @override_settings(CMS_BASE=CMS_BASE_TEST) @@ -229,29 +217,17 @@ class MongoCourseImageTestCase(ModuleStoreTestCase): def test_get_image_url(self): """Test image URL formatting.""" course = CourseFactory.create(org='edX', course='999') - self.assertEqual(course_image_url(course), '/c4x/edX/999/asset/{0}'.format(course.course_image)) + assert course_image_url(course) == '/c4x/edX/999/asset/{0}'.format(course.course_image) def test_non_ascii_image_name(self): # Verify that non-ascii image names are cleaned course = CourseFactory.create(course_image=u'before_\N{SNOWMAN}_after.jpg') - self.assertEqual( - course_image_url(course), - '/c4x/{org}/{course}/asset/before___after.jpg'.format( - org=course.location.org, - course=course.location.course - ) - ) + assert course_image_url(course) == '/c4x/{org}/{course}/asset/before___after.jpg'.format(org=course.location.org, course=course.location.course) # pylint: disable=line-too-long def test_spaces_in_image_name(self): # Verify that image names with spaces in them are cleaned course = CourseFactory.create(course_image=u'before after.jpg') - self.assertEqual( - course_image_url(course), - '/c4x/{org}/{course}/asset/before_after.jpg'.format( - org=course.location.org, - course=course.location.course - ) - ) + assert course_image_url(course) == '/c4x/{org}/{course}/asset/before_after.jpg'.format(org=course.location.org, course=course.location.course) # pylint: disable=line-too-long def test_static_asset_path_course_image_default(self): """ @@ -259,10 +235,7 @@ class MongoCourseImageTestCase(ModuleStoreTestCase): being set that we get the right course_image url. """ course = CourseFactory.create(static_asset_path="foo") - self.assertEqual( - course_image_url(course), - '/static/foo/images/course_image.jpg' - ) + assert course_image_url(course) == '/static/foo/images/course_image.jpg' def test_static_asset_path_course_image_set(self): """ @@ -271,10 +244,7 @@ class MongoCourseImageTestCase(ModuleStoreTestCase): """ course = CourseFactory.create(course_image=u'things_stuff.jpg', static_asset_path="foo") - self.assertEqual( - course_image_url(course), - '/static/foo/things_stuff.jpg' - ) + assert course_image_url(course) == '/static/foo/things_stuff.jpg' class XmlCourseImageTestCase(XModuleXmlImportTest): @@ -283,15 +253,15 @@ class XmlCourseImageTestCase(XModuleXmlImportTest): def test_get_image_url(self): """Test image URL formatting.""" course = self.process_xml(xml.CourseFactory.build()) - self.assertEqual(course_image_url(course), '/static/xml_test_course/images/course_image.jpg') + assert course_image_url(course) == '/static/xml_test_course/images/course_image.jpg' def test_non_ascii_image_name(self): course = self.process_xml(xml.CourseFactory.build(course_image=u'before_\N{SNOWMAN}_after.jpg')) - self.assertEqual(course_image_url(course), u'/static/xml_test_course/before_\N{SNOWMAN}_after.jpg') + assert course_image_url(course) == u'/static/xml_test_course/before_☃_after.jpg' def test_spaces_in_image_name(self): course = self.process_xml(xml.CourseFactory.build(course_image=u'before after.jpg')) - self.assertEqual(course_image_url(course), u'/static/xml_test_course/before after.jpg') + assert course_image_url(course) == u'/static/xml_test_course/before after.jpg' class CoursesRenderTest(ModuleStoreTestCase): @@ -315,7 +285,7 @@ class CoursesRenderTest(ModuleStoreTestCase): def test_get_course_info_section_render(self): # Test render works okay course_info = get_course_info_section(self.request, self.request.user, self.course, 'handouts') - self.assertEqual(course_info, u"<a href='/c4x/edX/toy/asset/handouts_sample_handout.txt'>Sample</a>") + assert course_info == u"<a href='/c4x/edX/toy/asset/handouts_sample_handout.txt'>Sample</a>" # Test when render raises an exception with mock.patch('lms.djangoapps.courseware.courses.get_module') as mock_module_render: @@ -323,13 +293,13 @@ class CoursesRenderTest(ModuleStoreTestCase): render=mock.Mock(side_effect=Exception('Render failed!')) ) course_info = get_course_info_section(self.request, self.request.user, self.course, 'handouts') - self.assertIn("this module is temporarily unavailable", course_info) + assert 'this module is temporarily unavailable' in course_info def test_get_course_about_section_render(self): # Test render works okay course_about = get_course_about_section(self.request, self.course, 'short_description') - self.assertEqual(course_about, "A course about toys.") + assert course_about == 'A course about toys.' # Test when render raises an exception with mock.patch('lms.djangoapps.courseware.courses.get_module') as mock_module_render: @@ -337,7 +307,7 @@ class CoursesRenderTest(ModuleStoreTestCase): render=mock.Mock(side_effect=Exception('Render failed!')) ) course_about = get_course_about_section(self.request, self.course, 'short_description') - self.assertIn("this module is temporarily unavailable", course_about) + assert 'this module is temporarily unavailable' in course_about class CourseEnrollmentOpenTests(ModuleStoreTestCase): # lint-amnesty, pylint: disable=missing-class-docstring @@ -349,41 +319,41 @@ class CourseEnrollmentOpenTests(ModuleStoreTestCase): # lint-amnesty, pylint: d start = self.now - datetime.timedelta(days=1) end = self.now + datetime.timedelta(days=1) course = CourseFactory(enrollment_start=start, enrollment_end=end) - self.assertTrue(course_open_for_self_enrollment(course.id)) + assert course_open_for_self_enrollment(course.id) def test_course_enrollment_closed_future(self): start = self.now + datetime.timedelta(days=1) end = self.now + datetime.timedelta(days=2) course = CourseFactory(enrollment_start=start, enrollment_end=end) - self.assertFalse(course_open_for_self_enrollment(course.id)) + assert not course_open_for_self_enrollment(course.id) def test_course_enrollment_closed_past(self): start = self.now - datetime.timedelta(days=2) end = self.now - datetime.timedelta(days=1) course = CourseFactory(enrollment_start=start, enrollment_end=end) - self.assertFalse(course_open_for_self_enrollment(course.id)) + assert not course_open_for_self_enrollment(course.id) def test_course_enrollment_dates_missing(self): course = CourseFactory() - self.assertTrue(course_open_for_self_enrollment(course.id)) + assert course_open_for_self_enrollment(course.id) def test_course_enrollment_dates_missing_start(self): end = self.now + datetime.timedelta(days=1) course = CourseFactory(enrollment_end=end) - self.assertTrue(course_open_for_self_enrollment(course.id)) + assert course_open_for_self_enrollment(course.id) end = self.now - datetime.timedelta(days=1) course = CourseFactory(enrollment_end=end) - self.assertFalse(course_open_for_self_enrollment(course.id)) + assert not course_open_for_self_enrollment(course.id) def test_course_enrollment_dates_missing_end(self): start = self.now - datetime.timedelta(days=1) course = CourseFactory(enrollment_start=start) - self.assertTrue(course_open_for_self_enrollment(course.id)) + assert course_open_for_self_enrollment(course.id) start = self.now + datetime.timedelta(days=1) course = CourseFactory(enrollment_start=start) - self.assertFalse(course_open_for_self_enrollment(course.id)) + assert not course_open_for_self_enrollment(course.id) @ddt.ddt @@ -427,7 +397,7 @@ class CourseInstantiationTests(ModuleStoreTestCase): for chapter in course_module.get_children(): for section in chapter.get_children(): for item in section.get_children(): - self.assertTrue(item.graded) + assert item.graded class TestGetCourseChapters(ModuleStoreTestCase): @@ -439,10 +409,10 @@ class TestGetCourseChapters(ModuleStoreTestCase): """ Test non-existant course returns empty list. """ - self.assertEqual(get_course_chapter_ids(None), []) + assert get_course_chapter_ids(None) == [] # build a fake key fake_course_key = CourseKey.from_string('course-v1:FakeOrg+CN1+CR-FALLNEVER1') - self.assertEqual(get_course_chapter_ids(fake_course_key), []) + assert get_course_chapter_ids(fake_course_key) == [] def test_get_chapters(self): """ @@ -452,11 +422,8 @@ class TestGetCourseChapters(ModuleStoreTestCase): ItemFactory(parent=course, category='chapter') ItemFactory(parent=course, category='chapter') course_chapter_ids = get_course_chapter_ids(course.location.course_key) - self.assertEqual(len(course_chapter_ids), 2) - self.assertEqual( - course_chapter_ids, - [six.text_type(child) for child in course.children] - ) + assert len(course_chapter_ids) == 2 + assert course_chapter_ids == [six.text_type(child) for child in course.children] class TestGetCourseAssignments(CompletionWaffleTestMixin, ModuleStoreTestCase): @@ -478,5 +445,5 @@ class TestGetCourseAssignments(CompletionWaffleTestMixin, ModuleStoreTestCase): BlockCompletion.objects.submit_completion(self.user, problem.location, 1) assignments = get_course_assignments(course.location.context_key, self.user, None) - self.assertEqual(len(assignments), 1) - self.assertTrue(assignments[0].complete) + assert len(assignments) == 1 + assert assignments[0].complete diff --git a/lms/djangoapps/courseware/tests/test_credit_requirements.py b/lms/djangoapps/courseware/tests/test_credit_requirements.py index 70132a86732fa6eed542eafee5abc0c4d25f89e4..b92b547c6998f5381b70b9f4de3437145222a623 100644 --- a/lms/djangoapps/courseware/tests/test_credit_requirements.py +++ b/lms/djangoapps/courseware/tests/test_credit_requirements.py @@ -69,7 +69,7 @@ class ProgressPageCreditRequirementsTest(SharedModuleStoreTestCase): self.user.profile.save() result = self.client.login(username=self.USERNAME, password=self.PASSWORD) - self.assertTrue(result, msg="Could not log in") + assert result, 'Could not log in' # Enroll the user in the course as "verified" self.enrollment = CourseEnrollmentFactory( diff --git a/lms/djangoapps/courseware/tests/test_date_summary.py b/lms/djangoapps/courseware/tests/test_date_summary.py index 3b049f6fc9fa1cfc6a6290d743ca44ed91d761e3..9601c6d68d925972d6ffedb5239b05571a50a736 100644 --- a/lms/djangoapps/courseware/tests/test_date_summary.py +++ b/lms/djangoapps/courseware/tests/test_date_summary.py @@ -89,14 +89,14 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): course = create_course_run() url = reverse('openedx.course_experience.course_home', args=(course.id,)) response = self.client.get(url) - self.assertEqual(200, response.status_code) + assert 200 == response.status_code # Tests for which blocks are enabled def assert_block_types(self, course, user, expected_blocks): """Assert that the enabled block types for this course are as expected.""" blocks = get_course_date_blocks(course, user) - self.assertEqual(len(blocks), len(expected_blocks)) - self.assertEqual(set(type(b) for b in blocks), set(expected_blocks)) + assert len(blocks) == len(expected_blocks) + assert set((type(b) for b in blocks)) == set(expected_blocks) @ddt.data( # Verified enrollment with no photo-verification before course start @@ -241,22 +241,22 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): TodaysDate, CourseAssignmentDate, CourseAssignmentDate, CourseEndDate, VerificationDeadlineDate ) blocks = get_course_date_blocks(course, user, request, num_assignments=2) - self.assertEqual(len(blocks), len(expected_blocks)) - self.assertEqual(set(type(b) for b in blocks), set(expected_blocks)) + assert len(blocks) == len(expected_blocks) + assert set((type(b) for b in blocks)) == set(expected_blocks) assignment_blocks = filter(lambda b: isinstance(b, CourseAssignmentDate), blocks) for assignment in assignment_blocks: assignment_title = str(assignment.title_html) or str(assignment.title) - self.assertNotEqual(assignment_title, 'Third nearest assignment') - self.assertNotEqual(assignment_title, 'Past due date') - self.assertNotEqual(assignment_title, 'Not returned since we do not get non-graded subsections') + assert assignment_title != 'Third nearest assignment' + assert assignment_title != 'Past due date' + assert assignment_title != 'Not returned since we do not get non-graded subsections' # checking if it is _in_ the title instead of being the title since released assignments # are actually links. Unreleased assignments are just the string of the title. if 'Released' in assignment_title: for html_tag in assignment_title_html: - self.assertIn(html_tag, assignment_title) + assert html_tag in assignment_title elif assignment_title == 'Not released': for html_tag in assignment_title_html: - self.assertNotIn(html_tag, assignment_title) + assert html_tag not in assignment_title # No restrictions on number of assignments to return expected_blocks = ( @@ -265,46 +265,46 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): VerificationDeadlineDate ) blocks = get_course_date_blocks(course, user, request, include_past_dates=True) - self.assertEqual(len(blocks), len(expected_blocks)) - self.assertEqual(set(type(b) for b in blocks), set(expected_blocks)) + assert len(blocks) == len(expected_blocks) + assert set((type(b) for b in blocks)) == set(expected_blocks) assignment_blocks = filter(lambda b: isinstance(b, CourseAssignmentDate), blocks) for assignment in assignment_blocks: assignment_title = str(assignment.title_html) or str(assignment.title) - self.assertNotEqual(assignment_title, 'Not returned since we do not get non-graded subsections') + assert assignment_title != 'Not returned since we do not get non-graded subsections' assignment_type = str(assignment.assignment_type) # checking if it is _in_ the title instead of being the title since released assignments # are actually links. Unreleased assignments are just the string of the title. # also checking that the assignment type is returned for graded subsections if 'Released' in assignment_title: - self.assertEqual(assignment_type, 'Homework') + assert assignment_type == 'Homework' for html_tag in assignment_title_html: - self.assertIn(html_tag, assignment_title) + assert html_tag in assignment_title elif assignment_title == 'Not released': - self.assertEqual(assignment_type, 'Homework') + assert assignment_type == 'Homework' for html_tag in assignment_title_html: - self.assertNotIn(html_tag, assignment_title) + assert html_tag not in assignment_title elif assignment_title == 'Third nearest assignment': - self.assertEqual(assignment_type, 'Exam') + assert assignment_type == 'Exam' # It's still not released for html_tag in assignment_title_html: - self.assertNotIn(html_tag, assignment_title) + assert html_tag not in assignment_title elif 'Past due date' in assignment_title: - self.assertGreater(now, assignment.date) - self.assertEqual(assignment_type, 'Exam') + assert now > assignment.date + assert assignment_type == 'Exam' for html_tag in assignment_title_html: - self.assertIn(html_tag, assignment_title) + assert html_tag in assignment_title elif 'No start date' == assignment_title: - self.assertEqual(assignment_type, 'Speech') + assert assignment_type == 'Speech' # Can't determine if it is released so it does not get a link for html_tag in assignment_title_html: - self.assertNotIn(html_tag, assignment_title) + assert html_tag not in assignment_title # This is the item with no display name where we set one ourselves. elif 'Assignment' in assignment_title: - self.assertEqual(assignment_type, None) + assert assignment_type is None # Can't determine if it is released so it does not get a link for html_tag in assignment_title_html: - self.assertIn(html_tag, assignment_title) + assert html_tag in assignment_title @override_experiment_waffle_flag(RELATIVE_DATES_FLAG, active=True) @ddt.data( @@ -370,7 +370,7 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): submission_end=(now + timedelta(days=7)).isoformat(), ) blocks = get_course_date_blocks(course, user, request, include_past_dates=True) - self.assertEqual(len(blocks), date_block_count) + assert len(blocks) == date_block_count @override_experiment_waffle_flag(RELATIVE_DATES_FLAG, active=True) def test_enabled_block_types_with_expired_course(self): @@ -417,10 +417,10 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): course = create_course_run() user = create_user() block = TodaysDate(course, user) - self.assertTrue(block.is_enabled) - self.assertTrue(block.is_allowed) - self.assertEqual(block.date, datetime.now(utc)) - self.assertEqual(block.title, 'current_datetime') + assert block.is_enabled + assert block.is_allowed + assert block.date == datetime.now(utc) + assert block.title == 'current_datetime' @ddt.data( 'info', @@ -472,7 +472,7 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): course = create_course_run() user = create_user() block = CourseStartDate(course, user) - self.assertEqual(block.date, course.start) + assert block.date == course.start @ddt.data( 'info', @@ -518,32 +518,24 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): user = create_user() CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.VERIFIED) block = CourseEndDate(course, user) - self.assertEqual( - block.description, - 'To earn a certificate, you must complete all requirements before this date.' - ) + assert block.description == 'To earn a certificate, you must complete all requirements before this date.' def test_course_end_date_for_non_certificate_eligible_mode(self): course = create_course_run(days_till_start=-1) user = create_user() CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.AUDIT) block = CourseEndDate(course, user) - self.assertEqual( - block.description, - 'After this date, course content will be archived.' - ) - self.assertEqual(block.title, 'Course End') + assert block.description == 'After this date, course content will be archived.' + assert block.title == 'Course End' def test_course_end_date_after_course(self): course = create_course_run(days_till_start=-2, days_till_end=-1) user = create_user() CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.VERIFIED) block = CourseEndDate(course, user) - self.assertEqual( - block.description, - 'This course is archived, which means you can review course content but it is no longer active.' - ) - self.assertEqual(block.title, 'Course End') + assert block.description ==\ + 'This course is archived, which means you can review course content but it is no longer active.' + assert block.title == 'Course End' @ddt.data( {'weeks_to_complete': 7}, # Weeks to complete > time til end (end date shown) @@ -567,11 +559,11 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): with patch('lms.djangoapps.courseware.date_summary.get_course_run_details') as mock_get_cr_details: mock_get_cr_details.return_value = cr_details block = CourseEndDate(course, user) - self.assertEqual(block.title, 'Course End') + assert block.title == 'Course End' if cr_details['weeks_to_complete'] > end_timedelta_number: - self.assertEqual(block.date, course.end) + assert block.date == course.end else: - self.assertIsNone(block.date) + assert block.date is None def test_ecommerce_checkout_redirect(self): """Verify the block link redirects to ecommerce checkout if it's enabled.""" @@ -585,7 +577,7 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.VERIFIED) block = VerifiedUpgradeDeadlineDate(course, user) - self.assertEqual(block.link, '{}?sku={}'.format(configuration.basket_checkout_page, sku)) + assert block.link == '{}?sku={}'.format(configuration.basket_checkout_page, sku) ## CertificateAvailableDate @waffle.testutils.override_switch('certificates.auto_certificate_generation', True) @@ -594,8 +586,8 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): user = create_user() CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.AUDIT) block = CertificateAvailableDate(course, user) - self.assertEqual(block.date, None) - self.assertFalse(block.is_allowed) + assert block.date is None + assert not block.is_allowed ## CertificateAvailableDate @waffle.testutils.override_switch('certificates.auto_certificate_generation', True) @@ -606,8 +598,8 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): course.certificate_available_date = datetime.now(utc) + timedelta(days=7) course.save() block = CertificateAvailableDate(course, verified_user) - self.assertNotEqual(block.date, None) - self.assertFalse(block.is_allowed) + assert block.date is not None + assert not block.is_allowed def test_no_certificate_available_date_for_audit_course(self): """ @@ -621,16 +613,16 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): CourseEnrollmentFactory(course_id=course.id, user=audit_user, mode=CourseMode.AUDIT) CourseMode.objects.get(course_id=course.id, mode_slug=CourseMode.VERIFIED).delete() all_course_modes = CourseMode.modes_for_course(course.id) - self.assertEqual(len(all_course_modes), 1) - self.assertEqual(all_course_modes[0].slug, CourseMode.AUDIT) + assert len(all_course_modes) == 1 + assert all_course_modes[0].slug == CourseMode.AUDIT course.certificate_available_date = datetime.now(utc) + timedelta(days=7) course.save() # Verify Certificate Available Date is not enabled for learner. block = CertificateAvailableDate(course, audit_user) - self.assertFalse(block.is_allowed) - self.assertNotEqual(block.date, None) + assert not block.is_allowed + assert block.date is not None @waffle.testutils.override_switch('certificates.auto_certificate_generation', True) def test_certificate_available_date_defined(self): @@ -646,9 +638,9 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): ] self.assert_block_types(course, verified_user, expected_blocks) for block in (CertificateAvailableDate(course, audit_user), CertificateAvailableDate(course, verified_user)): - self.assertIsNotNone(course.certificate_available_date) - self.assertEqual(block.date, course.certificate_available_date) - self.assertTrue(block.is_allowed) + assert course.certificate_available_date is not None + assert block.date == course.certificate_available_date + assert block.is_allowed ## VerificationDeadlineDate def test_no_verification_deadline(self): @@ -656,15 +648,15 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): user = create_user() CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.VERIFIED) block = VerificationDeadlineDate(course, user) - self.assertIsNone(block.date) - self.assertTrue(block.is_allowed) + assert block.date is None + assert block.is_allowed def test_no_verified_enrollment(self): course = create_course_run(days_till_start=-1) user = create_user() CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.AUDIT) block = VerificationDeadlineDate(course, user) - self.assertFalse(block.is_allowed) + assert not block.is_allowed def test_verification_deadline_date_upcoming(self): with freeze_time('2015-01-02'): @@ -673,15 +665,13 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.VERIFIED) block = VerificationDeadlineDate(course, user) - self.assertEqual(block.css_class, 'verification-deadline-upcoming') - self.assertEqual(block.title, 'Verification Deadline') - self.assertEqual(block.date, datetime.now(utc) + timedelta(days=14)) - self.assertEqual( - block.description, - 'You must successfully complete verification before this date to qualify for a Verified Certificate.' - ) - self.assertEqual(block.link_text, 'Verify My Identity') - self.assertEqual(block.link, IDVerificationService.get_verify_location(course.id)) + assert block.css_class == 'verification-deadline-upcoming' + assert block.title == 'Verification Deadline' + assert block.date == (datetime.now(utc) + timedelta(days=14)) + assert block.description ==\ + 'You must successfully complete verification before this date to qualify for a Verified Certificate.' + assert block.link_text == 'Verify My Identity' + assert block.link == IDVerificationService.get_verify_location(course.id) def test_verification_deadline_date_retry(self): with freeze_time('2015-01-02'): @@ -690,15 +680,13 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.VERIFIED) block = VerificationDeadlineDate(course, user) - self.assertEqual(block.css_class, 'verification-deadline-retry') - self.assertEqual(block.title, 'Verification Deadline') - self.assertEqual(block.date, datetime.now(utc) + timedelta(days=14)) - self.assertEqual( - block.description, - 'You must successfully complete verification before this date to qualify for a Verified Certificate.' - ) - self.assertEqual(block.link_text, 'Retry Verification') - self.assertEqual(block.link, IDVerificationService.get_verify_location()) + assert block.css_class == 'verification-deadline-retry' + assert block.title == 'Verification Deadline' + assert block.date == (datetime.now(utc) + timedelta(days=14)) + assert block.description ==\ + 'You must successfully complete verification before this date to qualify for a Verified Certificate.' + assert block.link_text == 'Retry Verification' + assert block.link == IDVerificationService.get_verify_location() def test_verification_deadline_date_denied(self): with freeze_time('2015-01-02'): @@ -707,15 +695,12 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.VERIFIED) block = VerificationDeadlineDate(course, user) - self.assertEqual(block.css_class, 'verification-deadline-passed') - self.assertEqual(block.title, 'Missed Verification Deadline') - self.assertEqual(block.date, datetime.now(utc) + timedelta(days=-1)) - self.assertEqual( - block.description, - "Unfortunately you missed this course's deadline for a successful verification." - ) - self.assertEqual(block.link_text, 'Learn More') - self.assertEqual(block.link, '') + assert block.css_class == 'verification-deadline-passed' + assert block.title == 'Missed Verification Deadline' + assert block.date == (datetime.now(utc) + timedelta(days=(- 1))) + assert block.description == "Unfortunately you missed this course's deadline for a successful verification." + assert block.link_text == 'Learn More' + assert block.link == '' @ddt.data( (-1, u'1 day ago - {date}'), @@ -729,7 +714,7 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.VERIFIED) block = VerificationDeadlineDate(course, user) - self.assertEqual(block.relative_datestring, expected_date_string) + assert block.relative_datestring == expected_date_string @ddt.data( ('info', True), @@ -816,10 +801,10 @@ class TestDateAlerts(SharedModuleStoreTestCase): block.register_alerts(self.request, self.course) messages = list(CourseHomeMessages.user_messages(self.request)) if expected_message_html: - self.assertEqual(len(messages), 1) - self.assertIn(expected_message_html, messages[0].message_html) + assert len(messages) == 1 + assert expected_message_html in messages[0].message_html else: - self.assertEqual(len(messages), 0) + assert len(messages) == 0 @ddt.data( ['2017-06-30 09:00:00', None], @@ -840,10 +825,10 @@ class TestDateAlerts(SharedModuleStoreTestCase): block.register_alerts(self.request, self.course) messages = list(CourseHomeMessages.user_messages(self.request)) if expected_message_html: - self.assertEqual(len(messages), 1) - self.assertIn(expected_message_html, messages[0].message_html) + assert len(messages) == 1 + assert expected_message_html in messages[0].message_html else: - self.assertEqual(len(messages), 0) + assert len(messages) == 0 @ddt.data( ['2017-06-20 09:00:00', None], @@ -865,10 +850,10 @@ class TestDateAlerts(SharedModuleStoreTestCase): block.register_alerts(self.request, self.course) messages = list(CourseHomeMessages.user_messages(self.request)) if expected_message_html: - self.assertEqual(len(messages), 1) - self.assertIn(expected_message_html, messages[0].message_html) + assert len(messages) == 1 + assert expected_message_html in messages[0].message_html else: - self.assertEqual(len(messages), 0) + assert len(messages) == 0 @ddt.data( ['2017-07-15 08:00:00', None], @@ -889,10 +874,10 @@ class TestDateAlerts(SharedModuleStoreTestCase): block.register_alerts(self.request, self.course) messages = list(CourseHomeMessages.user_messages(self.request)) if expected_message_html: - self.assertEqual(len(messages), 1) - self.assertIn(expected_message_html, messages[0].message_html) + assert len(messages) == 1 + assert expected_message_html in messages[0].message_html else: - self.assertEqual(len(messages), 0) + assert len(messages) == 0 @ddt.ddt @@ -918,18 +903,16 @@ class TestScheduleOverrides(SharedModuleStoreTestCase): expected = overview.start + timedelta(days=global_config.deadline_days) enrollment = CourseEnrollmentFactory(course_id=course.id, mode=CourseMode.AUDIT) block = VerifiedUpgradeDeadlineDate(course, enrollment.user) - self.assertEqual(block.date, expected) + assert block.date == expected self._check_text(block) def _check_text(self, upgrade_date_summary): """ Validates the text on an upgrade_date_summary """ - self.assertEqual(upgrade_date_summary.title, 'Upgrade to Verified Certificate') - self.assertEqual( - upgrade_date_summary.description, - 'Don\'t miss the opportunity to highlight your new knowledge and skills by earning a verified' - ' certificate.' - ) - self.assertEqual(upgrade_date_summary.relative_datestring, u'by {date}') + assert upgrade_date_summary.title == 'Upgrade to Verified Certificate' + assert upgrade_date_summary.description ==\ + "Don't miss the opportunity to highlight your new knowledge and skills by earning a verified" \ + " certificate." + assert upgrade_date_summary.relative_datestring == u'by {date}' @override_waffle_flag(CREATE_SCHEDULE_WAFFLE_FLAG, True) def test_date_with_self_paced_with_enrollment_after_course_start(self): @@ -944,7 +927,7 @@ class TestScheduleOverrides(SharedModuleStoreTestCase): enrollment = CourseEnrollmentFactory(course_id=course.id, mode=CourseMode.AUDIT) block = VerifiedUpgradeDeadlineDate(course, enrollment.user) expected = enrollment.created + timedelta(days=global_config.deadline_days) - self.assertEqual(block.date, expected) + assert block.date == expected # Orgs should be able to override the deadline org_config = OrgDynamicUpgradeDeadlineConfiguration.objects.create( @@ -953,7 +936,7 @@ class TestScheduleOverrides(SharedModuleStoreTestCase): enrollment = CourseEnrollmentFactory(course_id=course.id, mode=CourseMode.AUDIT) block = VerifiedUpgradeDeadlineDate(course, enrollment.user) expected = enrollment.created + timedelta(days=org_config.deadline_days) - self.assertEqual(block.date, expected) + assert block.date == expected # Courses should be able to override the deadline (and the org-level override) course_config = CourseDynamicUpgradeDeadlineConfiguration.objects.create( @@ -962,7 +945,7 @@ class TestScheduleOverrides(SharedModuleStoreTestCase): enrollment = CourseEnrollmentFactory(course_id=course.id, mode=CourseMode.AUDIT) block = VerifiedUpgradeDeadlineDate(course, enrollment.user) expected = enrollment.created + timedelta(days=course_config.deadline_days) - self.assertEqual(block.date, expected) + assert block.date == expected @override_waffle_flag(CREATE_SCHEDULE_WAFFLE_FLAG, True) def test_date_with_self_paced_without_dynamic_upgrade_deadline(self): @@ -973,7 +956,7 @@ class TestScheduleOverrides(SharedModuleStoreTestCase): expected = CourseMode.objects.get(course_id=course.id, mode_slug=CourseMode.VERIFIED).expiration_datetime enrollment = CourseEnrollmentFactory(course_id=course.id, mode=CourseMode.AUDIT) block = VerifiedUpgradeDeadlineDate(course, enrollment.user) - self.assertEqual(block.date, expected) + assert block.date == expected @override_waffle_flag(CREATE_SCHEDULE_WAFFLE_FLAG, True) def test_date_with_existing_schedule(self): @@ -985,18 +968,18 @@ class TestScheduleOverrides(SharedModuleStoreTestCase): enrollment = CourseEnrollmentFactory(course_id=course.id, mode=CourseMode.AUDIT) # The enrollment has a schedule, but the upgrade deadline should be None - self.assertIsNone(enrollment.schedule.upgrade_deadline) + assert enrollment.schedule.upgrade_deadline is None block = VerifiedUpgradeDeadlineDate(course, enrollment.user) expected = CourseMode.objects.get(course_id=course.id, mode_slug=CourseMode.VERIFIED).expiration_datetime - self.assertEqual(block.date, expected) + assert block.date == expected # Now if we turn on the feature for this course, this existing enrollment should be unaffected course_config.enabled = True course_config.save() block = VerifiedUpgradeDeadlineDate(course, enrollment.user) - self.assertEqual(block.date, expected) + assert block.date == expected @ddt.data( # (enroll before configs, org enabled, org opt-out, course enabled, course opt-out, expected dynamic deadline) @@ -1056,9 +1039,9 @@ class TestScheduleOverrides(SharedModuleStoreTestCase): # The enrollment has a schedule, and the upgrade_deadline is set when expected_dynamic_deadline is True if not enroll_first: - self.assertEqual(enrollment.schedule.upgrade_deadline is not None, expected_dynamic_deadline) + assert (enrollment.schedule.upgrade_deadline is not None) == expected_dynamic_deadline # The CourseEnrollment.upgrade_deadline property method is checking the configs - self.assertEqual(enrollment.dynamic_upgrade_deadline is not None, expected_dynamic_deadline) + assert (enrollment.dynamic_upgrade_deadline is not None) == expected_dynamic_deadline def create_user(verification_status=None): diff --git a/lms/djangoapps/courseware/tests/test_discussion_xblock.py b/lms/djangoapps/courseware/tests/test_discussion_xblock.py index b65e1f36658b56bea430ee9a88ef29a3669c3f61..c411c02ad8cdcf09a561d8e91e7783914cb5a3ed 100644 --- a/lms/djangoapps/courseware/tests/test_discussion_xblock.py +++ b/lms/djangoapps/courseware/tests/test_discussion_xblock.py @@ -109,14 +109,14 @@ class TestGetDjangoUser(TestDiscussionXBlock): actual_user = self.block.django_user self.runtime.service.assert_called_once_with( # lint-amnesty, pylint: disable=no-member self.block, 'user') - self.assertEqual(actual_user, self.django_user) + assert actual_user == self.django_user def test_django_user_handles_missing_service(self): """ Tests that get_django gracefully handles missing user service. """ self.runtime.service.return_value = None - self.assertEqual(self.block.django_user, None) + assert self.block.django_user is None @ddt.ddt @@ -143,14 +143,14 @@ class TestViews(TestDiscussionXBlock): Returns context passed to rendering of the django template (rendered by runtime). """ - self.assertEqual(self.render_template.call_count, 1) + assert self.render_template.call_count == 1 return self.render_template.call_args_list[0][0][1] def get_rendered_template(self): """ Returns the name of the template rendered by runtime. """ - self.assertEqual(self.render_template.call_count, 1) + assert self.render_template.call_count == 1 return self.render_template.call_args_list[0][0][0] def test_studio_view(self): @@ -158,8 +158,8 @@ class TestViews(TestDiscussionXBlock): Test for the studio view. """ fragment = self.block.author_view() - self.assertIsInstance(fragment, Fragment) - self.assertEqual(fragment.content, self.template_canary) + assert isinstance(fragment, Fragment) + assert fragment.content == self.template_canary self.render_template.assert_called_once_with( 'discussion/_discussion_inline_studio.html', {'discussion_id': self.discussion_id} @@ -194,7 +194,7 @@ class TestViews(TestDiscussionXBlock): context = self.get_template_context() for permission_name, expected_value in expected_permissions.items(): - self.assertEqual(expected_value, context[permission_name]) + assert expected_value == context[permission_name] def test_js_init(self): """ @@ -202,7 +202,7 @@ class TestViews(TestDiscussionXBlock): """ with mock.patch.object(loader, 'render_template', mock.Mock): fragment = self.block.student_view() - self.assertEqual(fragment.js_init_fn, 'DiscussionInlineBlock') + assert fragment.js_init_fn == 'DiscussionInlineBlock' @ddt.ddt @@ -221,13 +221,13 @@ class TestTemplates(TestDiscussionXBlock): return_value=permission_canary, ) as has_perm: actual_permission = self.block.has_permission("test_permission") - self.assertEqual(actual_permission, permission_canary) + assert actual_permission == permission_canary has_perm.assert_called_once_with(self.django_user_canary, 'test_permission', 'test_course') def test_studio_view(self): """Test for studio view.""" fragment = self.block.author_view({}) - self.assertIn('data-discussion-id="{}"'.format(self.discussion_id), fragment.content) + assert 'data-discussion-id="{}"'.format(self.discussion_id) in fragment.content @ddt.data( (True, False, False), @@ -247,10 +247,10 @@ class TestTemplates(TestDiscussionXBlock): self.block.has_permission = lambda perm: permission_dict[perm] fragment = self.block.student_view() read_only = 'false' if permissions[0] else 'true' - self.assertIn('data-discussion-id="{}"'.format(self.discussion_id), fragment.content) - self.assertIn('data-user-create-comment="{}"'.format(json.dumps(permissions[1])), fragment.content) - self.assertIn('data-user-create-subcomment="{}"'.format(json.dumps(permissions[2])), fragment.content) - self.assertIn('data-read-only="{read_only}"'.format(read_only=read_only), fragment.content) + assert 'data-discussion-id="{}"'.format(self.discussion_id) in fragment.content + assert 'data-user-create-comment="{}"'.format(json.dumps(permissions[1])) in fragment.content + assert 'data-user-create-subcomment="{}"'.format(json.dumps(permissions[2])) in fragment.content + assert 'data-read-only="{read_only}"'.format(read_only=read_only) in fragment.content @ddt.ddt @@ -303,8 +303,8 @@ class TestXBlockInCourse(SharedModuleStoreTestCase): fragment = discussion_xblock.render('student_view') html = fragment.content - self.assertIn('data-user-create-comment="false"', html) - self.assertIn('data-user-create-subcomment="false"', html) + assert 'data-user-create-comment="false"' in html + assert 'data-user-create-subcomment="false"' in html @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_discussion_render_successfully_with_orphan_parent(self, default_store): @@ -333,8 +333,8 @@ class TestXBlockInCourse(SharedModuleStoreTestCase): root = self.get_root(discussion) # Assert that orphan sequential is root of the discussion xblock. - self.assertEqual(orphan_sequential.location.block_type, root.location.block_type) - self.assertEqual(orphan_sequential.location.block_id, root.location.block_id) + assert orphan_sequential.location.block_type == root.location.block_type + assert orphan_sequential.location.block_id == root.location.block_id # Get xblock bound to a user and a descriptor. discussion_xblock = get_module_for_descriptor_internal( @@ -350,9 +350,9 @@ class TestXBlockInCourse(SharedModuleStoreTestCase): fragment = discussion_xblock.render('student_view') html = fragment.content - self.assertIsInstance(discussion_xblock, DiscussionXBlock) - self.assertIn('data-user-create-comment="false"', html) - self.assertIn('data-user-create-subcomment="false"', html) + assert isinstance(discussion_xblock, DiscussionXBlock) + assert 'data-user-create-comment="false"' in html + assert 'data-user-create-subcomment="false"' in html def test_discussion_student_view_data(self): """ @@ -367,14 +367,14 @@ class TestXBlockInCourse(SharedModuleStoreTestCase): 'student_view_data': 'discussion' } response = self.client.get(url, query_params) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.data['root'], six.text_type(self.course_usage_key)) + assert response.status_code == 200 + assert response.data['root'] == six.text_type(self.course_usage_key) for block_key_string, block_data in six.iteritems(response.data['blocks']): block_key = deserialize_usage_key(block_key_string, self.course_key) - self.assertEqual(block_data['id'], block_key_string) - self.assertEqual(block_data['type'], block_key.block_type) - self.assertEqual(block_data['display_name'], self.store.get_item(block_key).display_name or '') - self.assertEqual(block_data['student_view_data'], {"topic_id": self.discussion_id}) + assert block_data['id'] == block_key_string + assert block_data['type'] == block_key.block_type + assert block_data['display_name'] == (self.store.get_item(block_key).display_name or '') + assert block_data['student_view_data'] == {'topic_id': self.discussion_id} class TestXBlockQueryLoad(SharedModuleStoreTestCase): @@ -424,5 +424,5 @@ class TestXBlockQueryLoad(SharedModuleStoreTestCase): num_queries = 0 html = fragment.content - self.assertIn('data-user-create-comment="false"', html) - self.assertIn('data-user-create-subcomment="false"', html) + assert 'data-user-create-comment="false"' in html + assert 'data-user-create-subcomment="false"' in html diff --git a/lms/djangoapps/courseware/tests/test_entrance_exam.py b/lms/djangoapps/courseware/tests/test_entrance_exam.py index f28dbb6e3d9b875d66beef7ecb674b8deb2d8b0d..0694e2cc28d7ea79cd31878fcc06eff73d491b3f 100644 --- a/lms/djangoapps/courseware/tests/test_entrance_exam.py +++ b/lms/djangoapps/courseware/tests/test_entrance_exam.py @@ -281,15 +281,15 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest test get entrance exam content method """ exam_chapter = get_entrance_exam_content(self.request.user, self.course) - self.assertEqual(exam_chapter.url_name, self.entrance_exam.url_name) - self.assertFalse(user_has_passed_entrance_exam(self.request.user, self.course)) + assert exam_chapter.url_name == self.entrance_exam.url_name + assert not user_has_passed_entrance_exam(self.request.user, self.course) answer_entrance_exam_problem(self.course, self.request, self.problem_1) answer_entrance_exam_problem(self.course, self.request, self.problem_2) exam_chapter = get_entrance_exam_content(self.request.user, self.course) - self.assertEqual(exam_chapter, None) - self.assertTrue(user_has_passed_entrance_exam(self.request.user, self.course)) + assert exam_chapter is None + assert user_has_passed_entrance_exam(self.request.user, self.course) def test_entrance_exam_requirement_message(self): """ @@ -331,7 +331,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest resp, u'To access course materials, you must score {}% or higher'.format(minimum_score_pct), ) - self.assertIn(u'Your current score is 20%.', resp.content.decode(resp.charset)) + assert u'Your current score is 20%.' in resp.content.decode(resp.charset) def test_entrance_exam_requirement_message_hidden(self): """ @@ -352,7 +352,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest } ) resp = self.client.get(url) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 self.assertNotContains(resp, 'To access course materials, you must score') self.assertNotContains(resp, 'You have passed the entrance exam.') @@ -388,7 +388,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest chaos_user = UserFactory() locked_toc = self._return_table_of_contents() for toc_section in self.expected_locked_toc: - self.assertIn(toc_section, locked_toc) + assert toc_section in locked_toc # Set up the chaos user answer_entrance_exam_problem(self.course, self.request, self.problem_1, chaos_user) @@ -398,7 +398,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest unlocked_toc = self._return_table_of_contents() for toc_section in self.expected_unlocked_toc: - self.assertIn(toc_section, unlocked_toc) + assert toc_section in unlocked_toc def test_skip_entrance_exam_gating(self): """ @@ -407,7 +407,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest # make sure toc is locked before allowing user to skip entrance exam locked_toc = self._return_table_of_contents() for toc_section in self.expected_locked_toc: - self.assertIn(toc_section, locked_toc) + assert toc_section in locked_toc # hit skip entrance exam api in instructor app instructor = InstructorFactory(course_key=self.course.id) @@ -416,11 +416,11 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest response = self.client.post(url, { 'unique_student_identifier': self.request.user.email, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 unlocked_toc = self._return_table_of_contents() for toc_section in self.expected_unlocked_toc: - self.assertIn(toc_section, unlocked_toc) + assert toc_section in unlocked_toc def test_entrance_exam_gating_for_staff(self): """ @@ -437,7 +437,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest self.request.user = staff_user unlocked_toc = self._return_table_of_contents() for toc_section in self.expected_unlocked_toc: - self.assertIn(toc_section, unlocked_toc) + assert toc_section in unlocked_toc def test_courseware_page_access_without_passing_entrance_exam(self): """ @@ -508,14 +508,14 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest """ Test can_skip_entrance_exam method with anonymous user """ - self.assertFalse(user_can_skip_entrance_exam(self.anonymous_user, self.course)) + assert not user_can_skip_entrance_exam(self.anonymous_user, self.course) def test_has_passed_entrance_exam_with_anonymous_user(self): """ Test has_passed_entrance_exam method with anonymous user """ self.request.user = self.anonymous_user - self.assertFalse(user_has_passed_entrance_exam(self.request.user, self.course)) + assert not user_has_passed_entrance_exam(self.request.user, self.course) def test_course_has_entrance_exam_missing_exam_id(self): course = CourseFactory.create( @@ -523,12 +523,12 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest 'entrance_exam_enabled': True, } ) - self.assertFalse(course_has_entrance_exam(course)) + assert not course_has_entrance_exam(course) def test_user_has_passed_entrance_exam_short_circuit_missing_exam(self): course = CourseFactory.create( ) - self.assertTrue(user_has_passed_entrance_exam(self.request.user, course)) + assert user_has_passed_entrance_exam(self.request.user, course) @patch.dict("django.conf.settings.FEATURES", {'ENABLE_MASQUERADE': False}) def test_entrance_exam_xblock_response(self): @@ -549,7 +549,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest 'xmodule_handler', 'problem_check', ) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'entrance_exam_passed') def _assert_chapter_loaded(self, course, chapter): @@ -561,7 +561,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest kwargs={'course_id': six.text_type(course.id), 'chapter': chapter.url_name} ) response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 def _return_table_of_contents(self): """ diff --git a/lms/djangoapps/courseware/tests/test_favicon.py b/lms/djangoapps/courseware/tests/test_favicon.py index a799acc47b401f81fcc703c431bace0fe5409c92..d42576871c4336ae8984eef7581baf9fbc28ec21 100644 --- a/lms/djangoapps/courseware/tests/test_favicon.py +++ b/lms/djangoapps/courseware/tests/test_favicon.py @@ -16,7 +16,7 @@ class FaviconTestCase(UrlResetMixin, TestCase): def test_favicon_redirect(self): resp = self.client.get("/favicon.ico") - self.assertEqual(resp.status_code, 301) + assert resp.status_code == 301 self.assertRedirects( resp, "/static/images/favicon.ico", @@ -28,7 +28,7 @@ class FaviconTestCase(UrlResetMixin, TestCase): self.reset_urls() resp = self.client.get("/favicon.ico") - self.assertEqual(resp.status_code, 301) + assert resp.status_code == 301 self.assertRedirects( resp, "/static/images/foo.ico", diff --git a/lms/djangoapps/courseware/tests/test_field_overrides.py b/lms/djangoapps/courseware/tests/test_field_overrides.py index db69b78aac7c671a68236701fd1d7fdc6f590782..17417e38fb2dfece49e05adc8a08822b3c2a48d1 100644 --- a/lms/djangoapps/courseware/tests/test_field_overrides.py +++ b/lms/djangoapps/courseware/tests/test_field_overrides.py @@ -2,7 +2,7 @@ Tests for `field_overrides` module. """ import unittest - +import pytest from django.test.utils import override_settings from xblock.field_data import DictFieldData @@ -84,49 +84,49 @@ class OverrideFieldDataTests(OverrideFieldBase): def test_get(self): data = self.make_one() - self.assertEqual(data.get('block', 'foo'), 'fu') - self.assertEqual(data.get('block', 'bees'), 'knees') + assert data.get('block', 'foo') == 'fu' + assert data.get('block', 'bees') == 'knees' with disable_overrides(): - self.assertEqual(data.get('block', 'foo'), 'bar') + assert data.get('block', 'foo') == 'bar' def test_set(self): data = self.make_one() data.set('block', 'foo', 'yowza') - self.assertEqual(data.get('block', 'foo'), 'fu') + assert data.get('block', 'foo') == 'fu' with disable_overrides(): - self.assertEqual(data.get('block', 'foo'), 'yowza') + assert data.get('block', 'foo') == 'yowza' def test_delete(self): data = self.make_one() data.delete('block', 'foo') - self.assertEqual(data.get('block', 'foo'), 'fu') + assert data.get('block', 'foo') == 'fu' with disable_overrides(): # Since field_data is responsible for attribute access, you'd # expect it to raise AttributeError. In fact, it raises KeyError, # so we check for that. - with self.assertRaises(KeyError): + with pytest.raises(KeyError): data.get('block', 'foo') def test_has(self): data = self.make_one() - self.assertTrue(data.has('block', 'foo')) - self.assertTrue(data.has('block', 'bees')) - self.assertTrue(data.has('block', 'oh')) + assert data.has('block', 'foo') + assert data.has('block', 'bees') + assert data.has('block', 'oh') with disable_overrides(): - self.assertFalse(data.has('block', 'oh')) + assert not data.has('block', 'oh') def test_many(self): data = self.make_one() data.set_many('block', {'foo': 'baz', 'ah': 'ic'}) - self.assertEqual(data.get('block', 'foo'), 'fu') - self.assertEqual(data.get('block', 'ah'), 'ic') + assert data.get('block', 'foo') == 'fu' + assert data.get('block', 'ah') == 'ic' with disable_overrides(): - self.assertEqual(data.get('block', 'foo'), 'baz') + assert data.get('block', 'foo') == 'baz' @override_settings(FIELD_OVERRIDE_PROVIDERS=()) def test_no_overrides_configured(self): data = self.make_one() - self.assertIsInstance(data, DictFieldData) + assert isinstance(data, DictFieldData) @override_settings( @@ -142,7 +142,7 @@ class OverrideModulestoreFieldDataTests(FieldOverrideTestMixin, OverrideFieldDat @override_settings(MODULESTORE_FIELD_OVERRIDE_PROVIDERS=[]) def test_no_overrides_configured(self): data = self.make_one() - self.assertIsInstance(data, DictFieldData) + assert isinstance(data, DictFieldData) class ResolveDottedTests(unittest.TestCase): @@ -151,18 +151,15 @@ class ResolveDottedTests(unittest.TestCase): """ def test_bad_sub_import(self): - with self.assertRaises(ImportError): + with pytest.raises(ImportError): resolve_dotted('lms.djangoapps.courseware.tests.test_foo') def test_bad_import(self): - with self.assertRaises(ImportError): + with pytest.raises(ImportError): resolve_dotted('nosuchpackage') def test_import_something_that_isnt_already_loaded(self): - self.assertEqual( - resolve_dotted('lms.djangoapps.courseware.tests.animport.SOMENAME'), - 'bar' - ) + assert resolve_dotted('lms.djangoapps.courseware.tests.animport.SOMENAME') == 'bar' def inject_field_overrides(blocks, course, user): diff --git a/lms/djangoapps/courseware/tests/test_footer.py b/lms/djangoapps/courseware/tests/test_footer.py index 840f031b258534ba1c8c1842ce867706da8d923f..c8ec1a7bed29b85a1570e302ee5ee1893c282d96 100644 --- a/lms/djangoapps/courseware/tests/test_footer.py +++ b/lms/djangoapps/courseware/tests/test_footer.py @@ -48,7 +48,7 @@ class TestFooter(TestCase): Verify that the homepage, when accessed at edx.org, has the edX footer """ resp = self.client.get('/') - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 self.assertContains(resp, 'footer-edx-v3') def test_openedx_footer(self): @@ -57,7 +57,7 @@ class TestFooter(TestCase): edx.org, has the Open edX footer """ resp = self.client.get('/') - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 self.assertContains(resp, 'footer-openedx') @with_comprehensive_theme("edx.org") diff --git a/lms/djangoapps/courseware/tests/test_group_access.py b/lms/djangoapps/courseware/tests/test_group_access.py index 976664435f5c91b99ddac0ca10268f42c2121b30..bf5d27c193f0908a0ddbbf9e80ea0d0a8f7b57b8 100644 --- a/lms/djangoapps/courseware/tests/test_group_access.py +++ b/lms/djangoapps/courseware/tests/test_group_access.py @@ -182,17 +182,15 @@ class GroupAccessTestCase(ModuleStoreTestCase): """ DRY helper. """ - self.assertIs( - bool(access.has_access(user, 'load', modulestore().get_item(block_location), self.course.id)), - is_accessible - ) + assert bool(access.has_access(user, 'load', modulestore().get_item(block_location), self.course.id))\ + is is_accessible def ensure_staff_access(self, block_location): """ Another DRY helper. """ block = modulestore().get_item(block_location) - self.assertTrue(access.has_access(self.staff, 'load', block, self.course.id)) + assert access.has_access(self.staff, 'load', block, self.course.id) # NOTE: in all the tests that follow, `block_specified` and # `block_accessed` designate the place where group_access rules are diff --git a/lms/djangoapps/courseware/tests/test_i18n.py b/lms/djangoapps/courseware/tests/test_i18n.py index ead6ebd7d5c47b4df04c0bed96eb518accff12f0..5e04f001761df772869d8d1bda2f4965675eca8f 100644 --- a/lms/djangoapps/courseware/tests/test_i18n.py +++ b/lms/djangoapps/courseware/tests/test_i18n.py @@ -39,9 +39,9 @@ class BaseI18nTestCase(CacheIsolationTestCase): regex_string = six.text_type(r"""<{tag} [^>]*\b{attname}=['"]([\w\d\- ]+)['"][^>]*>""") # noqa: W605,E501 regex = regex_string.format(tag=tag, attname=attname) match = re.search(regex, content) - self.assertTrue(match, u"Couldn't find desired tag '%s' with attr '%s' in %r" % (tag, attname, content)) + assert match, (u"Couldn't find desired tag '%s' with attr '%s' in %r" % (tag, attname, content)) attvalues = match.group(1).split() - self.assertIn(value, attvalues) + assert value in attvalues def release_languages(self, languages): """ @@ -80,27 +80,27 @@ class I18nTestCase(BaseI18nTestCase): self.release_languages('fr') response = self.client.get('/') self.assert_tag_has_attr(response.content.decode('utf-8'), "html", "lang", "en") - self.assertEqual(response['Content-Language'], 'en') + assert response['Content-Language'] == 'en' self.assert_tag_has_attr(response.content.decode('utf-8'), "body", "class", "lang_en") def test_esperanto(self): self.release_languages('fr, eo') response = self.client.get('/', HTTP_ACCEPT_LANGUAGE='eo') self.assert_tag_has_attr(response.content.decode('utf-8'), "html", "lang", "eo") - self.assertEqual(response['Content-Language'], 'eo') + assert response['Content-Language'] == 'eo' self.assert_tag_has_attr(response.content.decode('utf-8'), "body", "class", "lang_eo") def test_switching_languages_bidi(self): self.release_languages('ar, eo') response = self.client.get('/') self.assert_tag_has_attr(response.content.decode('utf-8'), "html", "lang", "en") - self.assertEqual(response['Content-Language'], 'en') + assert response['Content-Language'] == 'en' self.assert_tag_has_attr(response.content.decode('utf-8'), "body", "class", "lang_en") self.assert_tag_has_attr(response.content.decode('utf-8'), "body", "class", "ltr") response = self.client.get('/', HTTP_ACCEPT_LANGUAGE='ar') self.assert_tag_has_attr(response.content.decode('utf-8'), "html", "lang", "ar") - self.assertEqual(response['Content-Language'], 'ar') + assert response['Content-Language'] == 'ar' self.assert_tag_has_attr(response.content.decode('utf-8'), "body", "class", "lang_ar") self.assert_tag_has_attr(response.content.decode('utf-8'), "body", "class", "rtl") @@ -178,7 +178,7 @@ class I18nLangPrefTests(BaseI18nTestCase): json.dumps({LANGUAGE_KEY: language}), content_type="application/merge-patch+json" ) - self.assertEqual(response.status_code, 204) + assert response.status_code == 204 def test_lang_preference(self): # Regression test; LOC-87 diff --git a/lms/djangoapps/courseware/tests/test_lti_integration.py b/lms/djangoapps/courseware/tests/test_lti_integration.py index 4e476c74883e45e712c00b5592f9bc6eb0461441..b2bf22201f69ea49b3b98671b9c0a50feebf6d89 100644 --- a/lms/djangoapps/courseware/tests/test_lti_integration.py +++ b/lms/djangoapps/courseware/tests/test_lti_integration.py @@ -118,12 +118,12 @@ class TestLTI(BaseTestXmodule): def test_lti_constructor(self): generated_content = self.item_descriptor.render(STUDENT_VIEW).content expected_content = self.runtime.render_template('lti.html', self.expected_context) - self.assertEqual(generated_content, expected_content) + assert generated_content == expected_content def test_lti_preview_handler(self): generated_content = self.item_descriptor.preview_handler(None, None).body expected_content = self.runtime.render_template('lti_form.html', self.expected_context) - self.assertEqual(generated_content.decode('utf-8'), expected_content) + assert generated_content.decode('utf-8') == expected_content class TestLTIBlockListing(SharedModuleStoreTestCase): @@ -187,7 +187,7 @@ class TestLTIBlockListing(SharedModuleStoreTestCase): for bad_course_id in bad_ids: lti_rest_endpoints_url = 'courses/{}/lti_rest_endpoints/'.format(bad_course_id) response = self.client.get(lti_rest_endpoints_url) - self.assertEqual(404, response.status_code) + assert 404 == response.status_code def test_lti_rest_listing(self): """tests that the draft lti module is part of the endpoint response""" @@ -195,8 +195,8 @@ class TestLTIBlockListing(SharedModuleStoreTestCase): request.method = 'GET' response = get_course_lti_endpoints(request, course_id=text_type(self.course.id)) - self.assertEqual(200, response.status_code) - self.assertEqual('application/json', response['Content-Type']) + assert 200 == response.status_code + assert 'application/json' == response['Content-Type'] expected = { "lti_1_1_result_service_xml_endpoint": self.expected_handler_url('grade_handler'), @@ -204,7 +204,7 @@ class TestLTIBlockListing(SharedModuleStoreTestCase): self.expected_handler_url('lti_2_0_result_rest_handler') + "/user/{anon_user_id}", "display_name": self.lti_published.display_name, } - self.assertEqual([expected], json.loads(response.content.decode('utf-8'))) + assert [expected] == json.loads(response.content.decode('utf-8')) def test_lti_rest_non_get(self): """tests that the endpoint returns 404 when hit with NON-get""" @@ -213,4 +213,4 @@ class TestLTIBlockListing(SharedModuleStoreTestCase): request = mock.Mock() request.method = method response = get_course_lti_endpoints(request, text_type(self.course.id)) - self.assertEqual(405, response.status_code) + assert 405 == response.status_code diff --git a/lms/djangoapps/courseware/tests/test_masquerade.py b/lms/djangoapps/courseware/tests/test_masquerade.py index e0cf8d1041038f4d59652d95c7a054739d81ff91..549dc39ff63ee89509b36da221ac42bf5537b6ba 100644 --- a/lms/djangoapps/courseware/tests/test_masquerade.py +++ b/lms/djangoapps/courseware/tests/test_masquerade.py @@ -7,7 +7,7 @@ Unit tests for masquerade. import json import pickle from datetime import datetime - +import pytest import ddt import six from django.conf import settings @@ -132,8 +132,8 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase, Mas Verifies that the staff debug control visibility is as expected (for staff only). """ content = self.get_courseware_page().content.decode('utf-8') - self.assertIn(self.sequential_display_name, content, "Subsection should be visible") - self.assertEqual(staff_debug_expected, 'Staff Debug Info' in content) + assert self.sequential_display_name in content, 'Subsection should be visible' + assert staff_debug_expected == ('Staff Debug Info' in content) def get_problem(self): """ @@ -155,8 +155,8 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase, Mas Verifies that "Show answer" is only present when expected (for staff only). """ problem_html = json.loads(self.get_problem().content.decode('utf-8'))['html'] - self.assertIn(self.problem_display_name, problem_html) - self.assertEqual(show_answer_expected, "Show answer" in problem_html) + assert self.problem_display_name in problem_html + assert show_answer_expected == ('Show answer' in problem_html) def ensure_masquerade_as_group_member(self, partition_id, group_id): """ @@ -169,7 +169,7 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase, Mas configured in the course. group_id (int); the integer group id, within the specified partition. """ - self.assertEqual(200, masquerade_as_group_member(self.test_user, self.course, partition_id, group_id)) + assert 200 == masquerade_as_group_member(self.test_user, self.course, partition_id, group_id) class NormalStudentVisibilityTest(MasqueradeTestCase): @@ -294,12 +294,8 @@ class TestStaffMasqueradeAsSpecificStudent(StaffMasqueradeTestCase, ProblemSubmi user: User model instance expected_language_code: string indicating a language code """ - self.assertEqual( - get_user_preference(user, LANGUAGE_KEY), expected_language_code - ) - self.assertEqual( - self.client.cookies[settings.LANGUAGE_COOKIE].value, expected_language_code - ) + assert get_user_preference(user, LANGUAGE_KEY) == expected_language_code + assert self.client.cookies[settings.LANGUAGE_COOKIE].value == expected_language_code @override_waffle_flag(DISABLE_UNIFIED_COURSE_TAB_FLAG, active=True) @patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) @@ -340,32 +336,32 @@ class TestStaffMasqueradeAsSpecificStudent(StaffMasqueradeTestCase, ProblemSubmi self.login(student.email, 'test') # Answer correctly as the student, and check progress. self.submit_answer('Correct', 'Correct') - self.assertEqual(self.get_progress_detail(), u'2/2') + assert self.get_progress_detail() == u'2/2' # Log in as staff, and check the problem is unanswered. self.login_staff() - self.assertEqual(self.get_progress_detail(), u'0/2') + assert self.get_progress_detail() == u'0/2' # Masquerade as the student, and check we can see the student state. self.update_masquerade(role='student', username=student.username) - self.assertEqual(self.get_progress_detail(), u'2/2') + assert self.get_progress_detail() == u'2/2' # Temporarily override the student state. self.submit_answer('Correct', 'Incorrect') - self.assertEqual(self.get_progress_detail(), u'1/2') + assert self.get_progress_detail() == u'1/2' # Reload the page and check we see the student state again. self.get_courseware_page() - self.assertEqual(self.get_progress_detail(), u'2/2') + assert self.get_progress_detail() == u'2/2' # Become the staff user again, and check the problem is still unanswered. self.update_masquerade(role='staff') - self.assertEqual(self.get_progress_detail(), u'0/2') + assert self.get_progress_detail() == u'0/2' # Verify the student state did not change. self.logout() self.login(student.email, 'test') - self.assertEqual(self.get_progress_detail(), u'2/2') + assert self.get_progress_detail() == u'2/2' def test_masquerading_with_language_preference(self): """ @@ -404,12 +400,12 @@ class TestStaffMasqueradeAsSpecificStudent(StaffMasqueradeTestCase, ProblemSubmi # Log in as staff, and check we can see the info page. self.login_staff() content = self.get_course_info_page().content.decode('utf-8') - self.assertIn("OOGIE BLOOGIE", content) + assert 'OOGIE BLOOGIE' in content # Masquerade as the student, and check we can see the info page. self.update_masquerade(role='student', username=self.student_user.username) content = self.get_course_info_page().content.decode('utf-8') - self.assertIn("OOGIE BLOOGIE", content) + assert 'OOGIE BLOOGIE' in content def test_masquerade_as_specific_student_progress(self): """ @@ -419,21 +415,21 @@ class TestStaffMasqueradeAsSpecificStudent(StaffMasqueradeTestCase, ProblemSubmi self.login_student() self.submit_answer('Correct', 'Correct') student_progress = self.get_progress_page().content.decode('utf-8') - self.assertNotIn("1 of 2 possible points", student_progress) - self.assertIn("2 of 2 possible points", student_progress) + assert '1 of 2 possible points' not in student_progress + assert '2 of 2 possible points' in student_progress # Staff answers are slightly different self.login_staff() self.submit_answer('Incorrect', 'Correct') staff_progress = self.get_progress_page().content.decode('utf-8') - self.assertNotIn("2 of 2 possible points", staff_progress) - self.assertIn("1 of 2 possible points", staff_progress) + assert '2 of 2 possible points' not in staff_progress + assert '1 of 2 possible points' in staff_progress # Should now see the student's scores self.update_masquerade(role='student', username=self.student_user.username) masquerade_progress = self.get_progress_page().content.decode('utf-8') - self.assertNotIn("1 of 2 possible points", masquerade_progress) - self.assertIn("2 of 2 possible points", masquerade_progress) + assert '1 of 2 possible points' not in masquerade_progress + assert '2 of 2 possible points' in masquerade_progress class TestGetMasqueradingGroupId(StaffMasqueradeTestCase): @@ -457,14 +453,14 @@ class TestGetMasqueradingGroupId(StaffMasqueradeTestCase): """ # Verify there is no masquerading group initially group = get_masquerading_user_group(self.course.id, self.test_user, self.user_partition) - self.assertIsNone(group) + assert group is None # Install a masquerading group self.ensure_masquerade_as_group_member(0, 1) # Verify that the masquerading group is returned group = get_masquerading_user_group(self.course.id, self.test_user, self.user_partition) - self.assertEqual(group.id, 1) + assert group.id == 1 class ReadOnlyKeyValueStore(DictKeyValueStore): @@ -499,32 +495,32 @@ class MasqueradingKeyValueStoreTest(TestCase): self.kvs = MasqueradingKeyValueStore(self.ro_kvs, self.session) def test_all(self): - self.assertEqual(self.kvs.get('a'), 42) - self.assertEqual(self.kvs.get('b'), None) - self.assertEqual(self.kvs.get('c'), 'OpenCraft') - with self.assertRaises(KeyError): + assert self.kvs.get('a') == 42 + assert self.kvs.get('b') is None + assert self.kvs.get('c') == 'OpenCraft' + with pytest.raises(KeyError): self.kvs.get('d') - self.assertTrue(self.kvs.has('a')) - self.assertTrue(self.kvs.has('b')) - self.assertTrue(self.kvs.has('c')) - self.assertFalse(self.kvs.has('d')) + assert self.kvs.has('a') + assert self.kvs.has('b') + assert self.kvs.has('c') + assert not self.kvs.has('d') self.kvs.set_many({'a': 'Norwegian Blue', 'd': 'Giraffe'}) self.kvs.set('b', 7) - self.assertEqual(self.kvs.get('a'), 'Norwegian Blue') - self.assertEqual(self.kvs.get('b'), 7) - self.assertEqual(self.kvs.get('c'), 'OpenCraft') - self.assertEqual(self.kvs.get('d'), 'Giraffe') + assert self.kvs.get('a') == 'Norwegian Blue' + assert self.kvs.get('b') == 7 + assert self.kvs.get('c') == 'OpenCraft' + assert self.kvs.get('d') == 'Giraffe' for key in 'abd': - self.assertTrue(self.kvs.has(key)) + assert self.kvs.has(key) self.kvs.delete(key) - with self.assertRaises(KeyError): + with pytest.raises(KeyError): self.kvs.get(key) - self.assertEqual(self.kvs.get('c'), 'OpenCraft') + assert self.kvs.get('c') == 'OpenCraft' class CourseMasqueradeTest(TestCase): @@ -540,4 +536,4 @@ class CourseMasqueradeTest(TestCase): del cmasq.user_name pickled_cmasq = pickle.dumps(cmasq) unpickled_cmasq = pickle.loads(pickled_cmasq) - self.assertEqual(unpickled_cmasq.user_name, None) + assert unpickled_cmasq.user_name is None diff --git a/lms/djangoapps/courseware/tests/test_middleware.py b/lms/djangoapps/courseware/tests/test_middleware.py index 273601d2c827425c0920b12bd927439cc12ae9e1..013dd3de139ecb42df1c688a0e7cb68d20bd4df1 100644 --- a/lms/djangoapps/courseware/tests/test_middleware.py +++ b/lms/djangoapps/courseware/tests/test_middleware.py @@ -26,7 +26,7 @@ class CoursewareMiddlewareTestCase(SharedModuleStoreTestCase): response = RedirectMiddleware().process_exception( request, Http404() ) - self.assertIsNone(response) + assert response is None def test_redirect_exceptions(self): """ @@ -38,6 +38,6 @@ class CoursewareMiddlewareTestCase(SharedModuleStoreTestCase): response = RedirectMiddleware().process_exception( request, exception ) - self.assertEqual(response.status_code, 302) + assert response.status_code == 302 target_url = response._headers['location'][1] # lint-amnesty, pylint: disable=protected-access - self.assertTrue(target_url.endswith(test_url)) + assert target_url.endswith(test_url) diff --git a/lms/djangoapps/courseware/tests/test_model_data.py b/lms/djangoapps/courseware/tests/test_model_data.py index 307135b751c3f0b64b33a03a3e0f9d1963df0023..05be73a91a9bf304f8bccff84cfc89095053c5e7 100644 --- a/lms/djangoapps/courseware/tests/test_model_data.py +++ b/lms/djangoapps/courseware/tests/test_model_data.py @@ -5,7 +5,7 @@ Test for lms courseware app, module data (runtime data storage for XBlocks) import json from functools import partial - +import pytest from django.db import connections, DatabaseError from django.test import TestCase from mock import Mock, patch @@ -89,14 +89,14 @@ class OtherUserFailureTestMixin(object): """ Test for assert failure when a user who didn't create the kvs tries to get from it it """ - with self.assertRaises(AssertionError): + with pytest.raises(AssertionError): self.kvs.get(self.other_key_factory(self.existing_field_name)) def test_other_user_kvs_set_failure(self): """ Test for assert failure when a user who didn't create the kvs tries to get from it it """ - with self.assertRaises(AssertionError): + with pytest.raises(AssertionError): self.kvs.set(self.other_key_factory(self.existing_field_name), "new_value") @@ -111,7 +111,8 @@ class TestStudentModuleStorage(OtherUserFailureTestMixin, TestCase): super(TestStudentModuleStorage, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments student_module = StudentModuleFactory(state=json.dumps({'a_field': 'a_value', 'b_field': 'b_value'})) self.user = student_module.student - self.assertEqual(self.user.id, 1) # check our assumption hard-coded in the key functions above. + assert self.user.id == 1 + # check our assumption hard-coded in the key functions above. # There should be only one query to load a single descriptor with a single user_state field with self.assertNumQueries(1): @@ -125,7 +126,7 @@ class TestStudentModuleStorage(OtherUserFailureTestMixin, TestCase): "Test that getting an existing field in an existing StudentModule works" # This should only read from the cache, not the database with self.assertNumQueries(0): - self.assertEqual('a_value', self.kvs.get(user_state_key('a_field'))) + assert 'a_value' == self.kvs.get(user_state_key('a_field')) def test_get_missing_field(self): "Test that getting a missing field from an existing StudentModule raises a KeyError" @@ -143,8 +144,9 @@ class TestStudentModuleStorage(OtherUserFailureTestMixin, TestCase): with self.assertNumQueries(4, using='default'): with self.assertNumQueries(1, using='student_module_history'): self.kvs.set(user_state_key('a_field'), 'new_value') - self.assertEqual(1, StudentModule.objects.all().count()) - self.assertEqual({'b_field': 'b_value', 'a_field': 'new_value'}, json.loads(StudentModule.objects.all()[0].state)) # lint-amnesty, pylint: disable=line-too-long + assert 1 == StudentModule.objects.all().count() + assert {'b_field': 'b_value', 'a_field': 'new_value'} == json.loads(StudentModule.objects.all()[0].state) + # lint-amnesty, pylint: disable=line-too-long def test_set_missing_field(self): "Test that setting a new user_state field changes the value" @@ -156,8 +158,9 @@ class TestStudentModuleStorage(OtherUserFailureTestMixin, TestCase): with self.assertNumQueries(4, using='default'): with self.assertNumQueries(1, using='student_module_history'): self.kvs.set(user_state_key('not_a_field'), 'new_value') - self.assertEqual(1, StudentModule.objects.all().count()) - self.assertEqual({'b_field': 'b_value', 'a_field': 'a_value', 'not_a_field': 'new_value'}, json.loads(StudentModule.objects.all()[0].state)) # lint-amnesty, pylint: disable=line-too-long + assert 1 == StudentModule.objects.all().count() + assert {'b_field': 'b_value', 'a_field': 'a_value', 'not_a_field': 'new_value'} == json.loads(StudentModule.objects.all()[0].state) + # lint-amnesty, pylint: disable=line-too-long def test_delete_existing_field(self): "Test that deleting an existing field removes it from the StudentModule" @@ -169,25 +172,25 @@ class TestStudentModuleStorage(OtherUserFailureTestMixin, TestCase): with self.assertNumQueries(2, using='default'): with self.assertNumQueries(1, using='student_module_history'): self.kvs.delete(user_state_key('a_field')) - self.assertEqual(1, StudentModule.objects.all().count()) + assert 1 == StudentModule.objects.all().count() self.assertRaises(KeyError, self.kvs.get, user_state_key('not_a_field')) def test_delete_missing_field(self): "Test that deleting a missing field from an existing StudentModule raises a KeyError" with self.assertNumQueries(0): self.assertRaises(KeyError, self.kvs.delete, user_state_key('not_a_field')) - self.assertEqual(1, StudentModule.objects.all().count()) - self.assertEqual({'b_field': 'b_value', 'a_field': 'a_value'}, json.loads(StudentModule.objects.all()[0].state)) + assert 1 == StudentModule.objects.all().count() + assert {'b_field': 'b_value', 'a_field': 'a_value'} == json.loads(StudentModule.objects.all()[0].state) def test_has_existing_field(self): "Test that `has` returns True for existing fields in StudentModules" with self.assertNumQueries(0): - self.assertTrue(self.kvs.has(user_state_key('a_field'))) + assert self.kvs.has(user_state_key('a_field')) def test_has_missing_field(self): "Test that `has` returns False for missing fields in StudentModule" with self.assertNumQueries(0): - self.assertFalse(self.kvs.has(user_state_key('not_a_field'))) + assert not self.kvs.has(user_state_key('not_a_field')) def construct_kv_dict(self): """Construct a kv_dict that can be passed to set_many""" @@ -212,7 +215,7 @@ class TestStudentModuleStorage(OtherUserFailureTestMixin, TestCase): self.kvs.set_many(kv_dict) for key in kv_dict: - self.assertEqual(self.kvs.get(key), kv_dict[key]) + assert self.kvs.get(key) == kv_dict[key] def test_set_many_failure(self): "Test failures when setting many fields that are scoped to Scope.user_state" @@ -223,9 +226,9 @@ class TestStudentModuleStorage(OtherUserFailureTestMixin, TestCase): self.kvs.set(key, 'test_value') with patch('django.db.models.Model.save', side_effect=DatabaseError): - with self.assertRaises(KeyValueMultiSaveError) as exception_context: + with pytest.raises(KeyValueMultiSaveError) as exception_context: self.kvs.set_many(kv_dict) - self.assertEqual(exception_context.exception.saved_field_names, []) + assert exception_context.value.saved_field_names == [] class TestMissingStudentModule(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring @@ -236,7 +239,8 @@ class TestMissingStudentModule(TestCase): # lint-amnesty, pylint: disable=missi super(TestMissingStudentModule, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments self.user = UserFactory.create(username='user') - self.assertEqual(self.user.id, 1) # check our assumption hard-coded in the key functions above. + assert self.user.id == 1 + # check our assumption hard-coded in the key functions above. # The descriptor has no fields, so FDC shouldn't send any queries with self.assertNumQueries(0): @@ -250,8 +254,8 @@ class TestMissingStudentModule(TestCase): # lint-amnesty, pylint: disable=missi def test_set_field_in_missing_student_module(self): "Test that setting a field in a missing StudentModule creates the student module" - self.assertEqual(0, len(self.field_data_cache)) - self.assertEqual(0, StudentModule.objects.all().count()) + assert 0 == len(self.field_data_cache) + assert 0 == StudentModule.objects.all().count() # We are updating a problem, so we write to courseware_studentmodulehistoryextended # as well as courseware_studentmodule. We also need to read the database @@ -263,14 +267,14 @@ class TestMissingStudentModule(TestCase): # lint-amnesty, pylint: disable=missi with self.assertNumQueries(1, using='student_module_history'): self.kvs.set(user_state_key('a_field'), 'a_value') - self.assertEqual(1, sum(len(cache) for cache in self.field_data_cache.cache.values())) - self.assertEqual(1, StudentModule.objects.all().count()) + assert 1 == sum((len(cache) for cache in self.field_data_cache.cache.values())) + assert 1 == StudentModule.objects.all().count() student_module = StudentModule.objects.all()[0] - self.assertEqual({'a_field': 'a_value'}, json.loads(student_module.state)) - self.assertEqual(self.user, student_module.student) - self.assertEqual(location('usage_id').replace(run=None), student_module.module_state_key) - self.assertEqual(course_id, student_module.course_id) + assert {'a_field': 'a_value'} == json.loads(student_module.state) + assert self.user == student_module.student + assert location('usage_id').replace(run=None) == student_module.module_state_key + assert course_id == student_module.course_id def test_delete_field_from_missing_student_module(self): "Test that deleting a field from a missing StudentModule raises a KeyError" @@ -280,7 +284,7 @@ class TestMissingStudentModule(TestCase): # lint-amnesty, pylint: disable=missi def test_has_field_for_missing_student_module(self): "Test that `has` returns False for missing StudentModules" with self.assertNumQueries(0): - self.assertFalse(self.kvs.has(user_state_key('a_field'))) + assert not self.kvs.has(user_state_key('a_field')) class StorageTestBase(object): @@ -315,12 +319,12 @@ class StorageTestBase(object): with self.assertNumQueries(1): self.kvs.set(self.key_factory('existing_field'), 'test_value') with self.assertNumQueries(0): - self.assertEqual('test_value', self.kvs.get(self.key_factory('existing_field'))) + assert 'test_value' == self.kvs.get(self.key_factory('existing_field')) def test_get_existing_field(self): "Test that getting an existing field in an existing Storage Field works" with self.assertNumQueries(0): - self.assertEqual('old_value', self.kvs.get(self.key_factory('existing_field'))) + assert 'old_value' == self.kvs.get(self.key_factory('existing_field')) def test_get_missing_field(self): "Test that getting a missing field from an existing Storage Field raises a KeyError" @@ -331,38 +335,38 @@ class StorageTestBase(object): "Test that setting an existing field changes the value" with self.assertNumQueries(1): self.kvs.set(self.key_factory('existing_field'), 'new_value') - self.assertEqual(1, self.storage_class.objects.all().count()) - self.assertEqual('new_value', json.loads(self.storage_class.objects.all()[0].value)) + assert 1 == self.storage_class.objects.all().count() + assert 'new_value' == json.loads(self.storage_class.objects.all()[0].value) def test_set_missing_field(self): "Test that setting a new field changes the value" with self.assertNumQueries(1): self.kvs.set(self.key_factory('missing_field'), 'new_value') - self.assertEqual(2, self.storage_class.objects.all().count()) - self.assertEqual('old_value', json.loads(self.storage_class.objects.get(field_name='existing_field').value)) - self.assertEqual('new_value', json.loads(self.storage_class.objects.get(field_name='missing_field').value)) + assert 2 == self.storage_class.objects.all().count() + assert 'old_value' == json.loads(self.storage_class.objects.get(field_name='existing_field').value) + assert 'new_value' == json.loads(self.storage_class.objects.get(field_name='missing_field').value) def test_delete_existing_field(self): "Test that deleting an existing field removes it" with self.assertNumQueries(1): self.kvs.delete(self.key_factory('existing_field')) - self.assertEqual(0, self.storage_class.objects.all().count()) + assert 0 == self.storage_class.objects.all().count() def test_delete_missing_field(self): "Test that deleting a missing field from an existing Storage Field raises a KeyError" with self.assertNumQueries(0): self.assertRaises(KeyError, self.kvs.delete, self.key_factory('missing_field')) - self.assertEqual(1, self.storage_class.objects.all().count()) + assert 1 == self.storage_class.objects.all().count() def test_has_existing_field(self): "Test that `has` returns True for an existing Storage Field" with self.assertNumQueries(0): - self.assertTrue(self.kvs.has(self.key_factory('existing_field'))) + assert self.kvs.has(self.key_factory('existing_field')) def test_has_missing_field(self): "Test that `has` return False for an existing Storage Field" with self.assertNumQueries(0): - self.assertFalse(self.kvs.has(self.key_factory('missing_field'))) + assert not self.kvs.has(self.key_factory('missing_field')) def construct_kv_dict(self): """Construct a kv_dict that can be passed to set_many""" @@ -381,7 +385,7 @@ class StorageTestBase(object): with self.assertNumQueries(len(kv_dict)): self.kvs.set_many(kv_dict) for key in kv_dict: - self.assertEqual(self.kvs.get(key), kv_dict[key]) + assert self.kvs.get(key) == kv_dict[key] def test_set_many_failure(self): """Test that setting many regular fields with a DB error """ @@ -391,11 +395,11 @@ class StorageTestBase(object): self.kvs.set(key, 'test value') with patch('django.db.models.Model.save', side_effect=[None, DatabaseError]): - with self.assertRaises(KeyValueMultiSaveError) as exception_context: + with pytest.raises(KeyValueMultiSaveError) as exception_context: self.kvs.set_many(kv_dict) - exception = exception_context.exception - self.assertEqual(exception.saved_field_names, ['existing_field', 'other_existing_field']) + exception = exception_context.value + assert exception.saved_field_names == ['existing_field', 'other_existing_field'] class TestUserStateSummaryStorage(StorageTestBase, TestCase): diff --git a/lms/djangoapps/courseware/tests/test_module_render.py b/lms/djangoapps/courseware/tests/test_module_render.py index a25f71540dcbc3a00290fbcae160541c0b2ce90f..f61d099b46aeee3715bfe8c5fec56d1e484d90db 100644 --- a/lms/djangoapps/courseware/tests/test_module_render.py +++ b/lms/djangoapps/courseware/tests/test_module_render.py @@ -9,7 +9,7 @@ import json import textwrap from datetime import datetime from functools import partial - +import pytest import ddt import pytz import six @@ -229,10 +229,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): super(ModuleRenderTestCase, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments def test_get_module(self): - self.assertEqual( - None, - render.get_module('dummyuser', None, 'invalid location', None) - ) + assert render.get_module('dummyuser', None, 'invalid location', None) is None def test_module_render_with_jump_to_id(self): """ @@ -260,7 +257,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): # See if the url got rewritten to the target link # note if the URL mapping changes then this assertion will break - self.assertIn('/courses/' + text_type(self.course_key) + '/jump_to_id/vertical_test', html) + assert '/courses/' + text_type(self.course_key) + '/jump_to_id/vertical_test' in html def test_xqueue_callback_success(self): """ @@ -298,7 +295,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): with patch('lms.djangoapps.courseware.module_render.load_single_xblock', return_value=self.mock_module): # Test with missing xqueue data - with self.assertRaises(Http404): + with pytest.raises(Http404): request = self.request_factory.post(self.callback_url, {}) render.xqueue_callback( request, @@ -309,7 +306,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): ) # Test with missing xqueue_header - with self.assertRaises(Http404): + with pytest.raises(Http404): request = self.request_factory.post(self.callback_url, data) render.xqueue_callback( request, @@ -335,7 +332,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """Test that anonymous GET is allowed.""" dispatch_url = self._get_dispatch_url() response = self.client.get(dispatch_url) - self.assertEqual(200, response.status_code) + assert 200 == response.status_code def test_anonymous_post_xblock_callback(self): """Test that anonymous POST is not allowed.""" @@ -343,15 +340,15 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): response = self.client.post(dispatch_url, {'position': 2}) # https://openedx.atlassian.net/browse/LEARNER-7131 - self.assertEqual('Unauthenticated', response.content.decode('utf-8')) - self.assertEqual(403, response.status_code) + assert 'Unauthenticated' == response.content.decode('utf-8') + assert 403 == response.status_code def test_session_authentication(self): """ Test that the xblock endpoint supports session authentication.""" self.client.login(username=self.mock_user.username, password="test") dispatch_url = self._get_dispatch_url() response = self.client.post(dispatch_url) - self.assertEqual(200, response.status_code) + assert 200 == response.status_code def test_oauth_authentication(self): """ Test that the xblock endpoint supports OAuth authentication.""" @@ -359,7 +356,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): access_token = AccessTokenFactory(user=self.mock_user, application=ApplicationFactory()).token headers = {'HTTP_AUTHORIZATION': 'Bearer ' + access_token} response = self.client.post(dispatch_url, {}, **headers) - self.assertEqual(200, response.status_code) + assert 200 == response.status_code def test_jwt_authentication(self): """ Test that the xblock endpoint supports JWT authentication.""" @@ -367,7 +364,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): token = create_jwt_for_user(self.mock_user) headers = {'HTTP_AUTHORIZATION': 'JWT ' + token} response = self.client.post(dispatch_url, {}, **headers) - self.assertEqual(200, response.status_code) + assert 200 == response.status_code def test_missing_position_handler(self): """ @@ -376,28 +373,28 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.client.login(username=self.mock_user.username, password="test") dispatch_url = self._get_dispatch_url() response = self.client.post(dispatch_url) - self.assertEqual(200, response.status_code) - self.assertEqual(json.loads(response.content.decode('utf-8')), {'success': True}) + assert 200 == response.status_code + assert json.loads(response.content.decode('utf-8')) == {'success': True} response = self.client.post(dispatch_url, {'position': ''}) - self.assertEqual(200, response.status_code) - self.assertEqual(json.loads(response.content.decode('utf-8')), {'success': True}) + assert 200 == response.status_code + assert json.loads(response.content.decode('utf-8')) == {'success': True} response = self.client.post(dispatch_url, {'position': '-1'}) - self.assertEqual(200, response.status_code) - self.assertEqual(json.loads(response.content.decode('utf-8')), {'success': True}) + assert 200 == response.status_code + assert json.loads(response.content.decode('utf-8')) == {'success': True} response = self.client.post(dispatch_url, {'position': "string"}) - self.assertEqual(200, response.status_code) - self.assertEqual(json.loads(response.content.decode('utf-8')), {'success': True}) + assert 200 == response.status_code + assert json.loads(response.content.decode('utf-8')) == {'success': True} response = self.client.post(dispatch_url, {'position': u"Φυσικά"}) - self.assertEqual(200, response.status_code) - self.assertEqual(json.loads(response.content.decode('utf-8')), {'success': True}) + assert 200 == response.status_code + assert json.loads(response.content.decode('utf-8')) == {'success': True} response = self.client.post(dispatch_url, {'position': ''}) - self.assertEqual(200, response.status_code) - self.assertEqual(json.loads(response.content.decode('utf-8')), {'success': True}) + assert 200 == response.status_code + assert json.loads(response.content.decode('utf-8')) == {'success': True} @ddt.data('pure', 'vertical') @XBlock.register_temp_plugin(PureXBlock, identifier='pure') @@ -479,8 +476,8 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): # check that _unwrapped_field_data is the same as the original # _field_data, but now _field_data as been reset. # pylint: disable=protected-access - self.assertIs(descriptor._unwrapped_field_data, original_field_data) # lint-amnesty, pylint: disable=no-member - self.assertIsNot(descriptor._unwrapped_field_data, descriptor._field_data) # lint-amnesty, pylint: disable=no-member + assert descriptor._unwrapped_field_data is original_field_data # lint-amnesty, pylint: disable=no-member + assert descriptor._unwrapped_field_data is not descriptor._field_data # lint-amnesty, pylint: disable=no-member # now bind this module to a few other students for user in [UserFactory(), UserFactory(), self.mock_user]: @@ -495,25 +492,14 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): # _field_data should now be wrapped by LmsFieldData # pylint: disable=protected-access - self.assertIsInstance(descriptor._field_data, LmsFieldData) # lint-amnesty, pylint: disable=no-member + assert isinstance(descriptor._field_data, LmsFieldData) # lint-amnesty, pylint: disable=no-member # the LmsFieldData should now wrap OverrideFieldData - self.assertIsInstance( - # pylint: disable=protected-access - descriptor._field_data._authored_data._source, # lint-amnesty, pylint: disable=no-member - OverrideFieldData - ) + assert isinstance(descriptor._field_data._authored_data._source, OverrideFieldData) # lint-amnesty, pylint: disable=no-member, line-too-long # the OverrideFieldData should point to the date FieldData - self.assertIsInstance( - # pylint: disable=protected-access - descriptor._field_data._authored_data._source.fallback, # lint-amnesty, pylint: disable=no-member - DateLookupFieldData - ) - self.assertIs( - descriptor._field_data._authored_data._source.fallback._defaults, # lint-amnesty, pylint: disable=no-member - descriptor._unwrapped_field_data # lint-amnesty, pylint: disable=no-member - ) + assert isinstance(descriptor._field_data._authored_data._source.fallback, DateLookupFieldData) # lint-amnesty, pylint: disable=no-member, line-too-long + assert descriptor._field_data._authored_data._source.fallback._defaults is descriptor._unwrapped_field_data # lint-amnesty, pylint: disable=no-member, line-too-long def test_hash_resource(self): """ @@ -521,7 +507,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): decoded or otherwise. """ resources = ['ASCII text', u'â„ I am a special snowflake.', "â„ So am I, but I didn't tell you."] - self.assertEqual(hash_resource(resources), '50c2ae79fbce9980e0803848914b0a09') + assert hash_resource(resources) == '50c2ae79fbce9980e0803848914b0a09' @ddt.ddt @@ -603,7 +589,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas 'xmodule_handler', 'goto_position', ) - self.assertEqual(403, response.status_code) + assert 403 == response.status_code def test_valid_csrf_token(self): """ @@ -620,12 +606,12 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas 'xmodule_handler', 'goto_position', ) - self.assertEqual(200, response.status_code) + assert 200 == response.status_code def test_invalid_location(self): request = self.request_factory.post('dummy_url', data={'position': 1}) request.user = self.mock_user - with self.assertRaises(Http404): + with pytest.raises(Http404): render.handle_xblock_callback( request, text_type(self.course_key), @@ -640,18 +626,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas data={'file_id': (self._mock_file(), ) * (settings.MAX_FILEUPLOADS_PER_INPUT + 1)} ) request.user = self.mock_user - self.assertEqual( - render.handle_xblock_callback( - request, - text_type(self.course_key), - quote_slashes(text_type(self.location)), - 'dummy_handler' - ).content.decode('utf-8'), - json.dumps({ - 'success': u'Submission aborted! Maximum %d files may be submitted at once' % - settings.MAX_FILEUPLOADS_PER_INPUT - }, indent=2) - ) + assert render.handle_xblock_callback(request, text_type(self.course_key), quote_slashes(text_type(self.location)), 'dummy_handler').content.decode('utf-8') == json.dumps({'success': (f'Submission aborted! Maximum {settings.MAX_FILEUPLOADS_PER_INPUT:d} files may be submitted at once')}, indent=2) # pylint: disable=line-too-long def test_too_large_file(self): inputfile = self._mock_file(size=1 + settings.STUDENT_FILEUPLOAD_MAX_SIZE) @@ -660,18 +635,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas data={'file_id': inputfile} ) request.user = self.mock_user - self.assertEqual( - render.handle_xblock_callback( - request, - text_type(self.course_key), - quote_slashes(text_type(self.location)), - 'dummy_handler' - ).content.decode('utf-8'), - json.dumps({ - 'success': u'Submission aborted! Your file "%s" is too large (max size: %d MB)' % - (inputfile.name, settings.STUDENT_FILEUPLOAD_MAX_SIZE / (1000 ** 2)) - }, indent=2) - ) + assert render.handle_xblock_callback(request, text_type(self.course_key), quote_slashes(text_type(self.location)), 'dummy_handler').content.decode('utf-8') == json.dumps({'success': (u'Submission aborted! Your file "%s" is too large (max size: %d MB)' % (inputfile.name, (settings.STUDENT_FILEUPLOAD_MAX_SIZE / (1000 ** 2))))}, indent=2) # pylint: disable=line-too-long def test_xmodule_dispatch(self): request = self.request_factory.post('dummy_url', data={'position': 1}) @@ -683,12 +647,12 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas 'xmodule_handler', 'goto_position', ) - self.assertIsInstance(response, HttpResponse) + assert isinstance(response, HttpResponse) def test_bad_course_id(self): request = self.request_factory.post('dummy_url') request.user = self.mock_user - with self.assertRaises(Http404): + with pytest.raises(Http404): render.handle_xblock_callback( request, 'bad_course_id', @@ -700,7 +664,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas def test_bad_location(self): request = self.request_factory.post('dummy_url') request.user = self.mock_user - with self.assertRaises(Http404): + with pytest.raises(Http404): render.handle_xblock_callback( request, text_type(self.course_key), @@ -712,7 +676,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas def test_bad_xmodule_dispatch(self): request = self.request_factory.post('dummy_url') request.user = self.mock_user - with self.assertRaises(Http404): + with pytest.raises(Http404): render.handle_xblock_callback( request, text_type(self.course_key), @@ -724,7 +688,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas def test_missing_handler(self): request = self.request_factory.post('dummy_url') request.user = self.mock_user - with self.assertRaises(Http404): + with pytest.raises(Http404): render.handle_xblock_callback( request, text_type(self.course_key), @@ -752,13 +716,13 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas 'set_score', '', ) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 student_module = StudentModule.objects.get( student=self.mock_user, module_state_key=block.scope_ids.usage_id, ) - self.assertEqual(student_module.grade, 0.75) - self.assertEqual(student_module.max_grade, 1) + assert student_module.grade == 0.75 + assert student_module.max_grade == 1 @ddt.data( ('complete', {'completion': 0.625}), @@ -785,7 +749,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas '', ) mock_complete.assert_not_called() - self.assertFalse(BlockCompletion.objects.filter(block_key=block.scope_ids.usage_id).exists()) + assert not BlockCompletion.objects.filter(block_key=block.scope_ids.usage_id).exists() @XBlock.register_temp_plugin(StubCompletableXBlock, identifier='comp') def test_completion_signal_for_completable_xblock(self): @@ -797,9 +761,9 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas {'completion': 0.625}, course, block, 'complete' ) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 completion = BlockCompletion.objects.get(block_key=block.scope_ids.usage_id) - self.assertEqual(completion.completion, 0.625) + assert completion.completion == 0.625 @XBlock.register_temp_plugin(StubCompletableXBlock, identifier='comp') @ddt.data((True, True), (False, False),) @@ -877,8 +841,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas {}, course, block, 'progress' ) - self.assertEqual(response.status_code, 200) - self.assertFalse(BlockCompletion.objects.filter(block_key=block.scope_ids.usage_id).exists()) + assert response.status_code == 200 + assert not BlockCompletion.objects.filter(block_key=block.scope_ids.usage_id).exists() @XBlock.register_temp_plugin(XBlockWithoutCompletionAPI, identifier='no_comp') def test_progress_signal_processed_for_xblock_without_completion_api(self): @@ -890,9 +854,9 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas {}, course, block, 'progress' ) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 completion = BlockCompletion.objects.get(block_key=block.scope_ids.usage_id) - self.assertEqual(completion.completion, 1.0) + assert completion.completion == 1.0 @XBlock.register_temp_plugin(StubCompletableXBlock, identifier='comp') def test_skip_handlers_for_masquerading_staff(self): @@ -918,8 +882,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas '', ) mock_masq.assert_called() - self.assertEqual(response.status_code, 200) - with self.assertRaises(BlockCompletion.DoesNotExist): + assert response.status_code == 200 + with pytest.raises(BlockCompletion.DoesNotExist): BlockCompletion.objects.get(block_key=block.scope_ids.usage_id) @XBlock.register_temp_plugin(GradedStatelessXBlock, identifier='stateless_scorer') @@ -940,7 +904,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas 'xmodule_handler', 'problem_check', ) - self.assertFalse(mock_score_signal.called) + assert not mock_score_signal.called @ddt.ddt @@ -968,14 +932,14 @@ class TestXBlockView(SharedModuleStoreTestCase, LoginEnrollmentTestCase): request = self.request_factory.get(self.xblock_view_url) request.user = UserFactory.create() response = render.xblock_view(request, *self.view_args) - self.assertEqual(200, response.status_code) + assert 200 == response.status_code expected = ['csrf_token', 'html', 'resources'] content = json.loads(response.content.decode('utf-8')) for section in expected: - self.assertIn(section, content) + assert section in content doc = PyQuery(content['html']) - self.assertEqual(len(doc('div.xblock-student_view-html')), 1) + assert len(doc('div.xblock-student_view-html')) == 1 @ddt.data(True, False) def test_hide_staff_markup(self, hide): @@ -989,16 +953,16 @@ class TestXBlockView(SharedModuleStoreTestCase, LoginEnrollmentTestCase): if hide: request.GET = {'hide_staff_markup': 'true'} response = render.xblock_view(request, *self.view_args) - self.assertEqual(200, response.status_code) + assert 200 == response.status_code html = json.loads(response.content.decode('utf-8'))['html'] - self.assertEqual('Staff Debug Info' in html, not hide) + assert ('Staff Debug Info' in html) == (not hide) def test_xblock_view_handler_not_authenticated(self): request = self.request_factory.get(self.xblock_view_url) request.user = AnonymousUser() response = render.xblock_view(request, *self.view_args) - self.assertEqual(401, response.status_code) + assert 401 == response.status_code @ddt.ddt @@ -1059,9 +1023,9 @@ class TestTOC(ModuleStoreTestCase): self.request.user, self.request, course, self.chapter, None, self.field_data_cache ) for toc_section in expected: - self.assertIn(toc_section, actual['chapters']) - self.assertIsNone(actual['previous_of_active_section']) - self.assertIsNone(actual['next_of_active_section']) + assert toc_section in actual['chapters'] + assert actual['previous_of_active_section'] is None + assert actual['next_of_active_section'] is None # Mongo makes 3 queries to load the course to depth 2: # - 1 for the course @@ -1098,9 +1062,9 @@ class TestTOC(ModuleStoreTestCase): self.request.user, self.request, self.toy_course, self.chapter, section, self.field_data_cache ) for toc_section in expected: - self.assertIn(toc_section, actual['chapters']) - self.assertEqual(actual['previous_of_active_section']['url_name'], 'Toy_Videos') - self.assertEqual(actual['next_of_active_section']['url_name'], 'video_123456789012') + assert toc_section in actual['chapters'] + assert actual['previous_of_active_section']['url_name'] == 'Toy_Videos' + assert actual['next_of_active_section']['url_name'] == 'video_123456789012' @ddt.ddt @@ -1252,12 +1216,12 @@ class TestProctoringRendering(SharedModuleStoreTestCase): section_actual = self._find_section(actual['chapters'], 'Overview', 'Toy_Videos') if expected: - self.assertIn(expected, [section_actual['proctoring']]) + assert expected in [section_actual['proctoring']] else: # we expect there not to be a 'proctoring' key in the dict - self.assertNotIn('proctoring', section_actual) - self.assertIsNone(actual['previous_of_active_section']) - self.assertEqual(actual['next_of_active_section']['url_name'], u"Welcome") + assert 'proctoring' not in section_actual + assert actual['previous_of_active_section'] is None + assert actual['next_of_active_section']['url_name'] == u'Welcome' @ddt.data( ( @@ -1364,7 +1328,7 @@ class TestProctoringRendering(SharedModuleStoreTestCase): ) content = module.render(STUDENT_VIEW).content - self.assertIn(expected, content) + assert expected in content def _setup_test_data(self, enrollment_mode, is_practice_exam, attempt_status): """ @@ -1521,11 +1485,11 @@ class TestGatedSubsectionRendering(SharedModuleStoreTestCase, MilestonesTestCase self.open_seq.display_name, self.field_data_cache ) - self.assertIsNotNone(self._find_sequential(actual['chapters'], 'Chapter', 'Open_Sequential')) - self.assertIsNotNone(self._find_sequential(actual['chapters'], 'Chapter', 'Gated_Sequential')) - self.assertIsNone(self._find_sequential(actual['chapters'], 'Non-existent_Chapter', 'Non-existent_Sequential')) - self.assertIsNone(actual['previous_of_active_section']) - self.assertIsNone(actual['next_of_active_section']) + assert self._find_sequential(actual['chapters'], 'Chapter', 'Open_Sequential') is not None + assert self._find_sequential(actual['chapters'], 'Chapter', 'Gated_Sequential') is not None + assert self._find_sequential(actual['chapters'], 'Non-existent_Chapter', 'Non-existent_Sequential') is None + assert actual['previous_of_active_section'] is None + assert actual['next_of_active_section'] is None @ddt.ddt @@ -1566,7 +1530,7 @@ class TestHtmlModifiers(ModuleStoreTestCase): ) result_fragment = module.render(STUDENT_VIEW) - self.assertEqual(len(PyQuery(result_fragment.content)('div.xblock.xblock-student_view.xmodule_HtmlBlock')), 1) + assert len(PyQuery(result_fragment.content)('div.xblock.xblock-student_view.xmodule_HtmlBlock')) == 1 def test_xmodule_display_wrapper_disabled(self): module = render.get_module( @@ -1578,8 +1542,7 @@ class TestHtmlModifiers(ModuleStoreTestCase): ) result_fragment = module.render(STUDENT_VIEW) - self.assertNotIn('div class="xblock xblock-student_view xmodule_display xmodule_HtmlBlock"', - result_fragment.content) + assert 'div class="xblock xblock-student_view xmodule_display xmodule_HtmlBlock"' not in result_fragment.content def test_static_link_rewrite(self): module = render.get_module( @@ -1590,13 +1553,8 @@ class TestHtmlModifiers(ModuleStoreTestCase): ) result_fragment = module.render(STUDENT_VIEW) - self.assertIn( - '/c4x/{org}/{course}/asset/foo_content'.format( - org=self.course.location.org, - course=self.course.location.course, - ), - result_fragment.content - ) + assert f'/c4x/{self.course.location.org}/{self.course.location.course}/asset/foo_content' \ + in result_fragment.content def test_static_badlink_rewrite(self): module = render.get_module( @@ -1607,13 +1565,8 @@ class TestHtmlModifiers(ModuleStoreTestCase): ) result_fragment = module.render(STUDENT_VIEW) - self.assertIn( - '/c4x/{org}/{course}/asset/file.jpg'.format( - org=self.course.location.org, - course=self.course.location.course, - ), - result_fragment.content - ) + assert f'/c4x/{self.course.location.org}/{self.course.location.course}/asset/file.jpg'\ + in result_fragment.content def test_static_asset_path_use(self): ''' @@ -1629,15 +1582,15 @@ class TestHtmlModifiers(ModuleStoreTestCase): static_asset_path="toy_course_dir", ) result_fragment = module.render(STUDENT_VIEW) - self.assertIn('href="/static/toy_course_dir', result_fragment.content) + assert 'href="/static/toy_course_dir' in result_fragment.content def test_course_image(self): url = course_image_url(self.course) - self.assertTrue(url.startswith('/c4x/')) + assert url.startswith('/c4x/') self.course.static_asset_path = "toy_course_dir" url = course_image_url(self.course) - self.assertTrue(url.startswith('/static/toy_course_dir/')) + assert url.startswith('/static/toy_course_dir/') self.course.static_asset_path = "" @override_settings(DEFAULT_COURSE_ABOUT_IMAGE_URL='test.png') @@ -1652,7 +1605,7 @@ class TestHtmlModifiers(ModuleStoreTestCase): self.course.course_image = '' url = course_image_url(self.course) - self.assertEqual('static/test.png', url) + assert 'static/test.png' == url def test_get_course_info_section(self): self.course.static_asset_path = "toy_course_dir" @@ -1669,12 +1622,7 @@ class TestHtmlModifiers(ModuleStoreTestCase): ) result_fragment = module.render(STUDENT_VIEW) - self.assertIn( - '/courses/{course_id}/bar/content'.format( - course_id=text_type(self.course.id) - ), - result_fragment.content - ) + assert '/courses/{course_id}/bar/content'.format(course_id=text_type(self.course.id)) in result_fragment.content class XBlockWithJsonInitData(XBlock): @@ -1720,9 +1668,9 @@ class JsonInitDataTest(ModuleStoreTestCase): course=course ) html = module.render(STUDENT_VIEW).content - self.assertIn(json_output, html) + assert json_output in html # No matter what data goes in, there should only be one close-script tag. - self.assertEqual(html.count("</script>"), 1) + assert html.count('</script>') == 1 @XBlock.tag("detached") @@ -1785,7 +1733,7 @@ class TestStaffDebugInfo(SharedModuleStoreTestCase): self.field_data_cache, ) result_fragment = module.render(STUDENT_VIEW) - self.assertNotIn('Staff Debug', result_fragment.content) + assert 'Staff Debug' not in result_fragment.content def test_staff_debug_info_enabled(self): module = render.get_module( @@ -1795,7 +1743,7 @@ class TestStaffDebugInfo(SharedModuleStoreTestCase): self.field_data_cache, ) result_fragment = module.render(STUDENT_VIEW) - self.assertIn('Staff Debug', result_fragment.content) + assert 'Staff Debug' in result_fragment.content def test_staff_debug_info_score_for_invalid_dropdown(self): """ @@ -1833,10 +1781,8 @@ class TestStaffDebugInfo(SharedModuleStoreTestCase): <label for="sd_fs_{block_id}"> / 0</label> </div>""") - self.assertIn( - expected_score_override_html.format(block_id=problem_descriptor.location.block_id), - html_fragment.content - ) + assert expected_score_override_html.format(block_id=problem_descriptor.location.block_id) in\ + html_fragment.content @XBlock.register_temp_plugin(DetachedXBlock, identifier='detached-block') def test_staff_debug_info_disabled_for_detached_blocks(self): @@ -1858,7 +1804,7 @@ class TestStaffDebugInfo(SharedModuleStoreTestCase): field_data_cache, ) result_fragment = module.render(STUDENT_VIEW) - self.assertNotIn('Staff Debug', result_fragment.content) + assert 'Staff Debug' not in result_fragment.content @patch.dict('django.conf.settings.FEATURES', {'DISPLAY_HISTOGRAMS_TO_STAFF': False}) def test_histogram_disabled(self): @@ -1869,7 +1815,7 @@ class TestStaffDebugInfo(SharedModuleStoreTestCase): self.field_data_cache, ) result_fragment = module.render(STUDENT_VIEW) - self.assertNotIn('histrogram', result_fragment.content) + assert 'histrogram' not in result_fragment.content def test_histogram_enabled_for_unscored_xmodules(self): """Histograms should not display for xmodules which are not scored.""" @@ -1892,7 +1838,7 @@ class TestStaffDebugInfo(SharedModuleStoreTestCase): field_data_cache, ) module.render(STUDENT_VIEW) - self.assertFalse(mock_grade_histogram.called) + assert not mock_grade_histogram.called def test_histogram_enabled_for_scored_xmodules(self): """Histograms should display for xmodules which are scored.""" @@ -1914,7 +1860,7 @@ class TestStaffDebugInfo(SharedModuleStoreTestCase): self.field_data_cache, ) module.render(STUDENT_VIEW) - self.assertTrue(mock_grade_histogram.called) + assert mock_grade_histogram.called PER_COURSE_ANONYMIZED_XBLOCKS = ( @@ -1993,28 +1939,16 @@ class TestAnonymousStudentId(SharedModuleStoreTestCase, LoginEnrollmentTestCase) @ddt.data(*PER_STUDENT_ANONYMIZED_DESCRIPTORS) def test_per_student_anonymized_id(self, descriptor_class): for course_id in ('MITx/6.00x/2012_Fall', 'MITx/6.00x/2013_Spring'): - self.assertEqual( - # This value is set by observation, so that later changes to the student - # id computation don't break old data - 'de619ab51c7f4e9c7216b4644c24f3b5', - self._get_anonymous_id(CourseKey.from_string(course_id), descriptor_class) - ) + assert 'de619ab51c7f4e9c7216b4644c24f3b5' == \ + self._get_anonymous_id(CourseKey.from_string(course_id), descriptor_class) @ddt.data(*PER_COURSE_ANONYMIZED_XBLOCKS) def test_per_course_anonymized_id(self, xblock_class): - self.assertEqual( - # This value is set by observation, so that later changes to the student - # id computation don't break old data - '0c706d119cad686d28067412b9178454', - self._get_anonymous_id(CourseKey.from_string('MITx/6.00x/2012_Fall'), xblock_class) - ) + assert '0c706d119cad686d28067412b9178454' == \ + self._get_anonymous_id(CourseKey.from_string('MITx/6.00x/2012_Fall'), xblock_class) - self.assertEqual( - # This value is set by observation, so that later changes to the student - # id computation don't break old data - 'e9969c28c12c8efa6e987d6dbeedeb0b', - self._get_anonymous_id(CourseKey.from_string('MITx/6.00x/2013_Spring'), xblock_class) - ) + assert 'e9969c28c12c8efa6e987d6dbeedeb0b' == \ + self._get_anonymous_id(CourseKey.from_string('MITx/6.00x/2013_Spring'), xblock_class) @patch('common.djangoapps.track.views.eventtracker', autospec=True) @@ -2048,7 +1982,7 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): def test_context_contains_display_name(self, mock_tracker): problem_display_name = u'Option Response Problem' module_info = self.handle_callback_and_get_module_info(mock_tracker, problem_display_name) - self.assertEqual(problem_display_name, module_info['display_name']) + assert problem_display_name == module_info['display_name'] @XBlockAside.register_temp_plugin(AsideTestType, 'test_aside') @patch('xmodule.modulestore.mongo.base.CachingDescriptorSystem.applicable_aside_types', @@ -2074,12 +2008,12 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): # We are sending this `call_idx` to get the mock call that we are interested in. context_info = self.handle_callback_and_get_context_info(mock_tracker, problem_display_name, call_idx=4) - self.assertIn('asides', context_info) - self.assertIn('test_aside', context_info['asides']) - self.assertIn('content', context_info['asides']['test_aside']) - self.assertEqual(context_info['asides']['test_aside']['content'], 'test1') - self.assertIn('data_field', context_info['asides']['test_aside']) - self.assertEqual(context_info['asides']['test_aside']['data_field'], 'test2') + assert 'asides' in context_info + assert 'test_aside' in context_info['asides'] + assert 'content' in context_info['asides']['test_aside'] + assert context_info['asides']['test_aside']['content'] == 'test1' + assert 'data_field' in context_info['asides']['test_aside'] + assert context_info['asides']['test_aside']['data_field'] == 'test2' def handle_callback_and_get_context_info(self, mock_tracker, @@ -2107,11 +2041,13 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): 'problem_check', ) - self.assertEquals(len(mock_tracker.emit.mock_calls), 1) # lint-amnesty, pylint: disable=deprecated-method + assert len(mock_tracker.emit.mock_calls) == 1 + # lint-amnesty, pylint: disable=deprecated-method mock_call = mock_tracker.emit.mock_calls[0] event = mock_call[2] - self.assertEquals(event['name'], 'problem_check') # lint-amnesty, pylint: disable=deprecated-method + assert event['name'] == 'problem_check' + # lint-amnesty, pylint: disable=deprecated-method # for different operations, there are different number of context calls. # We are sending this `call_idx` to get the mock call that we are interested in. @@ -2131,7 +2067,7 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): def test_missing_display_name(self, mock_tracker): actual_display_name = self.handle_callback_and_get_module_info(mock_tracker)['display_name'] - self.assertTrue(actual_display_name.startswith('problem')) + assert actual_display_name.startswith('problem') def test_library_source_information(self, mock_tracker): """ @@ -2144,10 +2080,10 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): mock_get_original_usage = lambda _, key: (original_usage_key, original_usage_version) with patch('xmodule.modulestore.mixed.MixedModuleStore.get_block_original_usage', mock_get_original_usage): module_info = self.handle_callback_and_get_module_info(mock_tracker) - self.assertIn('original_usage_key', module_info) - self.assertEqual(module_info['original_usage_key'], text_type(original_usage_key)) - self.assertIn('original_usage_version', module_info) - self.assertEqual(module_info['original_usage_version'], text_type(original_usage_version)) + assert 'original_usage_key' in module_info + assert module_info['original_usage_key'] == text_type(original_usage_key) + assert 'original_usage_version' in module_info + assert module_info['original_usage_version'] == text_type(original_usage_version) class TestXmoduleRuntimeEvent(TestSubmittingProblems): @@ -2186,16 +2122,16 @@ class TestXmoduleRuntimeEvent(TestSubmittingProblems): """Tests the publish mechanism""" self.set_module_grade_using_publish(self.grade_dict) student_module = StudentModule.objects.get(student=self.student_user, module_state_key=self.problem.location) - self.assertEqual(student_module.grade, self.grade_dict['value']) - self.assertEqual(student_module.max_grade, self.grade_dict['max_value']) + assert student_module.grade == self.grade_dict['value'] + assert student_module.max_grade == self.grade_dict['max_value'] def test_xmodule_runtime_publish_delete(self): """Test deleting the grade using the publish mechanism""" module = self.set_module_grade_using_publish(self.grade_dict) module.system.publish(module, 'grade', self.delete_dict) student_module = StudentModule.objects.get(student=self.student_user, module_state_key=self.problem.location) - self.assertIsNone(student_module.grade) - self.assertIsNone(student_module.max_grade) + assert student_module.grade is None + assert student_module.max_grade is None @patch('lms.djangoapps.grades.signals.handlers.PROBLEM_RAW_SCORE_CHANGED.send') def test_score_change_signal(self, send_mock): @@ -2279,7 +2215,7 @@ class TestRebindModule(TestSubmittingProblems): render.LmsModuleRenderError, "rebind_noauth_module_to_user can only be called from a module bound to an anonymous user" ): - self.assertTrue(module.system.rebind_noauth_module_to_user(module, user2)) + assert module.system.rebind_noauth_module_to_user(module, user2) def test_rebind_noauth_module_to_user_anonymous(self): """ @@ -2290,10 +2226,10 @@ class TestRebindModule(TestSubmittingProblems): user2 = UserFactory() user2.id = 2 module.system.rebind_noauth_module_to_user(module, user2) - self.assertTrue(module) - self.assertEqual(module.system.anonymous_student_id, anonymous_id_for_user(user2, self.course.id)) - self.assertEqual(module.scope_ids.user_id, user2.id) - self.assertEqual(module.scope_ids.user_id, user2.id) + assert module + assert module.system.anonymous_student_id == anonymous_id_for_user(user2, self.course.id) + assert module.scope_ids.user_id == user2.id + assert module.scope_ids.user_id == user2.id @ddt.ddt @@ -2374,7 +2310,7 @@ class LMSXBlockServiceBindingTest(SharedModuleStoreTestCase): course=self.course ) service = runtime.service(descriptor, expected_service) - self.assertIsNotNone(service) + assert service is not None def test_beta_tester_fields_added(self): """ @@ -2394,8 +2330,8 @@ class LMSXBlockServiceBindingTest(SharedModuleStoreTestCase): ) # pylint: disable=no-member - self.assertFalse(runtime.user_is_beta_tester) - self.assertEqual(runtime.days_early_for_beta, 5) + assert not runtime.user_is_beta_tester + assert runtime.days_early_for_beta == 5 class PureXBlockWithChildren(PureXBlock): @@ -2575,7 +2511,7 @@ class TestFilteredChildren(SharedModuleStoreTestCase): """ Used to assert that sets of children are equivalent. """ - self.assertEqual(set(child_usage_ids), set(child.scope_ids.usage_id for child in block.get_children())) + assert set(child_usage_ids) == set((child.scope_ids.usage_id for child in block.get_children())) @ddt.ddt @@ -2621,5 +2557,5 @@ class TestDisabledXBlockTypes(ModuleStoreTestCase): item_id = item.scope_ids.usage_id # lint-amnesty, pylint: disable=no-member item = self.store.get_item(item_id) - self.assertEqual(item.__class__.__name__, descriptor) + assert item.__class__.__name__ == descriptor return item_id diff --git a/lms/djangoapps/courseware/tests/test_navigation.py b/lms/djangoapps/courseware/tests/test_navigation.py index ea6769667678bb44df74451045ce2dfdf77da9b2..b79d74375ef0d9b86d8f7a636b8e08fc514d4c69 100644 --- a/lms/djangoapps/courseware/tests/test_navigation.py +++ b/lms/djangoapps/courseware/tests/test_navigation.py @@ -122,8 +122,8 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): 'chapter': 'Chrome', 'section': displayname, })) - self.assertEqual('course-tabs' in response.content.decode('utf-8'), tabs) - self.assertEqual('course-navigation' in response.content.decode('utf-8'), accordion) + assert ('course-tabs' in response.content.decode('utf-8')) == tabs + assert ('course-navigation' in response.content.decode('utf-8')) == accordion self.assertTabInactive('progress', response) self.assertTabActive('courseware', response) @@ -148,7 +148,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): # make sure we can access courseware immediately resp = self.client.get(reverse('dashboard')) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 # then wait a bit and see if we get timed out time.sleep(2) diff --git a/lms/djangoapps/courseware/tests/test_rules.py b/lms/djangoapps/courseware/tests/test_rules.py index 19489999b4258fbd0ae4392df321ec9c2d1cceb4..015218b8195e85e7ba595aa4206cf90c7d55fc05 100644 --- a/lms/djangoapps/courseware/tests/test_rules.py +++ b/lms/djangoapps/courseware/tests/test_rules.py @@ -61,7 +61,7 @@ class PermissionTests(ModuleStoreTestCase): has_perm = self.user.has_perm( 'edx_proctoring.can_take_proctored_exam', {'course_id': str(self.course_id)} ) - self.assertFalse(has_perm) + assert not has_perm @patch.dict( 'django.conf.settings.PROCTORING_BACKENDS', @@ -78,13 +78,6 @@ class PermissionTests(ModuleStoreTestCase): enable_proctored_exams=True, proctoring_provider='mock_proctoring_allow_honor_mode' ) CourseEnrollment.enroll(self.user, course_allow_honor.id, mode='honor') - self.assertTrue( - self.user.has_perm( - 'edx_proctoring.can_take_proctored_exam', - { - 'course_id': str(course_allow_honor.id), - 'backend': 'mock_proctoring_allow_honor_mode', - 'is_proctored': True, - }, - ) - ) + assert self.user.has_perm('edx_proctoring.can_take_proctored_exam', + {'course_id': str(course_allow_honor.id), + 'backend': 'mock_proctoring_allow_honor_mode', 'is_proctored': True}) diff --git a/lms/djangoapps/courseware/tests/test_self_paced_overrides.py b/lms/djangoapps/courseware/tests/test_self_paced_overrides.py index 7a3fcb989f4aee322d66244a98807f2ef9f5fac0..83057e2ab38e0ebe090c45f842925c286b9e2bf2 100644 --- a/lms/djangoapps/courseware/tests/test_self_paced_overrides.py +++ b/lms/djangoapps/courseware/tests/test_self_paced_overrides.py @@ -77,11 +77,11 @@ class SelfPacedDateOverrideTest(ModuleStoreTestCase): def test_instructor_paced_due_date(self): __, ip_section = self.setup_course(display_name="Instructor Paced Course", self_paced=False) - self.assertEqual(ip_section.due, self.now) + assert ip_section.due == self.now def test_self_paced_due_date(self): __, sp_section = self.setup_course(display_name="Self-Paced Course", self_paced=True) - self.assertIsNone(sp_section.due) + assert sp_section.due is None @patch.dict('lms.djangoapps.courseware.access.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_course_access_to_beta_users(self): @@ -100,16 +100,16 @@ class SelfPacedDateOverrideTest(ModuleStoreTestCase): beta_tester = BetaTesterFactory(course_key=self_paced_course.id) # Verify course is `self_paced` and course has start date but not section. - self.assertTrue(self_paced_course.self_paced) - self.assertEqual(self_paced_course.start, one_month_from_now) - self.assertIsNone(self_paced_section.start) + assert self_paced_course.self_paced + assert self_paced_course.start == one_month_from_now + assert self_paced_section.start is None # Verify that non-staff user do not have access to the course - self.assertFalse(has_access(self.non_staff_user, 'load', self_paced_course)) + assert not has_access(self.non_staff_user, 'load', self_paced_course) # Verify beta tester can access the course as well as the course sections - self.assertTrue(has_access(beta_tester, 'load', self_paced_course)) - self.assertTrue(has_access(beta_tester, 'load', self_paced_section, self_paced_course.id)) + assert has_access(beta_tester, 'load', self_paced_course) + assert has_access(beta_tester, 'load', self_paced_section, self_paced_course.id) @patch.dict('lms.djangoapps.courseware.access.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_instructor_paced_discussion_xblock_visibility(self): @@ -122,9 +122,7 @@ class SelfPacedDateOverrideTest(ModuleStoreTestCase): # Only the released xblocks should be visible when the course is instructor-paced. xblocks = get_accessible_discussion_xblocks(course, self.non_staff_user) - self.assertTrue( - all(xblock.display_name == 'released' for xblock in xblocks) - ) + assert all(((xblock.display_name == 'released') for xblock in xblocks)) @patch.dict('lms.djangoapps.courseware.access.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_self_paced_discussion_xblock_visibility(self): @@ -137,7 +135,5 @@ class SelfPacedDateOverrideTest(ModuleStoreTestCase): # The scheduled xblocks should be visible when the course is self-paced. xblocks = get_accessible_discussion_xblocks(course, self.non_staff_user) - self.assertEqual(len(xblocks), 2) - self.assertTrue( - any(xblock.display_name == 'scheduled' for xblock in xblocks) - ) + assert len(xblocks) == 2 + assert any(((xblock.display_name == 'scheduled') for xblock in xblocks)) diff --git a/lms/djangoapps/courseware/tests/test_services.py b/lms/djangoapps/courseware/tests/test_services.py index 5f269e7643eb1ba6d6f4a56cdfeadd78830cc44a..55cca7da7906c8bd5e68c680730d60cce8b7dfb1 100644 --- a/lms/djangoapps/courseware/tests/test_services.py +++ b/lms/djangoapps/courseware/tests/test_services.py @@ -122,4 +122,4 @@ class TestUserStateService(ModuleStoreTestCase): params.update(state_params) self._create_student_module({'key_1': 'value_1'}) state = UserStateService().get_state_as_dict(**params) - self.assertFalse(state) + assert not state diff --git a/lms/djangoapps/courseware/tests/test_split_module.py b/lms/djangoapps/courseware/tests/test_split_module.py index 03bce091dcf001961ee17f8109bd2827340bc1d2..f0fdb0d65f4938e833dd41e7ef12b6eee73dca3e 100644 --- a/lms/djangoapps/courseware/tests/test_split_module.py +++ b/lms/djangoapps/courseware/tests/test_split_module.py @@ -127,24 +127,21 @@ class SplitTestBase(SharedModuleStoreTestCase): unicode_content = resp.content.decode(resp.charset) # Assert we see the proper icon in the top display - self.assertIn( - u'<button class="{} inactive nav-item tab"'.format(self.ICON_CLASSES[user_tag]), - unicode_content - ) + assert u'<button class="{} inactive nav-item tab"'.format(self.ICON_CLASSES[user_tag]) in unicode_content # And proper tooltips for tooltip in self.TOOLTIPS[user_tag]: - self.assertIn(tooltip, unicode_content) + assert tooltip in unicode_content for key in self.included_usage_keys[user_tag]: - self.assertIn(six.text_type(key), unicode_content) + assert six.text_type(key) in unicode_content for key in self.excluded_usage_keys[user_tag]: - self.assertNotIn(six.text_type(key), unicode_content) + assert six.text_type(key) not in unicode_content # Assert that we can see the data from the appropriate test condition for visible in self.VISIBLE_CONTENT[user_tag]: - self.assertIn(visible, unicode_content) + assert visible in unicode_content class TestSplitTestVert(SplitTestBase): diff --git a/lms/djangoapps/courseware/tests/test_submitting_problems.py b/lms/djangoapps/courseware/tests/test_submitting_problems.py index f7feed9d07d1e50dc56dd157d40e1ddc3c366ee2..b8e375037a945dd6ad5ef742a7ef78ce494bdbac 100644 --- a/lms/djangoapps/courseware/tests/test_submitting_problems.py +++ b/lms/djangoapps/courseware/tests/test_submitting_problems.py @@ -269,7 +269,7 @@ class TestSubmittingProblems(ModuleStoreTestCase, LoginEnrollmentTestCase, Probl """ Assert that percent grade is as expected. """ - self.assertEqual(self.get_course_grade().percent, percent) + assert self.get_course_grade().percent == percent def earned_hw_scores(self): """ @@ -316,7 +316,7 @@ class TestCourseGrades(TestSubmittingProblems): Submits correct answer to the problem. """ resp = self.submit_question_answer('p1', {'2_1': 'Correct'}) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 def _verify_grade(self, expected_problem_score, expected_hw_grade): """ @@ -324,8 +324,8 @@ class TestCourseGrades(TestSubmittingProblems): """ hw_grade = self.hw_grade('homework') problem_score = list(hw_grade.problem_scores.values())[0] - self.assertEqual((problem_score.earned, problem_score.possible), expected_problem_score) - self.assertEqual((hw_grade.graded_total.earned, hw_grade.graded_total.possible), expected_hw_grade) + assert (problem_score.earned, problem_score.possible) == expected_problem_score + assert (hw_grade.graded_total.earned, hw_grade.graded_total.possible) == expected_hw_grade def test_basic(self): self._submit_correct_answer() @@ -452,12 +452,12 @@ class TestCourseGrader(TestSubmittingProblems): """Test problem for due date in the past""" self.basic_setup(late=True) resp = self.submit_question_answer('p1', {'2_1': 'Correct'}) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 err_msg = ( "The state of this problem has changed since you loaded this page. " "Please refresh your page." ) - self.assertEqual(json.loads(resp.content.decode('utf-8')).get("success"), err_msg) + assert json.loads(resp.content.decode('utf-8')).get('success') == err_msg def test_submission_reset(self): """Test problem ProcessingErrors due to resets""" @@ -465,23 +465,23 @@ class TestCourseGrader(TestSubmittingProblems): resp = self.submit_question_answer('p1', {'2_1': 'Correct'}) # submit a second time to draw NotFoundError resp = self.submit_question_answer('p1', {'2_1': 'Correct'}) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 err_msg = ( "The state of this problem has changed since you loaded this page. " "Please refresh your page." ) - self.assertEqual(json.loads(resp.content.decode('utf-8')).get("success"), err_msg) + assert json.loads(resp.content.decode('utf-8')).get('success') == err_msg def test_submission_show_answer(self): """Test problem for ProcessingErrors due to showing answer""" self.basic_setup(showanswer=True) resp = self.show_question_answer('p1') - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 err_msg = ( "The state of this problem has changed since you loaded this page. " "Please refresh your page." ) - self.assertEqual(json.loads(resp.content.decode('utf-8')).get("success"), err_msg) + assert json.loads(resp.content.decode('utf-8')).get('success') == err_msg def test_show_answer_doesnt_write_to_csm(self): self.basic_setup() @@ -494,14 +494,14 @@ class TestCourseGrader(TestSubmittingProblems): ) # count how many state history entries there are baseline = BaseStudentModuleHistory.get_history(student_module) - self.assertEqual(len(baseline), 2) + assert len(baseline) == 2 # now click "show answer" self.show_question_answer('p1') # check that we don't have more state history entries csmh = BaseStudentModuleHistory.get_history(student_module) - self.assertEqual(len(csmh), 2) + assert len(csmh) == 2 def test_grade_with_collected_max_score(self): """ @@ -511,11 +511,7 @@ class TestCourseGrader(TestSubmittingProblems): self.basic_setup() self.submit_question_answer('p1', {'2_1': 'Correct'}) self.look_at_question('p2') - self.assertTrue( - StudentModule.objects.filter( - module_state_key=self.problem_location('p2') - ).exists() - ) + assert StudentModule.objects.filter(module_state_key=self.problem_location('p2')).exists() # problem isn't in the cache, but will be when graded self.check_grade_percent(0.33) @@ -529,7 +525,7 @@ class TestCourseGrader(TestSubmittingProblems): """ self.basic_setup() self.check_grade_percent(0) - self.assertEqual(self.get_course_grade().letter_grade, None) + assert self.get_course_grade().letter_grade is None def test_b_grade_exact(self): """ @@ -538,7 +534,7 @@ class TestCourseGrader(TestSubmittingProblems): self.basic_setup() self.submit_question_answer('p1', {'2_1': 'Correct'}) self.check_grade_percent(0.33) - self.assertEqual(self.get_course_grade().letter_grade, 'B') + assert self.get_course_grade().letter_grade == 'B' def test_b_grade_above(self): """ @@ -548,7 +544,7 @@ class TestCourseGrader(TestSubmittingProblems): self.submit_question_answer('p1', {'2_1': 'Correct'}) self.submit_question_answer('p2', {'2_1': 'Correct'}) self.check_grade_percent(0.67) - self.assertEqual(self.get_course_grade().letter_grade, 'B') + assert self.get_course_grade().letter_grade == 'B' def test_a_grade(self): """ @@ -559,7 +555,7 @@ class TestCourseGrader(TestSubmittingProblems): self.submit_question_answer('p2', {'2_1': 'Correct'}) self.submit_question_answer('p3', {'2_1': 'Correct'}) self.check_grade_percent(1.0) - self.assertEqual(self.get_course_grade().letter_grade, 'A') + assert self.get_course_grade().letter_grade == 'A' def test_wrong_answers(self): """ @@ -570,7 +566,7 @@ class TestCourseGrader(TestSubmittingProblems): self.submit_question_answer('p2', {'2_1': 'Correct'}) self.submit_question_answer('p3', {'2_1': 'Incorrect'}) self.check_grade_percent(0.67) - self.assertEqual(self.get_course_grade().letter_grade, 'B') + assert self.get_course_grade().letter_grade == 'B' def test_submissions_api_overrides_scores(self): """ @@ -581,7 +577,7 @@ class TestCourseGrader(TestSubmittingProblems): self.submit_question_answer('p2', {'2_1': 'Correct'}) self.submit_question_answer('p3', {'2_1': 'Incorrect'}) self.check_grade_percent(0.67) - self.assertEqual(self.get_course_grade().letter_grade, 'B') + assert self.get_course_grade().letter_grade == 'B' student_item = { 'student_id': anonymous_id_for_user(self.student_user, self.course.id), @@ -592,7 +588,7 @@ class TestCourseGrader(TestSubmittingProblems): submission = submissions_api.create_submission(student_item, 'any answer') submissions_api.set_score(submission['uuid'], 1, 1) self.check_grade_percent(1.0) - self.assertEqual(self.get_course_grade().letter_grade, 'A') + assert self.get_course_grade().letter_grade == 'A' def test_submissions_api_anonymous_student_id(self): """ @@ -627,8 +623,9 @@ class TestCourseGrader(TestSubmittingProblems): # Get both parts correct self.submit_question_answer('H1P1', {'2_1': 'Correct', '2_2': 'Correct'}) self.check_grade_percent(0.25) - self.assertEqual(self.earned_hw_scores(), [2.0]) # Order matters - self.assertEqual(self.score_for_hw('homework'), [2.0]) + assert self.earned_hw_scores() == [2.0] + # Order matters + assert self.score_for_hw('homework') == [2.0] def test_weighted_exam(self): """ @@ -674,9 +671,10 @@ class TestCourseGrader(TestSubmittingProblems): self.dropping_setup() self.dropping_homework_stage1() - self.assertEqual(self.score_for_hw('homework1'), [1.0, 0.0]) - self.assertEqual(self.score_for_hw('homework2'), [1.0, 1.0]) - self.assertEqual(self.earned_hw_scores(), [1.0, 2.0, 0]) # Order matters + assert self.score_for_hw('homework1') == [1.0, 0.0] + assert self.score_for_hw('homework2') == [1.0, 1.0] + assert self.earned_hw_scores() == [1.0, 2.0, 0] + # Order matters self.check_grade_percent(0.75) def test_dropping_nochange(self): @@ -687,10 +685,11 @@ class TestCourseGrader(TestSubmittingProblems): self.dropping_homework_stage1() self.submit_question_answer(self.hw3_names[0], {'2_1': 'Correct'}) - self.assertEqual(self.score_for_hw('homework1'), [1.0, 0.0]) - self.assertEqual(self.score_for_hw('homework2'), [1.0, 1.0]) - self.assertEqual(self.score_for_hw('homework3'), [1.0, 0.0]) - self.assertEqual(self.earned_hw_scores(), [1.0, 2.0, 1.0]) # Order matters + assert self.score_for_hw('homework1') == [1.0, 0.0] + assert self.score_for_hw('homework2') == [1.0, 1.0] + assert self.score_for_hw('homework3') == [1.0, 0.0] + assert self.earned_hw_scores() == [1.0, 2.0, 1.0] + # Order matters self.check_grade_percent(0.75) def test_dropping_all_correct(self): @@ -704,8 +703,9 @@ class TestCourseGrader(TestSubmittingProblems): self.submit_question_answer(name, {'2_1': 'Correct'}) self.check_grade_percent(1.0) - self.assertEqual(self.earned_hw_scores(), [1.0, 2.0, 2.0]) # Order matters - self.assertEqual(self.score_for_hw('homework3'), [1.0, 1.0]) + assert self.earned_hw_scores() == [1.0, 2.0, 2.0] + # Order matters + assert self.score_for_hw('homework3') == [1.0, 1.0] @ddt.data( *CourseMode.CREDIT_ELIGIBLE_MODES @@ -743,14 +743,14 @@ class TestCourseGrader(TestSubmittingProblems): # Credit requirement is not satisfied before passing grade req_status = get_credit_requirement_status(self.course.id, self.student_user.username, 'grade', 'grade') - self.assertEqual(req_status[0]["status"], None) + assert req_status[0]['status'] is None self.submit_question_answer('p1', {'2_1': 'Correct'}) self.submit_question_answer('p2', {'2_1': 'Correct'}) # Credit requirement is now satisfied after passing grade req_status = get_credit_requirement_status(self.course.id, self.student_user.username, 'grade', 'grade') - self.assertEqual(req_status[0]["status"], 'satisfied') + assert req_status[0]['status'] == 'satisfied' class ProblemWithUploadedFilesTest(TestSubmittingProblems): @@ -794,15 +794,15 @@ class ProblemWithUploadedFilesTest(TestSubmittingProblems): with patch('lms.djangoapps.courseware.module_render.XQUEUE_INTERFACE.session') as mock_session: resp = self.submit_question_answer("the_problem", {'2_1': fileobjs}) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 json_resp = json.loads(resp.content.decode('utf-8')) - self.assertEqual(json_resp['success'], "incorrect") + assert json_resp['success'] == 'incorrect' # See how post got called. name, args, kwargs = mock_session.mock_calls[0] - self.assertEqual(name, "post") - self.assertEqual(len(args), 1) - self.assertTrue(args[0].endswith("/submit/")) + assert name == 'post' + assert len(args) == 1 + assert args[0].endswith('/submit/') six.assertCountEqual(self, list(kwargs.keys()), ["files", "data", "timeout"]) six.assertCountEqual(self, list(kwargs['files'].keys()), filenames.split()) @@ -986,7 +986,7 @@ class TestPythonGradedResponse(TestSubmittingProblems): resp = self.submit_question_answer(name, {'2_1': self.correct_responses[name]}) respdata = json.loads(resp.content.decode('utf-8')) - self.assertEqual(respdata['success'], 'correct') + assert respdata['success'] == 'correct' def _check_incorrect(self, name): """ @@ -995,7 +995,7 @@ class TestPythonGradedResponse(TestSubmittingProblems): resp = self.submit_question_answer(name, {'2_1': self.incorrect_responses[name]}) respdata = json.loads(resp.content.decode('utf-8')) - self.assertEqual(respdata['success'], 'incorrect') + assert respdata['success'] == 'incorrect' def _check_ireset(self, name): """ @@ -1009,7 +1009,7 @@ class TestPythonGradedResponse(TestSubmittingProblems): resp = self.submit_question_answer(name, {'2_1': self.correct_responses[name]}) respdata = json.loads(resp.content.decode('utf-8')) - self.assertEqual(respdata['success'], 'correct') + assert respdata['success'] == 'correct' def test_schematic_correct(self): name = "schematic_problem" @@ -1183,9 +1183,9 @@ class TestConditionalContent(TestSubmittingProblems): self.submit_question_answer('H2P1_GROUP0', {'2_1': 'Correct'}) self.submit_question_answer('H2P2_GROUP0', {'2_1': 'Correct', '2_2': 'Incorrect', '2_3': 'Correct'}) - self.assertEqual(self.score_for_hw('homework1'), [1.0]) - self.assertEqual(self.score_for_hw('homework2'), [1.0, 2.0]) - self.assertEqual(self.earned_hw_scores(), [1.0, 3.0]) + assert self.score_for_hw('homework1') == [1.0] + assert self.score_for_hw('homework2') == [1.0, 2.0] + assert self.earned_hw_scores() == [1.0, 3.0] # Grade percent is .63. Here is the calculation: # homework_1_score = 1.0 / 2 @@ -1202,9 +1202,9 @@ class TestConditionalContent(TestSubmittingProblems): self.submit_question_answer('H2P1_GROUP1', {'2_1': 'Correct'}) - self.assertEqual(self.score_for_hw('homework1'), [1.0]) - self.assertEqual(self.score_for_hw('homework2'), [1.0]) - self.assertEqual(self.earned_hw_scores(), [1.0, 1.0]) + assert self.score_for_hw('homework1') == [1.0] + assert self.score_for_hw('homework2') == [1.0] + assert self.earned_hw_scores() == [1.0, 1.0] # Grade percent is .75. Here is the calculation: # homework_1_score = 1.0 / 2 @@ -1236,9 +1236,9 @@ class TestConditionalContent(TestSubmittingProblems): """ self.split_one_group_no_problems_setup(self.user_partition_group_0) - self.assertEqual(self.score_for_hw('homework1'), [1.0]) - self.assertEqual(self.score_for_hw('homework2'), []) - self.assertEqual(self.earned_hw_scores(), [1.0]) + assert self.score_for_hw('homework1') == [1.0] + assert self.score_for_hw('homework2') == [] + assert self.earned_hw_scores() == [1.0] # Grade percent is .25. Here is the calculation: # homework_1_score = 1.0 / 2 @@ -1254,9 +1254,9 @@ class TestConditionalContent(TestSubmittingProblems): self.submit_question_answer('H2P1_GROUP1', {'2_1': 'Correct'}) - self.assertEqual(self.score_for_hw('homework1'), [1.0]) - self.assertEqual(self.score_for_hw('homework2'), [1.0]) - self.assertEqual(self.earned_hw_scores(), [1.0, 1.0]) + assert self.score_for_hw('homework1') == [1.0] + assert self.score_for_hw('homework2') == [1.0] + assert self.earned_hw_scores() == [1.0, 1.0] # Grade percent is .75. Here is the calculation. # homework_1_score = 1.0 / 2 diff --git a/lms/djangoapps/courseware/tests/test_tabs.py b/lms/djangoapps/courseware/tests/test_tabs.py index 245e3d8c0933bb4ccf741db69dc0d959c10de70c..8e31e802ab9c2a61cfc24ac26c5ef61600e5cb2f 100644 --- a/lms/djangoapps/courseware/tests/test_tabs.py +++ b/lms/djangoapps/courseware/tests/test_tabs.py @@ -2,7 +2,7 @@ Test cases for tabs. """ - +import pytest import six from crum import set_current_request from django.contrib.auth.models import AnonymousUser @@ -109,18 +109,18 @@ class TabTestCase(SharedModuleStoreTestCase): tab = tab_class(tab_dict=dict_tab) # name is as expected - self.assertEqual(tab.name, expected_name) + assert tab.name == expected_name # link is as expected - self.assertEqual(tab.link_func(self.course, self.reverse), expected_link) + assert tab.link_func(self.course, self.reverse) == expected_link # verify active page name - self.assertEqual(tab.tab_id, expected_tab_id) + assert tab.tab_id == expected_tab_id # validate tab - self.assertTrue(tab.validate(dict_tab)) + assert tab.validate(dict_tab) if invalid_dict_tab: - with self.assertRaises(xmodule_tabs.InvalidTabsException): + with pytest.raises(xmodule_tabs.InvalidTabsException): tab.validate(invalid_dict_tab) # check get and set methods @@ -137,17 +137,20 @@ class TabTestCase(SharedModuleStoreTestCase): def check_tab_equality(self, tab, dict_tab): """Tests the equality methods on the given tab""" - self.assertEqual(tab, dict_tab) # test __eq__ + assert tab == dict_tab + # test __eq__ ne_dict_tab = dict_tab ne_dict_tab['type'] = 'fake_type' - self.assertNotEqual(tab, ne_dict_tab) # test __ne__: incorrect type - self.assertNotEqual(tab, {'fake_key': 'fake_value'}) # test __ne__: missing type + assert tab != ne_dict_tab + # test __ne__: incorrect type + assert tab != {'fake_key': 'fake_value'} + # test __ne__: missing type def check_tab_json_methods(self, tab): """Tests the json from and to methods on the given tab""" serialized_tab = tab.to_json() deserialized_tab = tab.from_json(serialized_tab) - self.assertEqual(serialized_tab, deserialized_tab) + assert serialized_tab == deserialized_tab def check_can_display_results( self, @@ -160,27 +163,27 @@ class TabTestCase(SharedModuleStoreTestCase): """Checks can display results for various users""" if for_staff_only: user = self.create_mock_user(is_staff=True, is_enrolled=True) - self.assertEqual(expected_value, self.is_tab_enabled(tab, self.course, user)) + assert expected_value == self.is_tab_enabled(tab, self.course, user) if for_authenticated_users_only: user = self.create_mock_user(is_staff=False, is_enrolled=False) - self.assertEqual(expected_value, self.is_tab_enabled(tab, self.course, user)) + assert expected_value == self.is_tab_enabled(tab, self.course, user) if not for_staff_only and not for_authenticated_users_only and not for_enrolled_users_only: user = AnonymousUser() - self.assertEqual(expected_value, self.is_tab_enabled(tab, self.course, user)) + assert expected_value == self.is_tab_enabled(tab, self.course, user) if for_enrolled_users_only: user = self.create_mock_user(is_staff=False, is_enrolled=True) - self.assertEqual(expected_value, self.is_tab_enabled(tab, self.course, user)) + assert expected_value == self.is_tab_enabled(tab, self.course, user) def check_get_and_set_methods(self, tab): """Test __getitem__ and __setitem__ calls""" - self.assertEqual(tab['type'], tab.type) - self.assertEqual(tab['tab_id'], tab.tab_id) - with self.assertRaises(KeyError): + assert tab['type'] == tab.type + assert tab['tab_id'] == tab.tab_id + with pytest.raises(KeyError): _ = tab['invalid_key'] self.check_get_and_set_method_for_key(tab, 'name') self.check_get_and_set_method_for_key(tab, 'tab_id') - with self.assertRaises(KeyError): + with pytest.raises(KeyError): tab['invalid_key'] = 'New Value' def check_get_and_set_method_for_key(self, tab, key): @@ -188,9 +191,9 @@ class TabTestCase(SharedModuleStoreTestCase): old_value = tab[key] new_value = 'New Value' tab[key] = new_value - self.assertEqual(tab[key], new_value) + assert tab[key] == new_value tab[key] = old_value - self.assertEqual(tab[key], old_value) + assert tab[key] == old_value class TextbooksTestCase(TabTestCase): @@ -227,10 +230,10 @@ class TextbooksTestCase(TabTestCase): type_to_reverse_name[book_type], args=[text_type(self.course.id), book_index] ) - self.assertEqual(tab.link_func(self.course, self.reverse), expected_link) - self.assertTrue(tab.name.startswith('Book{0}'.format(book_index))) + assert tab.link_func(self.course, self.reverse) == expected_link + assert tab.name.startswith('Book{0}'.format(book_index)) num_textbooks_found = num_textbooks_found + 1 - self.assertEqual(num_textbooks_found, self.num_textbooks) + assert num_textbooks_found == self.num_textbooks class StaticTabDateTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase): @@ -264,7 +267,7 @@ class StaticTabDateTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase): self.setup_user() self.addCleanup(set_current_request, None) request = get_mock_request(self.user) - with self.assertRaises(Http404): + with pytest.raises(Http404): StaticCourseTabView().get(request, course_id='edX/toy', tab_slug='new_tab') def test_get_static_tab_fragment(self): @@ -276,8 +279,8 @@ class StaticTabDateTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase): # Test render works okay tab_content = get_static_tab_fragment(request, course, tab).content - self.assertIn(text_type(self.course.id), tab_content) - self.assertIn('static_tab', tab_content) + assert text_type(self.course.id) in tab_content + assert 'static_tab' in tab_content # Test when render raises an exception with patch('lms.djangoapps.courseware.views.views.get_module') as mock_module_render: @@ -285,7 +288,7 @@ class StaticTabDateTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase): render=Mock(side_effect=Exception('Render failed!')) ) static_tab_content = get_static_tab_fragment(request, course, tab).content - self.assertIn("this module is temporarily unavailable", static_tab_content) + assert 'this module is temporarily unavailable' in static_tab_content class StaticTabDateTestCaseXML(LoginEnrollmentTestCase, ModuleStoreTestCase): @@ -400,9 +403,9 @@ class EntranceExamsTabsTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, Mi milestone ) course_tab_list = get_course_tab_list(self.user, self.course) - self.assertEqual(len(course_tab_list), 1) - self.assertEqual(course_tab_list[0]['tab_id'], 'courseware') - self.assertEqual(course_tab_list[0]['name'], 'Entrance Exam') + assert len(course_tab_list) == 1 + assert course_tab_list[0]['tab_id'] == 'courseware' + assert course_tab_list[0]['name'] == 'Entrance Exam' def test_get_course_tabs_list_skipped_entrance_exam(self): """ @@ -419,13 +422,13 @@ class EntranceExamsTabsTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, Mi response = self.client.post(url, { 'unique_student_identifier': student.email, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # log in again as student self.client.logout() self.login(self.email, self.password) course_tab_list = get_course_tab_list(self.user, self.course) - self.assertEqual(len(course_tab_list), 4) + assert len(course_tab_list) == 4 def test_course_tabs_list_for_staff_members(self): """ @@ -437,7 +440,7 @@ class EntranceExamsTabsTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, Mi staff_user = StaffFactory(course_key=self.course.id) self.client.login(username=staff_user.username, password='test') course_tab_list = get_course_tab_list(staff_user, self.course) - self.assertEqual(len(course_tab_list), 4) + assert len(course_tab_list) == 4 class TextBookCourseViewsTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase): @@ -488,14 +491,14 @@ class TextBookCourseViewsTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest args=[text_type(self.course.id), book_index] ) tab_link = tab.link_func(self.course, reverse) - self.assertEqual(tab_link, expected_link) + assert tab_link == expected_link num_of_textbooks_found += 1 - self.assertEqual(num_of_textbooks_found, self.num_textbooks) + assert num_of_textbooks_found == self.num_textbooks @patch.dict("django.conf.settings.FEATURES", {"ENABLE_TEXTBOOK": False}) def test_textbooks_disabled(self): tab = xmodule_tabs.CourseTab.load('textbooks') - self.assertFalse(tab.is_enabled(self.course, self.user)) + assert not tab.is_enabled(self.course, self.user) class TabListTestCase(TabTestCase): @@ -571,12 +574,12 @@ class ValidateTabsTestCase(TabListTestCase): def test_validate_tabs(self): tab_list = xmodule_tabs.CourseTabList() for invalid_tab_list in self.invalid_tabs: - with self.assertRaises(xmodule_tabs.InvalidTabsException): + with pytest.raises(xmodule_tabs.InvalidTabsException): tab_list.from_json(invalid_tab_list) for valid_tab_list in self.valid_tabs: from_json_result = tab_list.from_json(valid_tab_list) - self.assertEqual(len(from_json_result), len(valid_tab_list)) + assert len(from_json_result) == len(valid_tab_list) def test_invalid_tab_type(self): """ @@ -584,14 +587,9 @@ class ValidateTabsTestCase(TabListTestCase): the tabs to be undisplayable. """ tab_list = xmodule_tabs.CourseTabList() - self.assertEqual( - len(tab_list.from_json([ - {'type': CoursewareTab.type}, - {'type': CourseInfoTab.type, 'name': 'fake_name'}, - {'type': 'no_such_type'} - ])), - 2 - ) + assert len(tab_list.from_json([{'type': CoursewareTab.type}, + {'type': CourseInfoTab.type, 'name': 'fake_name'}, + {'type': 'no_such_type'}])) == 2 class CourseTabListTestCase(TabListTestCase): @@ -612,27 +610,27 @@ class CourseTabListTestCase(TabListTestCase): self.course.tabs = [] self.course.syllabus_present = False xmodule_tabs.CourseTabList.initialize_default(self.course) - self.assertFalse(self.has_tab(self.course.tabs, 'syllabus')) + assert not self.has_tab(self.course.tabs, 'syllabus') def test_initialize_default_with_syllabus(self): self.course.tabs = [] self.course.syllabus_present = True xmodule_tabs.CourseTabList.initialize_default(self.course) - self.assertTrue(self.has_tab(self.course.tabs, 'syllabus')) + assert self.has_tab(self.course.tabs, 'syllabus') def test_initialize_default_with_external_link(self): self.course.tabs = [] self.course.discussion_link = "other_discussion_link" xmodule_tabs.CourseTabList.initialize_default(self.course) - self.assertTrue(self.has_tab(self.course.tabs, 'external_discussion')) - self.assertFalse(self.has_tab(self.course.tabs, 'discussion')) + assert self.has_tab(self.course.tabs, 'external_discussion') + assert not self.has_tab(self.course.tabs, 'discussion') def test_initialize_default_without_external_link(self): self.course.tabs = [] self.course.discussion_link = "" xmodule_tabs.CourseTabList.initialize_default(self.course) - self.assertFalse(self.has_tab(self.course.tabs, 'external_discussion')) - self.assertTrue(self.has_tab(self.course.tabs, 'discussion')) + assert not self.has_tab(self.course.tabs, 'external_discussion') + assert self.has_tab(self.course.tabs, 'discussion') @patch.dict("django.conf.settings.FEATURES", { "ENABLE_TEXTBOOK": True, @@ -663,23 +661,19 @@ class CourseTabListTestCase(TabListTestCase): for i, tab in enumerate(xmodule_tabs.CourseTabList.iterate_displayable(self.course, user=user)): if getattr(tab, 'is_collection_item', False): # a collection item was found as a result of a collection tab - self.assertTrue(getattr(self.course.tabs[i], 'is_collection', False)) + assert getattr(self.course.tabs[i], 'is_collection', False) else: # all other tabs must match the expected type - self.assertEqual(tab.type, self.course.tabs[i].type) + assert tab.type == self.course.tabs[i].type # test including non-empty collections - self.assertIn( - {'type': 'html_textbooks'}, - list(xmodule_tabs.CourseTabList.iterate_displayable(self.course, inline_collections=False)), - ) + assert {'type': 'html_textbooks'} in\ + list(xmodule_tabs.CourseTabList.iterate_displayable(self.course, inline_collections=False)) # test not including empty collections self.course.html_textbooks = [] - self.assertNotIn( - {'type': 'html_textbooks'}, - list(xmodule_tabs.CourseTabList.iterate_displayable(self.course, inline_collections=False)), - ) + assert {'type': 'html_textbooks'} not in\ + list(xmodule_tabs.CourseTabList.iterate_displayable(self.course, inline_collections=False)) def test_get_tab_by_methods(self): """Tests the get_tab methods in CourseTabList""" @@ -687,10 +681,10 @@ class CourseTabListTestCase(TabListTestCase): for tab in self.course.tabs: # get tab by type - self.assertEqual(xmodule_tabs.CourseTabList.get_tab_by_type(self.course.tabs, tab.type), tab) + assert xmodule_tabs.CourseTabList.get_tab_by_type(self.course.tabs, tab.type) == tab # get tab by id - self.assertEqual(xmodule_tabs.CourseTabList.get_tab_by_id(self.course.tabs, tab.tab_id), tab) + assert xmodule_tabs.CourseTabList.get_tab_by_id(self.course.tabs, tab.tab_id) == tab def test_course_tabs_staff_only(self): """ @@ -708,8 +702,8 @@ class CourseTabListTestCase(TabListTestCase): self.addCleanup(set_current_request, None) course_tab_list = get_course_tab_list(user, self.course) name_list = [x.name for x in course_tab_list] - self.assertIn('Static Tab Free', name_list) - self.assertNotIn('Static Tab Instructors Only', name_list) + assert 'Static Tab Free' in name_list + assert 'Static Tab Instructors Only' not in name_list # Login as member of staff self.client.logout() @@ -717,8 +711,8 @@ class CourseTabListTestCase(TabListTestCase): self.client.login(username=staff_user.username, password='test') course_tab_list_staff = get_course_tab_list(staff_user, self.course) name_list_staff = [x.name for x in course_tab_list_staff] - self.assertIn('Static Tab Free', name_list_staff) - self.assertIn('Static Tab Instructors Only', name_list_staff) + assert 'Static Tab Free' in name_list_staff + assert 'Static Tab Instructors Only' in name_list_staff class ProgressTestCase(TabTestCase): @@ -783,13 +777,13 @@ class CourseInfoTabTestCase(TabTestCase): # a lower priority than courseware so seems odd that it would ever be first. # As such, I feel comfortable updating this test so it passes until it is removed # as part of the linked ticket - self.assertEqual(tabs[1].type, 'course_info') + assert tabs[1].type == 'course_info' @override_waffle_flag(DISABLE_UNIFIED_COURSE_TAB_FLAG, active=False) def test_default_tab_for_new_course_experience(self): # Verify that the unified course experience hides the course info tab tabs = get_course_tab_list(self.user, self.course) - self.assertEqual(tabs[0].type, 'courseware') + assert tabs[0].type == 'courseware' # TODO: LEARNER-611 - remove once course_info is removed. @override_waffle_flag(DISABLE_UNIFIED_COURSE_TAB_FLAG, active=False) @@ -797,7 +791,7 @@ class CourseInfoTabTestCase(TabTestCase): tabs = xmodule_tabs.CourseTabList.iterate_displayable(self.course, self.user) for i, tab in enumerate(tabs): if i == 0: - self.assertEqual(tab.type, 'course_info') + assert tab.type == 'course_info' class DiscussionLinkTestCase(TabTestCase): @@ -836,14 +830,9 @@ class DiscussionLinkTestCase(TabTestCase): user = self.create_mock_user(is_staff=is_staff, is_enrolled=is_enrolled) with patch('common.djangoapps.student.models.CourseEnrollment.is_enrolled') as check_is_enrolled: check_is_enrolled.return_value = is_enrolled - self.assertEqual( - ( - discussion_tab is not None and - self.is_tab_enabled(discussion_tab, self.course, user) and - (discussion_tab.link_func(self.course, self._reverse(self.course)) == expected_discussion_link) - ), - expected_can_display_value - ) + assert ((discussion_tab is not None) and self.is_tab_enabled(discussion_tab, self.course, user) and + (discussion_tab.link_func(self.course, self._reverse(self.course)) + == expected_discussion_link)) == expected_can_display_value @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": False}) def test_explicit_discussion_link(self): @@ -917,14 +906,14 @@ class DatesTabTestCase(TabListTestCase): is_enrolled.return_value = False unenrolled_user = self.create_mock_user(is_staff=False, is_enrolled=False) - self.assertFalse(self.is_tab_enabled(tab, self.course, unenrolled_user)) + assert not self.is_tab_enabled(tab, self.course, unenrolled_user) staff_user = self.create_mock_user(is_staff=True, is_enrolled=False) - self.assertTrue(self.is_tab_enabled(tab, self.course, staff_user)) + assert self.is_tab_enabled(tab, self.course, staff_user) is_enrolled.return_value = True enrolled_user = self.create_mock_user(is_staff=False, is_enrolled=True) - self.assertTrue(self.is_tab_enabled(tab, self.course, enrolled_user)) + assert self.is_tab_enabled(tab, self.course, enrolled_user) @patch('lms.djangoapps.courseware.tabs.RELATIVE_DATES_FLAG') def test_singular_dates_tab(self, mock_flag): @@ -939,7 +928,7 @@ class DatesTabTestCase(TabListTestCase): for tab in self.course.tabs: if tab.type == 'dates': has_dates_tab = True - self.assertTrue(has_dates_tab) + assert has_dates_tab # Verify that there is only 1 'dates' tab in the returned result from get_course_tab_list() tabs = get_course_tab_list(user, self.course) @@ -947,4 +936,4 @@ class DatesTabTestCase(TabListTestCase): for tab in tabs: if tab.type == 'dates': num_dates_tabs += 1 - self.assertEqual(num_dates_tabs, 1) + assert num_dates_tabs == 1 diff --git a/lms/djangoapps/courseware/tests/test_video_handlers.py b/lms/djangoapps/courseware/tests/test_video_handlers.py index 07e12ed4992b179c96739593cd25ccd787db7f4b..633680316d680d18ac3566d711576502c28929d1 100644 --- a/lms/djangoapps/courseware/tests/test_video_handlers.py +++ b/lms/djangoapps/courseware/tests/test_video_handlers.py @@ -7,7 +7,7 @@ import os import tempfile import textwrap from datetime import timedelta - +import pytest import ddt import freezegun import six @@ -168,25 +168,25 @@ class TestVideo(BaseTestVideoXBlock): } status_codes = {response.status_code for response in responses.values()} - self.assertEqual(status_codes.pop(), 404) + assert status_codes.pop() == 404 def test_handle_ajax_for_speed_with_nan(self): self.item_descriptor.handle_ajax('save_user_state', {'speed': json.dumps(1.0)}) - self.assertEqual(self.item_descriptor.speed, 1.0) - self.assertEqual(self.item_descriptor.global_speed, 1.0) + assert self.item_descriptor.speed == 1.0 + assert self.item_descriptor.global_speed == 1.0 # try to set NaN value for speed. response = self.item_descriptor.handle_ajax( 'save_user_state', {'speed': json.dumps(float('NaN'))} ) - self.assertFalse(json.loads(response)['success']) + assert not json.loads(response)['success'] expected_error = u"Invalid speed value nan, must be a float." - self.assertEqual(json.loads(response)['error'], expected_error) + assert json.loads(response)['error'] == expected_error # verify that the speed and global speed are still 1.0 - self.assertEqual(self.item_descriptor.speed, 1.0) - self.assertEqual(self.item_descriptor.global_speed, 1.0) + assert self.item_descriptor.speed == 1.0 + assert self.item_descriptor.global_speed == 1.0 def test_handle_ajax(self): @@ -203,32 +203,32 @@ class TestVideo(BaseTestVideoXBlock): self.get_url('save_user_state'), sample, HTTP_X_REQUESTED_WITH='XMLHttpRequest') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 - self.assertEqual(self.item_descriptor.speed, None) + assert self.item_descriptor.speed is None self.item_descriptor.handle_ajax('save_user_state', {'speed': json.dumps(2.0)}) - self.assertEqual(self.item_descriptor.speed, 2.0) - self.assertEqual(self.item_descriptor.global_speed, 2.0) + assert self.item_descriptor.speed == 2.0 + assert self.item_descriptor.global_speed == 2.0 - self.assertEqual(self.item_descriptor.saved_video_position, timedelta(0)) + assert self.item_descriptor.saved_video_position == timedelta(0) self.item_descriptor.handle_ajax('save_user_state', {'saved_video_position': "00:00:10"}) - self.assertEqual(self.item_descriptor.saved_video_position, timedelta(0, 10)) + assert self.item_descriptor.saved_video_position == timedelta(0, 10) - self.assertEqual(self.item_descriptor.transcript_language, 'en') + assert self.item_descriptor.transcript_language == 'en' self.item_descriptor.handle_ajax('save_user_state', {'transcript_language': "uk"}) - self.assertEqual(self.item_descriptor.transcript_language, 'uk') + assert self.item_descriptor.transcript_language == 'uk' - self.assertEqual(self.item_descriptor.bumper_do_not_show_again, False) + assert self.item_descriptor.bumper_do_not_show_again is False self.item_descriptor.handle_ajax('save_user_state', {'bumper_do_not_show_again': True}) - self.assertEqual(self.item_descriptor.bumper_do_not_show_again, True) + assert self.item_descriptor.bumper_do_not_show_again is True with freezegun.freeze_time(now()): - self.assertEqual(self.item_descriptor.bumper_last_view_date, None) + assert self.item_descriptor.bumper_last_view_date is None self.item_descriptor.handle_ajax('save_user_state', {'bumper_last_view_date': True}) - self.assertEqual(self.item_descriptor.bumper_last_view_date, now()) + assert self.item_descriptor.bumper_last_view_date == now() response = self.item_descriptor.handle_ajax('save_user_state', {u'demoo�': "sample"}) - self.assertEqual(json.loads(response)['success'], True) + assert json.loads(response)['success'] is True def get_handler_url(self, handler, suffix): """ @@ -278,14 +278,14 @@ class TestTranscriptAvailableTranslationsDispatch(TestVideo): # lint-amnesty, p request = Request.blank('/available_translations') response = self.item.transcript(request=request, dispatch='available_translations') - self.assertEqual(json.loads(response.body.decode('utf-8')), ['en']) + assert json.loads(response.body.decode('utf-8')) == ['en'] def test_available_translation_non_en(self): _upload_file(_create_srt_file(), self.item_descriptor.location, os.path.split(self.srt_file.name)[1]) request = Request.blank('/available_translations') response = self.item.transcript(request=request, dispatch='available_translations') - self.assertEqual(json.loads(response.body.decode('utf-8')), ['uk']) + assert json.loads(response.body.decode('utf-8')) == ['uk'] @patch('xmodule.video_module.transcripts_utils.get_video_transcript_content') def test_multiple_available_translations(self, mock_get_video_transcript_content): @@ -311,7 +311,7 @@ class TestTranscriptAvailableTranslationsDispatch(TestVideo): # lint-amnesty, p request = Request.blank('/available_translations') response = self.item.transcript(request=request, dispatch='available_translations') - self.assertEqual(sorted(json.loads(response.body.decode('utf-8'))), sorted(['en', 'uk'])) + assert sorted(json.loads(response.body.decode('utf-8'))) == sorted(['en', 'uk']) @patch('xmodule.video_module.transcripts_utils.get_video_transcript_content') @patch('xmodule.video_module.transcripts_utils.get_available_transcript_languages') @@ -398,7 +398,7 @@ class TestTranscriptAvailableTranslationsDispatch(TestVideo): # lint-amnesty, p mock_get_available_transcript_languages.return_value = ['en', 'de', 'ro'] request = Request.blank('/available_translations') response = self.item.transcript(request=request, dispatch='available_translations') - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 @ddt.ddt @@ -438,7 +438,7 @@ class TestTranscriptAvailableTranslationsBumperDispatch(TestVideo): # lint-amne request = Request.blank('/' + self.dispatch) response = self.item.transcript(request=request, dispatch=self.dispatch) - self.assertEqual(json.loads(response.body.decode('utf-8')), [lang]) + assert json.loads(response.body.decode('utf-8')) == [lang] @patch('xmodule.video_module.transcripts_utils.get_available_transcript_languages') def test_multiple_available_translations(self, mock_get_transcript_languages): @@ -463,7 +463,7 @@ class TestTranscriptAvailableTranslationsBumperDispatch(TestVideo): # lint-amne request = Request.blank('/' + self.dispatch) response = self.item.transcript(request=request, dispatch=self.dispatch) # Assert that bumper only get its own translations. - self.assertEqual(sorted(json.loads(response.body.decode('utf-8'))), sorted(['en', 'uk'])) + assert sorted(json.loads(response.body.decode('utf-8'))) == sorted(['en', 'uk']) @ddt.ddt @@ -497,7 +497,7 @@ class TestTranscriptDownloadDispatch(TestVideo): # lint-amnesty, pylint: disabl def test_download_transcript_not_exist(self): request = Request.blank('/download') response = self.item.transcript(request=request, dispatch='download') - self.assertEqual(response.status, '404 Not Found') + assert response.status == '404 Not Found' @patch( 'xmodule.video_module.video_handlers.get_transcript', @@ -506,9 +506,9 @@ class TestTranscriptDownloadDispatch(TestVideo): # lint-amnesty, pylint: disabl def test_download_srt_exist(self, __): request = Request.blank('/download') response = self.item.transcript(request=request, dispatch='download') - self.assertEqual(response.body.decode('utf-8'), 'Subs!') - self.assertEqual(response.headers['Content-Type'], 'application/x-subrip; charset=utf-8') - self.assertEqual(response.headers['Content-Language'], 'en') + assert response.body.decode('utf-8') == 'Subs!' + assert response.headers['Content-Type'] == 'application/x-subrip; charset=utf-8' + assert response.headers['Content-Language'] == 'en' @patch( 'xmodule.video_module.video_handlers.get_transcript', @@ -518,15 +518,15 @@ class TestTranscriptDownloadDispatch(TestVideo): # lint-amnesty, pylint: disabl self.item.transcript_format = 'txt' request = Request.blank('/download') response = self.item.transcript(request=request, dispatch='download') - self.assertEqual(response.body.decode('utf-8'), 'Subs!') - self.assertEqual(response.headers['Content-Type'], 'text/plain; charset=utf-8') - self.assertEqual(response.headers['Content-Language'], 'en') + assert response.body.decode('utf-8') == 'Subs!' + assert response.headers['Content-Type'] == 'text/plain; charset=utf-8' + assert response.headers['Content-Language'] == 'en' def test_download_en_no_sub(self): request = Request.blank('/download') response = self.item.transcript(request=request, dispatch='download') - self.assertEqual(response.status, '404 Not Found') - with self.assertRaises(NotFoundError): + assert response.status == '404 Not Found' + with pytest.raises(NotFoundError): get_transcript(self.item) @patch( @@ -536,9 +536,9 @@ class TestTranscriptDownloadDispatch(TestVideo): # lint-amnesty, pylint: disabl def test_download_non_en_non_ascii_filename(self, __): request = Request.blank('/download') response = self.item.transcript(request=request, dispatch='download') - self.assertEqual(response.body.decode('utf-8'), 'Subs!') - self.assertEqual(response.headers['Content-Type'], 'application/x-subrip; charset=utf-8') - self.assertEqual(response.headers['Content-Disposition'], 'attachment; filename="en_å¡ž.srt"') + assert response.body.decode('utf-8') == 'Subs!' + assert response.headers['Content-Type'] == 'application/x-subrip; charset=utf-8' + assert response.headers['Content-Disposition'] == 'attachment; filename="en_å¡ž.srt"' @patch('xmodule.video_module.transcripts_utils.edxval_api.get_video_transcript_data') @patch('xmodule.video_module.get_transcript', Mock(side_effect=NotFoundError)) @@ -568,10 +568,10 @@ class TestTranscriptDownloadDispatch(TestVideo): # lint-amnesty, pylint: disabl } # Assert the actual response - self.assertEqual(response.status_code, 200) - self.assertEqual(response.text, expected_content) + assert response.status_code == 200 + assert response.text == expected_content for attribute, value in six.iteritems(expected_headers): - self.assertEqual(response.headers[attribute], value) + assert response.headers[attribute] == value @ddt.ddt @@ -623,7 +623,7 @@ class TestTranscriptTranslationGetDispatch(TestVideo): # lint-amnesty, pylint: def test_translation_fails(self, url, dispatch, status_code): request = Request.blank(url) response = self.item.transcript(request=request, dispatch=dispatch) - self.assertEqual(response.status, status_code) + assert response.status == status_code @ddt.data( ('translation/en?videoId={}', 'translation/en', attach_sub), @@ -734,27 +734,21 @@ class TestTranscriptTranslationGetDispatch(TestVideo): # lint-amnesty, pylint: # Test youtube style en request = Request.blank('/translation/en?videoId=12345') response = self.item.transcript(request=request, dispatch='translation/en') - self.assertEqual(response.status, '307 Temporary Redirect') - self.assertIn( - ('Location', '/static/dummy/static/subs_12345.srt.sjson'), - response.headerlist - ) + assert response.status == '307 Temporary Redirect' + assert ('Location', '/static/dummy/static/subs_12345.srt.sjson') in response.headerlist # Test HTML5 video style self.item.sub = 'OEoXaMPEzfM' request = Request.blank('/translation/en') response = self.item.transcript(request=request, dispatch='translation/en') - self.assertEqual(response.status, '307 Temporary Redirect') - self.assertIn( - ('Location', '/static/dummy/static/subs_OEoXaMPEzfM.srt.sjson'), - response.headerlist - ) + assert response.status == '307 Temporary Redirect' + assert ('Location', '/static/dummy/static/subs_OEoXaMPEzfM.srt.sjson') in response.headerlist # Test different language to ensure we are just ignoring it since we can't # translate with static fallback request = Request.blank('/translation/uk') response = self.item.transcript(request=request, dispatch='translation/uk') - self.assertEqual(response.status, '404 Not Found') + assert response.status == '404 Not Found' @ddt.data( # Test youtube style en @@ -782,12 +776,9 @@ class TestTranscriptTranslationGetDispatch(TestVideo): # lint-amnesty, pylint: attach(self.item, sub) request = Request.blank(url) response = self.item.transcript(request=request, dispatch=dispatch) - self.assertEqual(response.status, status_code) + assert response.status == status_code if sub: - self.assertIn( - ('Location', '/static/dummy/static/subs_{}.srt.sjson'.format(sub)), - response.headerlist - ) + assert ('Location', '/static/dummy/static/subs_{}.srt.sjson'.format(sub)) in response.headerlist @patch('xmodule.video_module.VideoBlock.course_id', return_value='not_a_course_locator') def test_translation_static_non_course(self, __): @@ -800,7 +791,7 @@ class TestTranscriptTranslationGetDispatch(TestVideo): # lint-amnesty, pylint: # When course_id is not mocked out, these values would result in 307, as tested above. request = Request.blank('/translation/en?videoId=12345') response = self.item.transcript(request=request, dispatch='translation/en') - self.assertEqual(response.status, '404 Not Found') + assert response.status == '404 Not Found' def _set_static_asset_path(self): """ Helper method for setting up the static_asset_path information """ @@ -838,10 +829,10 @@ class TestTranscriptTranslationGetDispatch(TestVideo): # lint-amnesty, pylint: } # Assert the actual response - self.assertEqual(response.status_code, 200) - self.assertEqual(response.text, transcript['content']) + assert response.status_code == 200 + assert response.text == transcript['content'] for attribute, value in six.iteritems(expected_headers): - self.assertEqual(response.headers[attribute], value) + assert response.headers[attribute] == value @patch('xmodule.video_module.VideoBlock.translation', Mock(side_effect=NotFoundError)) @patch('xmodule.video_module.VideoBlock.get_static_transcript', Mock(return_value=Response(status=404))) @@ -852,7 +843,7 @@ class TestTranscriptTranslationGetDispatch(TestVideo): # lint-amnesty, pylint: # Make request to XModule transcript handler response = self.item.transcript(request=Request.blank('/translation/en'), dispatch='translation/en') # Assert the actual response - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 class TestStudioTranscriptTranslationGetDispatch(TestVideo): # lint-amnesty, pylint: disable=test-inherits-tests @@ -879,13 +870,13 @@ class TestStudioTranscriptTranslationGetDispatch(TestVideo): # lint-amnesty, py # No language request = Request.blank("") response = self.item_descriptor.studio_transcript(request=request, dispatch="translation") - self.assertEqual(response.status, "400 Bad Request") + assert response.status == '400 Bad Request' # No language_code param in request.GET request = Request.blank("") response = self.item_descriptor.studio_transcript(request=request, dispatch="translation") - self.assertEqual(response.status, "400 Bad Request") - self.assertEqual(response.json["error"], "Language is required.") + assert response.status == '400 Bad Request' + assert response.json['error'] == 'Language is required.' # Correct case: filename = os.path.split(self.srt_file.name)[1] @@ -893,13 +884,10 @@ class TestStudioTranscriptTranslationGetDispatch(TestVideo): # lint-amnesty, py request = Request.blank(u"translation?language_code=uk") response = self.item_descriptor.studio_transcript(request=request, dispatch="translation?language_code=uk") self.srt_file.seek(0) - self.assertEqual(response.body, self.srt_file.read()) - self.assertEqual(response.headers["Content-Type"], "application/x-subrip; charset=utf-8") - self.assertEqual( - response.headers["Content-Disposition"], - u'attachment; filename="uk_{}"'.format(filename) - ) - self.assertEqual(response.headers["Content-Language"], "uk") + assert response.body == self.srt_file.read() + assert response.headers['Content-Type'] == 'application/x-subrip; charset=utf-8' + assert response.headers['Content-Disposition'] == u'attachment; filename="uk_{}"'.format(filename) + assert response.headers['Content-Language'] == 'uk' # Non ascii file name download: self.srt_file.seek(0) @@ -907,10 +895,10 @@ class TestStudioTranscriptTranslationGetDispatch(TestVideo): # lint-amnesty, py request = Request.blank("translation?language_code=zh") response = self.item_descriptor.studio_transcript(request=request, dispatch="translation?language_code=zh") self.srt_file.seek(0) - self.assertEqual(response.body, self.srt_file.read()) - self.assertEqual(response.headers["Content-Type"], "application/x-subrip; charset=utf-8") - self.assertEqual(response.headers["Content-Disposition"], 'attachment; filename="zh_å¡ž.srt"') - self.assertEqual(response.headers["Content-Language"], "zh") + assert response.body == self.srt_file.read() + assert response.headers['Content-Type'] == 'application/x-subrip; charset=utf-8' + assert response.headers['Content-Disposition'] == 'attachment; filename="zh_å¡ž.srt"' + assert response.headers['Content-Language'] == 'zh' @ddt.ddt @@ -959,7 +947,7 @@ class TestStudioTranscriptTranslationPostDispatch(TestVideo): # lint-amnesty, p self.item_descriptor.available_translations = lambda transcripts, verify_assets: ['ur'] request = Request.blank('/translation', POST=post_data) response = self.item_descriptor.studio_transcript(request=request, dispatch='translation') - self.assertEqual(response.json["error"], error_message) + assert response.json['error'] == error_message @ddt.data( { @@ -993,11 +981,11 @@ class TestStudioTranscriptTranslationPostDispatch(TestVideo): # lint-amnesty, p request = Request.blank('/translation', POST=post_data) response = self.item_descriptor.studio_transcript(request=request, dispatch='translation') - self.assertEqual(response.status, '201 Created') + assert response.status == '201 Created' response = json.loads(response.text) - self.assertTrue(response["language_code"], "uk") + assert response['language_code'], 'uk' self.assertDictEqual(self.item_descriptor.transcripts, {}) - self.assertTrue(edxval_api.get_video_transcript_data(video_id=response["edx_video_id"], language_code="uk")) + assert edxval_api.get_video_transcript_data(video_id=response['edx_video_id'], language_code='uk') def test_studio_transcript_post_bad_content(self): """ @@ -1012,11 +1000,8 @@ class TestStudioTranscriptTranslationPostDispatch(TestVideo): # lint-amnesty, p request = Request.blank("/translation", POST=post_data) response = self.item_descriptor.studio_transcript(request=request, dispatch="translation") - self.assertEqual(response.status_code, 400) - self.assertEqual( - response.json["error"], - "There is a problem with this transcript file. Try to upload a different file." - ) + assert response.status_code == 400 + assert response.json['error'] == 'There is a problem with this transcript file. Try to upload a different file.' @ddt.ddt @@ -1048,7 +1033,7 @@ class TestStudioTranscriptTranslationDeleteDispatch(TestVideo): # lint-amnesty, """ request = Request(self.REQUEST_META, body=json.dumps(params).encode('utf-8')) response = self.item_descriptor.studio_transcript(request=request, dispatch='translation') - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_translation_delete_w_edx_video_id(self): """ @@ -1071,15 +1056,15 @@ class TestStudioTranscriptTranslationDeleteDispatch(TestVideo): # lint-amnesty, ) # verify that a video transcript exists for expected data - self.assertTrue(api.get_video_transcript_data(video_id=self.EDX_VIDEO_ID, language_code=self.LANGUAGE_CODE_UK)) + assert api.get_video_transcript_data(video_id=self.EDX_VIDEO_ID, language_code=self.LANGUAGE_CODE_UK) request = Request(self.REQUEST_META, body=request_body.encode('utf-8')) self.item_descriptor.edx_video_id = self.EDX_VIDEO_ID response = self.item_descriptor.studio_transcript(request=request, dispatch='translation') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # verify that a video transcript dose not exist for expected data - self.assertFalse(api.get_video_transcript_data(video_id=self.EDX_VIDEO_ID, language_code=self.LANGUAGE_CODE_UK)) + assert not api.get_video_transcript_data(video_id=self.EDX_VIDEO_ID, language_code=self.LANGUAGE_CODE_UK) def test_translation_delete_wo_edx_video_id(self): """ @@ -1091,19 +1076,19 @@ class TestStudioTranscriptTranslationDeleteDispatch(TestVideo): # lint-amnesty, # upload and verify that srt file exists in assets _upload_file(self.SRT_FILE, self.item_descriptor.location, srt_file_name_uk) - self.assertTrue(_check_asset(self.item_descriptor.location, srt_file_name_uk)) + assert _check_asset(self.item_descriptor.location, srt_file_name_uk) # verify transcripts field - self.assertNotEqual(self.item_descriptor.transcripts, {}) - self.assertTrue(self.LANGUAGE_CODE_UK in self.item_descriptor.transcripts) # lint-amnesty, pylint: disable=wrong-assert-type + assert self.item_descriptor.transcripts != {} + assert self.LANGUAGE_CODE_UK in self.item_descriptor.transcripts # make request and verify response response = self.item_descriptor.studio_transcript(request=request, dispatch='translation') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # verify that srt file is deleted - self.assertEqual(self.item_descriptor.transcripts, {}) - self.assertFalse(_check_asset(self.item_descriptor.location, srt_file_name_uk)) + assert self.item_descriptor.transcripts == {} + assert not _check_asset(self.item_descriptor.location, srt_file_name_uk) def test_translation_delete_w_english_lang(self): """ @@ -1116,15 +1101,15 @@ class TestStudioTranscriptTranslationDeleteDispatch(TestVideo): # lint-amnesty, # upload and verify that srt file exists in assets _upload_file(self.SRT_FILE, self.item_descriptor.location, srt_file_name_en) - self.assertTrue(_check_asset(self.item_descriptor.location, srt_file_name_en)) + assert _check_asset(self.item_descriptor.location, srt_file_name_en) # make request and verify response response = self.item_descriptor.studio_transcript(request=request, dispatch='translation') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # verify that srt file is deleted - self.assertTrue(self.LANGUAGE_CODE_EN not in self.item_descriptor.transcripts) # lint-amnesty, pylint: disable=wrong-assert-type - self.assertFalse(_check_asset(self.item_descriptor.location, srt_file_name_en)) + assert self.LANGUAGE_CODE_EN not in self.item_descriptor.transcripts + assert not _check_asset(self.item_descriptor.location, srt_file_name_en) def test_translation_delete_w_sub(self): """ @@ -1135,19 +1120,21 @@ class TestStudioTranscriptTranslationDeleteDispatch(TestVideo): # lint-amnesty, request = Request(self.REQUEST_META, body=request_body.encode('utf-8')) # sub should not be empy - self.assertFalse(self.item_descriptor.sub == u'') # lint-amnesty, pylint: disable=wrong-assert-type + assert not self.item_descriptor.sub == u'' + # lint-amnesty, pylint: disable=wrong-assert-type # upload and verify that srt file exists in assets _upload_file(self.SRT_FILE, self.item_descriptor.location, sub_file_name) - self.assertTrue(_check_asset(self.item_descriptor.location, sub_file_name)) + assert _check_asset(self.item_descriptor.location, sub_file_name) # make request and verify response response = self.item_descriptor.studio_transcript(request=request, dispatch='translation') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # verify that sub is empty and transcript is deleted also - self.assertTrue(self.item_descriptor.sub == u'') # lint-amnesty, pylint: disable=wrong-assert-type - self.assertFalse(_check_asset(self.item_descriptor.location, sub_file_name)) + assert self.item_descriptor.sub == u'' + # lint-amnesty, pylint: disable=wrong-assert-type + assert not _check_asset(self.item_descriptor.location, sub_file_name) class TestGetTranscript(TestVideo): # lint-amnesty, pylint: disable=test-inherits-tests @@ -1213,9 +1200,9 @@ class TestGetTranscript(TestVideo): # lint-amnesty, pylint: disable=test-inheri """) - self.assertEqual(text, expected_text) - self.assertEqual(filename[:-4], 'en_' + self.item.sub) - self.assertEqual(mime_type, 'application/x-subrip; charset=utf-8') + assert text == expected_text + assert filename[:(- 4)] == ('en_' + self.item.sub) + assert mime_type == 'application/x-subrip; charset=utf-8' def test_good_txt_transcript(self): good_sjson = _create_file(content=textwrap.dedent("""\ @@ -1242,21 +1229,21 @@ class TestGetTranscript(TestVideo): # lint-amnesty, pylint: disable=test-inheri Hi, welcome to Edx. Let's start with what is on your screen right now.""") - self.assertEqual(text, expected_text) - self.assertEqual(filename, 'en_' + self.item.sub + '.txt') - self.assertEqual(mime_type, 'text/plain; charset=utf-8') + assert text == expected_text + assert filename == (('en_' + self.item.sub) + '.txt') + assert mime_type == 'text/plain; charset=utf-8' def test_en_with_empty_sub(self): self.item.sub = "" self.item.transcripts = None # no self.sub, self.youttube_1_0 exist, but no file in assets - with self.assertRaises(NotFoundError): + with pytest.raises(NotFoundError): get_transcript(self.item) # no self.sub and no self.youtube_1_0, no non-en transcritps self.item.youtube_id_1_0 = None - with self.assertRaises(NotFoundError): + with pytest.raises(NotFoundError): get_transcript(self.item) # no self.sub but youtube_1_0 exists with file in assets @@ -1291,9 +1278,9 @@ class TestGetTranscript(TestVideo): # lint-amnesty, pylint: disable=test-inheri """) - self.assertEqual(text, expected_text) - self.assertEqual(filename, 'en_' + self.item.youtube_id_1_0 + '.srt') - self.assertEqual(mime_type, 'application/x-subrip; charset=utf-8') + assert text == expected_text + assert filename == (('en_' + self.item.youtube_id_1_0) + '.srt') + assert mime_type == 'application/x-subrip; charset=utf-8' def test_non_en_with_non_ascii_filename(self): self.item.transcript_language = 'zh' @@ -1307,9 +1294,9 @@ class TestGetTranscript(TestVideo): # lint-amnesty, pylint: disable=test-inheri 00:00:00,12 --> 00:00:00,100 Привіт, edX вітає ваÑ. """) - self.assertEqual(text, expected_text) - self.assertEqual(filename, u"zh_å¡ž.srt") - self.assertEqual(mime_type, 'application/x-subrip; charset=utf-8') + assert text == expected_text + assert filename == u'zh_å¡ž.srt' + assert mime_type == 'application/x-subrip; charset=utf-8' def test_value_error(self): good_sjson = _create_file(content='bad content') @@ -1318,7 +1305,7 @@ class TestGetTranscript(TestVideo): # lint-amnesty, pylint: disable=test-inheri self.item.sub = _get_subs_id(good_sjson.name) transcripts = self.item.get_transcripts_info() # lint-amnesty, pylint: disable=unused-variable - with self.assertRaises(ValueError): + with pytest.raises(ValueError): get_transcript(self.item) def test_key_error(self): @@ -1339,5 +1326,5 @@ class TestGetTranscript(TestVideo): # lint-amnesty, pylint: disable=test-inheri self.item.sub = _get_subs_id(good_sjson.name) transcripts = self.item.get_transcripts_info() # lint-amnesty, pylint: disable=unused-variable - with self.assertRaises(KeyError): + with pytest.raises(KeyError): get_transcript(self.item) diff --git a/lms/djangoapps/courseware/tests/test_video_mongo.py b/lms/djangoapps/courseware/tests/test_video_mongo.py index 79d3032c473c8a95eea1d3f89d05ef079d47740a..7297cc945b31bdabb052beda89d0f1f97921627d 100644 --- a/lms/djangoapps/courseware/tests/test_video_mongo.py +++ b/lms/djangoapps/courseware/tests/test_video_mongo.py @@ -10,7 +10,7 @@ import shutil from collections import OrderedDict from tempfile import mkdtemp from uuid import uuid4 - +import pytest import ddt import six from django.conf import settings @@ -133,12 +133,9 @@ class TestVideoYouTube(TestVideo): # lint-amnesty, pylint: disable=missing-clas 'poster': 'null', } - self.assertEqual( - get_context_dict_from_string(context), - get_context_dict_from_string( - self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) - ) - ) + assert get_context_dict_from_string(context) ==\ + get_context_dict_from_string(self.item_descriptor.xmodule_runtime.render_template('video.html', + expected_context)) class TestVideoNonYouTube(TestVideo): # pylint: disable=test-inherits-tests @@ -220,12 +217,9 @@ class TestVideoNonYouTube(TestVideo): # pylint: disable=test-inherits-tests expected_result = get_context_dict_from_string( self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) ) - self.assertEqual( - get_context_dict_from_string(context), - expected_result - ) - self.assertEqual(expected_result['download_video_link'], 'example.mp4') - self.assertEqual(expected_result['display_name'], 'A Name') + assert get_context_dict_from_string(context) == expected_result + assert expected_result['download_video_link'] == 'example.mp4' + assert expected_result['display_name'] == 'A Name' @ddt.ddt @@ -392,12 +386,9 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): 'metadata': json.dumps(metadata) }) - self.assertEqual( - get_context_dict_from_string(context), - get_context_dict_from_string( - self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) - ) - ) + assert get_context_dict_from_string(context) ==\ + get_context_dict_from_string(self.item_descriptor.xmodule_runtime.render_template('video.html', + expected_context)) def test_get_html_source(self): # lint-amnesty, pylint: disable=invalid-name, redefined-outer-name @@ -503,12 +494,9 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): 'metadata': json.dumps(expected_context['metadata']) }) - self.assertEqual( - get_context_dict_from_string(context), - get_context_dict_from_string( - self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) - ) - ) + assert get_context_dict_from_string(context) ==\ + get_context_dict_from_string(self.item_descriptor.xmodule_runtime.render_template('video.html', + expected_context)) def test_get_html_with_non_existent_edx_video_id(self): """ @@ -550,7 +538,7 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): # Referencing a non-existent VAL ID in courseware won't cause an error -- # it'll just fall back to the values in the VideoBlock. - self.assertIn("example.mp4", self.item_descriptor.render(STUDENT_VIEW).content) + assert 'example.mp4' in self.item_descriptor.render(STUDENT_VIEW).content def test_get_html_with_mocked_edx_video_id(self): # lint-amnesty, pylint: disable=invalid-name, redefined-outer-name @@ -646,12 +634,9 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): 'metadata': json.dumps(expected_context['metadata']) }) - self.assertEqual( - get_context_dict_from_string(context), - get_context_dict_from_string( - self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) - ) - ) + assert get_context_dict_from_string(context) ==\ + get_context_dict_from_string(self.item_descriptor.xmodule_runtime.render_template('video.html', + expected_context)) def test_get_html_with_existing_edx_video_id(self): """ @@ -677,12 +662,9 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): # context returned by get_html when provided with above data # expected_context, a dict to assert with context context, expected_context = self.helper_get_html_with_edx_video_id(data) - self.assertEqual( - get_context_dict_from_string(context), - get_context_dict_from_string( - self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) - ) - ) + assert get_context_dict_from_string(context) ==\ + get_context_dict_from_string(self.item_descriptor.xmodule_runtime.render_template('video.html', + expected_context)) def test_get_html_with_existing_unstripped_edx_video_id(self): """ @@ -711,12 +693,9 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): # expected_context, a dict to assert with context context, expected_context = self.helper_get_html_with_edx_video_id(data) - self.assertEqual( - get_context_dict_from_string(context), - get_context_dict_from_string( - self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) - ) - ) + assert get_context_dict_from_string(context) ==\ + get_context_dict_from_string(self.item_descriptor.xmodule_runtime.render_template('video.html', + expected_context)) def encode_and_create_video(self, edx_video_id): """ @@ -742,7 +721,7 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): encoded_videos=encoded_videos, ) ) - self.assertEqual(result, edx_video_id) + assert result == edx_video_id return encoded_videos def helper_get_html_with_edx_video_id(self, data): @@ -923,12 +902,9 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): 'metadata': json.dumps(expected_context['metadata']) }) - self.assertEqual( - get_context_dict_from_string(context), - get_context_dict_from_string( - self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) - ) - ) + assert get_context_dict_from_string(context) ==\ + get_context_dict_from_string(self.item_descriptor.xmodule_runtime.render_template('video.html', + expected_context)) # pylint: disable=invalid-name def test_get_html_cdn_source_external_video(self): @@ -1028,12 +1004,9 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): 'metadata': json.dumps(expected_context['metadata']) }) - self.assertEqual( - get_context_dict_from_string(context), - get_context_dict_from_string( - self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) - ) - ) + assert get_context_dict_from_string(context) ==\ + get_context_dict_from_string(self.item_descriptor.xmodule_runtime.render_template('video.html', + expected_context)) @ddt.data( (True, ['youtube', 'desktop_webm', 'desktop_mp4', 'hls']), @@ -1082,12 +1055,10 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): self.initialize_block(data=video_xml) context = self.item_descriptor.render(STUDENT_VIEW).content - self.assertIn("'download_video_link': 'https://mp4.com/dm.mp4'", context) - self.assertIn('"streams": "1.00:https://yt.com/?v=v0TFmdO4ZP0"', context) - self.assertEqual( - sorted(["https://webm.com/dw.webm", "https://mp4.com/dm.mp4", "https://hls.com/hls.m3u8"]), - sorted(get_context_dict_from_string(context)['metadata']['sources']) - ) + assert "'download_video_link': 'https://mp4.com/dm.mp4'" in context + assert '"streams": "1.00:https://yt.com/?v=v0TFmdO4ZP0"' in context + assert sorted(['https://webm.com/dw.webm', 'https://mp4.com/dm.mp4', 'https://hls.com/hls.m3u8']) ==\ + sorted(get_context_dict_from_string(context)['metadata']['sources']) def test_get_html_hls_no_video_id(self): """ @@ -1101,7 +1072,7 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): self.initialize_block(data=video_xml) context = self.item_descriptor.render(STUDENT_VIEW).content - self.assertIn("'download_video_link': None", context) + assert "'download_video_link': None" in context def test_html_student_public_view(self): """ @@ -1115,9 +1086,9 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): self.initialize_block(data=video_xml) context = self.item_descriptor.render(STUDENT_VIEW).content - self.assertIn('"saveStateEnabled": true', context) + assert '"saveStateEnabled": true' in context context = self.item_descriptor.render(PUBLIC_VIEW).content - self.assertIn('"saveStateEnabled": false', context) + assert '"saveStateEnabled": false' in context @patch('xmodule.video_module.video_module.edxval_api.get_course_video_image_url') def test_poster_image(self, get_course_video_image_url): @@ -1130,7 +1101,7 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): self.initialize_block(data=video_xml) context = self.item_descriptor.render(STUDENT_VIEW).content - self.assertIn('"poster": "/media/video-images/poster.png"', context) + assert '"poster": "/media/video-images/poster.png"' in context @patch('xmodule.video_module.video_module.edxval_api.get_course_video_image_url') def test_poster_image_without_edx_video_id(self, get_course_video_image_url): @@ -1143,7 +1114,7 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): self.initialize_block(data=video_xml) context = self.item_descriptor.render(STUDENT_VIEW).content - self.assertIn("\'poster\': \'null\'", context) + assert "'poster': 'null'" in context @patch('xmodule.video_module.video_module.HLSPlaybackEnabledFlag.feature_enabled', Mock(return_value=False)) def test_hls_primary_playback_on_toggling_hls_feature(self): @@ -1153,7 +1124,7 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): video_xml = '<video display_name="Video" download_video="true" edx_video_id="12345-67890">[]</video>' self.initialize_block(data=video_xml) context = self.item_descriptor.render(STUDENT_VIEW).content - self.assertIn('"prioritizeHls": false', context) + assert '"prioritizeHls": false' in context @ddt.data( { @@ -1208,7 +1179,7 @@ class TestGetHtmlMethod(BaseTestVideoXBlock): with override_flag(DEPRECATE_YOUTUBE_FLAG.name, active=data['waffle_enabled']): self.initialize_block(data=video_xml, metadata=metadata) context = self.item_descriptor.render(STUDENT_VIEW).content - self.assertIn(u'"prioritizeHls": {}'.format(data['result']), context) + assert u'"prioritizeHls": {}'.format(data['result']) in context @ddt.ddt @@ -1272,7 +1243,7 @@ class TestVideoBlockInitialization(BaseTestVideoXBlock): data='<video display_name="Video" download_video="true" edx_video_id="12345-67890">[]</video>' ) context = self.item_descriptor.get_context() - self.assertEqual(context['transcripts_basic_tab_metadata']['video_url']['value'], video_url) + assert context['transcripts_basic_tab_metadata']['video_url']['value'] == video_url @ddt.data( ( @@ -1310,7 +1281,7 @@ class TestVideoBlockInitialization(BaseTestVideoXBlock): data='<video display_name="Video" youtube_id_1_0="" download_video="true" edx_video_id="12345-67890">[]</video>' ) context = self.item_descriptor.get_context() - self.assertEqual(context['transcripts_basic_tab_metadata']['video_url']['value'], video_url) + assert context['transcripts_basic_tab_metadata']['video_url']['value'] == video_url @ddt.ddt @@ -1348,12 +1319,12 @@ class TestEditorSavedMethod(BaseTestVideoXBlock): save_to_store(myfile.read(), self.file_name, 'text/sjson', item.location) item.sub = "3_yD_cEKoCk" # subs_video.srt.sjson does not exist before calling editor_saved function - with self.assertRaises(NotFoundError): + with pytest.raises(NotFoundError): Transcript.get_asset(item.location, 'subs_video.srt.sjson') old_metadata = own_metadata(item) # calling editor_saved will generate new file subs_video.srt.sjson for html5_sources item.editor_saved(self.user, old_metadata, None) - self.assertIsInstance(Transcript.get_asset(item.location, 'subs_3_yD_cEKoCk.srt.sjson'), StaticContent) + assert isinstance(Transcript.get_asset(item.location, 'subs_3_yD_cEKoCk.srt.sjson'), StaticContent) @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_editor_saved_when_youtube_and_html5_subs_exist(self, default_store): @@ -1369,12 +1340,12 @@ class TestEditorSavedMethod(BaseTestVideoXBlock): save_to_store(myfile.read(), 'subs_video.srt.sjson', 'text/sjson', item.location) item.sub = "3_yD_cEKoCk" # subs_3_yD_cEKoCk.srt.sjson and subs_video.srt.sjson already exist - self.assertIsInstance(Transcript.get_asset(item.location, self.file_name), StaticContent) - self.assertIsInstance(Transcript.get_asset(item.location, 'subs_video.srt.sjson'), StaticContent) + assert isinstance(Transcript.get_asset(item.location, self.file_name), StaticContent) + assert isinstance(Transcript.get_asset(item.location, 'subs_video.srt.sjson'), StaticContent) old_metadata = own_metadata(item) with patch('xmodule.video_module.video_module.manage_video_subtitles_save') as manage_video_subtitles_save: item.editor_saved(self.user, old_metadata, None) - self.assertFalse(manage_video_subtitles_save.called) + assert not manage_video_subtitles_save.called @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_editor_saved_with_unstripped_video_id(self, default_store): @@ -1389,13 +1360,13 @@ class TestEditorSavedMethod(BaseTestVideoXBlock): }) self.initialize_block(metadata=self.metadata) item = self.store.get_item(self.item_descriptor.location) - self.assertEqual(item.edx_video_id, unstripped_video_id) + assert item.edx_video_id == unstripped_video_id # Now, modifying and saving the video module should strip the video id. old_metadata = own_metadata(item) item.display_name = u'New display name' item.editor_saved(self.user, old_metadata, None) - self.assertEqual(item.edx_video_id, stripped_video_id) + assert item.edx_video_id == stripped_video_id @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) @patch('xmodule.video_module.video_module.edxval_api.get_url_for_profile', Mock(return_value='test_yt_id')) @@ -1407,13 +1378,13 @@ class TestEditorSavedMethod(BaseTestVideoXBlock): self.MODULESTORE = MODULESTORES[default_store] self.initialize_block(metadata=self.metadata) item = self.store.get_item(self.item_descriptor.location) - self.assertEqual(item.youtube_id_1_0, '3_yD_cEKoCk') + assert item.youtube_id_1_0 == '3_yD_cEKoCk' # Now, modify `edx_video_id` and save should override `youtube_id_1_0`. old_metadata = own_metadata(item) item.edx_video_id = six.text_type(uuid4()) item.editor_saved(self.user, old_metadata, None) - self.assertEqual(item.youtube_id_1_0, 'test_yt_id') + assert item.youtube_id_1_0 == 'test_yt_id' @ddt.ddt @@ -1657,10 +1628,8 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): self.assertListEqual(rendered_context['tabs'], correct_tabs) # Assert that the Video ID field is present in basic tab metadata context. - self.assertEqual( - rendered_context['transcripts_basic_tab_metadata']['edx_video_id'], - self.descriptor.editable_metadata_fields['edx_video_id'] - ) + assert rendered_context['transcripts_basic_tab_metadata']['edx_video_id'] ==\ + self.descriptor.editable_metadata_fields['edx_video_id'] def test_export_val_data_with_internal(self): """ @@ -1718,13 +1687,13 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): self.assertXmlEqual(expected, actual) # Verify transcript file is created. - self.assertEqual([transcript_file_name], self.file_system.listdir(EXPORT_IMPORT_STATIC_DIR)) + assert [transcript_file_name] == self.file_system.listdir(EXPORT_IMPORT_STATIC_DIR) # Also verify the content of created transcript file. expected_transcript_content = File(io.open(expected_transcript_path)).read() transcript = get_video_transcript_data(video_id=self.descriptor.edx_video_id, language_code=language_code) - self.assertEqual(transcript['content'].decode('utf-8'), expected_transcript_content) + assert transcript['content'].decode('utf-8') == expected_transcript_content @ddt.data( (['en', 'da'], 'test_sub', ''), @@ -1765,7 +1734,7 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): video_xml = self.descriptor.definition_to_xml(resource_fs=self.file_system) # Assert `sub` and `transcripts` attribute in the xml - self.assertEqual(video_xml.get('sub'), expected_sub) + assert video_xml.get('sub') == expected_sub expected_transcripts = { language: "{edx_video_id}-{language}.srt".format( @@ -1785,7 +1754,7 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): expected_transcript_content = File(io.open(expected_transcript_path)).read() transcript = get_video_transcript_data(video_id=self.descriptor.edx_video_id, language_code=language) - self.assertEqual(transcript['content'].decode('utf-8'), expected_transcript_content) + assert transcript['content'].decode('utf-8') == expected_transcript_content def test_export_val_data_not_found(self): """ @@ -1874,16 +1843,16 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): id_generator.target_course_id = "test_course_id" video = self.descriptor.from_xml(xml_data, module_system, id_generator) - self.assertEqual(video.edx_video_id, 'test_edx_video_id') + assert video.edx_video_id == 'test_edx_video_id' video_data = get_video_info(video.edx_video_id) - self.assertEqual(video_data['client_video_id'], 'test_client_video_id') - self.assertEqual(video_data['duration'], 111.0) - self.assertEqual(video_data['status'], 'imported') - self.assertEqual(video_data['courses'], [{id_generator.target_course_id: None}]) - self.assertEqual(video_data['encoded_videos'][0]['profile'], 'mobile') - self.assertEqual(video_data['encoded_videos'][0]['url'], 'http://example.com/video') - self.assertEqual(video_data['encoded_videos'][0]['file_size'], 222) - self.assertEqual(video_data['encoded_videos'][0]['bitrate'], 333) + assert video_data['client_video_id'] == 'test_client_video_id' + assert video_data['duration'] == 111.0 + assert video_data['status'] == 'imported' + assert video_data['courses'] == [{id_generator.target_course_id: None}] + assert video_data['encoded_videos'][0]['profile'] == 'mobile' + assert video_data['encoded_videos'][0]['url'] == 'http://example.com/video' + assert video_data['encoded_videos'][0]['file_size'] == 222 + assert video_data['encoded_videos'][0]['bitrate'] == 333 # Verify that VAL transcript is imported. self.assertDictContainsSubset( @@ -1922,17 +1891,17 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): id_generator = Mock() # Verify edx_video_id is empty before. - self.assertEqual(self.descriptor.edx_video_id, u'') + assert self.descriptor.edx_video_id == u'' video = self.descriptor.from_xml(xml_data, module_system, id_generator) # Verify edx_video_id is populated after the import. - self.assertNotEqual(video.edx_video_id, u'') + assert video.edx_video_id != u'' video_data = get_video_info(video.edx_video_id) - self.assertEqual(video_data['client_video_id'], 'External Video') - self.assertEqual(video_data['duration'], 0.0) - self.assertEqual(video_data['status'], 'external') + assert video_data['client_video_id'] == 'External Video' + assert video_data['duration'] == 0.0 + assert video_data['status'] == 'external' def test_import_val_transcript(self): """ @@ -1969,15 +1938,15 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): ) # Verify edx_video_id is empty before. - self.assertEqual(self.descriptor.edx_video_id, u'') + assert self.descriptor.edx_video_id == u'' video = self.descriptor.from_xml(xml_data, module_system, id_generator) # Verify edx_video_id is populated after the import. - self.assertNotEqual(video.edx_video_id, u'') + assert video.edx_video_id != u'' video_data = get_video_info(video.edx_video_id) - self.assertEqual(video_data['status'], 'external') + assert video_data['status'] == 'external' # Verify that VAL transcript is imported. self.assertDictContainsSubset( @@ -2110,15 +2079,15 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): xml_data += '</video_asset></video>' # Verify edx_video_id is empty before import. - self.assertEqual(self.descriptor.edx_video_id, u'') + assert self.descriptor.edx_video_id == u'' video = self.descriptor.from_xml(xml_data, module_system, id_generator) # Verify edx_video_id is not empty after import. - self.assertNotEqual(video.edx_video_id, u'') + assert video.edx_video_id != u'' video_data = get_video_info(video.edx_video_id) - self.assertEqual(video_data['status'], 'external') + assert video_data['status'] == 'external' # Verify that correct transcripts are imported. self.assertDictContainsSubset( @@ -2138,9 +2107,9 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): </video_asset> </video> """ - with self.assertRaises(ValCannotCreateError): + with pytest.raises(ValCannotCreateError): VideoBlock.from_xml(xml_data, module_system, id_generator=Mock()) - with self.assertRaises(ValVideoNotFoundError): + with pytest.raises(ValVideoNotFoundError): get_video_info("test_edx_video_id") @@ -2170,12 +2139,12 @@ class TestVideoWithBumper(TestVideo): # pylint: disable=test-inherits-tests "transcripts": {}, } with override_settings(FEATURES=self.FEATURES): - self.assertTrue(bumper_utils.is_bumper_enabled(self.item_descriptor)) + assert bumper_utils.is_bumper_enabled(self.item_descriptor) self.FEATURES.update({"ENABLE_VIDEO_BUMPER": False}) with override_settings(FEATURES=self.FEATURES): - self.assertFalse(bumper_utils.is_bumper_enabled(self.item_descriptor)) + assert not bumper_utils.is_bumper_enabled(self.item_descriptor) @patch('xmodule.video_module.bumper_utils.is_bumper_enabled') @patch('xmodule.video_module.bumper_utils.get_bumper_settings') @@ -2269,9 +2238,7 @@ class TestVideoWithBumper(TestVideo): # pylint: disable=test-inherits-tests } expected_content = self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) - self.assertEqual( - get_context_dict_from_string(content), get_context_dict_from_string(expected_content) - ) + assert get_context_dict_from_string(content) == get_context_dict_from_string(expected_content) @ddt.ddt @@ -2364,7 +2331,7 @@ class TestAutoAdvanceVideo(TestVideo): # lint-amnesty, pylint: disable=test-inh with override_settings(FEATURES=self.FEATURES): expected_content = self.item_descriptor.xmodule_runtime.render_template('video.html', expected_context) - self.assertEqual(get_context_dict_from_string(content), get_context_dict_from_string(expected_content)) + assert get_context_dict_from_string(content) == get_context_dict_from_string(expected_content) def change_course_setting_autoadvance(self, new_value): """ diff --git a/lms/djangoapps/courseware/tests/test_video_xml.py b/lms/djangoapps/courseware/tests/test_video_xml.py index d887f72d15ee88388478f019a4754c438b2440b7..6b5a471980225c82b101566f168c27e27b96c6ff 100644 --- a/lms/djangoapps/courseware/tests/test_video_xml.py +++ b/lms/djangoapps/courseware/tests/test_video_xml.py @@ -45,10 +45,7 @@ class VideoBlockLogicTest(TestCase): """Test parsing old-style Youtube ID strings into a dict.""" youtube_str = '0.75:jNCf2gIqpeE,1.00:ZwkTiUPN0mg,1.25:rsq9auxASqI,1.50:kMyNdzVHHgg' output = VideoBlock._parse_youtube(youtube_str) - self.assertEqual(output, {'0.75': 'jNCf2gIqpeE', - '1.00': 'ZwkTiUPN0mg', - '1.25': 'rsq9auxASqI', - '1.50': 'kMyNdzVHHgg'}) + assert output == {'0.75': 'jNCf2gIqpeE', '1.00': 'ZwkTiUPN0mg', '1.25': 'rsq9auxASqI', '1.50': 'kMyNdzVHHgg'} def test_parse_youtube_one_video(self): """ @@ -57,10 +54,7 @@ class VideoBlockLogicTest(TestCase): """ youtube_str = '0.75:jNCf2gIqpeE' output = VideoBlock._parse_youtube(youtube_str) - self.assertEqual(output, {'0.75': 'jNCf2gIqpeE', - '1.00': '', - '1.25': '', - '1.50': ''}) + assert output == {'0.75': 'jNCf2gIqpeE', '1.00': '', '1.25': '', '1.50': ''} def test_parse_youtube_key_format(self): """ @@ -68,18 +62,11 @@ class VideoBlockLogicTest(TestCase): """ youtube_str = '1.00:p2Q6BrNhdh8' youtube_str_hack = '1.0:p2Q6BrNhdh8' - self.assertEqual( - VideoBlock._parse_youtube(youtube_str), - VideoBlock._parse_youtube(youtube_str_hack) - ) + assert VideoBlock._parse_youtube(youtube_str) == VideoBlock._parse_youtube(youtube_str_hack) def test_parse_youtube_empty(self): """ Some courses have empty youtube attributes, so we should handle that well. """ - self.assertEqual(VideoBlock._parse_youtube(''), - {'0.75': '', - '1.00': '', - '1.25': '', - '1.50': ''}) + assert VideoBlock._parse_youtube('') == {'0.75': '', '1.00': '', '1.25': '', '1.50': ''} diff --git a/lms/djangoapps/courseware/tests/test_view_authentication.py b/lms/djangoapps/courseware/tests/test_view_authentication.py index baedf5d4208ad6f7c92b3f186cb9a934ad3fc9e9..bc6b8f303c7eda4b86ac8e2d540bd8126f06e319 100644 --- a/lms/djangoapps/courseware/tests/test_view_authentication.py +++ b/lms/djangoapps/courseware/tests/test_view_authentication.py @@ -321,8 +321,8 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro self.course = self.update_course(self.course, self.user.id) self.test_course = self.update_course(self.test_course, self.user.id) - self.assertFalse(self.course.has_started()) - self.assertFalse(self.test_course.has_started()) + assert not self.course.has_started() + assert not self.test_course.has_started() # First, try with an enrolled student self.login(self.enrolled_user) @@ -400,18 +400,18 @@ class TestViewAuth(EnterpriseTestConsentRequired, ModuleStoreTestCase, LoginEnro # First, try with an enrolled student self.login(self.unenrolled_user) - self.assertFalse(self.enroll(self.course)) - self.assertTrue(self.enroll(self.test_course)) + assert not self.enroll(self.course) + assert self.enroll(self.test_course) # Then, try as an instructor self.logout() self.login(self.instructor_user) - self.assertTrue(self.enroll(self.course)) + assert self.enroll(self.course) # Then, try as global staff self.logout() self.login(self.global_staff_user) - self.assertTrue(self.enroll(self.course)) + assert self.enroll(self.course) class TestBetatesterAccess(ModuleStoreTestCase, CourseAccessTestMixin): @@ -436,7 +436,7 @@ class TestBetatesterAccess(ModuleStoreTestCase, CourseAccessTestMixin): """ Check that beta-test access works for courses. """ - self.assertFalse(self.course.has_started()) # lint-amnesty, pylint: disable=no-member + assert not self.course.has_started() # lint-amnesty, pylint: disable=no-member self.assertCannotAccessCourse(self.normal_student, 'load', self.course) self.assertCanAccessCourse(self.beta_tester, 'load', self.course) @@ -446,7 +446,7 @@ class TestBetatesterAccess(ModuleStoreTestCase, CourseAccessTestMixin): Check that beta-test access works for content. """ # student user shouldn't see it - self.assertFalse(has_access(self.normal_student, 'load', self.content, self.course.id)) # lint-amnesty, pylint: disable=no-member + assert not has_access(self.normal_student, 'load', self.content, self.course.id) # lint-amnesty, pylint: disable=no-member, line-too-long # now the student should see it - self.assertTrue(has_access(self.beta_tester, 'load', self.content, self.course.id)) # lint-amnesty, pylint: disable=no-member + assert has_access(self.beta_tester, 'load', self.content, self.course.id) # lint-amnesty, pylint: disable=no-member, line-too-long diff --git a/lms/djangoapps/courseware/tests/test_views.py b/lms/djangoapps/courseware/tests/test_views.py index b3d1196bb5a9eaefbacc81fd9d5f35012540dcae..6cfe09c645c08d63c7836f351019ba683adf3293 100644 --- a/lms/djangoapps/courseware/tests/test_views.py +++ b/lms/djangoapps/courseware/tests/test_views.py @@ -132,7 +132,7 @@ class TestJumpTo(ModuleStoreTestCase): # can't use the reverse calls from the CMS jumpto_url = '{0}/{1}/jump_to/{2}'.format('/courses', six.text_type(self.course_key), six.text_type(location)) response = self.client.get(jumpto_url) - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 def test_jumpto_from_section(self): course = CourseFactory.create() @@ -223,7 +223,7 @@ class TestJumpTo(ModuleStoreTestCase): six.text_type(self.course_key), six.text_type(location)) response = self.client.get(jumpto_url) - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 @ddt.data( (False, '1'), @@ -258,7 +258,7 @@ class TestJumpTo(ModuleStoreTestCase): ) expected_url += "?{}".format(urlencode({'activate_block_id': six.text_type(staff_only_vertical.location)})) - self.assertEqual(expected_url, get_redirect_url(course_key, usage_key, request)) + assert expected_url == get_redirect_url(course_key, usage_key, request) @ddt.ddt @@ -301,7 +301,7 @@ class IndexQueryTestCase(ModuleStoreTestCase): } ) response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 class BaseViewsTestCase(ModuleStoreTestCase): # lint-amnesty, pylint: disable=missing-class-docstring @@ -361,7 +361,7 @@ class BaseViewsTestCase(ModuleStoreTestCase): # lint-amnesty, pylint: disable=m self.org = u"ꜱᴛᴀʀᴋ ɪɴᴅᴜꜱᴛʀɪᴇꜱ" self.org_html = "<p>'+Stark/Industries+'</p>" - self.assertTrue(self.client.login(username=self.user.username, password=TEST_PASSWORD)) + assert self.client.login(username=self.user.username, password=TEST_PASSWORD) # refresh the course from the modulestore so that it has children self.course = modulestore().get_course(self.course.id) @@ -371,7 +371,7 @@ class BaseViewsTestCase(ModuleStoreTestCase): # lint-amnesty, pylint: disable=m Create global staff user and log them in """ self.global_staff = GlobalStaffFactory.create() # pylint: disable=attribute-defined-outside-init - self.assertTrue(self.client.login(username=self.global_staff.username, password=TEST_PASSWORD)) + assert self.client.login(username=self.global_staff.username, password=TEST_PASSWORD) @ddt.ddt @@ -392,7 +392,7 @@ class ViewsTestCase(BaseViewsTestCase): # re-access to the main course page redirects to last accessed view. url = reverse('courseware', kwargs={'course_id': six.text_type(self.course_key)}) response = self.client.get(url) - self.assertEqual(response.status_code, 302) + assert response.status_code == 302 response = self.client.get(response.url) self.assertNotContains(response, self.problem.location) self.assertContains(response, self.problem2.location) @@ -429,7 +429,7 @@ class ViewsTestCase(BaseViewsTestCase): } ) response = self.client.get(url) - self.assertEqual(response.status_code, expected_response_code) + assert response.status_code == expected_response_code return response def test_index_no_visible_section_in_chapter(self): @@ -448,7 +448,7 @@ class ViewsTestCase(BaseViewsTestCase): 'chapter': six.text_type(self.chapter.location.block_id)}, ) response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertNotContains(response, 'Problem 1') self.assertNotContains(response, 'Problem 2') @@ -483,11 +483,11 @@ class ViewsTestCase(BaseViewsTestCase): self._create_global_staff_user() courseware_url, enroll_url = self._create_url_for_enroll_staff() response = self.client.post(enroll_url, data=data, follow=True) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # we were redirected to our current location - self.assertIn(302, response.redirect_chain[0]) - self.assertEqual(len(response.redirect_chain), 1) + assert 302 in response.redirect_chain[0] + assert len(response.redirect_chain) == 1 if enrollment: self.assertRedirects(response, courseware_url) else: @@ -501,7 +501,7 @@ class ViewsTestCase(BaseViewsTestCase): self._create_global_staff_user() __, enroll_url = self._create_url_for_enroll_staff() response = self.client.post(enroll_url, data={'test': "test"}) - self.assertEqual(response.status_code, 302) + assert response.status_code == 302 self.assertRedirects(response, '/courses/{}/about'.format(six.text_type(self.course_key))) def assert_enrollment_link_present(self, is_anonymous): @@ -519,7 +519,7 @@ class ViewsTestCase(BaseViewsTestCase): if is_anonymous: self.client.logout() else: - self.assertTrue(self.client.login(username=self.user.username, password=TEST_PASSWORD)) + assert self.client.login(username=self.user.username, password=TEST_PASSWORD) # Construct the link according the following scenarios and verify its presence in the response: # (1) shopping cart is enabled and the user is not logged in @@ -538,39 +538,27 @@ class ViewsTestCase(BaseViewsTestCase): if not is_anonymous: self.assert_enrollment_link_present(is_anonymous=is_anonymous) else: - self.assertEqual(EcommerceService().is_enabled(AnonymousUser()), False) + assert EcommerceService().is_enabled(AnonymousUser()) is False def test_user_groups(self): # deprecated function mock_user = MagicMock() type(mock_user).is_authenticated = PropertyMock(return_value=False) - self.assertEqual(views.user_groups(mock_user), []) + assert views.user_groups(mock_user) == [] def test_get_redirect_url(self): # test the course location - self.assertEqual( - u'/courses/{course_key}/courseware?{activate_block_id}'.format( - course_key=text_type(self.course_key), - activate_block_id=urlencode({'activate_block_id': text_type(self.course.location)}) - ), - get_redirect_url(self.course_key, self.course.location), - ) + assert u'/courses/{course_key}/courseware?{activate_block_id}'.format(course_key=text_type(self.course_key), activate_block_id=urlencode({'activate_block_id': text_type(self.course.location)})) == get_redirect_url(self.course_key, self.course.location) # pylint: disable=line-too-long # test a section location - self.assertEqual( - u'/courses/{course_key}/courseware/Chapter_1/Sequential_1/?{activate_block_id}'.format( - course_key=text_type(self.course_key), - activate_block_id=urlencode({'activate_block_id': text_type(self.section.location)}) - ), - get_redirect_url(self.course_key, self.section.location), - ) + assert u'/courses/{course_key}/courseware/Chapter_1/Sequential_1/?{activate_block_id}'.format(course_key=text_type(self.course_key), activate_block_id=urlencode({'activate_block_id': text_type(self.section.location)})) == get_redirect_url(self.course_key, self.section.location) # pylint: disable=line-too-long def test_invalid_course_id(self): response = self.client.get('/courses/MITx/3.091X/') - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 def test_incomplete_course_id(self): response = self.client.get('/courses/MITx/') - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 def test_index_invalid_position(self): request_url = '/'.join([ @@ -581,9 +569,9 @@ class ViewsTestCase(BaseViewsTestCase): self.section.location.block_id, 'f' ]) - self.assertTrue(self.client.login(username=self.user.username, password=TEST_PASSWORD)) + assert self.client.login(username=self.user.username, password=TEST_PASSWORD) response = self.client.get(request_url) - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 def test_unicode_handling_in_url(self): url_parts = [ @@ -594,19 +582,19 @@ class ViewsTestCase(BaseViewsTestCase): self.section.location.block_id, '1' ] - self.assertTrue(self.client.login(username=self.user.username, password=TEST_PASSWORD)) + assert self.client.login(username=self.user.username, password=TEST_PASSWORD) for idx, val in enumerate(url_parts): url_parts_copy = url_parts[:] url_parts_copy[idx] = val + u'χ' request_url = '/'.join(url_parts_copy) response = self.client.get(request_url) - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 def test_jump_to_invalid(self): # TODO add a test for invalid location # TODO add a test for no data * response = self.client.get(reverse('jump_to', args=['foo/bar/baz', 'baz'])) - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 def verify_end_date(self, course_id, expected_end_text=None): """ @@ -626,7 +614,7 @@ class ViewsTestCase(BaseViewsTestCase): # log into a staff account admin = AdminFactory() - self.assertTrue(self.client.login(username=admin.username, password='test')) + assert self.client.login(username=admin.username, password='test') url = reverse('submission_history', kwargs={ 'course_id': six.text_type(self.course_key), @@ -641,7 +629,7 @@ class ViewsTestCase(BaseViewsTestCase): # log into a staff account admin = AdminFactory() - self.assertTrue(self.client.login(username=admin.username, password='test')) + assert self.client.login(username=admin.username, password='test') # try it with an existing user and a malicious location url = reverse('submission_history', kwargs={ @@ -665,7 +653,7 @@ class ViewsTestCase(BaseViewsTestCase): # log into a staff account admin = AdminFactory.create() - self.assertTrue(self.client.login(username=admin.username, password='test')) + assert self.client.login(username=admin.username, password='test') usage_key = self.course_key.make_usage_key('problem', 'test-history') state_client = DjangoXBlockUserStateClient(admin) @@ -699,12 +687,12 @@ class ViewsTestCase(BaseViewsTestCase): # displayed (but not the order), and also the indexes assigned in the output # #1 - #4 - self.assertIn('#1', response_content) - self.assertIn(json.dumps({'field_a': 'a', 'field_b': 'b'}, sort_keys=True, indent=2), response_content) - self.assertIn("Score: 0.0 / 3.0", response_content) - self.assertIn(json.dumps({'field_a': 'x', 'field_b': 'y'}, sort_keys=True, indent=2), response_content) - self.assertIn("Score: 3.0 / 3.0", response_content) - self.assertIn('#4', response_content) + assert '#1' in response_content + assert json.dumps({'field_a': 'a', 'field_b': 'b'}, sort_keys=True, indent=2) in response_content + assert 'Score: 0.0 / 3.0' in response_content + assert json.dumps({'field_a': 'x', 'field_b': 'y'}, sort_keys=True, indent=2) in response_content + assert 'Score: 3.0 / 3.0' in response_content + assert '#4' in response_content @ddt.data(('America/New_York', -5), # UTC - 5 ('Asia/Pyongyang', 9), # UTC + 9 @@ -719,7 +707,7 @@ class ViewsTestCase(BaseViewsTestCase): course_key = course.id client = Client() admin = AdminFactory.create() - self.assertTrue(client.login(username=admin.username, password='test')) + assert client.login(username=admin.username, password='test') state_client = DjangoXBlockUserStateClient(admin) usage_key = course_key.make_usage_key('problem', 'test-history') state_client.set( @@ -754,7 +742,7 @@ class ViewsTestCase(BaseViewsTestCase): url = reverse('financial_assistance') response = self.client.get(url) # This is a static page, so just assert that it is returned correctly - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'Financial Assistance Application') @ddt.data(([CourseMode.AUDIT, CourseMode.VERIFIED], CourseMode.AUDIT, True, YESTERDAY), @@ -790,7 +778,7 @@ class ViewsTestCase(BaseViewsTestCase): url = reverse('financial_assistance_form') response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertNotContains(response, str(course.id)) @@ -812,7 +800,7 @@ class ViewsTestCase(BaseViewsTestCase): url = reverse('financial_assistance_form') response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, str(course)) @@ -844,7 +832,7 @@ class ViewsTestCase(BaseViewsTestCase): 'mktg-permission': False, } response = self._submit_financial_assistance_form(data) - self.assertEqual(response.status_code, 204) + assert response.status_code == 204 __, __, ticket_subject, __ = mock_create_zendesk_ticket.call_args[0] mocked_kwargs = mock_create_zendesk_ticket.call_args[1] @@ -854,20 +842,14 @@ class ViewsTestCase(BaseViewsTestCase): private_comment = '\n'.join(list(additional_info.values())) for info in (country, income, reason_for_applying, goals, effort, username, legal_name, course): - self.assertIn(info, private_comment) + assert info in private_comment - self.assertEqual(additional_info['Allowed for marketing purposes'], 'No') + assert additional_info['Allowed for marketing purposes'] == 'No' - self.assertEqual( - ticket_subject, - u'Financial assistance request for learner {username} in course {course}'.format( - username=username, - course=self.course.display_name - ) - ) + assert ticket_subject == u'Financial assistance request for learner {username} in course {course}'.format(username=username, course=self.course.display_name) # pylint: disable=line-too-long self.assertDictContainsSubset({'course_id': course}, tags) - self.assertIn('Client IP', additional_info) - self.assertEqual(group_name, 'Financial Assistance') + assert 'Client IP' in additional_info + assert group_name == 'Financial Assistance' @patch.object(views, 'create_zendesk_ticket', return_value=500) def test_zendesk_submission_failed(self, _mock_create_zendesk_ticket): @@ -883,7 +865,7 @@ class ViewsTestCase(BaseViewsTestCase): 'effort': '', 'mktg-permission': False, }) - self.assertEqual(response.status_code, 500) + assert response.status_code == 500 @ddt.data( ({}, 400), @@ -893,7 +875,7 @@ class ViewsTestCase(BaseViewsTestCase): @ddt.unpack def test_submit_financial_assistance_errors(self, data, status): response = self._submit_financial_assistance_form(data) - self.assertEqual(response.status_code, status) + assert response.status_code == status def test_financial_assistance_login_required(self): for url in ( @@ -910,13 +892,13 @@ class ViewsTestCase(BaseViewsTestCase): course_id = six.text_type(self.course_key) response = self.client.get(reverse('info', args=[course_id])) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 response = self.client.get(reverse('info', args=[course_id]), HTTP_REFERER=reverse('dashboard')) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 response = self.client.get(reverse('info', args=[course_id]), HTTP_REFERER='foo') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # TODO: TNL-6387: Remove test @override_waffle_flag(DISABLE_COURSE_OUTLINE_PAGE_FLAG, active=True) @@ -968,7 +950,7 @@ class TestProgramMarketingView(SharedModuleStoreTestCase): mock_cache.get.return_value = None response = self.client.get(self.url) - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 def test_200(self, mock_cache): """ @@ -977,7 +959,7 @@ class TestProgramMarketingView(SharedModuleStoreTestCase): mock_cache.get.return_value = self.data response = self.client.get(self.url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # setting TIME_ZONE_DISPLAYED_FOR_DEADLINES explicitly @@ -1010,7 +992,7 @@ class BaseDueDateTests(ModuleStoreTestCase): ItemFactory.create(category='problem', parent_location=vertical.location) course = modulestore().get_course(course.id) - self.assertIsNotNone(course.get_children()[0].get_children()[0].due) + assert course.get_children()[0].get_children()[0].due is not None CourseEnrollmentFactory(user=self.user, course_id=course.id) CourseOverview.load_from_module_store(course.id) return course @@ -1018,7 +1000,7 @@ class BaseDueDateTests(ModuleStoreTestCase): def setUp(self): super(BaseDueDateTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments self.user = UserFactory.create() - self.assertTrue(self.client.login(username=self.user.username, password='test')) + assert self.client.login(username=self.user.username, password='test') self.time_with_tz = "2013-09-18 11:30:00+00:00" @@ -1031,7 +1013,7 @@ class BaseDueDateTests(ModuleStoreTestCase): response = self.get_response(course) self.assertContains(response, self.time_with_tz) # Test that show_timezone has been cleared (which means you get the default value of True). - self.assertTrue(course.show_timezone) + assert course.show_timezone def test_defaults(self): course = self.set_up_course() @@ -1160,7 +1142,7 @@ class ProgressPageBaseTests(ModuleStoreTestCase): def setUp(self): super(ProgressPageBaseTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments self.user = UserFactory.create() - self.assertTrue(self.client.login(username=self.user.username, password='test')) + assert self.client.login(username=self.user.username, password='test') self.setup_course() @@ -1191,7 +1173,7 @@ class ProgressPageBaseTests(ModuleStoreTestCase): resp = self.client.get( reverse('progress', args=[six.text_type(self.course.id)]) ) - self.assertEqual(resp.status_code, expected_status_code) + assert resp.status_code == expected_status_code return resp def _get_student_progress_page(self, expected_status_code=200): @@ -1201,7 +1183,7 @@ class ProgressPageBaseTests(ModuleStoreTestCase): resp = self.client.get( reverse('student_progress', args=[six.text_type(self.course.id), self.user.id]) ) - self.assertEqual(resp.status_code, expected_status_code) + assert resp.status_code == expected_status_code return resp @@ -1247,7 +1229,7 @@ class ProgressPageTests(ProgressPageBaseTests): resp = self.client.get( reverse('student_progress', args=[six.text_type(self.course.id), invalid_id]) ) - self.assertEqual(resp.status_code, 404) + assert resp.status_code == 404 # Assert that valid 'student_id' returns 200 status self._get_student_progress_page() @@ -1262,7 +1244,7 @@ class ProgressPageTests(ProgressPageBaseTests): # Create a new course, a user which will not be enrolled in course, admin user for staff access course = CourseFactory.create(default_store=default_store) admin = AdminFactory.create() - self.assertTrue(self.client.login(username=admin.username, password='test')) + assert self.client.login(username=admin.username, password='test') # Create and enable Credit course CreditCourse.objects.create(course_key=course.id, enabled=True) @@ -1326,7 +1308,7 @@ class ProgressPageTests(ProgressPageBaseTests): CourseEnrollment.enroll(self.user, self.course.id, mode="verified") # Check that the user is unverified - self.assertFalse(IDVerificationService.user_is_verified(self.user)) + assert not IDVerificationService.user_is_verified(self.user) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: course_grade = mock_create.return_value course_grade.passed = True @@ -1495,10 +1477,7 @@ class ProgressPageTests(ProgressPageBaseTests): cert_button_hidden = course_mode is CourseMode.AUDIT or \ course_mode in CourseMode.VERIFIED_MODES and not user_verified - self.assertEqual( - cert_button_hidden, - 'Request Certificate' not in resp.content.decode('utf-8') - ) + assert cert_button_hidden == ('Request Certificate' not in resp.content.decode('utf-8')) @patch.dict('django.conf.settings.FEATURES', {'CERTIFICATES_HTML_VIEW': True}) def test_page_with_invalidated_certificate_with_html_view(self): @@ -1619,7 +1598,7 @@ class ProgressPageTests(ProgressPageBaseTests): """ CourseDurationLimitConfig.objects.create(enabled=True, enabled_as_of=datetime(2018, 1, 1)) user = UserFactory.create() - self.assertTrue(self.client.login(username=user.username, password='test')) + assert self.client.login(username=user.username, password='test') add_course_mode(self.course, mode_slug=CourseMode.AUDIT) add_course_mode(self.course) CourseEnrollmentFactory(user=user, course_id=self.course.id, mode=course_mode) @@ -1652,7 +1631,7 @@ class ProgressPageTests(ProgressPageBaseTests): """ CourseDurationLimitConfig.objects.create(enabled=False) user = UserFactory.create() - self.assertTrue(self.client.login(username=user.username, password='test')) + assert self.client.login(username=user.username, password='test') CourseModeFactory.create( course_id=self.course.id, mode_slug=course_mode @@ -1671,7 +1650,7 @@ class ProgressPageTests(ProgressPageBaseTests): in an ineligible mode. """ user = UserFactory.create() - self.assertTrue(self.client.login(username=user.username, password='test')) + assert self.client.login(username=user.username, password='test') CourseEnrollmentFactory(user=user, course_id=self.course.id, mode=course_mode) with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_create: @@ -1700,8 +1679,8 @@ class ProgressPageTests(ProgressPageBaseTests): # Invalidate user certificate generated_certificate.invalidate() response = views.get_cert_data(self.user, self.course, CourseMode.HONOR, MagicMock(passed=True)) - self.assertEqual(response.cert_status, 'invalidated') - self.assertEqual(response.title, 'Your certificate has been invalidated') + assert response.cert_status == 'invalidated' + assert response.title == 'Your certificate has been invalidated' @override_settings(FEATURES=FEATURES_WITH_DISABLE_HONOR_CERTIFICATE) def test_downloadable_get_cert_data(self): @@ -1716,8 +1695,8 @@ class ProgressPageTests(ProgressPageBaseTests): self.user, self.course, CourseMode.HONOR, MagicMock(passed=True) ) - self.assertEqual(response.cert_status, 'downloadable') - self.assertEqual(response.title, 'Your certificate is available') + assert response.cert_status == 'downloadable' + assert response.title == 'Your certificate is available' def test_generating_get_cert_data(self): """ @@ -1730,8 +1709,8 @@ class ProgressPageTests(ProgressPageBaseTests): return_value=self.mock_certificate_downloadable_status(is_generating=True)): response = views.get_cert_data(self.user, self.course, CourseMode.HONOR, MagicMock(passed=True)) - self.assertEqual(response.cert_status, 'generating') - self.assertEqual(response.title, "We're working on it...") + assert response.cert_status == 'generating' + assert response.title == "We're working on it..." def test_unverified_get_cert_data(self): """ @@ -1744,8 +1723,8 @@ class ProgressPageTests(ProgressPageBaseTests): return_value=self.mock_certificate_downloadable_status(is_unverified=True)): response = views.get_cert_data(self.user, self.course, CourseMode.HONOR, MagicMock(passed=True)) - self.assertEqual(response.cert_status, 'unverified') - self.assertEqual(response.title, "Certificate unavailable") + assert response.cert_status == 'unverified' + assert response.title == 'Certificate unavailable' def test_request_get_cert_data(self): """ @@ -1758,8 +1737,8 @@ class ProgressPageTests(ProgressPageBaseTests): return_value=self.mock_certificate_downloadable_status()): response = views.get_cert_data(self.user, self.course, CourseMode.HONOR, MagicMock(passed=True)) - self.assertEqual(response.cert_status, 'requesting') - self.assertEqual(response.title, "Congratulations, you qualified for a certificate!") + assert response.cert_status == 'requesting' + assert response.title == 'Congratulations, you qualified for a certificate!' def test_earned_but_not_available_get_cert_data(self): """ @@ -1772,8 +1751,8 @@ class ProgressPageTests(ProgressPageBaseTests): return_value=self.mock_certificate_downloadable_status(earned_but_not_available=True)): response = views.get_cert_data(self.user, self.course, CourseMode.VERIFIED, MagicMock(passed=True)) - self.assertEqual(response.cert_status, 'earned_but_not_available') - self.assertEqual(response.title, "Your certificate will be available soon!") + assert response.cert_status == 'earned_but_not_available' + assert response.title == 'Your certificate will be available soon!' def assert_invalidate_certificate(self, certificate): """ Dry method to mark certificate as invalid. And assert the response. """ @@ -2128,13 +2107,13 @@ class VerifyCourseKeyDecoratorTests(TestCase): mocked_view = create_autospec(views.course_about) view_function = ensure_valid_course_key(mocked_view) view_function(self.request, course_id=self.valid_course_id) - self.assertTrue(mocked_view.called) + assert mocked_view.called def test_decorator_with_invalid_course_id(self): mocked_view = create_autospec(views.course_about) view_function = ensure_valid_course_key(mocked_view) self.assertRaises(Http404, view_function, self.request, course_id=self.invalid_course_id) - self.assertFalse(mocked_view.called) + assert not mocked_view.called class GenerateUserCertTests(ModuleStoreTestCase): @@ -2155,7 +2134,7 @@ class GenerateUserCertTests(ModuleStoreTestCase): self_paced=True ) self.enrollment = CourseEnrollment.enroll(self.student, self.course.id, mode='honor') - self.assertTrue(self.client.login(username=self.student, password=TEST_PASSWORD)) + assert self.client.login(username=self.student, password=TEST_PASSWORD) self.url = reverse('generate_user_cert', kwargs={'course_id': six.text_type(self.course.id)}) def test_user_with_out_passing_grades(self): @@ -2182,7 +2161,7 @@ class GenerateUserCertTests(ModuleStoreTestCase): mock_send_to_queue.return_value = (0, "Successfully queued") resp = self.client.post(self.url) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 # Verify Google Analytics event fired after generating certificate mock_tracker.track.assert_called_once_with( @@ -2245,7 +2224,7 @@ class GenerateUserCertTests(ModuleStoreTestCase): def test_user_with_invalid_course_id(self): # If try to access a course with invalid key pattern then 404 will return resp = self.client.post('/courses/def/generate_user_cert') - self.assertEqual(resp.status_code, 404) + assert resp.status_code == 404 def test_user_without_login_return_error(self): # If user try to access without login should see a bad request status code with message @@ -2334,7 +2313,7 @@ class TestIndexView(ModuleStoreTestCase): CourseOverview.load_from_module_store(course.id) CourseEnrollmentFactory(user=user, course_id=course.id) - self.assertTrue(self.client.login(username=user.username, password='test')) + assert self.client.login(username=user.username, password='test') response = self.client.get( reverse( 'courseware_section', @@ -2362,7 +2341,7 @@ class TestIndexView(ModuleStoreTestCase): CourseOverview.load_from_module_store(course.id) CourseEnrollmentFactory(user=user, course_id=course.id) - self.assertTrue(self.client.login(username=user.username, password='test')) + assert self.client.login(username=user.username, password='test') response = self.client.get( reverse( 'courseware_section', @@ -2434,23 +2413,23 @@ class TestIndexView(ModuleStoreTestCase): unicode_content = response.content.decode('utf-8') if expected_course_content: if user_type in (CourseUserType.ANONYMOUS, CourseUserType.UNENROLLED): - self.assertIn('data-save-position="false"', unicode_content) - self.assertIn('data-show-completion="false"', unicode_content) - self.assertIn('xblock-public_view-sequential', unicode_content) - self.assertIn('xblock-public_view-vertical', unicode_content) - self.assertIn('xblock-public_view-html', unicode_content) - self.assertIn('xblock-public_view-video', unicode_content) + assert 'data-save-position="false"' in unicode_content + assert 'data-show-completion="false"' in unicode_content + assert 'xblock-public_view-sequential' in unicode_content + assert 'xblock-public_view-vertical' in unicode_content + assert 'xblock-public_view-html' in unicode_content + assert 'xblock-public_view-video' in unicode_content if user_type == CourseUserType.ANONYMOUS and course_visibility == COURSE_VISIBILITY_PRIVATE: - self.assertIn('To see course content', unicode_content) + assert 'To see course content' in unicode_content if user_type == CourseUserType.UNENROLLED and course_visibility == COURSE_VISIBILITY_PRIVATE: - self.assertIn('You must be enrolled', unicode_content) + assert 'You must be enrolled' in unicode_content else: - self.assertIn('data-save-position="true"', unicode_content) - self.assertIn('data-show-completion="true"', unicode_content) - self.assertIn('xblock-student_view-sequential', unicode_content) - self.assertIn('xblock-student_view-vertical', unicode_content) - self.assertIn('xblock-student_view-html', unicode_content) - self.assertIn('xblock-student_view-video', unicode_content) + assert 'data-save-position="true"' in unicode_content + assert 'data-show-completion="true"' in unicode_content + assert 'xblock-student_view-sequential' in unicode_content + assert 'xblock-student_view-vertical' in unicode_content + assert 'xblock-student_view-html' in unicode_content + assert 'xblock-student_view-video' in unicode_content @patch('lms.djangoapps.courseware.views.views.CourseTabView.course_open_for_learner_enrollment') @patch('openedx.core.djangoapps.util.user_messages.PageLevelMessages.register_warning_message') @@ -2532,10 +2511,7 @@ class TestIndexView(ModuleStoreTestCase): patch_is_masters_only.return_value = is_masters_only course.invitation_only = invitation_only - self.assertEqual( - views.CourseTabView.course_open_for_learner_enrollment(course), - expected_should_show_enroll_button - ) + assert views.CourseTabView.course_open_for_learner_enrollment(course) == expected_should_show_enroll_button @ddt.ddt @@ -2615,7 +2591,7 @@ class TestIndexViewCompleteOnView(ModuleStoreTestCase, CompletionWaffleTestMixin def test_completion_service_disabled(self, default_store): self.setup_course(default_store) - self.assertTrue(self.client.login(username=self.user.username, password='test')) + assert self.client.login(username=self.user.username, password='test') response = self.client.get(self.section_1_url) self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') @@ -2629,7 +2605,7 @@ class TestIndexViewCompleteOnView(ModuleStoreTestCase, CompletionWaffleTestMixin self.override_waffle_switch(True) self.setup_course(default_store) - self.assertTrue(self.client.login(username=self.user.username, password='test')) + assert self.client.login(username=self.user.username, password='test') response = self.client.get(self.section_1_url) self.assertContains(response, 'data-mark-completed-on-view-after-delay') @@ -2647,7 +2623,7 @@ class TestIndexViewCompleteOnView(ModuleStoreTestCase, CompletionWaffleTestMixin quote_slashes(six.text_type(self.html_1_1.scope_ids.usage_id)), 'publish_completion', ) - self.assertEqual(json.loads(response.content.decode('utf-8')), {'result': "ok"}) + assert json.loads(response.content.decode('utf-8')) == {'result': 'ok'} response = self.client.get(self.section_1_url) self.assertContains(response, 'data-mark-completed-on-view-after-delay') @@ -2665,7 +2641,7 @@ class TestIndexViewCompleteOnView(ModuleStoreTestCase, CompletionWaffleTestMixin quote_slashes(six.text_type(self.html_1_2.scope_ids.usage_id)), 'publish_completion', ) - self.assertEqual(json.loads(response.content.decode('utf-8')), {'result': "ok"}) + assert json.loads(response.content.decode('utf-8')) == {'result': 'ok'} response = self.client.get(self.section_1_url) self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') @@ -2775,7 +2751,7 @@ class TestIndexViewWithGating(ModuleStoreTestCase, MilestonesTestCaseMixin): """ Test index view with a gated sequential raises Http404 """ - self.assertTrue(self.client.login(username=self.user.username, password='test')) + assert self.client.login(username=self.user.username, password='test') response = self.client.get( reverse( 'courseware_section', @@ -2786,7 +2762,7 @@ class TestIndexViewWithGating(ModuleStoreTestCase, MilestonesTestCaseMixin): } ) ) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, "Content Locked") @@ -2816,7 +2792,7 @@ class TestIndexViewWithCourseDurationLimits(ModuleStoreTestCase): when course_duration_limits are enabled. """ CourseDurationLimitConfig.objects.create(enabled=True, enabled_as_of=datetime(2018, 1, 1)) - self.assertTrue(self.client.login(username=self.user.username, password='test')) + assert self.client.login(username=self.user.username, password='test') add_course_mode(self.course, mode_slug=CourseMode.AUDIT) add_course_mode(self.course) response = self.client.get( @@ -2835,7 +2811,7 @@ class TestIndexViewWithCourseDurationLimits(ModuleStoreTestCase): # work. Instead we remove all whitespace to verify content is correct. bannerText_no_spaces = escape(bannerText).replace(' ', '') response_no_spaces = response.content.decode('utf-8').replace(' ', '') - self.assertIn(bannerText_no_spaces, response_no_spaces) + assert bannerText_no_spaces in response_no_spaces def test_index_without_course_duration_limits(self): """ @@ -2843,7 +2819,7 @@ class TestIndexViewWithCourseDurationLimits(ModuleStoreTestCase): when course_duration_limits are disabled. """ CourseDurationLimitConfig.objects.create(enabled=False) - self.assertTrue(self.client.login(username=self.user.username, password='test')) + assert self.client.login(username=self.user.username, password='test') add_course_mode(self.course, upgrade_deadline_expired=False) response = self.client.get( reverse( @@ -2893,7 +2869,7 @@ class TestRenderXBlock(RenderXBlockTestMixin, ModuleStoreTestCase, CompletionWaf self.setup_user(admin=True, enroll=True, login=True) response = self.get_response(usage_key=self.html_block.location) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'data-enable-completion-on-view-service="false"') self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') @@ -2907,7 +2883,7 @@ class TestRenderXBlock(RenderXBlockTestMixin, ModuleStoreTestCase, CompletionWaf self.setup_user(admin=False, enroll=True, login=True) response = self.get_response(usage_key=self.html_block.location) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'data-enable-completion-on-view-service="true"') self.assertContains(response, 'data-mark-completed-on-view-after-delay') @@ -2923,16 +2899,16 @@ class TestRenderXBlock(RenderXBlockTestMixin, ModuleStoreTestCase, CompletionWaf quote_slashes(six.text_type(self.html_block.location)), 'publish_completion', ) - self.assertEqual(response.status_code, 200) - self.assertEqual(json.loads(response.content.decode('utf-8')), {'result': "ok"}) + assert response.status_code == 200 + assert json.loads(response.content.decode('utf-8')) == {'result': 'ok'} response = self.get_response(usage_key=self.html_block.location) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'data-enable-completion-on-view-service="false"') self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') response = self.get_response(usage_key=self.problem_block.location) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'data-enable-completion-on-view-service="false"') self.assertNotContains(response, 'data-mark-completed-on-view-after-delay') @@ -2974,14 +2950,11 @@ class TestRenderXBlock(RenderXBlockTestMixin, ModuleStoreTestCase, CompletionWaf seq_url = reverse('render_xblock', kwargs={'usage_key_string': str(self.sequence.location)}) for block in [self.problem_block, self.vertical_block]: response = self.get_response(usage_key=block.location) - self.assertEqual(response.status_code, 302) - self.assertEqual(response.get('Location'), seq_url) + assert response.status_code == 302 + assert response.get('Location') == seq_url # The Sequence itself 200s (or we risk infinite redirect loops). - self.assertEqual( - self.get_response(usage_key=self.sequence.location).status_code, - 200 - ) + assert self.get_response(usage_key=self.sequence.location).status_code == 200 class TestRenderXBlockSelfPaced(TestRenderXBlock): # lint-amnesty, pylint: disable=test-inherits-tests @@ -3033,12 +3006,12 @@ class TestIndexViewCrawlerStudentStateWrites(SharedModuleStoreTestCase): with patch('lms.djangoapps.courseware.model_data.UserStateCache.set_many') as patched_state_client_set_many: # Simulate someone using Chrome self._load_courseware('Mozilla/5.0 AppleWebKit/537.36') - self.assertTrue(patched_state_client_set_many.called) + assert patched_state_client_set_many.called patched_state_client_set_many.reset_mock() # Common crawler user agent self._load_courseware('edX-downloader/0.1') - self.assertTrue(patched_state_client_set_many.called) + assert patched_state_client_set_many.called def test_writes_with_config(self): """Test state writes (or lack thereof) based on config values.""" @@ -3046,15 +3019,15 @@ class TestIndexViewCrawlerStudentStateWrites(SharedModuleStoreTestCase): with patch('lms.djangoapps.courseware.model_data.UserStateCache.set_many') as patched_state_client_set_many: # Exact matching of crawler user agent self._load_courseware('crawler_foo') - self.assertFalse(patched_state_client_set_many.called) + assert not patched_state_client_set_many.called # Partial matching of crawler user agent self._load_courseware('edX-downloader/0.1') - self.assertFalse(patched_state_client_set_many.called) + assert not patched_state_client_set_many.called # Simulate an actual browser hitting it (we should write) self._load_courseware('Mozilla/5.0 AppleWebKit/537.36') - self.assertTrue(patched_state_client_set_many.called) + assert patched_state_client_set_many.called # Disabling the crawlers config should revert us to default behavior CrawlersConfig.objects.create(enabled=False) @@ -3073,7 +3046,7 @@ class TestIndexViewCrawlerStudentStateWrites(SharedModuleStoreTestCase): response = self.client.get(url, HTTP_USER_AGENT=user_agent) # Make sure we get back an actual 200, and aren't redirected because we # messed up the setup somehow (e.g. didn't enroll properly) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 class EnterpriseConsentTestCase(EnterpriseTestConsentRequired, ModuleStoreTestCase): @@ -3083,7 +3056,7 @@ class EnterpriseConsentTestCase(EnterpriseTestConsentRequired, ModuleStoreTestCa def setUp(self): super(EnterpriseConsentTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments self.user = UserFactory.create() - self.assertTrue(self.client.login(username=self.user.username, password='test')) + assert self.client.login(username=self.user.username, password='test') self.course = CourseFactory.create() CourseOverview.load_from_module_store(self.course.id) CourseEnrollmentFactory(user=self.user, course_id=self.course.id) @@ -3121,7 +3094,7 @@ class AccessUtilsTestCase(ModuleStoreTestCase): start_date = datetime.now(UTC) + timedelta(days=start_date_modifier) course = CourseFactory.create(start=start_date) - self.assertEqual(bool(check_course_open_for_learner(staff_user, course)), expected_value) + assert bool(check_course_open_for_learner(staff_user, course)) == expected_value @ddt.ddt @@ -3160,22 +3133,22 @@ class DatesTabTestCase(ModuleStoreTestCase): def test_tab_redirects_if_not_logged_in(self): self.client.logout() response = self._get_response(self.course) - self.assertEqual(response.status_code, 302) - self.assertIn('/login?next=/courses/', response.url) + assert response.status_code == 302 + assert '/login?next=/courses/' in response.url def test_tab_redirects_if_not_enrolled_and_not_staff(self): response = self._get_response(self.course) - self.assertEqual(response.status_code, 302) + assert response.status_code == 302 # Beginning of redirect URL - self.assertIn('/courses/', response.url) + assert '/courses/' in response.url # End of redirect URL - self.assertIn('/course/', response.url) + assert '/course/' in response.url # Now check staff users can see self.user.is_staff = True self.user.save() response = self._get_response(self.course) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # Enrolled users can also see self.client.logout() @@ -3183,7 +3156,7 @@ class DatesTabTestCase(ModuleStoreTestCase): CourseEnrollmentFactory(course_id=self.course.id, user=enrolled_user, mode=CourseMode.VERIFIED) self.client.login(username=enrolled_user.username, password=TEST_PASSWORD) response = self._get_response(self.course) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 @override_experiment_waffle_flag(RELATIVE_DATES_FLAG, active=True) @patch('edx_django_utils.monitoring.set_custom_attribute') @@ -3330,46 +3303,46 @@ class TestShowCoursewareMFE(TestCase): with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, active=True): # (preview=on, redirect=on) # Global and Course Staff can see the link. - self.assertTrue(show_courseware_mfe_link(global_staff_user, True, new_course_key)) - self.assertTrue(show_courseware_mfe_link(global_staff_user, False, new_course_key)) - self.assertTrue(show_courseware_mfe_link(regular_user, True, new_course_key)) + assert show_courseware_mfe_link(global_staff_user, True, new_course_key) + assert show_courseware_mfe_link(global_staff_user, False, new_course_key) + assert show_courseware_mfe_link(regular_user, True, new_course_key) # Regular users don't see the link. - self.assertFalse(show_courseware_mfe_link(regular_user, False, new_course_key)) + assert not show_courseware_mfe_link(regular_user, False, new_course_key) with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, active=False): # (preview=on, redirect=off) # Global and Course Staff can see the link. - self.assertTrue(show_courseware_mfe_link(global_staff_user, True, new_course_key)) - self.assertTrue(show_courseware_mfe_link(global_staff_user, False, new_course_key)) - self.assertTrue(show_courseware_mfe_link(regular_user, True, new_course_key)) + assert show_courseware_mfe_link(global_staff_user, True, new_course_key) + assert show_courseware_mfe_link(global_staff_user, False, new_course_key) + assert show_courseware_mfe_link(regular_user, True, new_course_key) # Regular users don't see the link. - self.assertFalse(show_courseware_mfe_link(regular_user, False, new_course_key)) + assert not show_courseware_mfe_link(regular_user, False, new_course_key) with override_waffle_flag(COURSEWARE_MICROFRONTEND_COURSE_TEAM_PREVIEW, False): with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, active=True): # (preview=off, redirect=on) # Global staff see the link anyway - self.assertTrue(show_courseware_mfe_link(global_staff_user, True, new_course_key)) - self.assertTrue(show_courseware_mfe_link(global_staff_user, False, new_course_key)) + assert show_courseware_mfe_link(global_staff_user, True, new_course_key) + assert show_courseware_mfe_link(global_staff_user, False, new_course_key) # If redirect is active for their students, course staff see the link even # if preview=off. - self.assertTrue(show_courseware_mfe_link(regular_user, True, new_course_key)) + assert show_courseware_mfe_link(regular_user, True, new_course_key) # Regular users don't see the link. - self.assertFalse(show_courseware_mfe_link(regular_user, False, new_course_key)) + assert not show_courseware_mfe_link(regular_user, False, new_course_key) with override_waffle_flag(REDIRECT_TO_COURSEWARE_MICROFRONTEND, active=False): # (preview=off, redirect=off) # Global staff see the link anyway - self.assertTrue(show_courseware_mfe_link(global_staff_user, True, new_course_key)) - self.assertTrue(show_courseware_mfe_link(global_staff_user, False, new_course_key)) + assert show_courseware_mfe_link(global_staff_user, True, new_course_key) + assert show_courseware_mfe_link(global_staff_user, False, new_course_key) # Course teams can NOT see the link because both rollout waffle flags are false. - self.assertFalse(show_courseware_mfe_link(regular_user, True, new_course_key)) + assert not show_courseware_mfe_link(regular_user, True, new_course_key) # Regular users don't see the link. - self.assertFalse(show_courseware_mfe_link(regular_user, False, new_course_key)) + assert not show_courseware_mfe_link(regular_user, False, new_course_key) @override_settings(LEARNING_MICROFRONTEND_URL='https://learningmfe.openedx.org') def test_url_generation(self): diff --git a/lms/djangoapps/courseware/tests/test_word_cloud.py b/lms/djangoapps/courseware/tests/test_word_cloud.py index 7f2603176900ad6c2518f004edaf0b0ea7fbca12..6eaa82cc32baa7f5fe771d91c4dd68bb7347a275 100644 --- a/lms/djangoapps/courseware/tests/test_word_cloud.py +++ b/lms/djangoapps/courseware/tests/test_word_cloud.py @@ -86,12 +86,7 @@ class TestWordCloud(BaseTestXmodule): """ users_state = self._get_users_state() - self.assertEqual( - ''.join(set([ # lint-amnesty, pylint: disable=consider-using-set-comprehension - content['status'] - for _, content in users_state.items() - ])), - 'success') + assert ''.join({content['status'] for (_, content) in users_state.items()}) == 'success' # correct initial data: correct_initial_data = { @@ -104,7 +99,7 @@ class TestWordCloud(BaseTestXmodule): } for _, response_content in users_state.items(): - self.assertEqual(response_content, correct_initial_data) + assert response_content == correct_initial_data def test_post_words(self): """Students can submit data succesfully. @@ -126,12 +121,7 @@ class TestWordCloud(BaseTestXmodule): users_state = self._post_words(input_words) - self.assertEqual( - ''.join(set([ # lint-amnesty, pylint: disable=consider-using-set-comprehension - content['status'] - for _, content in users_state.items() - ])), - 'success') + assert ''.join({content['status'] for (_, content) in users_state.items()}) == 'success' correct_state = {} for index, user in enumerate(self.users): @@ -174,23 +164,13 @@ class TestWordCloud(BaseTestXmodule): # 1. users_state = self._get_users_state() - self.assertEqual( - ''.join(set([ # lint-amnesty, pylint: disable=consider-using-set-comprehension - content['status'] - for _, content in users_state.items() - ])), - 'success') + assert ''.join({content['status'] for (_, content) in users_state.items()}) == 'success' # 2. # Invcemental state per user. users_state_after_post = self._post_words(['word1', 'word2']) - self.assertEqual( - ''.join(set([ # lint-amnesty, pylint: disable=consider-using-set-comprehension - content['status'] - for _, content in users_state_after_post.items() - ])), - 'success') + assert ''.join({content['status'] for (_, content) in users_state_after_post.items()}) == 'success' # Final state after all posts. users_state_before_fail = self._get_users_state() @@ -199,12 +179,7 @@ class TestWordCloud(BaseTestXmodule): users_state_after_post = self._post_words( ['word1', 'word2', 'word3']) - self.assertEqual( - ''.join(set([ # lint-amnesty, pylint: disable=consider-using-set-comprehension - content['status'] - for _, content in users_state_after_post.items() - ])), - 'fail') + assert ''.join({content['status'] for (_, content) in users_state_after_post.items()}) == 'fail' # 4. current_users_state = self._get_users_state() @@ -216,12 +191,7 @@ class TestWordCloud(BaseTestXmodule): users_state = self._post_words(input_words) - self.assertEqual( - ''.join(set([ # lint-amnesty, pylint: disable=consider-using-set-comprehension - content['status'] - for _, content in users_state.items() - ])), - 'success') + assert ''.join({content['status'] for (_, content) in users_state.items()}) == 'success' for user in self.users: self.assertListEqual( @@ -238,7 +208,7 @@ class TestWordCloud(BaseTestXmodule): } status_codes = {response.status_code for response in responses.values()} - self.assertEqual(status_codes.pop(), 200) + assert status_codes.pop() == 200 for user in self.users: self.assertDictEqual( @@ -264,4 +234,4 @@ class TestWordCloud(BaseTestXmodule): 'submitted': False, # default value, } - self.assertEqual(fragment.content, self.runtime.render_template('word_cloud.html', expected_context)) + assert fragment.content == self.runtime.render_template('word_cloud.html', expected_context) diff --git a/lms/djangoapps/courseware/tests/tests.py b/lms/djangoapps/courseware/tests/tests.py index c66bcf074c80d3d44bc5298687dc8cc9f634c2a6..67e68e60c14dc29db38b1ff3b48453525a674363 100644 --- a/lms/djangoapps/courseware/tests/tests.py +++ b/lms/djangoapps/courseware/tests/tests.py @@ -45,7 +45,7 @@ class ActivateLoginTest(LoginEnrollmentTestCase): has 'is_from_log_out' attribute set to true. """ response = self.client.get(reverse('logout')) - self.assertTrue(getattr(response.wsgi_request, 'is_from_logout', False)) + assert getattr(response.wsgi_request, 'is_from_logout', False) class PageLoaderTestCase(LoginEnrollmentTestCase): @@ -115,11 +115,11 @@ class PageLoaderTestCase(LoginEnrollmentTestCase): (response.status_code, descriptor.location)) if expect_redirect: - self.assertEqual(response.redirect_chain[0][1], 302) + assert response.redirect_chain[0][1] == 302 if check_content: self.assertNotContains(response, "this module is temporarily unavailable") - self.assertNotIsInstance(descriptor, ErrorBlock) + assert not isinstance(descriptor, ErrorBlock) class TestMongoCoursesLoad(ModuleStoreTestCase, PageLoaderTestCase): @@ -142,7 +142,7 @@ class TestMongoCoursesLoad(ModuleStoreTestCase, PageLoaderTestCase): """).strip() location = self.toy_course_key.make_usage_key('course', '2012_Fall') course = self.store.get_item(location) - self.assertGreater(len(course.textbooks), 0) + assert len(course.textbooks) > 0 class TestDraftModuleStore(ModuleStoreTestCase): # lint-amnesty, pylint: disable=missing-class-docstring @@ -174,5 +174,5 @@ class TestLmsFieldData(TestCase): base_student = mock.Mock() first_level = LmsFieldData(base_authored, base_student) second_level = LmsFieldData(first_level, base_student) - self.assertEqual(second_level._authored_data, first_level._authored_data) - self.assertNotIsInstance(second_level._authored_data, LmsFieldData) + assert second_level._authored_data == first_level._authored_data + assert not isinstance(second_level._authored_data, LmsFieldData)