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 cc341f3b24..4e02eeba46 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 e4f56b36c8..dc0ab1fd41 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 05ca31def5..fa51481d77 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"{}" - .format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']), - resp.content.decode(resp.charset).strip('\n')) + assert u'{}'.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"{}" - .format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']), - resp.content.decode(resp.charset).strip('\n')) + assert u'{}'.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 37a9e74914..a00333a3d7 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 - )) + assert not 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 - )) + 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) - 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 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 7d26a3d630..a5ced9d9d6 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 1c71fd7ec7..31373c2f0f 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 071de1d860..77c3f9deea 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 a0c2d4fbc9..c057c1a0b2 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''.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 a605dae8ef..d726bcd7fb 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 fbce5d1d1b..f177aeacae 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"Sample") + assert course_info == u"Sample" # 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 70132a8673..b92b547c69 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 3b049f6fc9..9601c6d68d 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 b65e1f3665..c411c02ad8 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 f28dbb6e3d..0694e2cc28 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 a799acc47b..d42576871c 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 db69b78aac..17417e38fb 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 840f031b25..c8ec1a7bed 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 976664435f..bf5d27c193 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 ead6ebd7d5..5e04f00176 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 4e476c7488..b2bf22201f 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 e0cf8d1041..549dc39ff6 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 273601d2c8..013dd3de13 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 307135b751..05be73a91a 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 a25f71540d..f61d099b46 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(""), 1) + assert html.count('') == 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): """) - 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 ea67696676..b79d74375e 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 19489999b4..015218b819 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 7a3fcb989f..83057e2ab3 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 5f269e7643..55cca7da79 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 03bce091dc..f0fdb0d65f 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'