diff --git a/lms/djangoapps/instructor/tests/test_access.py b/lms/djangoapps/instructor/tests/test_access.py index 91b2e3f2fe..7f83d4dcf8 100644 --- a/lms/djangoapps/instructor/tests/test_access.py +++ b/lms/djangoapps/instructor/tests/test_access.py @@ -33,11 +33,11 @@ class TestInstructorAccessList(SharedModuleStoreTestCase): def test_list_instructors(self): instructors = list_with_level(self.course, 'instructor') - self.assertEqual(set(instructors), set(self.instructors)) + assert set(instructors) == set(self.instructors) def test_list_beta(self): beta_testers = list_with_level(self.course, 'beta') - self.assertEqual(set(beta_testers), set(self.beta_testers)) + assert set(beta_testers) == set(self.beta_testers) class TestInstructorAccessAllow(EmailTemplateTagMixin, SharedModuleStoreTestCase): @@ -55,24 +55,24 @@ class TestInstructorAccessAllow(EmailTemplateTagMixin, SharedModuleStoreTestCase def test_allow(self): user = UserFactory() allow_access(self.course, user, 'staff') - self.assertTrue(CourseStaffRole(self.course.id).has_user(user)) + assert CourseStaffRole(self.course.id).has_user(user) def test_allow_twice(self): user = UserFactory() allow_access(self.course, user, 'staff') allow_access(self.course, user, 'staff') - self.assertTrue(CourseStaffRole(self.course.id).has_user(user)) + assert CourseStaffRole(self.course.id).has_user(user) def test_allow_ccx_coach(self): user = UserFactory() allow_access(self.course, user, 'ccx_coach') - self.assertTrue(CourseCcxCoachRole(self.course.id).has_user(user)) + assert CourseCcxCoachRole(self.course.id).has_user(user) def test_allow_beta(self): """ Test allow beta against list beta. """ user = UserFactory() allow_access(self.course, user, 'beta') - self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(user)) + assert CourseBetaTesterRole(self.course.id).has_user(user) def test_allow_badlevel(self): user = UserFactory() @@ -104,17 +104,17 @@ class TestInstructorAccessRevoke(SharedModuleStoreTestCase): def test_revoke(self): user = self.staff[0] revoke_access(self.course, user, 'staff') - self.assertFalse(CourseStaffRole(self.course.id).has_user(user)) + assert not CourseStaffRole(self.course.id).has_user(user) def test_revoke_twice(self): user = self.staff[0] revoke_access(self.course, user, 'staff') - self.assertFalse(CourseStaffRole(self.course.id).has_user(user)) + assert not CourseStaffRole(self.course.id).has_user(user) def test_revoke_beta(self): user = self.beta_testers[0] revoke_access(self.course, user, 'beta') - self.assertFalse(CourseBetaTesterRole(self.course.id).has_user(user)) + assert not CourseBetaTesterRole(self.course.id).has_user(user) def test_revoke_badrolename(self): user = UserFactory() @@ -144,14 +144,14 @@ class TestInstructorAccessForum(SharedModuleStoreTestCase): def test_allow(self): user = UserFactory.create() update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'allow') - self.assertIn(user, self.mod_role.users.all()) + assert user in self.mod_role.users.all() def test_allow_twice(self): user = UserFactory.create() update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'allow') - self.assertIn(user, self.mod_role.users.all()) + assert user in self.mod_role.users.all() update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'allow') - self.assertIn(user, self.mod_role.users.all()) + assert user in self.mod_role.users.all() def test_allow_badrole(self): user = UserFactory.create() @@ -161,19 +161,19 @@ class TestInstructorAccessForum(SharedModuleStoreTestCase): def test_revoke(self): user = self.moderators[0] update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'revoke') - self.assertNotIn(user, self.mod_role.users.all()) + assert user not in self.mod_role.users.all() def test_revoke_twice(self): user = self.moderators[0] update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'revoke') - self.assertNotIn(user, self.mod_role.users.all()) + assert user not in self.mod_role.users.all() update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'revoke') - self.assertNotIn(user, self.mod_role.users.all()) + assert user not in self.mod_role.users.all() def test_revoke_notallowed(self): user = UserFactory() update_forum_role(self.course.id, user, FORUM_ROLE_MODERATOR, 'revoke') - self.assertNotIn(user, self.mod_role.users.all()) + assert user not in self.mod_role.users.all() def test_revoke_badrole(self): user = self.moderators[0] diff --git a/lms/djangoapps/instructor/tests/test_api.py b/lms/djangoapps/instructor/tests/test_api.py index 6ddd656a4b..aac2719b33 100644 --- a/lms/djangoapps/instructor/tests/test_api.py +++ b/lms/djangoapps/instructor/tests/test_api.py @@ -258,7 +258,7 @@ class TestCommonExceptions400(TestCase): def test_happy_path(self): resp = view_success(self.request) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 def test_user_doesnotexist(self): self.request.is_ajax.return_value = False @@ -331,12 +331,8 @@ class TestEndpointHttpMethods(SharedModuleStoreTestCase, LoginEnrollmentTestCase url = reverse(data, kwargs={'course_id': text_type(self.course.id)}) response = self.client.get(url) - self.assertEqual( - response.status_code, 405, - u"Endpoint {} returned status code {} instead of a 405. It should not allow GET.".format( - data, response.status_code - ) - ) + assert response.status_code == 405, \ + f'Endpoint {data} returned status code {response.status_code} instead of a 405. It should not allow GET.' @ddt.data(*INSTRUCTOR_GET_ENDPOINTS) def test_endpoints_accept_get(self, data): @@ -346,12 +342,8 @@ class TestEndpointHttpMethods(SharedModuleStoreTestCase, LoginEnrollmentTestCase url = reverse(data, kwargs={'course_id': text_type(self.course.id)}) response = self.client.get(url) - self.assertNotEqual( - response.status_code, 405, - u"Endpoint {} returned status code 405 where it shouldn't, since it should allow GET.".format( - data - ) - ) + assert response.status_code != 405, \ + f"Endpoint {data} returned status code 405 where it shouldn't, since it should allow GET." @patch('lms.djangoapps.bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message', autospec=True)) # lint-amnesty, pylint: disable=line-too-long @@ -473,11 +465,7 @@ class TestInstructorAPIDenyLevels(SharedModuleStoreTestCase, LoginEnrollmentTest response = self.client.get(url, args) else: response = self.client.post(url, args) - self.assertEqual( - response.status_code, - status_code, - msg=msg - ) + assert response.status_code == status_code, msg def test_student_level(self): """ @@ -651,15 +639,15 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas csv_content = b"test_student@example.com,test_student_1,tester1,USA" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertEqual(len(data['row_errors']), 0) - self.assertEqual(len(data['warnings']), 0) - self.assertEqual(len(data['general_errors']), 0) + assert len(data['row_errors']) == 0 + assert len(data['warnings']) == 0 + assert len(data['general_errors']) == 0 manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ENROLLED # test the log for email that's send to new created user. info_log.assert_called_with(u'email sent to new created user at %s', 'test_student@example.com') @@ -672,15 +660,15 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas csv_content = b"\ntest_student@example.com,test_student_1,tester1,USA\n\n" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertEqual(len(data['row_errors']), 0) - self.assertEqual(len(data['warnings']), 0) - self.assertEqual(len(data['general_errors']), 0) + assert len(data['row_errors']) == 0 + assert len(data['warnings']) == 0 + assert len(data['general_errors']) == 0 manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ENROLLED # test the log for email that's send to new created user. info_log.assert_called_with(u'email sent to new created user at %s', 'test_student@example.com') @@ -695,15 +683,15 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas b"test_student@example.com,test_student_1,tester2,US" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertEqual(len(data['row_errors']), 0) - self.assertEqual(len(data['warnings']), 0) - self.assertEqual(len(data['general_errors']), 0) + assert len(data['row_errors']) == 0 + assert len(data['warnings']) == 0 + assert len(data['general_errors']) == 0 manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ENROLLED # test the log for email that's send to new created user. info_log.assert_called_with( @@ -718,16 +706,14 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas """ uploaded_file = SimpleUploadedFile("temp.jpg", io.BytesIO(b"some initial binary data: \x00\x01").read()) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertNotEqual(len(data['general_errors']), 0) - self.assertEqual( - data['general_errors'][0]['response'], - 'Make sure that the file you upload is in CSV format with no extraneous characters or rows.' - ) + assert len(data['general_errors']) != 0 + assert data['general_errors'][0]['response'] ==\ + 'Make sure that the file you upload is in CSV format with no extraneous characters or rows.' manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 0) + assert manual_enrollments.count() == 0 def test_bad_file_upload_type(self): """ @@ -735,13 +721,13 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas """ uploaded_file = SimpleUploadedFile("temp.csv", io.BytesIO(b"some initial binary data: \x00\x01").read()) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertNotEqual(len(data['general_errors']), 0) - self.assertEqual(data['general_errors'][0]['response'], 'Could not read uploaded file.') + assert len(data['general_errors']) != 0 + assert data['general_errors'][0]['response'] == 'Could not read uploaded file.' manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 0) + assert manual_enrollments.count() == 0 def test_insufficient_data(self): """ @@ -750,15 +736,17 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas csv_content = b"test_student@example.com,test_student_1\n" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertEqual(len(data['row_errors']), 0) - self.assertEqual(len(data['warnings']), 0) - self.assertEqual(len(data['general_errors']), 1) - self.assertEqual(data['general_errors'][0]['response'], 'Data in row #1 must have exactly four columns: email, username, full name, and country') # lint-amnesty, pylint: disable=line-too-long + assert len(data['row_errors']) == 0 + assert len(data['warnings']) == 0 + assert len(data['general_errors']) == 1 + assert data['general_errors'][0]['response'] ==\ + 'Data in row #1 must have exactly four columns: email, username, full name, and country' + # lint-amnesty, pylint: disable=line-too-long manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 0) + assert manual_enrollments.count() == 0 def test_invalid_email_in_csv(self): """ @@ -768,14 +756,14 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) data = json.loads(response.content.decode('utf-8')) - self.assertEqual(response.status_code, 200) - self.assertNotEqual(len(data['row_errors']), 0) - self.assertEqual(len(data['warnings']), 0) - self.assertEqual(len(data['general_errors']), 0) - self.assertEqual(data['row_errors'][0]['response'], u'Invalid email {0}.'.format('test_student.example.com')) + assert response.status_code == 200 + assert len(data['row_errors']) != 0 + assert len(data['warnings']) == 0 + assert len(data['general_errors']) == 0 + assert data['row_errors'][0]['response'] == u'Invalid email {0}.'.format('test_student.example.com') manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 0) + assert manual_enrollments.count() == 0 @patch('lms.djangoapps.instructor.views.api.log.info') def test_csv_user_exist_and_not_enrolled(self, info_log): @@ -786,15 +774,15 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas csv_content = b"nonenrolled@test.com,NotEnrolledStudent,tester1,USA" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 info_log.assert_called_with( u'user %s enrolled in the course %s', u'NotEnrolledStudent', self.course.id ) manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertTrue(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED def test_user_with_already_existing_email_in_csv(self): """ @@ -806,18 +794,18 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) warning_message = u'An account with email {email} exists but the provided username {username} ' \ u'is different. Enrolling anyway with {email}.'.format(email='test_student@example.com', username='test_student_2') # lint-amnesty, pylint: disable=line-too-long - self.assertNotEqual(len(data['warnings']), 0) - self.assertEqual(data['warnings'][0]['response'], warning_message) + assert len(data['warnings']) != 0 + assert data['warnings'][0]['response'] == warning_message user = User.objects.get(email='test_student@example.com') - self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id)) + assert CourseEnrollment.is_enrolled(user, self.course.id) manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertTrue(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED def test_user_with_retired_email_in_csv(self): """ @@ -839,14 +827,11 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas csv_content = "{email},{username},tester,USA".format(email=conflicting_email, username='new_test_student') uploaded_file = SimpleUploadedFile("temp.csv", six.b(csv_content)) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertNotEqual(len(data['row_errors']), 0) - self.assertEqual( - data['row_errors'][0]['response'], - u'Invalid email {email}.'.format(email=conflicting_email) - ) - self.assertFalse(User.objects.filter(email=conflicting_email).exists()) + assert len(data['row_errors']) != 0 + assert data['row_errors'][0]['response'] == u'Invalid email {email}.'.format(email=conflicting_email) + assert not User.objects.filter(email=conflicting_email).exists() def test_user_with_already_existing_username_in_csv(self): """ @@ -859,10 +844,11 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertNotEqual(len(data['row_errors']), 0) - self.assertEqual(data['row_errors'][0]['response'], u'Username {user} already exists.'.format(user='test_student_1')) # lint-amnesty, pylint: disable=line-too-long + assert len(data['row_errors']) != 0 + assert data['row_errors'][0]['response'] == u'Username {user} already exists.'.format(user='test_student_1') + # lint-amnesty, pylint: disable=line-too-long def test_csv_file_not_attached(self): """ @@ -874,13 +860,13 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'file_not_found': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertNotEqual(len(data['general_errors']), 0) - self.assertEqual(data['general_errors'][0]['response'], 'File is not attached.') + assert len(data['general_errors']) != 0 + assert data['general_errors'][0]['response'] == 'File is not attached.' manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 0) + assert manual_enrollments.count() == 0 def test_raising_exception_in_auto_registration_and_enrollment_case(self): """ @@ -894,22 +880,22 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas mock.side_effect = NonExistentCourseError() response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertNotEqual(len(data['row_errors']), 0) - self.assertEqual(data['row_errors'][0]['response'], 'NonExistentCourseError') + assert len(data['row_errors']) != 0 + assert data['row_errors'][0]['response'] == 'NonExistentCourseError' manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 0) + assert manual_enrollments.count() == 0 def test_generate_unique_password(self): """ generate_unique_password should generate a unique password string that excludes certain characters. """ password = generate_unique_password([], 12) - self.assertEqual(len(password), 12) + assert len(password) == 12 for letter in password: - self.assertNotIn(letter, 'aAeEiIoOuU1l') + assert letter not in 'aAeEiIoOuU1l' def test_users_created_and_enrolled_successfully_if_others_fail(self): @@ -927,24 +913,18 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertNotEqual(len(data['row_errors']), 0) - self.assertEqual( - data['row_errors'][0]['response'], - u'Username {user} already exists.'.format(user='test_student_1') - ) - self.assertEqual( - data['row_errors'][1]['response'], - u'Invalid email {email}.'.format(email='test_student4@example.com') - ) - self.assertTrue(User.objects.filter(username='test_student_1', email='test_student1@example.com').exists()) - self.assertTrue(User.objects.filter(username='test_student_2', email='test_student2@example.com').exists()) - self.assertFalse(User.objects.filter(email='test_student3@example.com').exists()) - self.assertFalse(User.objects.filter(email='test_student4@example.com').exists()) + assert len(data['row_errors']) != 0 + assert data['row_errors'][0]['response'] == u'Username {user} already exists.'.format(user='test_student_1') + assert data['row_errors'][1]['response'] == u'Invalid email {email}.'.format(email='test_student4@example.com') + assert User.objects.filter(username='test_student_1', email='test_student1@example.com').exists() + assert User.objects.filter(username='test_student_2', email='test_student2@example.com').exists() + assert not User.objects.filter(email='test_student3@example.com').exists() + assert not User.objects.filter(email='test_student4@example.com').exists() manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 2) + assert manual_enrollments.count() == 2 @patch('lms.djangoapps.instructor.views.api', 'generate_random_string', Mock(side_effect=['first', 'first', 'second'])) @@ -954,17 +934,17 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas """ generated_password = ['first'] password = generate_unique_password(generated_password, 12) - self.assertNotEqual(password, 'first') + assert password != 'first' @patch.dict(settings.FEATURES, {'ALLOW_AUTOMATED_SIGNUPS': False}) def test_allow_automated_signups_flag_not_set(self): csv_content = b"test_student1@example.com,test_student_1,tester1,USA" uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 403) + assert response.status_code == 403 manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 0) + assert manual_enrollments.count() == 0 @patch.dict(settings.FEATURES, {'ALLOW_AUTOMATED_SIGNUPS': True}) def test_audit_enrollment_mode(self): @@ -978,19 +958,19 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.audit_course_url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertEqual(len(data['row_errors']), 0) - self.assertEqual(len(data['warnings']), 0) - self.assertEqual(len(data['general_errors']), 0) + assert len(data['row_errors']) == 0 + assert len(data['warnings']) == 0 + assert len(data['general_errors']) == 0 manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ENROLLED # Verify enrollment modes to be 'audit' for enrollment in manual_enrollments: - self.assertEqual(enrollment.enrollment.mode, CourseMode.AUDIT) + assert enrollment.enrollment.mode == CourseMode.AUDIT @patch.dict(settings.FEATURES, {'ALLOW_AUTOMATED_SIGNUPS': True}) def test_honor_enrollment_mode(self): @@ -1009,19 +989,19 @@ class TestInstructorAPIBulkAccountCreationAndEnrollment(SharedModuleStoreTestCas uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.white_label_course_url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertEqual(len(data['row_errors']), 0) - self.assertEqual(len(data['warnings']), 0) - self.assertEqual(len(data['general_errors']), 0) + assert len(data['row_errors']) == 0 + assert len(data['warnings']) == 0 + assert len(data['general_errors']) == 0 manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ENROLLED # Verify enrollment modes to be 'honor' for enrollment in manual_enrollments: - self.assertEqual(enrollment.enrollment.mode, CourseMode.HONOR) + assert enrollment.enrollment.mode == CourseMode.HONOR @ddt.ddt @@ -1067,7 +1047,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest self.allowed_email = 'robot-allowed@robot.org' self.notregistered_email = 'robot-not-an-email-yet@robot.org' - self.assertEqual(User.objects.filter(email=self.notregistered_email).count(), 0) + assert User.objects.filter(email=self.notregistered_email).count() == 0 # uncomment to enable enable printing of large diffs # from failed assertions in the event of a test failure. @@ -1078,19 +1058,19 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest """ Test missing all query parameters. """ url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_bad_action(self): """ Test with an invalid action. """ action = 'robot-not-an-action' url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': action}) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_invalid_email(self): url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': 'percivaloctavius@', 'action': 'enroll', 'email_students': False}) # lint-amnesty, pylint: disable=line-too-long - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # test the response data expected = { @@ -1105,13 +1085,13 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected def test_invalid_username(self): url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': 'percivaloctavius', 'action': 'enroll', 'email_students': False}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # test the response data expected = { @@ -1126,13 +1106,13 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected def test_enroll_with_username(self): url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.notenrolled_student.username, 'action': 'enroll', 'email_students': False}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # test the response data expected = { @@ -1157,21 +1137,21 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest ] } manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ENROLLED res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected def test_enroll_without_email(self): url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'enroll', 'email_students': False}) print(u"type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # test that the user is now enrolled user = User.objects.get(email=self.notenrolled_student.email) - self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id)) + assert CourseEnrollment.is_enrolled(user, self.course.id) # test the response data expected = { @@ -1197,13 +1177,13 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest } manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ENROLLED res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 0) + assert len(mail.outbox) == 0 @ddt.data('http', 'https') def test_enroll_with_email(self, protocol): @@ -1213,11 +1193,11 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest response = self.client.post(url, params, **environ) print(u"type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # test that the user is now enrolled user = User.objects.get(email=self.notenrolled_student.email) - self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id)) + assert CourseEnrollment.is_enrolled(user, self.course.id) # test the response data expected = { @@ -1243,14 +1223,11 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 1) - self.assertEqual( - mail.outbox[0].subject, - u'You have been enrolled in {}'.format(self.course.display_name) - ) + assert len(mail.outbox) == 1 + assert mail.outbox[0].subject == u'You have been enrolled in {}'.format(self.course.display_name) text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -1258,19 +1235,14 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest assert text_body.startswith('Dear NotEnrolled Student\n\n') for body in [text_body, html_body]: - self.assertIn(u'You have been enrolled in {course_name} at edx.org by a member of the course staff.'.format( - course_name=self.course.display_name, - ), body) + assert f'You have been enrolled in {self.course.display_name} at edx.org by a member of the course staff.'\ + in body - self.assertIn('This course will now appear on your edx.org dashboard.', body) - self.assertIn('{proto}://{site}{course_path}'.format( - proto=protocol, - site=self.site_name, - course_path=self.course_path, - ), body) + assert 'This course will now appear on your edx.org dashboard.' in body + assert f'{protocol}://{self.site_name}{self.course_path}' in body - self.assertIn("To start accessing course materials, please visit", text_body) - self.assertIn("This email was automatically sent from edx.org to NotEnrolled Student\n\n", text_body) + assert 'To start accessing course materials, please visit' in text_body + assert 'This email was automatically sent from edx.org to NotEnrolled Student\n\n' in text_body @ddt.data('http', 'https') def test_enroll_with_email_not_registered(self, protocol): @@ -1279,16 +1251,13 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ALLOWEDTOENROLL) - self.assertEqual(response.status_code, 200) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ALLOWEDTOENROLL + assert response.status_code == 200 # Check the outbox - self.assertEqual(len(mail.outbox), 1) - self.assertEqual( - mail.outbox[0].subject, - u'You have been invited to register for {}'.format(self.course.display_name) - ) + assert len(mail.outbox) == 1 + assert mail.outbox[0].subject == u'You have been invited to register for {}'.format(self.course.display_name) text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -1328,9 +1297,9 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest response = self.client.post(url, params, **environ) manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ALLOWEDTOENROLL) - self.assertEqual(response.status_code, 200) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ALLOWEDTOENROLL + assert response.status_code == 200 text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -1366,17 +1335,14 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) print(u"type(self.notregistered_email): {}".format(type(self.notregistered_email))) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # Check the outbox - self.assertEqual(len(mail.outbox), 1) - self.assertEqual( - mail.outbox[0].subject, - u'You have been invited to register for {}'.format(self.course.display_name) - ) + assert len(mail.outbox) == 1 + assert mail.outbox[0].subject == u'You have been invited to register for {}'.format(self.course.display_name) manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ALLOWEDTOENROLL) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ALLOWEDTOENROLL text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -1414,11 +1380,11 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll', 'email_students': False}) print(u"type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # test that the user is now unenrolled user = User.objects.get(email=self.enrolled_student.email) - self.assertFalse(CourseEnrollment.is_enrolled(user, self.course.id)) + assert not CourseEnrollment.is_enrolled(user, self.course.id) # test the response data expected = { @@ -1444,24 +1410,24 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest } manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, ENROLLED_TO_UNENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == ENROLLED_TO_UNENROLLED res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 0) + assert len(mail.outbox) == 0 def test_unenroll_with_email(self): url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll', 'email_students': True}) print(u"type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # test that the user is now unenrolled user = User.objects.get(email=self.enrolled_student.email) - self.assertFalse(CourseEnrollment.is_enrolled(user, self.course.id)) + assert not CourseEnrollment.is_enrolled(user, self.course.id) # test the response data expected = { @@ -1487,17 +1453,15 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest } manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, ENROLLED_TO_UNENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == ENROLLED_TO_UNENROLLED res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 1) - self.assertEqual( - mail.outbox[0].subject, - u'You have been unenrolled from {display_name}'.format(display_name=self.course.display_name,) - ) + assert len(mail.outbox) == 1 + assert mail.outbox[0].subject ==\ + u'You have been unenrolled from {display_name}'.format(display_name=self.course.display_name) text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -1518,7 +1482,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest response = self.client.post(url, {'identifiers': self.allowed_email, 'action': 'unenroll', 'email_students': True}) print(u"type(self.allowed_email): {}".format(type(self.allowed_email))) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # test the response data expected = { @@ -1544,17 +1508,15 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest } manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, ALLOWEDTOENROLL_TO_UNENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == ALLOWEDTOENROLL_TO_UNENROLLED res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 1) - self.assertEqual( - mail.outbox[0].subject, - u'You have been unenrolled from {display_name}'.format(display_name=self.course.display_name,) - ) + assert len(mail.outbox) == 1 + assert mail.outbox[0].subject ==\ + u'You have been unenrolled from {display_name}'.format(display_name=self.course.display_name) text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -1577,14 +1539,12 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # Check the outbox - self.assertEqual(len(mail.outbox), 1) - self.assertEqual( - mail.outbox[0].subject, - u'You have been invited to register for {display_name}'.format(display_name=self.course.display_name,) - ) + assert len(mail.outbox) == 1 + assert mail.outbox[0].subject == u'You have been invited to register for {display_name}'\ + .format(display_name=self.course.display_name) text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -1619,7 +1579,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest response = self.client.post(url, {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -1643,14 +1603,12 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) print(u"type(self.notregistered_email): {}".format(type(self.notregistered_email))) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # Check the outbox - self.assertEqual(len(mail.outbox), 1) - self.assertEqual( - mail.outbox[0].subject, - u'You have been invited to register for {display_name}'.format(display_name=self.course.display_name,) - ) + assert len(mail.outbox) == 1 + assert mail.outbox[0].subject ==\ + u'You have been invited to register for {display_name}'.format(display_name=self.course.display_name) text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -1681,7 +1639,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest # make this enrollment "verified" course_enrollment.mode = u'verified' course_enrollment.save() - self.assertEqual(course_enrollment.mode, u'verified') + assert course_enrollment.mode == u'verified' # now re-enroll the student through the instructor dash self._change_student_enrollment(self.enrolled_student, self.course, 'enroll') @@ -1691,9 +1649,9 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest user=self.enrolled_student, course_id=self.course.id ) manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, ENROLLED_TO_ENROLLED) - self.assertEqual(course_enrollment.mode, u"verified") + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == ENROLLED_TO_ENROLLED + assert course_enrollment.mode == u'verified' def create_paid_course(self): """ @@ -1714,9 +1672,9 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest 'auto_enroll': False, 'reason': 'testing..', 'role': 'Learner'} response = self.client.post(url, params) manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_ALLOWEDTOENROLL) - self.assertEqual(response.status_code, 200) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_ALLOWEDTOENROLL + assert response.status_code == 200 # now registered the user UserFactory(email=self.notregistered_email) @@ -1725,9 +1683,9 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest 'auto_enroll': False, 'reason': 'testing', 'role': 'Learner'} response = self.client.post(url, params) manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 2) - self.assertEqual(manual_enrollments[1].state_transition, ALLOWEDTOENROLL_TO_ENROLLED) - self.assertEqual(response.status_code, 200) + assert manual_enrollments.count() == 2 + assert manual_enrollments[1].state_transition == ALLOWEDTOENROLL_TO_ENROLLED + assert response.status_code == 200 # test the response data expected = { @@ -1752,7 +1710,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest ] } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected def test_unenrolled_already_not_enrolled_user(self): """ @@ -1762,14 +1720,14 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest course_enrollment = CourseEnrollment.objects.filter( user__email=self.notregistered_email, course_id=paid_course.id ) - self.assertEqual(course_enrollment.count(), 0) + assert course_enrollment.count() == 0 url = reverse('students_update_enrollment', kwargs={'course_id': text_type(paid_course.id)}) params = {'identifiers': self.notregistered_email, 'action': 'unenroll', 'email_students': False, 'auto_enroll': False, 'reason': 'testing', 'role': 'Learner'} response = self.client.post(url, params) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # test the response data expected = { @@ -1795,11 +1753,11 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest } manual_enrollments = ManualEnrollmentAudit.objects.all() - self.assertEqual(manual_enrollments.count(), 1) - self.assertEqual(manual_enrollments[0].state_transition, UNENROLLED_TO_UNENROLLED) + assert manual_enrollments.count() == 1 + assert manual_enrollments[0].state_transition == UNENROLLED_TO_UNENROLLED res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected def test_unenroll_and_enroll_verified(self): """ @@ -1812,7 +1770,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest # upgrade enrollment course_enrollment.mode = u'verified' course_enrollment.save() - self.assertEqual(course_enrollment.mode, u'verified') + assert course_enrollment.mode == u'verified' self._change_student_enrollment(self.enrolled_student, self.course, 'unenroll') @@ -1821,7 +1779,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest course_enrollment = CourseEnrollment.objects.get( user=self.enrolled_student, course_id=self.course.id ) - self.assertEqual(course_enrollment.mode, CourseMode.DEFAULT_MODE_SLUG) + assert course_enrollment.mode == CourseMode.DEFAULT_MODE_SLUG def test_role_and_reason_are_persisted(self): """ @@ -1834,9 +1792,9 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest response = self.client.post(url, params) manual_enrollment = ManualEnrollmentAudit.objects.first() - self.assertEqual(manual_enrollment.reason, 'testing') - self.assertEqual(manual_enrollment.role, 'Learner') - self.assertEqual(response.status_code, 200) + assert manual_enrollment.reason == 'testing' + assert manual_enrollment.role == 'Learner' + assert response.status_code == 200 def _change_student_enrollment(self, user, course, action): """ @@ -1855,7 +1813,7 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest 'role': 'Learner' } response = self.client.post(url, params) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 return response def test_get_enrollment_status(self): @@ -1870,12 +1828,9 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest 'unique_student_identifier': 'EnrolledStudent' } response = self.client.post(url, params) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual( - res_json['enrollment_status'], - 'Enrollment status for EnrolledStudent: active' - ) + assert res_json['enrollment_status'] == 'Enrollment status for EnrolledStudent: active' # unenrolled, inactive CourseEnrollment.unenroll( @@ -1884,12 +1839,9 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest ) response = self.client.post(url, params) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual( - res_json['enrollment_status'], - 'Enrollment status for EnrolledStudent: inactive' - ) + assert res_json['enrollment_status'] == 'Enrollment status for EnrolledStudent: inactive' # invited, not yet registered params = { @@ -1897,12 +1849,9 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest } response = self.client.post(url, params) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual( - res_json['enrollment_status'], - 'Enrollment status for robot-allowed@robot.org: pending' - ) + assert res_json['enrollment_status'] == 'Enrollment status for robot-allowed@robot.org: pending' # never enrolled or invited params = { @@ -1910,12 +1859,9 @@ class TestInstructorAPIEnrollment(SharedModuleStoreTestCase, LoginEnrollmentTest } response = self.client.post(url, params) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual( - res_json['enrollment_status'], - 'Enrollment status for nonotever@example.com: never enrolled' - ) + assert res_json['enrollment_status'] == 'Enrollment status for nonotever@example.com: never enrolled' @ddt.ddt @@ -1946,12 +1892,12 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll self.beta_tester, self.course.id ) - self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester)) + assert CourseBetaTesterRole(self.course.id).has_user(self.beta_tester) self.notenrolled_student = UserFactory(username='NotEnrolledStudent') self.notregistered_email = 'robot-not-an-email-yet@robot.org' - self.assertEqual(User.objects.filter(email=self.notregistered_email).count(), 0) + assert User.objects.filter(email=self.notregistered_email).count() == 0 self.request = RequestFactory().request() @@ -1977,14 +1923,14 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll """ Test missing all query parameters. """ url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_bad_action(self): """ Test with an invalid action. """ action = 'robot-not-an-action' url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.beta_tester.email, 'action': action}) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def add_notenrolled(self, response, identifier): """ @@ -1997,8 +1943,8 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll response properly contains their identifier, 'error': False, and 'userDoesNotExist': False. Additionally asserts no email was sent. """ - self.assertEqual(response.status_code, 200) - self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student)) + assert response.status_code == 200 + assert CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student) # test the response data expected = { "action": "add", @@ -2013,34 +1959,34 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 0) + assert len(mail.outbox) == 0 def test_add_notenrolled_email(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': False}) # lint-amnesty, pylint: disable=line-too-long self.add_notenrolled(response, self.notenrolled_student.email) - self.assertFalse(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id)) + assert not CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id) def test_add_notenrolled_email_autoenroll(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': False, 'auto_enroll': True}) # lint-amnesty, pylint: disable=line-too-long self.add_notenrolled(response, self.notenrolled_student.email) - self.assertTrue(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id)) + assert CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id) def test_add_notenrolled_username(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.notenrolled_student.username, 'action': 'add', 'email_students': False}) # lint-amnesty, pylint: disable=line-too-long self.add_notenrolled(response, self.notenrolled_student.username) - self.assertFalse(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id)) + assert not CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id) def test_add_notenrolled_username_autoenroll(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.notenrolled_student.username, 'action': 'add', 'email_students': False, 'auto_enroll': True}) # lint-amnesty, pylint: disable=line-too-long self.add_notenrolled(response, self.notenrolled_student.username) - self.assertTrue(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id)) + assert CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id) @ddt.data('http', 'https') def test_add_notenrolled_with_email(self, protocol): @@ -2048,9 +1994,9 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll params = {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 - self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student)) + assert CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student) # test the response data expected = { "action": "add", @@ -2064,14 +2010,12 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll ] } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 1) - self.assertEqual( - mail.outbox[0].subject, - u'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name,) - ) + assert len(mail.outbox) == 1 + assert mail.outbox[0].subject ==\ + u'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name) text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -2104,9 +2048,9 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll 'auto_enroll': True} environ = {'wsgi.url_scheme': protocol} response = self.client.post(url, params, **environ) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 - self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student)) + assert CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student) # test the response data expected = { "action": "add", @@ -2120,14 +2064,12 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll ] } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 1) - self.assertEqual( - mail.outbox[0].subject, - u'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name) - ) + assert len(mail.outbox) == 1 + assert mail.outbox[0].subject ==\ + u'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name) text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -2158,7 +2100,7 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True}) # lint-amnesty, pylint: disable=line-too-long - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -2183,7 +2125,7 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll response = self.client.post(url, {'identifiers': self.notregistered_email, 'action': 'add', 'email_students': True, 'reason': 'testing'}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # test the response data expected = { "action": "add", @@ -2197,23 +2139,23 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll ] } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 0) + assert len(mail.outbox) == 0 def test_remove_without_email(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.beta_tester.email, 'action': 'remove', 'email_students': False, 'reason': 'testing'}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # Works around a caching bug which supposedly can't happen in prod. The instance here is not == # the instance fetched from the email above which had its cache cleared if hasattr(self.beta_tester, '_roles'): del self.beta_tester._roles - self.assertFalse(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester)) + assert not CourseBetaTesterRole(self.course.id).has_user(self.beta_tester) # test the response data expected = { @@ -2228,23 +2170,23 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll ] } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 0) + assert len(mail.outbox) == 0 def test_remove_with_email(self): url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'identifiers': self.beta_tester.email, 'action': 'remove', 'email_students': True, 'reason': 'testing'}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # Works around a caching bug which supposedly can't happen in prod. The instance here is not == # the instance fetched from the email above which had its cache cleared if hasattr(self.beta_tester, '_roles'): del self.beta_tester._roles - self.assertFalse(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester)) + assert not CourseBetaTesterRole(self.course.id).has_user(self.beta_tester) # test the response data expected = { @@ -2259,13 +2201,10 @@ class TestInstructorAPIBulkBetaEnrollment(SharedModuleStoreTestCase, LoginEnroll ] } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected # Check the outbox - self.assertEqual(len(mail.outbox), 1) - self.assertEqual( - mail.outbox[0].subject, - u'You have been removed from a beta test for {display_name}'.format(display_name=self.course.display_name,) - ) + assert len(mail.outbox) == 1 + assert mail.outbox[0].subject == f'You have been removed from a beta test for {self.course.display_name}' text_body = mail.outbox[0].body html_body = mail.outbox[0].alternatives[0][0] @@ -2316,7 +2255,7 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe """ Test missing all query parameters. """ url = reverse('modify_access', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_modify_access_bad_action(self): """ Test with an invalid action parameter. """ @@ -2326,7 +2265,7 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'rolename': 'staff', 'action': 'robot-not-an-action', }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_modify_access_bad_role(self): """ Test with an invalid action parameter. """ @@ -2336,7 +2275,7 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'rolename': 'robot-not-a-roll', 'action': 'revoke', }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_modify_access_allow(self): url = reverse('modify_access', kwargs={'course_id': text_type(self.course.id)}) @@ -2345,7 +2284,7 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'rolename': 'staff', 'action': 'allow', }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 def test_modify_access_allow_with_uname(self): url = reverse('modify_access', kwargs={'course_id': text_type(self.course.id)}) @@ -2354,7 +2293,7 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'rolename': 'staff', 'action': 'allow', }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 def test_modify_access_revoke(self): url = reverse('modify_access', kwargs={'course_id': text_type(self.course.id)}) @@ -2363,7 +2302,7 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'rolename': 'staff', 'action': 'revoke', }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 def test_modify_access_revoke_with_username(self): url = reverse('modify_access', kwargs={'course_id': text_type(self.course.id)}) @@ -2372,7 +2311,7 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'rolename': 'staff', 'action': 'revoke', }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 def test_modify_access_with_fake_user(self): url = reverse('modify_access', kwargs={'course_id': text_type(self.course.id)}) @@ -2381,13 +2320,13 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'rolename': 'staff', 'action': 'revoke', }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 expected = { 'unique_student_identifier': 'GandalfTheGrey', 'userDoesNotExist': True, } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected def test_modify_access_with_inactive_user(self): self.other_user.is_active = False @@ -2398,13 +2337,13 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'rolename': 'beta', 'action': 'allow', }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 expected = { 'unique_student_identifier': self.other_user.username, 'inactiveUser': True, } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected def test_modify_access_revoke_not_allowed(self): """ Test revoking access that a user does not have. """ @@ -2414,7 +2353,7 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'rolename': 'instructor', 'action': 'revoke', }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 def test_modify_access_revoke_self(self): """ @@ -2426,7 +2365,7 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'rolename': 'instructor', 'action': 'revoke', }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # check response content expected = { 'unique_student_identifier': self.instructor.username, @@ -2435,13 +2374,13 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'removingSelfAsInstructor': True, } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected def test_list_course_role_members_noparams(self): """ Test missing all query parameters. """ url = reverse('list_course_role_members', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_list_course_role_members_bad_rolename(self): """ Test with an invalid rolename parameter. """ @@ -2449,14 +2388,14 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe response = self.client.post(url, { 'rolename': 'robot-not-a-rolename', }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_list_course_role_members_staff(self): url = reverse('list_course_role_members', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, { 'rolename': 'staff', }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # check response content expected = { @@ -2471,14 +2410,14 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe ] } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected def test_list_course_role_members_beta(self): url = reverse('list_course_role_members', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, { 'rolename': 'beta', }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # check response content expected = { @@ -2486,7 +2425,7 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe 'beta': [] } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected) + assert res_json == expected def test_update_forum_role_membership(self): """ @@ -2518,13 +2457,13 @@ class TestInstructorAPILevelsAccess(SharedModuleStoreTestCase, LoginEnrollmentTe ) # Status code should be 200. - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 user_roles = current_user.roles.filter(course_id=self.course.id).values_list("name", flat=True) if action == 'allow': - self.assertIn(rolename, user_roles) + assert rolename in user_roles elif action == 'revoke': - self.assertNotIn(rolename, user_roles) + assert rolename not in user_roles @ddt.ddt @@ -2571,7 +2510,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment response = self.client.post(url, {'problem_location': problem_location}) res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, "Could not find problem with this location.") + assert res_json == 'Could not find problem with this location.' def valid_problem_location(test): # pylint: disable=no-self-argument """ @@ -2606,11 +2545,11 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment response = self.client.post(url, {'problem_location': problem_location}) res_json = json.loads(response.content.decode('utf-8')) - self.assertIn('status', res_json) + assert 'status' in res_json status = res_json['status'] - self.assertIn('is being created', status) - self.assertNotIn('already in progress', status) - self.assertIn("task_id", res_json) + assert 'is being created' in status + assert 'already in progress' not in status + assert 'task_id' in res_json @valid_problem_location def test_get_problem_responses_already_running(self): @@ -2642,16 +2581,16 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment url = reverse('get_students_features', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {}) res_json = json.loads(response.content.decode('utf-8')) - self.assertIn('students', res_json) + assert 'students' in res_json for student in self.students: student_json = [ x for x in res_json['students'] if x['username'] == student.username ][0] - self.assertEqual(student_json['username'], student.username) - self.assertEqual(student_json['email'], student.email) - self.assertEqual(student_json['city'], student.profile.city) - self.assertEqual(student_json['country'], "") + assert student_json['username'] == student.username + assert student_json['email'] == student.email + assert student_json['city'] == student.profile.city + assert student_json['country'] == '' @ddt.data(True, False) def test_get_students_features_cohorted(self, is_cohorted): @@ -2665,7 +2604,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment response = self.client.post(url, {}) res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual('cohort' in res_json['feature_names'], is_cohorted) + assert ('cohort' in res_json['feature_names']) == is_cohorted @ddt.data(True, False) def test_get_students_features_teams(self, has_teams): @@ -2686,7 +2625,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment response = self.client.post(url, {}) res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual('team' in res_json['feature_names'], has_teams) + assert ('team' in res_json['feature_names']) == has_teams def test_get_students_who_may_enroll(self): """ @@ -2700,7 +2639,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment ) # Successful case: response = self.client.post(url, {}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # CSV generation already in progress: task_type = 'may_enroll_info_csv' already_running_status = generate_already_running_error_message(task_type) @@ -2722,7 +2661,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment # Successful case: response = self.client.post(url, {}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # CSV generation already in progress: task_type = 'proctored_exam_results_report' already_running_status = generate_already_running_error_message(task_type) @@ -2741,8 +2680,8 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment decorated_func = require_finance_admin(func) request = self.mock_request() response = decorated_func(request, 'invalid_course_key') - self.assertEqual(response.status_code, 404) - self.assertFalse(func.called) + assert response.status_code == 404 + assert not func.called def mock_request(self): """ @@ -2761,8 +2700,8 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment decorated_func = require_finance_admin(func) request = self.mock_request() response = decorated_func(request, 'valid/course/key') - self.assertEqual(response.status_code, 403) - self.assertFalse(func.called) + assert response.status_code == 403 + assert not func.called def test_add_user_to_fiance_admin_role_with_valid_course(self): """ @@ -2774,7 +2713,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment request = self.mock_request() CourseFinanceAdminRole(self.course.id).add_users(self.instructor) decorated_func(request, text_type(self.course.id)) - self.assertTrue(func.called) + assert func.called @patch('lms.djangoapps.instructor.views.api.anonymous_id_for_user', Mock(return_value='42')) @patch('lms.djangoapps.instructor.views.api.unique_id_for_user', Mock(return_value='41')) @@ -2787,16 +2726,12 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment with freeze_time(base_time): response = self.client.post(url, {}) - self.assertEqual(response['Content-Type'], 'text/csv') + assert response['Content-Type'] == 'text/csv' body = response.content.decode("utf-8").replace('\r', '') - self.assertTrue(body.startswith( - '"User ID","Anonymized User ID","Course Specific Anonymized User ID"' - '\n"{user_id}","41","42"\n'.format(user_id=self.students[0].id) - )) - self.assertTrue( - body.endswith('"{user_id}","41","42"\n'.format(user_id=self.students[-1].id)) - ) - self.assertIn("attachment; filename=org", response['Content-Disposition']) + assert body.startswith( + f'"User ID","Anonymized User ID","Course Specific Anonymized User ID"\n"{self.students[0].id}","41","42"\n') + assert body.endswith('"{user_id}","41","42"\n'.format(user_id=self.students[(- 1)].id)) + assert 'attachment; filename=org' in response['Content-Disposition'] # Test rate-limiting # The get_anon_ids view is computationally intensive and its execution time can vary @@ -2832,7 +2767,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment ) res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, {"downloads": []}) + assert res_json == {'downloads': []} def test_list_report_downloads(self): url = reverse('list_report_downloads', kwargs={'course_id': text_type(self.course.id)}) @@ -2858,7 +2793,7 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment ] } res_json = json.loads(response.content.decode('utf-8')) - self.assertEqual(res_json, expected_response) + assert res_json == expected_response @ddt.data(*REPORTS_DATA) @ddt.unpack @@ -2931,30 +2866,30 @@ class TestInstructorAPILevelsDataDump(SharedModuleStoreTestCase, LoginEnrollment url = reverse('get_student_progress_url', kwargs={'course_id': text_type(self.course.id)}) data = {'unique_student_identifier': self.students[0].email} response = self.client.post(url, data) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) - self.assertIn('progress_url', res_json) + assert 'progress_url' in res_json def test_get_student_progress_url_from_uname(self): """ Test that progress_url is in the successful response. """ url = reverse('get_student_progress_url', kwargs={'course_id': text_type(self.course.id)}) data = {'unique_student_identifier': self.students[0].username} response = self.client.post(url, data) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) - self.assertIn('progress_url', res_json) + assert 'progress_url' in res_json def test_get_student_progress_url_noparams(self): """ Test that the endpoint 404's without the required query params. """ url = reverse('get_student_progress_url', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_get_student_progress_url_nostudent(self): """ Test that the endpoint 400's when requesting an unknown email. """ url = reverse('get_student_progress_url', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTestCase): @@ -2998,7 +2933,7 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes 'all_students': True, 'delete_module': True, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_reset_student_attempts_single(self): """ Test reset single student attempts. """ @@ -3007,13 +2942,10 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # make sure problem attempts have been reset. changed_module = StudentModule.objects.get(pk=self.module_to_reset.pk) - self.assertEqual( - json.loads(changed_module.state)['attempts'], - 0 - ) + assert json.loads(changed_module.state)['attempts'] == 0 # mock out the function which should be called to execute the action. @patch('lms.djangoapps.instructor_task.api.submit_reset_problem_attempts_for_all_students') @@ -3024,8 +2956,8 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes 'problem_to_reset': self.problem_urlname, 'all_students': True, }) - self.assertEqual(response.status_code, 200) - self.assertTrue(act.called) + assert response.status_code == 200 + assert act.called def test_reset_student_attempts_missingmodule(self): """ Test reset for non-existant problem. """ @@ -3034,7 +2966,7 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes 'problem_to_reset': 'robot-not-a-real-module', 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 @patch('lms.djangoapps.grades.signals.handlers.PROBLEM_WEIGHTED_SCORE_CHANGED.send') def test_reset_student_attempts_delete(self, _mock_signal): @@ -3045,16 +2977,10 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes 'unique_student_identifier': self.student.email, 'delete_module': True, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # make sure the module has been deleted - self.assertEqual( - StudentModule.objects.filter( - student=self.module_to_reset.student, - course_id=self.module_to_reset.course_id, - # module_id=self.module_to_reset.module_id, - ).count(), - 0 - ) + assert StudentModule.objects\ + .filter(student=self.module_to_reset.student, course_id=self.module_to_reset.course_id).count() == 0 def test_reset_student_attempts_nonsense(self): """ Test failure with both unique_student_identifier and all_students. """ @@ -3064,7 +2990,7 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes 'unique_student_identifier': self.student.email, 'all_students': True, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 @patch('lms.djangoapps.instructor_task.api.submit_rescore_problem_for_student') def test_rescore_problem_single(self, act): @@ -3074,8 +3000,8 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 200) - self.assertTrue(act.called) + assert response.status_code == 200 + assert act.called @patch('lms.djangoapps.instructor_task.api.submit_rescore_problem_for_student') def test_rescore_problem_single_from_uname(self, act): @@ -3085,8 +3011,8 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.username, }) - self.assertEqual(response.status_code, 200) - self.assertTrue(act.called) + assert response.status_code == 200 + assert act.called @patch('lms.djangoapps.instructor_task.api.submit_rescore_problem_for_all_students') def test_rescore_problem_all(self, act): @@ -3096,8 +3022,8 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes 'problem_to_reset': self.problem_urlname, 'all_students': True, }) - self.assertEqual(response.status_code, 200) - self.assertTrue(act.called) + assert response.status_code == 200 + assert act.called @patch.dict(settings.FEATURES, {'ENTRANCE_EXAMS': True}) def test_course_has_entrance_exam_in_student_attempts_reset(self): @@ -3108,7 +3034,7 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes 'all_students': True, 'delete_module': False, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 @patch.dict(settings.FEATURES, {'ENTRANCE_EXAMS': True}) def test_rescore_entrance_exam_with_invalid_exam(self): @@ -3117,7 +3043,7 @@ class TestInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginEnrollmentTes response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 @patch.dict(settings.FEATURES, {'ENTRANCE_EXAMS': True}) @@ -3210,8 +3136,8 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE ) grades = grade_histogram(usage_key) - self.assertEqual(grades[0], (50.0, 1)) - self.assertEqual(grades[1], (100.0, 1)) + assert grades[0] == (50.0, 1) + assert grades[1] == (100.0, 1) def test_reset_entrance_exam_student_attempts_delete_all(self): """ Make sure no one can delete all students state on entrance exam. """ @@ -3221,7 +3147,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE 'all_students': True, 'delete_module': True, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_reset_entrance_exam_student_attempts_single(self): """ Test reset single student attempts for entrance exam. """ @@ -3230,14 +3156,11 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # make sure problem attempts have been reset. changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules) for changed_module in changed_modules: - self.assertEqual( - json.loads(changed_module.state)['attempts'], - 0 - ) + assert json.loads(changed_module.state)['attempts'] == 0 # mock out the function which should be called to execute the action. @patch('lms.djangoapps.instructor_task.api.submit_reset_problem_attempts_in_entrance_exam') @@ -3248,8 +3171,8 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE response = self.client.post(url, { 'all_students': True, }) - self.assertEqual(response.status_code, 200) - self.assertTrue(act.called) + assert response.status_code == 200 + assert act.called def test_reset_student_attempts_invalid_entrance_exam(self): """ Test reset for invalid entrance exam. """ @@ -3258,7 +3181,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_entrance_exam_student_delete_state(self): """ Test delete single student entrance exam state. """ @@ -3268,10 +3191,10 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE 'unique_student_identifier': self.student.email, 'delete_module': True, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # make sure the module has been deleted changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules) - self.assertEqual(changed_modules.count(), 0) + assert changed_modules.count() == 0 def test_entrance_exam_delete_state_with_staff(self): """ Test entrance exam delete state failure with staff access. """ @@ -3284,7 +3207,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE 'unique_student_identifier': self.student.email, 'delete_module': True, }) - self.assertEqual(response.status_code, 403) + assert response.status_code == 403 def test_entrance_exam_reset_student_attempts_nonsense(self): """ Test failure with both unique_student_identifier and all_students. """ @@ -3294,7 +3217,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE 'unique_student_identifier': self.student.email, 'all_students': True, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 @patch('lms.djangoapps.instructor_task.api.submit_rescore_entrance_exam_for_student') def test_rescore_entrance_exam_single_student(self, act): @@ -3303,8 +3226,8 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 200) - self.assertTrue(act.called) + assert response.status_code == 200 + assert act.called def test_rescore_entrance_exam_all_student(self): """ Test rescoring for all students. """ @@ -3312,7 +3235,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE response = self.client.post(url, { 'all_students': True, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 def test_rescore_entrance_exam_if_higher_all_student(self): """ Test rescoring for all students only if higher. """ @@ -3321,7 +3244,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE 'all_students': True, 'only_if_higher': True, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 def test_rescore_entrance_exam_all_student_and_single(self): """ Test re-scoring with both all students and single student parameters. """ @@ -3330,7 +3253,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE 'unique_student_identifier': self.student.email, 'all_students': True, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_rescore_entrance_exam_with_invalid_exam(self): """ Test re-scoring of entrance exam with invalid exam. """ @@ -3338,7 +3261,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_list_entrance_exam_instructor_tasks_student(self): """ Test list task history for entrance exam AND student. """ @@ -3347,28 +3270,28 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # check response tasks = json.loads(response.content.decode('utf-8'))['tasks'] - self.assertEqual(len(tasks), 1) - self.assertEqual(tasks[0]['status'], _('Complete')) + assert len(tasks) == 1 + assert tasks[0]['status'] == _('Complete') def test_list_entrance_exam_instructor_tasks_all_student(self): """ Test list task history for entrance exam AND all student. """ url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # check response tasks = json.loads(response.content.decode('utf-8'))['tasks'] - self.assertEqual(len(tasks), 0) + assert len(tasks) == 0 def test_list_entrance_exam_instructor_with_invalid_exam_key(self): """ Test list task history for entrance exam failure if course has invalid exam. """ @@ -3377,7 +3300,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_skip_entrance_exam_student(self): """ Test skip entrance exam api for student. """ @@ -3386,7 +3309,7 @@ class TestEntranceExamInstructorAPIRegradeTask(SharedModuleStoreTestCase, LoginE response = self.client.post(url, { 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # check response message = _(u'This student (%s) will skip the entrance exam.') % self.student.email self.assertContains(response, message) @@ -3435,13 +3358,13 @@ class TestInstructorSendEmail(SiteMixin, SharedModuleStoreTestCase, LoginEnrollm def test_send_email_as_logged_in_instructor(self): url = reverse('send_email', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, self.full_test_message) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 def test_send_email_but_not_logged_in(self): self.client.logout() url = reverse('send_email', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, self.full_test_message) - self.assertEqual(response.status_code, 403) + assert response.status_code == 403 def test_send_email_but_not_staff(self): self.client.logout() @@ -3449,12 +3372,12 @@ class TestInstructorSendEmail(SiteMixin, SharedModuleStoreTestCase, LoginEnrollm self.client.login(username=student.username, password='test') url = reverse('send_email', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, self.full_test_message) - self.assertEqual(response.status_code, 403) + assert response.status_code == 403 def test_send_email_but_course_not_exist(self): url = reverse('send_email', kwargs={'course_id': 'GarbageCourse/DNE/NoTerm'}) response = self.client.post(url, self.full_test_message) - self.assertNotEqual(response.status_code, 200) + assert response.status_code != 200 def test_send_email_no_sendto(self): url = reverse('send_email', kwargs={'course_id': text_type(self.course.id)}) @@ -3462,7 +3385,7 @@ class TestInstructorSendEmail(SiteMixin, SharedModuleStoreTestCase, LoginEnrollm 'subject': 'test subject', 'message': 'test message', }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_send_email_invalid_sendto(self): url = reverse('send_email', kwargs={'course_id': text_type(self.course.id)}) @@ -3471,7 +3394,7 @@ class TestInstructorSendEmail(SiteMixin, SharedModuleStoreTestCase, LoginEnrollm 'subject': 'test subject', 'message': 'test message', }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_send_email_no_subject(self): url = reverse('send_email', kwargs={'course_id': text_type(self.course.id)}) @@ -3479,7 +3402,7 @@ class TestInstructorSendEmail(SiteMixin, SharedModuleStoreTestCase, LoginEnrollm 'send_to': '["staff"]', 'message': 'test message', }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_send_email_no_message(self): url = reverse('send_email', kwargs={'course_id': text_type(self.course.id)}) @@ -3487,7 +3410,7 @@ class TestInstructorSendEmail(SiteMixin, SharedModuleStoreTestCase, LoginEnrollm 'send_to': '["staff"]', 'subject': 'test subject', }) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 def test_send_email_with_site_template_and_from_addr(self): site_email = self.site_configuration.site_values.get('course_email_from_addr') @@ -3495,15 +3418,11 @@ class TestInstructorSendEmail(SiteMixin, SharedModuleStoreTestCase, LoginEnrollm CourseEmailTemplate.objects.create(name=site_template) url = reverse('send_email', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, self.full_test_message) - self.assertEqual(response.status_code, 200) - self.assertEqual(1, CourseEmail.objects.filter( - course_id=self.course.id, - sender=self.instructor, - subject=self.full_test_message['subject'], - html_message=self.full_test_message['message'], - template_name=site_template, - from_addr=site_email - ).count()) + assert response.status_code == 200 + assert 1 == CourseEmail.objects.filter(course_id=self.course.id, sender=self.instructor, + subject=self.full_test_message['subject'], + html_message=self.full_test_message['message'], + template_name=site_template, from_addr=site_email).count() def test_send_email_with_org_template_and_from_addr(self): org_email = 'fake_org@example.com' @@ -3516,15 +3435,11 @@ class TestInstructorSendEmail(SiteMixin, SharedModuleStoreTestCase, LoginEnrollm self.site_configuration.save() url = reverse('send_email', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, self.full_test_message) - self.assertEqual(response.status_code, 200) - self.assertEqual(1, CourseEmail.objects.filter( - course_id=self.course.id, - sender=self.instructor, - subject=self.full_test_message['subject'], - html_message=self.full_test_message['message'], - template_name=org_template, - from_addr=org_email - ).count()) + assert response.status_code == 200 + assert 1 == CourseEmail.objects.filter(course_id=self.course.id, sender=self.instructor, + subject=self.full_test_message['subject'], + html_message=self.full_test_message['message'], + template_name=org_template, from_addr=org_email).count() class MockCompletionInfo(object): @@ -3628,15 +3543,15 @@ class TestInstructorAPITaskLists(SharedModuleStoreTestCase, LoginEnrollmentTestC ) as mock_completion_info: mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info response = self.client.post(url, {}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # check response - self.assertTrue(act.called) + assert act.called expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content.decode('utf-8'))['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) - self.assertEqual(actual_tasks, expected_tasks) + assert actual_tasks == expected_tasks @patch('lms.djangoapps.instructor_task.api.get_instructor_task_history') def test_list_background_email_tasks(self, act): @@ -3649,15 +3564,15 @@ class TestInstructorAPITaskLists(SharedModuleStoreTestCase, LoginEnrollmentTestC ) as mock_completion_info: mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info response = self.client.post(url, {}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # check response - self.assertTrue(act.called) + assert act.called expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content.decode('utf-8'))['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) - self.assertEqual(actual_tasks, expected_tasks) + assert actual_tasks == expected_tasks @patch('lms.djangoapps.instructor_task.api.get_instructor_task_history') def test_list_instructor_tasks_problem(self, act): @@ -3672,15 +3587,15 @@ class TestInstructorAPITaskLists(SharedModuleStoreTestCase, LoginEnrollmentTestC response = self.client.post(url, { 'problem_location_str': self.problem_urlname, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # check response - self.assertTrue(act.called) + assert act.called expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content.decode('utf-8'))['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) - self.assertEqual(actual_tasks, expected_tasks) + assert actual_tasks == expected_tasks @patch('lms.djangoapps.instructor_task.api.get_instructor_task_history') def test_list_instructor_tasks_problem_student(self, act): @@ -3696,16 +3611,16 @@ class TestInstructorAPITaskLists(SharedModuleStoreTestCase, LoginEnrollmentTestC 'problem_location_str': self.problem_urlname, 'unique_student_identifier': self.student.email, }) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # check response - self.assertTrue(act.called) + assert act.called expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content.decode('utf-8'))['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) - self.assertEqual(actual_tasks, expected_tasks) + assert actual_tasks == expected_tasks @patch('lms.djangoapps.instructor_task.api.get_instructor_task_history', autospec=True) @@ -3753,45 +3668,45 @@ class TestInstructorEmailContentList(SharedModuleStoreTestCase, LoginEnrollmentT with patch('lms.djangoapps.instructor.views.api.CourseEmail.objects.get') as mock_email_info: mock_email_info.side_effect = self.get_matching_mock_email response = self.client.post(url, {}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 return response def check_emails_sent(self, num_emails, task_history_request, with_failures=False): """ Tests sending emails with or without failures """ response = self.get_email_content_response(num_emails, task_history_request, with_failures) - self.assertTrue(task_history_request.called) + assert task_history_request.called expected_email_info = [email_info.to_dict() for email_info in self.emails_info.values()] actual_email_info = json.loads(response.content.decode('utf-8'))['emails'] - self.assertEqual(len(actual_email_info), num_emails) + assert len(actual_email_info) == num_emails for exp_email, act_email in zip(expected_email_info, actual_email_info): self.assertDictEqual(exp_email, act_email) - self.assertEqual(expected_email_info, actual_email_info) + assert expected_email_info == actual_email_info def test_content_list_one_email(self, task_history_request): """ Test listing of bulk emails when email list has one email """ response = self.get_email_content_response(1, task_history_request) - self.assertTrue(task_history_request.called) + assert task_history_request.called email_info = json.loads(response.content.decode('utf-8'))['emails'] # Emails list should have one email - self.assertEqual(len(email_info), 1) + assert len(email_info) == 1 # Email content should be what's expected expected_message = self.emails[0].html_message returned_email_info = email_info[0] received_message = returned_email_info[u'email'][u'html_message'] - self.assertEqual(expected_message, received_message) + assert expected_message == received_message def test_content_list_no_emails(self, task_history_request): """ Test listing of bulk emails when email list empty """ response = self.get_email_content_response(0, task_history_request) - self.assertTrue(task_history_request.called) + assert task_history_request.called email_info = json.loads(response.content.decode('utf-8'))['emails'] # Emails list should be empty - self.assertEqual(len(email_info), 0) + assert len(email_info) == 0 def test_content_list_email_content_many(self, task_history_request): """ Test listing of bulk emails sent large amount of emails """ @@ -3804,14 +3719,14 @@ class TestInstructorEmailContentList(SharedModuleStoreTestCase, LoginEnrollmentT task_history_request.return_value = [invalid_task] url = reverse('list_email_content', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 - self.assertTrue(task_history_request.called) + assert task_history_request.called returned_email_info = json.loads(response.content.decode('utf-8'))['emails'] - self.assertEqual(len(returned_email_info), 1) + assert len(returned_email_info) == 1 returned_info = returned_email_info[0] for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']: - self.assertEqual(returned_info[info], None) + assert returned_info[info] is None def test_list_email_with_failure(self, task_history_request): """ Test the handling of email task that had failures """ @@ -3830,12 +3745,12 @@ class TestInstructorEmailContentList(SharedModuleStoreTestCase, LoginEnrollmentT with patch('lms.djangoapps.instructor.views.api.CourseEmail.objects.get') as mock_email_info: mock_email_info.return_value = email response = self.client.post(url, {}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 - self.assertTrue(task_history_request.called) + assert task_history_request.called returned_info_list = json.loads(response.content.decode('utf-8'))['emails'] - self.assertEqual(len(returned_info_list), 1) + assert len(returned_info_list) == 1 returned_info = returned_info_list[0] expected_info = email_info.to_dict() self.assertDictEqual(expected_info, returned_info) @@ -3853,23 +3768,20 @@ class TestInstructorAPIHelpers(TestCase): 'ut@lacinia.Sed']) for (stng, lst) in zip(strings, lists): - self.assertEqual(_split_input_list(stng), lst) + assert _split_input_list(stng) == lst def test_split_input_list_unicode(self): - self.assertEqual(_split_input_list('robot@robot.edu, robot2@robot.edu'), - ['robot@robot.edu', 'robot2@robot.edu']) - self.assertEqual(_split_input_list(u'robot@robot.edu, robot2@robot.edu'), - ['robot@robot.edu', 'robot2@robot.edu']) - self.assertEqual(_split_input_list(u'robot@robot.edu, robot2@robot.edu'), - [u'robot@robot.edu', 'robot2@robot.edu']) + assert _split_input_list('robot@robot.edu, robot2@robot.edu') == ['robot@robot.edu', 'robot2@robot.edu'] + assert _split_input_list(u'robot@robot.edu, robot2@robot.edu') == ['robot@robot.edu', 'robot2@robot.edu'] + assert _split_input_list(u'robot@robot.edu, robot2@robot.edu') == [u'robot@robot.edu', 'robot2@robot.edu'] scary_unistuff = unichr(40960) + u'abcd' + unichr(1972) - self.assertEqual(_split_input_list(scary_unistuff), [scary_unistuff]) + assert _split_input_list(scary_unistuff) == [scary_unistuff] def test_msk_from_problem_urlname(self): course_id = CourseKey.from_string('MITx/6.002x/2013_Spring') name = 'L2Node1' output = 'i4x://MITx/6.002x/problem/L2Node1' - self.assertEqual(text_type(msk_from_problem_urlname(course_id, name)), output) + assert text_type(msk_from_problem_urlname(course_id, name)) == output def test_msk_from_problem_urlname_error(self): args = ('notagoodcourse', 'L2Node1') @@ -3991,9 +3903,9 @@ class TestDueDateExtensions(SharedModuleStoreTestCase, LoginEnrollmentTestCase): 'url': text_type(self.week1.location), 'due_datetime': '12/30/2013 00:00' }) - self.assertEqual(response.status_code, 200, response.content) - self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=UTC), - get_extended_due(self.course, self.week1, self.user1)) + assert response.status_code == 200, response.content + assert datetime.datetime(2013, 12, 30, 0, 0, tzinfo=UTC) ==\ + get_extended_due(self.course, self.week1, self.user1) def test_change_to_invalid_due_date(self): url = reverse('change_due_date', kwargs={'course_id': text_type(self.course.id)}) @@ -4002,11 +3914,8 @@ class TestDueDateExtensions(SharedModuleStoreTestCase, LoginEnrollmentTestCase): 'url': text_type(self.week1.location), 'due_datetime': '01/01/2009 00:00' }) - self.assertEqual(response.status_code, 400, response.content) - self.assertEqual( - None, - get_extended_due(self.course, self.week1, self.user1) - ) + assert response.status_code == 400, response.content + assert get_extended_due(self.course, self.week1, self.user1) is None def test_change_nonexistent_due_date(self): url = reverse('change_due_date', kwargs={'course_id': text_type(self.course.id)}) @@ -4015,11 +3924,8 @@ class TestDueDateExtensions(SharedModuleStoreTestCase, LoginEnrollmentTestCase): 'url': text_type(self.week3.location), 'due_datetime': '12/30/2013 00:00' }) - self.assertEqual(response.status_code, 400, response.content) - self.assertEqual( - None, - get_extended_due(self.course, self.week3, self.user1) - ) + assert response.status_code == 400, response.content + assert get_extended_due(self.course, self.week3, self.user1) is None @override_experiment_waffle_flag(RELATIVE_DATES_FLAG, active=True) def test_reset_date(self): @@ -4029,24 +3935,21 @@ class TestDueDateExtensions(SharedModuleStoreTestCase, LoginEnrollmentTestCase): 'student': self.user1.username, 'url': text_type(self.week1.location), }) - self.assertEqual(response.status_code, 200, response.content) - self.assertEqual( - self.due, - get_extended_due(self.course, self.week1, self.user1) - ) + assert response.status_code == 200, response.content + assert self.due == get_extended_due(self.course, self.week1, self.user1) @override_experiment_waffle_flag(RELATIVE_DATES_FLAG, active=True) def test_reset_date_only_in_edx_when(self): # Start with a unit that only has a date in edx-when - self.assertEqual(get_date_for_block(self.course, self.week3, self.user1), None) + assert get_date_for_block(self.course, self.week3, self.user1) is None original_due = datetime.datetime(2010, 4, 1, tzinfo=UTC) set_date_for_block(self.course.id, self.week3.location, 'due', original_due) - self.assertEqual(get_date_for_block(self.course, self.week3, self.user1), original_due) + assert get_date_for_block(self.course, self.week3, self.user1) == original_due # set override, confirm it took override = datetime.datetime(2010, 7, 1, tzinfo=UTC) set_date_for_block(self.course.id, self.week3.location, 'due', override, user=self.user1) - self.assertEqual(get_date_for_block(self.course, self.week3, self.user1), override) + assert get_date_for_block(self.course, self.week3, self.user1) == override # Now test that we noticed the edx-when date url = reverse('reset_due_date', kwargs={'course_id': text_type(self.course.id)}) @@ -4055,34 +3958,30 @@ class TestDueDateExtensions(SharedModuleStoreTestCase, LoginEnrollmentTestCase): 'url': text_type(self.week3.location), }) self.assertContains(response, 'Successfully reset due date for student') - self.assertEqual(get_date_for_block(self.course, self.week3, self.user1), original_due) + assert get_date_for_block(self.course, self.week3, self.user1) == original_due def test_show_unit_extensions(self): self.test_change_due_date() url = reverse('show_unit_extensions', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'url': text_type(self.week1.location)}) - self.assertEqual(response.status_code, 200, response.content) - self.assertEqual(json.loads(response.content.decode('utf-8')), { - u'data': [{u'Extended Due Date': u'2013-12-30 00:00', - u'Full Name': self.user1.profile.name, - u'Username': self.user1.username}], - u'header': [u'Username', u'Full Name', u'Extended Due Date'], - u'title': u'Users with due date extensions for %s' % - self.week1.display_name}) + assert response.status_code == 200, response.content + assert json.loads(response.content.decode('utf-8')) ==\ + {u'data': [{u'Extended Due Date': u'2013-12-30 00:00', + u'Full Name': self.user1.profile.name, u'Username': self.user1.username}], + u'header': [u'Username', u'Full Name', u'Extended Due Date'], + u'title': (u'Users with due date extensions for %s' % self.week1.display_name)} def test_show_student_extensions(self): self.test_change_due_date() url = reverse('show_student_extensions', kwargs={'course_id': text_type(self.course.id)}) response = self.client.post(url, {'student': self.user1.username}) - self.assertEqual(response.status_code, 200, response.content) - self.assertEqual(json.loads(response.content.decode('utf-8')), { - u'data': [{u'Extended Due Date': u'2013-12-30 00:00', - u'Unit': self.week1.display_name}], - u'header': [u'Unit', u'Extended Due Date'], - u'title': u'Due date extensions for %s (%s)' % ( - self.user1.profile.name, self.user1.username)}) + assert response.status_code == 200, response.content + assert json.loads(response.content.decode('utf-8')) ==\ + {u'data': [{u'Extended Due Date': u'2013-12-30 00:00', u'Unit': self.week1.display_name}], + u'header': [u'Unit', u'Extended Due Date'], + u'title': (u'Due date extensions for %s (%s)' % (self.user1.profile.name, self.user1.username))} class TestDueDateExtensionsDeletedDate(ModuleStoreTestCase, LoginEnrollmentTestCase): @@ -4181,9 +4080,9 @@ class TestDueDateExtensionsDeletedDate(ModuleStoreTestCase, LoginEnrollmentTestC 'url': text_type(self.week1.location), 'due_datetime': '12/30/2013 00:00' }) - self.assertEqual(response.status_code, 200, response.content) - self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=UTC), - get_extended_due(self.course, self.week1, self.user1)) + assert response.status_code == 200, response.content + assert datetime.datetime(2013, 12, 30, 0, 0, tzinfo=UTC) ==\ + get_extended_due(self.course, self.week1, self.user1) self.week1.due = None self.week1 = self.store.update_item(self.week1, self.user1.id) @@ -4194,11 +4093,8 @@ class TestDueDateExtensionsDeletedDate(ModuleStoreTestCase, LoginEnrollmentTestC 'student': self.user1.username, 'url': text_type(self.week1.location), }) - self.assertEqual(response.status_code, 200, response.content) - self.assertEqual( - self.due, - get_extended_due(self.course, self.week1, self.user1) - ) + assert response.status_code == 200, response.content + assert self.due == get_extended_due(self.course, self.week1, self.user1) class TestCourseIssuedCertificatesData(SharedModuleStoreTestCase): @@ -4239,15 +4135,15 @@ class TestCourseIssuedCertificatesData(SharedModuleStoreTestCase): response = self.client.post(url) res_json = json.loads(response.content.decode('utf-8')) - self.assertIn('certificates', res_json) - self.assertEqual(len(res_json['certificates']), 0) + assert 'certificates' in res_json + assert len(res_json['certificates']) == 0 # Certificates with status 'downloadable' should be in response. self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable) response = self.client.post(url) res_json = json.loads(response.content.decode('utf-8')) - self.assertIn('certificates', res_json) - self.assertEqual(len(res_json['certificates']), 1) + assert 'certificates' in res_json + assert len(res_json['certificates']) == 1 def test_certificates_features_group_by_mode(self): """ @@ -4261,14 +4157,14 @@ class TestCourseIssuedCertificatesData(SharedModuleStoreTestCase): response = self.client.post(url) res_json = json.loads(response.content.decode('utf-8')) - self.assertIn('certificates', res_json) - self.assertEqual(len(res_json['certificates']), 1) + assert 'certificates' in res_json + assert len(res_json['certificates']) == 1 # retrieve the first certificate from the list, there should be 3 certificates for 'honor' mode. certificate = res_json['certificates'][0] - self.assertEqual(certificate.get('total_issued_certificate'), 3) - self.assertEqual(certificate.get('mode'), 'honor') - self.assertEqual(certificate.get('course_id'), str(self.course.id)) + assert certificate.get('total_issued_certificate') == 3 + assert certificate.get('mode') == 'honor' + assert certificate.get('course_id') == str(self.course.id) # Now generating downloadable certificates with 'verified' mode for __ in range(certificate_count): @@ -4280,15 +4176,15 @@ class TestCourseIssuedCertificatesData(SharedModuleStoreTestCase): response = self.client.post(url) res_json = json.loads(response.content.decode('utf-8')) - self.assertIn('certificates', res_json) + assert 'certificates' in res_json # total certificate count should be 2 for 'verified' mode. - self.assertEqual(len(res_json['certificates']), 2) + assert len(res_json['certificates']) == 2 # retrieve the second certificate from the list certificate = res_json['certificates'][1] - self.assertEqual(certificate.get('total_issued_certificate'), 3) - self.assertEqual(certificate.get('mode'), 'verified') + assert certificate.get('total_issued_certificate') == 3 + assert certificate.get('mode') == 'verified' def test_certificates_features_csv(self): """ @@ -4302,13 +4198,11 @@ class TestCourseIssuedCertificatesData(SharedModuleStoreTestCase): current_date = datetime.date.today().strftime(u"%B %d, %Y") response = self.client.get(url, {'csv': 'true'}) - self.assertEqual(response['Content-Type'], 'text/csv') - self.assertEqual(response['Content-Disposition'], u'attachment; filename={0}'.format('issued_certificates.csv')) - self.assertEqual( - response.content.strip().decode('utf-8'), - '"CourseID","Certificate Type","Total Certificates Issued","Date Report Run"\r\n"' - + str(self.course.id) + '","honor","3","' + current_date + '"' - ) + assert response['Content-Type'] == 'text/csv' + assert response['Content-Disposition'] == u'attachment; filename={0}'.format('issued_certificates.csv') + assert response.content.strip().decode('utf-8') == \ + (((('"CourseID","Certificate Type","Total Certificates Issued","Date Report Run"\r\n"' + + str(self.course.id)) + '","honor","3","') + current_date) + '"') class TestBulkCohorting(SharedModuleStoreTestCase): @@ -4345,9 +4239,9 @@ class TestBulkCohorting(SharedModuleStoreTestCase): """ self.client.login(username=self.staff_user.username, password='test') response = self.call_add_users_to_cohorts(file_content, suffix=file_suffix) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 result = json.loads(response.content.decode('utf-8')) - self.assertEqual(result['error'], error) + assert result['error'] == error def verify_success_on_file_content(self, file_content, mock_store_upload, mock_cohort_task): """ @@ -4358,9 +4252,9 @@ class TestBulkCohorting(SharedModuleStoreTestCase): mock_store_upload.return_value = (None, 'fake_file_name.csv') self.client.login(username=self.staff_user.username, password='test') response = self.call_add_users_to_cohorts(file_content) - self.assertEqual(response.status_code, 204) - self.assertTrue(mock_store_upload.called) - self.assertTrue(mock_cohort_task.called) + assert response.status_code == 204 + assert mock_store_upload.called + assert mock_cohort_task.called def test_no_cohort_field(self): """ @@ -4404,7 +4298,7 @@ class TestBulkCohorting(SharedModuleStoreTestCase): """ self.client.login(username=self.non_staff_user.username, password='test') response = self.call_add_users_to_cohorts('') - self.assertEqual(response.status_code, 403) + assert response.status_code == 403 @patch('lms.djangoapps.instructor_task.api.submit_cohort_students') @patch('lms.djangoapps.instructor.views.api.store_uploaded_file') diff --git a/lms/djangoapps/instructor/tests/test_api_email_localization.py b/lms/djangoapps/instructor/tests/test_api_email_localization.py index 4deae182e3..febed0910d 100644 --- a/lms/djangoapps/instructor/tests/test_api_email_localization.py +++ b/lms/djangoapps/instructor/tests/test_api_email_localization.py @@ -63,9 +63,9 @@ class TestInstructorAPIEnrollmentEmailLocalization(SharedModuleStoreTestCase): Check that the email outbox contains exactly one message for which both the message subject and body contain a certain string. """ - self.assertEqual(1, len(mail.outbox)) - self.assertIn(expected_message, mail.outbox[0].subject) - self.assertIn(expected_message, mail.outbox[0].body) + assert 1 == len(mail.outbox) + assert expected_message in mail.outbox[0].subject + assert expected_message in mail.outbox[0].body def test_enroll(self): self.update_enrollement("enroll", self.student.email) diff --git a/lms/djangoapps/instructor/tests/test_certificates.py b/lms/djangoapps/instructor/tests/test_certificates.py index 6c0c423a2a..b3c642ae27 100644 --- a/lms/djangoapps/instructor/tests/test_certificates.py +++ b/lms/djangoapps/instructor/tests/test_certificates.py @@ -5,7 +5,7 @@ import contextlib import io import json from datetime import datetime, timedelta - +import pytest import ddt import mock import pytz @@ -241,12 +241,12 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): # Instructors do not have access self.client.login(username=self.instructor.username, password='test') response = self.client.post(url) - self.assertEqual(response.status_code, 403) + assert response.status_code == 403 # Global staff have access self.client.login(username=self.global_staff.username, password='test') response = self.client.post(url) - self.assertEqual(response.status_code, 302) + assert response.status_code == 302 def test_generate_example_certificates(self): self.client.login(username=self.global_staff.username, password='test') @@ -263,7 +263,7 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): # Cert generation will fail here because XQueue isn't configured, # but the status should at least not be None. status = certs_api.example_certificates_status(self.course.id) - self.assertIsNot(status, None) + assert status is not None @ddt.data(True, False) def test_enable_certificate_generation(self, is_enabled): @@ -280,7 +280,7 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): # Expect that certificate generation is now enabled for the course actual_enabled = certs_api.cert_generation_enabled(self.course.id) - self.assertEqual(is_enabled, actual_enabled) + assert is_enabled == actual_enabled def _assert_redirects_to_instructor_dash(self, response): """Check that the response redirects to the certificates section. """ @@ -304,11 +304,11 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): ) response = self.client.post(url) - self.assertEqual(response.status_code, 403) + assert response.status_code == 403 self.client.login(username=self.instructor.username, password='test') response = self.client.post(url) - self.assertEqual(response.status_code, 403) + assert response.status_code == 403 def test_certificate_generation_api_with_global_staff(self): """ @@ -322,10 +322,10 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): ) response = self.client.post(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) - self.assertIsNotNone(res_json['message']) - self.assertIsNotNone(res_json['task_id']) + assert res_json['message'] is not None + assert res_json['task_id'] is not None def test_certificate_regeneration_success(self): """ @@ -347,18 +347,16 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): response = self.client.post(url, data={'certificate_statuses': [CertificateStatuses.downloadable]}) # Assert 200 status code in response - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) # Assert request is successful - self.assertTrue(res_json['success']) + assert res_json['success'] # Assert success message - self.assertEqual( - res_json['message'], - u'Certificate regeneration task has been started. You can view the status of the generation task in ' - u'the "Pending Tasks" section.' - ) + assert res_json['message'] ==\ + u'Certificate regeneration task has been started.' \ + u' You can view the status of the generation task in the "Pending Tasks" section.' @override_settings(AUDIT_CERT_CUTOFF_DATE=datetime.now(pytz.UTC) - timedelta(days=1)) @ddt.data( @@ -379,7 +377,7 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): """ # Check that user is enrolled in audit mode. enrollment = CourseEnrollment.get_enrollment(self.user, self.course.id) - self.assertEqual(enrollment.mode, CourseMode.AUDIT) + assert enrollment.mode == CourseMode.AUDIT with mock_passing_grade(): # Generate certificate for user and check that user has a audit passing certificate. @@ -390,11 +388,11 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): ) # Check that certificate status is 'audit_passing'. - self.assertEqual(cert_status, CertificateStatuses.audit_passing) + assert cert_status == CertificateStatuses.audit_passing # Update user enrollment mode to verified mode. enrollment.update_enrollment(mode=CourseMode.VERIFIED) - self.assertEqual(enrollment.mode, CourseMode.VERIFIED) + assert enrollment.mode == CourseMode.VERIFIED # Create and assert user's ID verification record. SoftwareSecurePhotoVerificationFactory.create(user=self.user, status=id_verification_status) @@ -402,7 +400,7 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): self.user, enrollment.mode ) - self.assertEqual(actual_verification_status, verification_output) + assert actual_verification_status == verification_output # Login the client and access the url with 'audit_passing' status. self.client.login(username=self.global_staff.username, password='test') @@ -419,24 +417,21 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): ) # Assert 200 status code in response - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) # Assert request is successful - self.assertTrue(res_json['success']) + assert res_json['success'] # Assert success message - self.assertEqual( - res_json['message'], - u'Certificate regeneration task has been started. ' - u'You can view the status of the generation task in ' - u'the "Pending Tasks" section.' - ) + assert res_json['message'] ==\ + u'Certificate regeneration task has been started.' \ + u' You can view the status of the generation task in the "Pending Tasks" section.' # Now, check whether user has audit certificate. cert = certs_api.get_certificate_for_user(self.user.username, self.course.id) - self.assertNotEqual(cert['status'], CertificateStatuses.audit_passing) - self.assertEqual(cert['status'], expected_cert_status) + assert cert['status'] != CertificateStatuses.audit_passing + assert cert['status'] == expected_cert_status def test_certificate_regeneration_error(self): """ @@ -460,25 +455,23 @@ class CertificatesInstructorApiTest(SharedModuleStoreTestCase): response = self.client.post(url) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Error Message - self.assertEqual( - res_json['message'], - u'Please select one or more certificate statuses that require certificate regeneration.' - ) + assert res_json['message'] ==\ + u'Please select one or more certificate statuses that require certificate regeneration.' # Access the url passing 'certificate_statuses' that are not present in db url = reverse('start_certificate_regeneration', kwargs={'course_id': six.text_type(self.course.id)}) response = self.client.post(url, data={'certificate_statuses': [CertificateStatuses.generating]}) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Error Message - self.assertEqual(res_json['message'], u'Please select certificate statuses from the list only.') + assert res_json['message'] == u'Please select certificate statuses from the list only.' @override_settings(CERT_QUEUE='certificates') @@ -537,13 +530,13 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): content_type='application/json' ) # Assert successful request processing - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 certificate_exception = json.loads(response.content.decode('utf-8')) # Assert Certificate Exception Updated data - self.assertEqual(certificate_exception['user_email'], self.user.email) - self.assertEqual(certificate_exception['user_name'], self.user.username) - self.assertEqual(certificate_exception['user_id'], self.user.id) + assert certificate_exception['user_email'] == self.user.email + assert certificate_exception['user_name'] == self.user.username + assert certificate_exception['user_id'] == self.user.id def test_certificate_exception_invalid_username_error(self): """ @@ -559,17 +552,14 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Request not successful - self.assertFalse(res_json['success']) + assert not res_json['success'] # Assert Error Message - self.assertEqual( - res_json['message'], - u"{user} does not exist in the LMS. Please check your spelling and retry.".format(user=invalid_user) - ) + assert res_json['message'] == f'{invalid_user} does not exist in the LMS. Please check your spelling and retry.' def test_certificate_exception_missing_username_and_email_error(self): """ @@ -584,18 +574,16 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Request not successful - self.assertFalse(res_json['success']) + assert not res_json['success'] # Assert Error Message - self.assertEqual( - res_json['message'], - u'Student username/email field is required and can not be empty. ' - u'Kindly fill in username/email and then press "Add to Exception List" button.' - ) + assert res_json['message'] ==\ + u'Student username/email field is required and can not be empty.' \ + u' Kindly fill in username/email and then press "Add to Exception List" button.' def test_certificate_exception_duplicate_user_error(self): """ @@ -609,18 +597,15 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Request not successful - self.assertFalse(res_json['success']) + assert not res_json['success'] user = self.certificate_exception_in_db['user_name'] # Assert Error Message - self.assertEqual( - res_json['message'], - u"Student (username/email={user_name}) already in certificate exception list.".format(user_name=user) - ) + assert res_json['message'] == f'Student (username/email={user}) already in certificate exception list.' def test_certificate_exception_same_user_in_two_different_courses(self): """ @@ -632,13 +617,13 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): data=json.dumps(self.certificate_exception), content_type='application/json' ) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 certificate_exception = json.loads(response.content.decode('utf-8')) # Assert Certificate Exception Updated data - self.assertEqual(certificate_exception['user_email'], self.user.email) - self.assertEqual(certificate_exception['user_name'], self.user.username) - self.assertEqual(certificate_exception['user_id'], self.user.id) + assert certificate_exception['user_email'] == self.user.email + assert certificate_exception['user_name'] == self.user.username + assert certificate_exception['user_id'] == self.user.id course2 = CourseFactory.create() url_course2 = reverse( @@ -653,13 +638,13 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): content_type='application/json' ) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 certificate_exception = json.loads(response.content.decode('utf-8')) # Assert Certificate Exception Updated data - self.assertEqual(certificate_exception['user_email'], self.user.email) - self.assertEqual(certificate_exception['user_name'], self.user.username) - self.assertEqual(certificate_exception['user_id'], self.user.id) + assert certificate_exception['user_email'] == self.user.email + assert certificate_exception['user_name'] == self.user.username + assert certificate_exception['user_id'] == self.user.id def test_certificate_exception_user_not_enrolled_error(self): """ @@ -675,19 +660,15 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Request not successful - self.assertFalse(res_json['success']) + assert not res_json['success'] # Assert Error Message - self.assertEqual( - res_json['message'], - u"{user} is not enrolled in this course. Please check your spelling and retry.".format( - user=self.certificate_exception['user_name'] - ) - ) + assert res_json['message'] == u'{user} is not enrolled in this course. Please check your spelling and retry.'\ + .format(user=self.certificate_exception['user_name']) def test_certificate_exception_removed_successfully(self): """ @@ -707,10 +688,10 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): REQUEST_METHOD='DELETE' ) # Assert successful request processing - self.assertEqual(response.status_code, 204) + assert response.status_code == 204 # Verify that certificate exception successfully removed from CertificateWhitelist and GeneratedCertificate - with self.assertRaises(ObjectDoesNotExist): + with pytest.raises(ObjectDoesNotExist): CertificateWhitelist.objects.get(user=self.user2, course_id=self.course.id) GeneratedCertificate.eligible_certificates.get( user=self.user2, course_id=self.course.id, status__not=CertificateStatuses.unavailable @@ -729,17 +710,15 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): REQUEST_METHOD='DELETE' ) # Assert error on request - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Request not successful - self.assertFalse(res_json['success']) + assert not res_json['success'] # Assert Error Message - self.assertEqual( - res_json['message'], - u"The record is not in the correct format. Please add a valid username or email address." - ) + assert res_json['message'] ==\ + u'The record is not in the correct format. Please add a valid username or email address.' def test_remove_certificate_exception_non_existing_error(self): """ @@ -753,18 +732,16 @@ class CertificateExceptionViewInstructorApiTest(SharedModuleStoreTestCase): REQUEST_METHOD='DELETE' ) # Assert error on request - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Request not successful - self.assertFalse(res_json['success']) + assert not res_json['success'] # Assert Error Message - self.assertEqual( - res_json['message'], - u"Certificate exception (user={user}) does not exist in certificate white list. " - u"Please refresh the page and try again.".format(user=self.certificate_exception['user_name']) - ) + assert res_json['message'] ==\ + u'Certificate exception (user={user}) does not exist in certificate white list.' \ + u' Please refresh the page and try again.'.format(user=self.certificate_exception['user_name']) @override_settings(CERT_QUEUE='certificates') @@ -815,17 +792,14 @@ class GenerateCertificatesInstructorApiTest(SharedModuleStoreTestCase): content_type='application/json' ) # Assert Success - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) # Assert Request is successful - self.assertTrue(res_json['success']) + assert res_json['success'] # Assert Message - self.assertEqual( - res_json['message'], - u"Certificate generation started for white listed students." - ) + assert res_json['message'] == u'Certificate generation started for white listed students.' def test_generate_certificate_exceptions_whitelist_not_generated(self): """ @@ -843,17 +817,14 @@ class GenerateCertificatesInstructorApiTest(SharedModuleStoreTestCase): ) # Assert Success - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 res_json = json.loads(response.content.decode('utf-8')) # Assert Request is successful - self.assertTrue(res_json['success']) + assert res_json['success'] # Assert Message - self.assertEqual( - res_json['message'], - u"Certificate generation started for white listed students." - ) + assert res_json['message'] == u'Certificate generation started for white listed students.' def test_generate_certificate_exceptions_generate_for_incorrect_value(self): """ @@ -871,17 +842,14 @@ class GenerateCertificatesInstructorApiTest(SharedModuleStoreTestCase): ) # Assert Failure - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Request is not successful - self.assertFalse(res_json['success']) + assert not res_json['success'] # Assert Message - self.assertEqual( - res_json['message'], - u'Invalid data, generate_for must be "new" or "all".' - ) + assert res_json['message'] == u'Invalid data, generate_for must be "new" or "all".' @ddt.ddt @@ -931,13 +899,13 @@ class TestCertificatesInstructorApiBulkWhiteListExceptions(SharedModuleStoreTest csv_content = b"test_student1@example.com,dummy_notes\n" \ b"test_student2@example.com,dummy_notes" data = self.upload_file(csv_content=csv_content) - self.assertEqual(len(data['general_errors']), 0) - self.assertEqual(len(data['row_errors']['data_format_error']), 0) - self.assertEqual(len(data['row_errors']['user_not_exist']), 0) - self.assertEqual(len(data['row_errors']['user_already_white_listed']), 0) - self.assertEqual(len(data['row_errors']['user_not_enrolled']), 0) - self.assertEqual(len(data['success']), 2) - self.assertEqual(len(CertificateWhitelist.objects.all()), 2) + assert len(data['general_errors']) == 0 + assert len(data['row_errors']['data_format_error']) == 0 + assert len(data['row_errors']['user_not_exist']) == 0 + assert len(data['row_errors']['user_already_white_listed']) == 0 + assert len(data['row_errors']['user_not_enrolled']) == 0 + assert len(data['success']) == 2 + assert len(CertificateWhitelist.objects.all()) == 2 def test_invalid_data_format_in_csv(self): """ @@ -947,10 +915,10 @@ class TestCertificatesInstructorApiBulkWhiteListExceptions(SharedModuleStoreTest b"test_student2@example.com,test,1" data = self.upload_file(csv_content=csv_content) - self.assertEqual(len(data['row_errors']['data_format_error']), 2) - self.assertEqual(len(data['general_errors']), 0) - self.assertEqual(len(data['success']), 0) - self.assertEqual(len(CertificateWhitelist.objects.all()), 0) + assert len(data['row_errors']['data_format_error']) == 2 + assert len(data['general_errors']) == 0 + assert len(data['success']) == 0 + assert len(CertificateWhitelist.objects.all()) == 0 def test_file_upload_type_not_csv(self): """ @@ -958,11 +926,11 @@ class TestCertificatesInstructorApiBulkWhiteListExceptions(SharedModuleStoreTest """ uploaded_file = SimpleUploadedFile("temp.jpg", io.BytesIO(b"some initial binary data: \x00\x01").read()) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertNotEqual(len(data['general_errors']), 0) - self.assertEqual(data['general_errors'][0], 'Make sure that the file you upload is in CSV format with ' - 'no extraneous characters or rows.') + assert len(data['general_errors']) != 0 + assert data['general_errors'][0] ==\ + 'Make sure that the file you upload is in CSV format with no extraneous characters or rows.' def test_bad_file_upload_type(self): """ @@ -970,10 +938,10 @@ class TestCertificatesInstructorApiBulkWhiteListExceptions(SharedModuleStoreTest """ uploaded_file = SimpleUploadedFile("temp.csv", io.BytesIO(b"some initial binary data: \x00\x01").read()) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertNotEqual(len(data['general_errors']), 0) - self.assertEqual(data['general_errors'][0], 'Could not read uploaded file.') + assert len(data['general_errors']) != 0 + assert data['general_errors'][0] == 'Could not read uploaded file.' def test_invalid_email_in_csv(self): """ @@ -982,9 +950,9 @@ class TestCertificatesInstructorApiBulkWhiteListExceptions(SharedModuleStoreTest csv_content = b"test_student.example.com,dummy_notes" data = self.upload_file(csv_content=csv_content) - self.assertEqual(len(data['row_errors']['user_not_exist']), 1) - self.assertEqual(len(data['success']), 0) - self.assertEqual(len(CertificateWhitelist.objects.all()), 0) + assert len(data['row_errors']['user_not_exist']) == 1 + assert len(data['success']) == 0 + assert len(CertificateWhitelist.objects.all()) == 0 def test_csv_user_not_enrolled(self): """ @@ -993,9 +961,9 @@ class TestCertificatesInstructorApiBulkWhiteListExceptions(SharedModuleStoreTest csv_content = b"nonenrolled@test.com,dummy_notes" data = self.upload_file(csv_content=csv_content) - self.assertEqual(len(data['row_errors']['user_not_enrolled']), 1) - self.assertEqual(len(data['general_errors']), 0) - self.assertEqual(len(data['success']), 0) + assert len(data['row_errors']['user_not_enrolled']) == 1 + assert len(data['general_errors']) == 0 + assert len(data['success']) == 0 def test_certificate_exception_already_exist(self): """ @@ -1009,10 +977,10 @@ class TestCertificatesInstructorApiBulkWhiteListExceptions(SharedModuleStoreTest ) csv_content = b"test_student1@example.com,dummy_notes" data = self.upload_file(csv_content=csv_content) - self.assertEqual(len(data['row_errors']['user_already_white_listed']), 1) - self.assertEqual(len(data['general_errors']), 0) - self.assertEqual(len(data['success']), 0) - self.assertEqual(len(CertificateWhitelist.objects.all()), 1) + assert len(data['row_errors']['user_already_white_listed']) == 1 + assert len(data['general_errors']) == 0 + assert len(data['success']) == 0 + assert len(CertificateWhitelist.objects.all()) == 1 def test_csv_file_not_attached(self): """ @@ -1024,10 +992,10 @@ class TestCertificatesInstructorApiBulkWhiteListExceptions(SharedModuleStoreTest uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'file_not_found': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) - self.assertEqual(len(data['general_errors']), 1) - self.assertEqual(len(data['success']), 0) + assert len(data['general_errors']) == 1 + assert len(data['success']) == 0 def upload_file(self, csv_content): """ @@ -1036,7 +1004,7 @@ class TestCertificatesInstructorApiBulkWhiteListExceptions(SharedModuleStoreTest """ uploaded_file = SimpleUploadedFile("temp.csv", csv_content) response = self.client.post(self.url, {'students_list': uploaded_file}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 data = json.loads(response.content.decode('utf-8')) return data @@ -1104,13 +1072,13 @@ class CertificateInvalidationViewTests(SharedModuleStoreTestCase): content_type='application/json', ) # Assert successful request processing - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 result = json.loads(response.content.decode('utf-8')) # Assert Certificate Exception Updated data - self.assertEqual(result['user'], self.enrolled_user_1.username) - self.assertEqual(result['invalidated_by'], self.global_staff.username) - self.assertEqual(result['notes'], self.notes) + assert result['user'] == self.enrolled_user_1.username + assert result['invalidated_by'] == self.global_staff.username + assert result['notes'] == self.notes # Verify that CertificateInvalidation record has been created in the database i.e. no DoesNotExist error try: @@ -1128,7 +1096,7 @@ class CertificateInvalidationViewTests(SharedModuleStoreTestCase): user=self.enrolled_user_1, course_id=self.course.id, ) - self.assertFalse(generated_certificate.is_valid()) + assert not generated_certificate.is_valid() def test_missing_username_and_email_error(self): """ @@ -1142,15 +1110,13 @@ class CertificateInvalidationViewTests(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Error Message - self.assertEqual( - res_json['message'], - u'Student username/email field is required and can not be empty. ' - u'Kindly fill in username/email and then press "Invalidate Certificate" button.', - ) + assert res_json['message'] == \ + u'Student username/email field is required and can not be empty.' \ + u' Kindly fill in username/email and then press "Invalidate Certificate" button.' def test_invalid_user_name_error(self): """ @@ -1167,14 +1133,11 @@ class CertificateInvalidationViewTests(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Error Message - self.assertEqual( - res_json['message'], - u"{user} does not exist in the LMS. Please check your spelling and retry.".format(user=invalid_user), - ) + assert res_json['message'] == f'{invalid_user} does not exist in the LMS. Please check your spelling and retry.' def test_user_not_enrolled_error(self): """ @@ -1189,16 +1152,12 @@ class CertificateInvalidationViewTests(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Error Message - self.assertEqual( - res_json['message'], - u"{user} is not enrolled in this course. Please check your spelling and retry.".format( - user=self.not_enrolled_student.username, - ), - ) + assert res_json['message'] == u'{user} is not enrolled in this course. Please check your spelling and retry.'\ + .format(user=self.not_enrolled_student.username) def test_no_generated_certificate_error(self): """ @@ -1213,18 +1172,11 @@ class CertificateInvalidationViewTests(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Error Message - self.assertEqual( - res_json['message'], - u"The student {student} does not have certificate for the course {course}. " - u"Kindly verify student username/email and the selected course are correct and try again.".format( - student=self.enrolled_user_2.username, - course=self.course.number, - ), - ) + assert res_json['message'] == u'The student {student} does not have certificate for the course {course}. Kindly verify student username/email and the selected course are correct and try again.'.format(student=self.enrolled_user_2.username, course=self.course.number) # pylint: disable=line-too-long def test_certificate_already_invalid_error(self): """ @@ -1240,17 +1192,11 @@ class CertificateInvalidationViewTests(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Error Message - self.assertEqual( - res_json['message'], - u"Certificate for student {user} is already invalid, kindly verify that certificate " - u"was generated for this student and then proceed.".format( - user=self.enrolled_user_1.username, - ), - ) + assert res_json['message'] == u'Certificate for student {user} is already invalid, kindly verify that certificate was generated for this student and then proceed.'.format(user=self.enrolled_user_1.username) # pylint: disable=line-too-long def test_duplicate_certificate_invalidation_error(self): """ @@ -1270,16 +1216,11 @@ class CertificateInvalidationViewTests(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Error Message - self.assertEqual( - res_json['message'], - u"Certificate of {user} has already been invalidated. Please check your spelling and retry.".format( - user=self.enrolled_user_1.username, - ), - ) + assert res_json['message'] == u'Certificate of {user} has already been invalidated. Please check your spelling and retry.'.format(user=self.enrolled_user_1.username) # pylint: disable=line-too-long def test_remove_certificate_invalidation(self): """ @@ -1301,10 +1242,10 @@ class CertificateInvalidationViewTests(SharedModuleStoreTestCase): ) # Assert 204 status code in response - self.assertEqual(response.status_code, 204) + assert response.status_code == 204 # Verify that certificate invalidation successfully removed from database - with self.assertRaises(ObjectDoesNotExist): + with pytest.raises(ObjectDoesNotExist): CertificateInvalidation.objects.get( generated_certificate=self.generated_certificate, invalidated_by=self.global_staff, @@ -1326,11 +1267,8 @@ class CertificateInvalidationViewTests(SharedModuleStoreTestCase): ) # Assert 400 status code in response - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 res_json = json.loads(response.content.decode('utf-8')) # Assert Error Message - self.assertEqual( - res_json['message'], - u"Certificate Invalidation does not exist, Please refresh the page and try again.", - ) + assert res_json['message'] == u'Certificate Invalidation does not exist, Please refresh the page and try again.' diff --git a/lms/djangoapps/instructor/tests/test_email.py b/lms/djangoapps/instructor/tests/test_email.py index 729012d20c..e990d8037b 100644 --- a/lms/djangoapps/instructor/tests/test_email.py +++ b/lms/djangoapps/instructor/tests/test_email.py @@ -51,14 +51,14 @@ class TestNewInstructorDashboardEmailViewMongoBacked(SharedModuleStoreTestCase): BulkEmailFlag.objects.create(enabled=True, require_course_email_auth=False) # Assert that instructor email is enabled for this course - since REQUIRE_COURSE_EMAIL_AUTH is False, # all courses should be authorized to use email. - self.assertTrue(is_bulk_email_feature_enabled(self.course.id)) + assert is_bulk_email_feature_enabled(self.course.id) # Assert that the URL for the email view is in the response response = self.client.get(self.url) self.assertContains(response, self.email_link) send_to_label = '
Send to:
' self.assertContains(response, send_to_label) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # The course is Mongo-backed but the flag is disabled (should not work) def test_email_flag_false_mongo_true(self): @@ -71,7 +71,7 @@ class TestNewInstructorDashboardEmailViewMongoBacked(SharedModuleStoreTestCase): def test_course_not_authorized(self): BulkEmailFlag.objects.create(enabled=True, require_course_email_auth=True) # Assert that instructor email is not enabled for this course - self.assertFalse(is_bulk_email_feature_enabled(self.course.id)) + assert not is_bulk_email_feature_enabled(self.course.id) # Assert that the URL for the email view is not in the response response = self.client.get(self.url) self.assertNotContains(response, self.email_link) @@ -80,7 +80,7 @@ class TestNewInstructorDashboardEmailViewMongoBacked(SharedModuleStoreTestCase): def test_course_authorized(self): BulkEmailFlag.objects.create(enabled=True, require_course_email_auth=True) # Assert that instructor email is not enabled for this course - self.assertFalse(is_bulk_email_feature_enabled(self.course.id)) + assert not is_bulk_email_feature_enabled(self.course.id) # Assert that the URL for the email view is not in the response response = self.client.get(self.url) self.assertNotContains(response, self.email_link) @@ -90,7 +90,7 @@ class TestNewInstructorDashboardEmailViewMongoBacked(SharedModuleStoreTestCase): cauth.save() # Assert that instructor email is enabled for this course - self.assertTrue(is_bulk_email_feature_enabled(self.course.id)) + assert is_bulk_email_feature_enabled(self.course.id) # Assert that the URL for the email view is in the response response = self.client.get(self.url) self.assertContains(response, self.email_link) @@ -103,8 +103,8 @@ class TestNewInstructorDashboardEmailViewMongoBacked(SharedModuleStoreTestCase): cauth.save() # Assert that this course is authorized for instructor email, but the feature is not enabled - self.assertFalse(is_bulk_email_feature_enabled(self.course.id)) - self.assertTrue(is_bulk_email_enabled_for_course(self.course.id)) + assert not is_bulk_email_feature_enabled(self.course.id) + assert is_bulk_email_enabled_for_course(self.course.id) # Assert that the URL for the email view IS NOT in the response response = self.client.get(self.url) self.assertNotContains(response, self.email_link) diff --git a/lms/djangoapps/instructor/tests/test_enrollment.py b/lms/djangoapps/instructor/tests/test_enrollment.py index ae2f9835f7..c4aaf04c7d 100644 --- a/lms/djangoapps/instructor/tests/test_enrollment.py +++ b/lms/djangoapps/instructor/tests/test_enrollment.py @@ -6,7 +6,7 @@ Unit tests for instructor.enrollment methods. import json from abc import ABCMeta - +import pytest import ddt import six from ccx_keys.locator import CCXLocator @@ -64,7 +64,7 @@ class TestSettableEnrollmentState(CacheIsolationTestCase): # enrollment objects eobjs = mes.create_user(self.course_key) ees = EmailEnrollmentState(self.course_key, eobjs.email) - self.assertEqual(mes, ees) + assert mes == ees class TestEnrollmentChangeBase(six.with_metaclass(ABCMeta, CacheIsolationTestCase)): @@ -94,7 +94,7 @@ class TestEnrollmentChangeBase(six.with_metaclass(ABCMeta, CacheIsolationTestCas print("checking initialization...") eobjs = before_ideal.create_user(self.course_key) before = EmailEnrollmentState(self.course_key, eobjs.email) - self.assertEqual(before, before_ideal) + assert before == before_ideal # do action print("running action...") @@ -103,7 +103,7 @@ class TestEnrollmentChangeBase(six.with_metaclass(ABCMeta, CacheIsolationTestCas # check after print("checking effects...") after = EmailEnrollmentState(self.course_key, eobjs.email) - self.assertEqual(after, after_ideal) + assert after == after_ideal @ddt.ddt @@ -234,7 +234,7 @@ class TestInstructorEnrollDB(TestEnrollmentChangeBase): print("checking initialization...") eobjs = before_ideal.create_user(self.course_key, is_active=False) before = EmailEnrollmentState(self.course_key, eobjs.email) - self.assertEqual(before, before_ideal) + assert before == before_ideal print('running action...') enroll_email(self.course_key, eobjs.email, auto_enroll=auto_enroll) @@ -248,7 +248,7 @@ class TestInstructorEnrollDB(TestEnrollmentChangeBase): auto_enroll=auto_enroll, ) after = EmailEnrollmentState(self.course_key, eobjs.email) - self.assertEqual(after, after_ideal) + assert after == after_ideal @ddt.data(True, False) def test_enroll_inactive_user_again(self, auto_enroll): @@ -272,7 +272,7 @@ class TestInstructorEnrollDB(TestEnrollmentChangeBase): ) ) before = EmailEnrollmentState(course_key, eobjs.email) - self.assertEqual(before, before_ideal) + assert before == before_ideal print('running action...') enroll_email(self.course_key, eobjs.email, auto_enroll=auto_enroll) @@ -286,7 +286,7 @@ class TestInstructorEnrollDB(TestEnrollmentChangeBase): auto_enroll=auto_enroll, ) after = EmailEnrollmentState(self.course_key, eobjs.email) - self.assertEqual(after, after_ideal) + assert after == after_ideal class TestInstructorUnenrollDB(TestEnrollmentChangeBase): @@ -440,9 +440,9 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): ) # lambda to reload the module state from the database module = lambda: StudentModule.objects.get(student=self.user, course_id=self.course_key, module_state_key=msk) - self.assertEqual(json.loads(module().state)['attempts'], 32) + assert json.loads(module().state)['attempts'] == 32 reset_student_attempts(self.course_key, self.user, msk, requesting_user=self.user) - self.assertEqual(json.loads(module().state)['attempts'], 0) + assert json.loads(module().state)['attempts'] == 0 @patch('lms.djangoapps.grades.signals.handlers.PROBLEM_WEIGHTED_SCORE_CHANGED.send') def test_delete_student_attempts(self, _mock_signal): @@ -454,19 +454,15 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): module_state_key=msk, state=original_state ) - self.assertEqual( - StudentModule.objects.filter( - student=self.user, - course_id=self.course_key, - module_state_key=msk - ).count(), 1) + assert StudentModule.objects.filter( + student=self.user, + course_id=self.course_key, + module_state_key=msk).count() == 1 reset_student_attempts(self.course_key, self.user, msk, requesting_user=self.user, delete_module=True) - self.assertEqual( - StudentModule.objects.filter( - student=self.user, - course_id=self.course_key, - module_state_key=msk - ).count(), 0) + assert StudentModule.objects.filter( + student=self.user, + course_id=self.course_key, + module_state_key=msk).count() == 0 # Disable the score change signal to prevent other components from being # pulled into tests. @@ -507,7 +503,7 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): # Verify that the student's scores have been reset in the submissions API score = sub_api.get_score(student_item) - self.assertIs(score, None) + assert score is None # pylint: disable=attribute-defined-outside-init def setup_team(self): @@ -567,9 +563,9 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): self.setup_team() team_ora_location = self.team_enabled_ora.location # All teammates should have a student module (except lazy_teammate) - self.assertIsNotNone(self.get_student_module(self.user, team_ora_location)) - self.assertIsNotNone(self.get_student_module(self.teammate_a, team_ora_location)) - self.assertIsNotNone(self.get_student_module(self.teammate_b, team_ora_location)) + assert self.get_student_module(self.user, team_ora_location) is not None + assert self.get_student_module(self.teammate_a, team_ora_location) is not None + assert self.get_student_module(self.teammate_b, team_ora_location) is not None self.assert_no_student_module(self.lazy_teammate, team_ora_location) reset_student_attempts(self.course_key, self.user, team_ora_location, requesting_user=self.user) @@ -580,7 +576,7 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): def _assert_student_module(user): student_module = self.get_student_module(user, team_ora_location) - self.assertIsNotNone(student_module) + assert student_module is not None student_state = json.loads(student_module.state) self.assertDictEqual(student_state, attempt_reset_team_state_dict) @@ -595,9 +591,9 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): self.setup_team() team_ora_location = self.team_enabled_ora.location # All teammates should have a student module (except lazy_teammate) - self.assertIsNotNone(self.get_student_module(self.user, team_ora_location)) - self.assertIsNotNone(self.get_student_module(self.teammate_a, team_ora_location)) - self.assertIsNotNone(self.get_student_module(self.teammate_b, team_ora_location)) + assert self.get_student_module(self.user, team_ora_location) is not None + assert self.get_student_module(self.teammate_a, team_ora_location) is not None + assert self.get_student_module(self.teammate_b, team_ora_location) is not None self.assert_no_student_module(self.lazy_teammate, team_ora_location) reset_student_attempts( @@ -619,9 +615,9 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): CourseTeamMembership.objects.get(user=self.user, team=self.team).delete() # All teammates should have a student module (except lazy_teammate) - self.assertIsNotNone(self.get_student_module(self.user, team_ora_location)) - self.assertIsNotNone(self.get_student_module(self.teammate_a, team_ora_location)) - self.assertIsNotNone(self.get_student_module(self.teammate_b, team_ora_location)) + assert self.get_student_module(self.user, team_ora_location) is not None + assert self.get_student_module(self.teammate_a, team_ora_location) is not None + assert self.get_student_module(self.teammate_b, team_ora_location) is not None self.assert_no_student_module(self.lazy_teammate, team_ora_location) reset_student_attempts( @@ -630,13 +626,13 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): # self.user should be deleted, but no other teammates should be affected. self.assert_no_student_module(self.user, team_ora_location) - self.assertIsNotNone(self.get_student_module(self.teammate_a, team_ora_location)) - self.assertIsNotNone(self.get_student_module(self.teammate_b, team_ora_location)) + assert self.get_student_module(self.teammate_a, team_ora_location) is not None + assert self.get_student_module(self.teammate_b, team_ora_location) is not None self.assert_no_student_module(self.lazy_teammate, team_ora_location) def assert_no_student_module(self, user, location): """ Assert that there is no student module for the given user and item for self.course_key """ - with self.assertRaises(StudentModule.DoesNotExist): + with pytest.raises(StudentModule.DoesNotExist): self.get_student_module(user, location) def get_student_module(self, user, location): @@ -651,43 +647,43 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): def test_reset_student_attempts_children(self): parent_state = json.loads(self.get_state(self.parent.location)) - self.assertEqual(parent_state['attempts'], 32) - self.assertEqual(parent_state['otherstuff'], 'alsorobots') + assert parent_state['attempts'] == 32 + assert parent_state['otherstuff'] == 'alsorobots' child_state = json.loads(self.get_state(self.child.location)) - self.assertEqual(child_state['attempts'], 10) - self.assertEqual(child_state['whatever'], 'things') + assert child_state['attempts'] == 10 + assert child_state['whatever'] == 'things' unrelated_state = json.loads(self.get_state(self.unrelated.location)) - self.assertEqual(unrelated_state['attempts'], 12) - self.assertEqual(unrelated_state['brains'], 'zombie') + assert unrelated_state['attempts'] == 12 + assert unrelated_state['brains'] == 'zombie' reset_student_attempts(self.course_key, self.user, self.parent.location, requesting_user=self.user) parent_state = json.loads(self.get_state(self.parent.location)) - self.assertEqual(json.loads(self.get_state(self.parent.location))['attempts'], 0) - self.assertEqual(parent_state['otherstuff'], 'alsorobots') + assert json.loads(self.get_state(self.parent.location))['attempts'] == 0 + assert parent_state['otherstuff'] == 'alsorobots' child_state = json.loads(self.get_state(self.child.location)) - self.assertEqual(child_state['attempts'], 0) - self.assertEqual(child_state['whatever'], 'things') + assert child_state['attempts'] == 0 + assert child_state['whatever'] == 'things' unrelated_state = json.loads(self.get_state(self.unrelated.location)) - self.assertEqual(unrelated_state['attempts'], 12) - self.assertEqual(unrelated_state['brains'], 'zombie') + assert unrelated_state['attempts'] == 12 + assert unrelated_state['brains'] == 'zombie' def test_delete_submission_scores_attempts_children(self): parent_state = json.loads(self.get_state(self.parent.location)) - self.assertEqual(parent_state['attempts'], 32) - self.assertEqual(parent_state['otherstuff'], 'alsorobots') + assert parent_state['attempts'] == 32 + assert parent_state['otherstuff'] == 'alsorobots' child_state = json.loads(self.get_state(self.child.location)) - self.assertEqual(child_state['attempts'], 10) - self.assertEqual(child_state['whatever'], 'things') + assert child_state['attempts'] == 10 + assert child_state['whatever'] == 'things' unrelated_state = json.loads(self.get_state(self.unrelated.location)) - self.assertEqual(unrelated_state['attempts'], 12) - self.assertEqual(unrelated_state['brains'], 'zombie') + assert unrelated_state['attempts'] == 12 + assert unrelated_state['brains'] == 'zombie' reset_student_attempts( self.course_key, @@ -701,8 +697,8 @@ class TestInstructorEnrollmentStudentModule(SharedModuleStoreTestCase): self.assertRaises(StudentModule.DoesNotExist, self.get_state, self.child.location) unrelated_state = json.loads(self.get_state(self.unrelated.location)) - self.assertEqual(unrelated_state['attempts'], 12) - self.assertEqual(unrelated_state['brains'], 'zombie') + assert unrelated_state['attempts'] == 12 + assert unrelated_state['brains'] == 'zombie' class TestStudentModuleGrading(SharedModuleStoreTestCase): @@ -761,10 +757,10 @@ class TestStudentModuleGrading(SharedModuleStoreTestCase): get_course_blocks(self.user, self.course.location) ) grade = subsection_grade_factory.create(self.sequence) - self.assertEqual(grade.all_total.earned, all_earned) - self.assertEqual(grade.graded_total.earned, graded_earned) - self.assertEqual(grade.all_total.possible, all_possible) - self.assertEqual(grade.graded_total.possible, graded_possible) + assert grade.all_total.earned == all_earned + assert grade.graded_total.earned == graded_earned + assert grade.all_total.possible == all_possible + assert grade.graded_total.possible == graded_possible @patch('crum.get_current_request') def test_delete_student_state(self, _crum_mock): @@ -912,11 +908,11 @@ class TestGetEmailParamsCCX(SharedModuleStoreTestCase): display_name=self.ccx.display_name ) - self.assertEqual(result['display_name'], self.ccx.display_name) - self.assertEqual(result['auto_enroll'], True) - self.assertEqual(result['course_about_url'], self.course_about_url) - self.assertEqual(result['registration_url'], self.registration_url) - self.assertEqual(result['course_url'], self.course_url) + assert result['display_name'] == self.ccx.display_name + assert result['auto_enroll'] is True + assert result['course_about_url'] == self.course_about_url + assert result['registration_url'] == self.registration_url + assert result['course_url'] == self.course_url class TestGetEmailParams(SharedModuleStoreTestCase): @@ -943,10 +939,10 @@ class TestGetEmailParams(SharedModuleStoreTestCase): # Also make sure `auto_enroll` is properly passed through. result = get_email_params(self.course, False) - self.assertEqual(result['auto_enroll'], False) - self.assertEqual(result['course_about_url'], self.course_about_url) - self.assertEqual(result['registration_url'], self.registration_url) - self.assertEqual(result['course_url'], self.course_url) + assert result['auto_enroll'] is False + assert result['course_about_url'] == self.course_about_url + assert result['registration_url'] == self.registration_url + assert result['course_url'] == self.course_url def test_marketing_params(self): # For a site with a marketing front end, what do we expect to get for the URLs? @@ -954,11 +950,11 @@ class TestGetEmailParams(SharedModuleStoreTestCase): with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True}): result = get_email_params(self.course, True) - self.assertEqual(result['auto_enroll'], True) + assert result['auto_enroll'] is True # We should *not* get a course about url (LMS doesn't know what the marketing site URLs are) - self.assertEqual(result['course_about_url'], None) - self.assertEqual(result['registration_url'], self.registration_url) - self.assertEqual(result['course_url'], self.course_url) + assert result['course_about_url'] is None + assert result['registration_url'] == self.registration_url + assert result['course_url'] == self.course_url @ddt.ddt @@ -1039,15 +1035,15 @@ class TestRenderMessageToString(EmailTemplateTagMixin, SharedModuleStoreTestCase language_after_rendering = get_language() you_have_been_invited_in_esperanto = u"Ýöü hävé ßéén" - self.assertIn(you_have_been_invited_in_esperanto, subject) - self.assertIn(you_have_been_invited_in_esperanto, message) - self.assertEqual(settings.LANGUAGE_CODE, language_after_rendering) + assert you_have_been_invited_in_esperanto in subject + assert you_have_been_invited_in_esperanto in message + assert settings.LANGUAGE_CODE == language_after_rendering def test_platform_language_is_used_for_logged_in_user(self): with override_language('zh_CN'): # simulate a user login subject, message = self.get_subject_and_message(None) - self.assertIn("You have been", subject) - self.assertIn("You have been", message) + assert 'You have been' in subject + assert 'You have been' in message @patch.dict('django.conf.settings.FEATURES', {'CUSTOM_COURSES_EDX': True}) @ddt.data('body.txt', 'body.html') @@ -1063,14 +1059,14 @@ class TestRenderMessageToString(EmailTemplateTagMixin, SharedModuleStoreTestCase subject, message = self.get_subject_and_message_ccx(subject_template, body_template) - self.assertIn(self.ccx.display_name, subject) - self.assertIn(self.ccx.display_name, message) + assert self.ccx.display_name in subject + assert self.ccx.display_name in message site = settings.SITE_NAME course_url = u'https://{}/courses/{}/'.format( site, self.course_key ) - self.assertIn(course_url, message) + assert course_url in message @patch.dict('django.conf.settings.FEATURES', {'CUSTOM_COURSES_EDX': True}) @ddt.data('body.txt', 'body.html') @@ -1085,8 +1081,8 @@ class TestRenderMessageToString(EmailTemplateTagMixin, SharedModuleStoreTestCase ) subject, message = self.get_subject_and_message_ccx(subject_template, body_template) - self.assertIn(self.ccx.display_name, subject) - self.assertIn(self.ccx.display_name, message) + assert self.ccx.display_name in subject + assert self.ccx.display_name in message @patch.dict('django.conf.settings.FEATURES', {'CUSTOM_COURSES_EDX': True}) @ddt.data('body.txt', 'body.html') @@ -1101,11 +1097,11 @@ class TestRenderMessageToString(EmailTemplateTagMixin, SharedModuleStoreTestCase ) subject, message = self.get_subject_and_message_ccx(subject_template, body_template) - self.assertIn(self.ccx.display_name, subject) - self.assertIn(self.ccx.display_name, message) + assert self.ccx.display_name in subject + assert self.ccx.display_name in message site = settings.SITE_NAME registration_url = u'https://{}/register'.format(site) - self.assertIn(registration_url, message) + assert registration_url in message @patch.dict('django.conf.settings.FEATURES', {'CUSTOM_COURSES_EDX': True}) @ddt.data('body.txt', 'body.html') @@ -1120,5 +1116,5 @@ class TestRenderMessageToString(EmailTemplateTagMixin, SharedModuleStoreTestCase ) subject, message = self.get_subject_and_message_ccx(subject_template, body_template) - self.assertIn(self.ccx.display_name, subject) - self.assertIn(self.ccx.display_name, message) + assert self.ccx.display_name in subject + assert self.ccx.display_name in message diff --git a/lms/djangoapps/instructor/tests/test_proctoring.py b/lms/djangoapps/instructor/tests/test_proctoring.py index bf8d38ca68..79e1a756ed 100644 --- a/lms/djangoapps/instructor/tests/test_proctoring.py +++ b/lms/djangoapps/instructor/tests/test_proctoring.py @@ -190,7 +190,7 @@ class TestProctoringDashboardViews(SharedModuleStoreTestCase): self.instructor.save() response = self.client.get(self.url) - self.assertIn('data-enable-exam-resume-proctoring-improvements="True"', response.content.decode('utf-8')) + assert 'data-enable-exam-resume-proctoring-improvements="True"' in response.content.decode('utf-8') @override_waffle_flag(EXAM_RESUME_PROCTORING_IMPROVEMENTS, False) def test_exam_resume_proctoring_improvements_toggle_disabled(self): @@ -203,7 +203,7 @@ class TestProctoringDashboardViews(SharedModuleStoreTestCase): self.instructor.save() response = self.client.get(self.url) - self.assertIn('data-enable-exam-resume-proctoring-improvements="False"', response.content.decode('utf-8')) + assert 'data-enable-exam-resume-proctoring-improvements="False"' in response.content.decode('utf-8') def test_review_dashboard(self): """ diff --git a/lms/djangoapps/instructor/tests/test_services.py b/lms/djangoapps/instructor/tests/test_services.py index c8efd426d0..b7985d6ff1 100644 --- a/lms/djangoapps/instructor/tests/test_services.py +++ b/lms/djangoapps/instructor/tests/test_services.py @@ -4,7 +4,7 @@ Tests for the InstructorService import json - +import pytest import mock import six from opaque_keys import InvalidKeyError @@ -63,14 +63,8 @@ class InstructorServiceTests(SharedModuleStoreTestCase): """ # make sure the attempt is there - self.assertEqual( - StudentModule.objects.filter( - student=self.module_to_reset.student, - course_id=self.course.id, - module_state_key=self.module_to_reset.module_state_key, - ).count(), - 1 - ) + assert StudentModule.objects.filter(student=self.module_to_reset.student, course_id=self.course.id, + module_state_key=self.module_to_reset.module_state_key).count() == 1 self.service.delete_student_attempt( self.student.username, @@ -80,14 +74,8 @@ class InstructorServiceTests(SharedModuleStoreTestCase): ) # make sure the module has been deleted - self.assertEqual( - StudentModule.objects.filter( - student=self.module_to_reset.student, - course_id=self.course.id, - module_state_key=self.module_to_reset.module_state_key, - ).count(), - 0 - ) + assert StudentModule.objects.filter(student=self.module_to_reset.student, course_id=self.course.id, + module_state_key=self.module_to_reset.module_state_key).count() == 0 def test_reset_bad_content_id(self): """ @@ -100,7 +88,7 @@ class InstructorServiceTests(SharedModuleStoreTestCase): 'foo/bar/baz', requesting_user=self.student, ) - self.assertIsNone(result) + assert result is None def test_reset_bad_user(self): """ @@ -113,7 +101,7 @@ class InstructorServiceTests(SharedModuleStoreTestCase): 'foo/bar/baz', requesting_user=self.student, ) - self.assertIsNone(result) + assert result is None def test_reset_non_existing_attempt(self): """ @@ -126,7 +114,7 @@ class InstructorServiceTests(SharedModuleStoreTestCase): self.other_problem_urlname, requesting_user=self.student, ) - self.assertIsNone(result) + assert result is None def test_is_user_staff(self): """ @@ -136,7 +124,7 @@ class InstructorServiceTests(SharedModuleStoreTestCase): self.student, six.text_type(self.course.id) ) - self.assertFalse(result) + assert not result # allow staff access to the student allow_access(self.course, self.student, 'staff') @@ -144,7 +132,7 @@ class InstructorServiceTests(SharedModuleStoreTestCase): self.student, six.text_type(self.course.id) ) - self.assertTrue(result) + assert result def test_report_suspicious_attempt(self): """ @@ -195,18 +183,18 @@ class InstructorServiceTests(SharedModuleStoreTestCase): Test that it returns the correct proctoring escalation email """ email = self.service.get_proctoring_escalation_email(str(self.course.id)) - self.assertEqual(email, self.email) + assert email == self.email def test_get_proctoring_escalation_email_no_course(self): """ Test that it raises an exception if the course is not found """ - with self.assertRaises(ObjectDoesNotExist): + with pytest.raises(ObjectDoesNotExist): self.service.get_proctoring_escalation_email('a/b/c') def test_get_proctoring_escalation_email_invalid_key(self): """ Test that it raises an exception if the course_key is invalid """ - with self.assertRaises(InvalidKeyError): + with pytest.raises(InvalidKeyError): self.service.get_proctoring_escalation_email('invalid key') diff --git a/lms/djangoapps/instructor/tests/test_spoc_gradebook.py b/lms/djangoapps/instructor/tests/test_spoc_gradebook.py index bea2463fa4..36f5e3ac8f 100644 --- a/lms/djangoapps/instructor/tests/test_spoc_gradebook.py +++ b/lms/djangoapps/instructor/tests/test_spoc_gradebook.py @@ -82,7 +82,7 @@ class TestGradebook(SharedModuleStoreTestCase): args=(text_type(self.course.id),) )) - self.assertEqual(self.response.status_code, 200) + assert self.response.status_code == 200 class TestDefaultGradingPolicy(TestGradebook): @@ -92,22 +92,22 @@ class TestDefaultGradingPolicy(TestGradebook): """ def test_all_users_listed(self): for user in self.users: - self.assertIn(user.username, text_type(self.response.content, 'utf-8')) + assert user.username in text_type(self.response.content, 'utf-8') def test_default_policy(self): # Default >= 50% passes, so Users 5-10 should be passing for Homework 1 [6] # One use at the top of the page [1] - self.assertEqual(7, self.response.content.count(b'grade_Pass')) + assert 7 == self.response.content.count(b'grade_Pass') # Users 1-5 attempted Homework 1 (and get Fs) [4] # Users 1-10 attempted any homework (and get Fs) [10] # Users 4-10 scored enough to not get rounded to 0 for the class (and get Fs) [7] # One use at top of the page [1] - self.assertEqual(23, self.response.content.count(b'grade_F')) + assert 23 == self.response.content.count(b'grade_F') # All other grades are None [29 categories * 11 users - 27 non-empty grades = 292] # One use at the top of the page [1] - self.assertEqual(292, self.response.content.count(b'grade_None')) + assert 292 == self.response.content.count(b'grade_None') class TestLetterCutoffPolicy(TestGradebook): @@ -144,29 +144,29 @@ class TestLetterCutoffPolicy(TestGradebook): # Users 9-10 have >= 90% on Homeworks [2] # Users 9-10 have >= 90% on the class [2] # One use at the top of the page [1] - self.assertEqual(5, self.response.content.count(b'grade_A')) + assert 5 == self.response.content.count(b'grade_A') # User 8 has 80 <= Homeworks < 90 [1] # User 8 has 80 <= class < 90 [1] # One use at the top of the page [1] - self.assertEqual(3, self.response.content.count(b'grade_B')) + assert 3 == self.response.content.count(b'grade_B') # User 7 has 70 <= Homeworks < 80 [1] # User 7 has 70 <= class < 80 [1] # One use at the top of the page [1] - self.assertEqual(3, self.response.content.count(b'grade_C')) + assert 3 == self.response.content.count(b'grade_C') # User 6 has 60 <= Homeworks < 70 [1] # User 6 has 60 <= class < 70 [1] # One use at the top of the page [1] - self.assertEqual(3, self.response.content.count(b'grade_C')) + assert 3 == self.response.content.count(b'grade_C') # Users 1-5 have 60% > grades > 0 on Homeworks [5] # Users 1-5 have 60% > grades > 0 on the class [5] # One use at top of the page [1] - self.assertEqual(11, self.response.content.count(b'grade_F')) + assert 11 == self.response.content.count(b'grade_F') # User 0 has 0 on Homeworks [1] # User 0 has 0 on the class [1] # One use at the top of the page [1] - self.assertEqual(3, self.response.content.count(b'grade_None')) + assert 3 == self.response.content.count(b'grade_None') diff --git a/lms/djangoapps/instructor/tests/test_tools.py b/lms/djangoapps/instructor/tests/test_tools.py index ec57255fca..c6a02a921e 100644 --- a/lms/djangoapps/instructor/tests/test_tools.py +++ b/lms/djangoapps/instructor/tests/test_tools.py @@ -6,7 +6,7 @@ Tests for views/tools.py. import datetime import json import unittest - +import pytest import mock import six from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user @@ -36,7 +36,7 @@ class TestDashboardError(unittest.TestCase): def test_response(self): error = tools.DashboardError(u'Oh noes!') response = json.loads(error.response().content.decode('utf-8')) - self.assertEqual(response, {'error': 'Oh noes!'}) + assert response == {'error': 'Oh noes!'} class TestHandleDashboardError(unittest.TestCase): @@ -52,7 +52,7 @@ class TestHandleDashboardError(unittest.TestCase): raise tools.DashboardError("Oh noes!") response = json.loads(view(None, None).content.decode('utf-8')) - self.assertEqual(response, {'error': 'Oh noes!'}) + assert response == {'error': 'Oh noes!'} def test_no_error(self): @tools.handle_dashboard_error @@ -62,7 +62,7 @@ class TestHandleDashboardError(unittest.TestCase): """ return "Oh yes!" - self.assertEqual(view(None, None), "Oh yes!") + assert view(None, None) == 'Oh yes!' class TestRequireStudentIdentifier(TestCase): @@ -77,13 +77,10 @@ class TestRequireStudentIdentifier(TestCase): self.student = UserFactory.create() def test_valid_student_id(self): - self.assertEqual( - self.student, - tools.require_student_from_identifier(self.student.username) - ) + assert self.student == tools.require_student_from_identifier(self.student.username) def test_invalid_student_id(self): - with self.assertRaises(tools.DashboardError): + with pytest.raises(tools.DashboardError): tools.require_student_from_identifier("invalid") @@ -92,12 +89,10 @@ class TestParseDatetime(unittest.TestCase): Test date parsing. """ def test_parse_no_error(self): - self.assertEqual( - tools.parse_datetime('5/12/2010 2:42'), - datetime.datetime(2010, 5, 12, 2, 42, tzinfo=UTC)) + assert tools.parse_datetime('5/12/2010 2:42') == datetime.datetime(2010, 5, 12, 2, 42, tzinfo=UTC) def test_parse_error(self): - with self.assertRaises(tools.DashboardError): + with pytest.raises(tools.DashboardError): tools.parse_datetime('foo') @@ -119,14 +114,14 @@ class TestFindUnit(SharedModuleStoreTestCase): """ url = six.text_type(self.homework.location) found_unit = tools.find_unit(self.course, url) - self.assertEqual(found_unit.location, self.homework.location) + assert found_unit.location == self.homework.location def test_find_unit_notfound(self): """ Test attempt to find a unit that does not exist. """ url = "i4x://MITx/999/chapter/notfound" - with self.assertRaises(tools.DashboardError): + with pytest.raises(tools.DashboardError): tools.find_unit(self.course, url) @@ -164,9 +159,7 @@ class TestGetUnitsWithDueDate(ModuleStoreTestCase): """ return sorted(six.text_type(i.location) for i in seq) - self.assertEqual( - urls(tools.get_units_with_due_date(self.course)), - urls((self.week1, self.week2))) + assert urls(tools.get_units_with_due_date(self.course)) == urls((self.week1, self.week2)) class TestTitleOrUrl(unittest.TestCase): @@ -175,7 +168,7 @@ class TestTitleOrUrl(unittest.TestCase): """ def test_title(self): unit = mock.Mock(display_name='hello') - self.assertEqual(tools.title_or_url(unit), 'hello') + assert tools.title_or_url(unit) == 'hello' def test_url(self): # pylint: disable=unused-argument @@ -190,7 +183,7 @@ class TestTitleOrUrl(unittest.TestCase): unit.location.__unicode__ = mock_location_text else: unit.location.__str__ = mock_location_text - self.assertEqual(tools.title_or_url(unit), u'test:hello') + assert tools.title_or_url(unit) == u'test:hello' def inject_field_data(blocks, course, user): @@ -249,33 +242,33 @@ class TestSetDueDateExtension(ModuleStoreTestCase): extended_hw = datetime.datetime(2013, 10, 25, 0, 0, tzinfo=UTC) tools.set_due_date_extension(self.course, self.assignment, self.user, extended_hw) self._clear_field_data_cache() - self.assertEqual(self.week1.due, self.due) - self.assertEqual(self.homework.due, self.due) - self.assertEqual(self.assignment.due, extended_hw) + assert self.week1.due == self.due + assert self.homework.due == self.due + assert self.assignment.due == extended_hw # Now, extend the whole section that the assignment was in. Both it and all under it should change extended_week = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=UTC) tools.set_due_date_extension(self.course, self.week1, self.user, extended_week) self._clear_field_data_cache() - self.assertEqual(self.week1.due, extended_week) - self.assertEqual(self.homework.due, extended_week) - self.assertEqual(self.assignment.due, extended_week) + assert self.week1.due == extended_week + assert self.homework.due == extended_week + assert self.assignment.due == extended_week def test_set_due_date_extension_invalid_date(self): extended = datetime.datetime(2009, 1, 1, 0, 0, tzinfo=UTC) - with self.assertRaises(tools.DashboardError): + with pytest.raises(tools.DashboardError): tools.set_due_date_extension(self.course, self.week1, self.user, extended) def test_set_due_date_extension_no_date(self): extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=UTC) - with self.assertRaises(tools.DashboardError): + with pytest.raises(tools.DashboardError): tools.set_due_date_extension(self.course, self.week3, self.user, extended) def test_reset_due_date_extension(self): extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=UTC) tools.set_due_date_extension(self.course, self.week1, self.user, extended) tools.set_due_date_extension(self.course, self.week1, self.user, None) - self.assertEqual(self.week1.due, self.due) + assert self.week1.due == self.due def test_reset_due_date_extension_with_no_enrollment(self): """ @@ -284,7 +277,7 @@ class TestSetDueDateExtension(ModuleStoreTestCase): """ user = UserFactory.create() extended = datetime.datetime(2013, 12, 25, 0, 0, tzinfo=UTC) - with self.assertRaises(tools.DashboardError): + with pytest.raises(tools.DashboardError): tools.set_due_date_extension(self.course, self.week3, user, extended) @@ -403,7 +396,7 @@ class TestStudentFromIdentifier(TestCase): An edge case where there is a user A with username example: foo@touchstone.com and there is user B with email example: foo@touchstone.com """ - with self.assertRaises(MultipleObjectsReturned): + with pytest.raises(MultipleObjectsReturned): tools.get_student_from_identifier(self.student_conflicting_username.username) # can get student with alternative identifier, in this case email. @@ -416,7 +409,7 @@ class TestStudentFromIdentifier(TestCase): An edge case where there is a user A with email example: foo@touchstone.com and there is user B with username example: foo@touchstone.com """ - with self.assertRaises(MultipleObjectsReturned): + with pytest.raises(MultipleObjectsReturned): tools.get_student_from_identifier(self.student_conflicting_email.email) # can get student with alternative identifier, in this case username. @@ -426,5 +419,5 @@ class TestStudentFromIdentifier(TestCase): def test_invalid_student_id(self): """Test with invalid identifier""" - with self.assertRaises(User.DoesNotExist): + with pytest.raises(User.DoesNotExist): assert tools.get_student_from_identifier("invalid") diff --git a/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py b/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py index c3de2244fb..c13b0acf8a 100644 --- a/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py +++ b/lms/djangoapps/instructor/tests/views/test_instructor_dashboard.py @@ -110,13 +110,13 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT tabs = get_course_tab_list(user, course) return len([tab for tab in tabs if tab.name == 'Instructor']) == 1 - self.assertTrue(has_instructor_tab(self.instructor, self.course)) + assert has_instructor_tab(self.instructor, self.course) staff = StaffFactory(course_key=self.course.id) - self.assertTrue(has_instructor_tab(staff, self.course)) + assert has_instructor_tab(staff, self.course) student = UserFactory.create() - self.assertFalse(has_instructor_tab(student, self.course)) + assert not has_instructor_tab(student, self.course) researcher = UserFactory.create() CourseAccessRoleFactory( @@ -125,7 +125,7 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT role='data_researcher', org=self.course.id.org ) - self.assertTrue(has_instructor_tab(researcher, self.course)) + assert has_instructor_tab(researcher, self.course) org_researcher = UserFactory.create() CourseAccessRoleFactory( @@ -134,7 +134,7 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT role='data_researcher', org=self.course.id.org ) - self.assertTrue(has_instructor_tab(org_researcher, self.course)) + assert has_instructor_tab(org_researcher, self.course) @ddt.data( ('staff', False, False), @@ -210,25 +210,13 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT response = self.client.get(url) content = pq(response.content) - self.assertEqual( - display_name, - content('#field-course-display-name b').contents()[0].strip() - ) + assert display_name == content('#field-course-display-name b').contents()[0].strip() - self.assertEqual( - run, - content('#field-course-name b').contents()[0].strip() - ) + assert run == content('#field-course-name b').contents()[0].strip() - self.assertEqual( - number, - content('#field-course-number b').contents()[0].strip() - ) + assert number == content('#field-course-number b').contents()[0].strip() - self.assertEqual( - org, - content('#field-course-organization b').contents()[0].strip() - ) + assert org == content('#field-course-organization b').contents()[0].strip() @ddt.data(True, False) def test_membership_reason_field_visibility(self, enbale_reason_field): @@ -394,10 +382,7 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT waffle_flag = waffle_flags()[WRITABLE_GRADEBOOK] with override_waffle_flag(waffle_flag, active=True): response = self.client.get(self.url) - self.assertNotIn( - TestInstructorDashboard.GRADEBOOK_LEARNER_COUNT_MESSAGE, - response.content.decode('utf-8') - ) + assert TestInstructorDashboard.GRADEBOOK_LEARNER_COUNT_MESSAGE not in response.content.decode('utf-8') self.assertContains(response, 'View Gradebook') def test_course_name_xss(self): @@ -466,7 +451,7 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT # link to dashboard shown expected_message = self.get_dashboard_enrollment_message() - self.assertIn(expected_message, response.content.decode(response.charset)) + assert expected_message in response.content.decode(response.charset) @override_settings(ANALYTICS_DASHBOARD_URL='') @override_settings(ANALYTICS_DASHBOARD_NAME='') @@ -491,7 +476,7 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT # link to dashboard shown expected_message = self.get_dashboard_analytics_message() - self.assertIn(expected_message, response.content.decode(response.charset)) + assert expected_message in response.content.decode(response.charset) @ddt.data( (True, True, True), @@ -512,9 +497,8 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT response = self.client.get(self.url) - self.assertEqual(expected_result, - 'CCX Coaches are able to create their own Custom Courses based on this course' - in response.content.decode('utf-8')) + assert expected_result == ('CCX Coaches are able to create their own Custom Courses based on this course' + in response.content.decode('utf-8')) def test_grade_cutoffs(self): """ @@ -526,11 +510,11 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT @patch('lms.djangoapps.instructor.views.gradebook_api.MAX_STUDENTS_PER_PAGE_GRADE_BOOK', 2) def test_calculate_page_info(self): page = calculate_page_info(offset=0, total_students=2) - self.assertEqual(page["offset"], 0) - self.assertEqual(page["page_num"], 1) - self.assertEqual(page["next_offset"], None) - self.assertEqual(page["previous_offset"], None) - self.assertEqual(page["total_pages"], 1) + assert page['offset'] == 0 + assert page['page_num'] == 1 + assert page['next_offset'] is None + assert page['previous_offset'] is None + assert page['total_pages'] == 1 @patch('lms.djangoapps.instructor.views.gradebook_api.render_to_response', intercept_renderer) @patch('lms.djangoapps.instructor.views.gradebook_api.MAX_STUDENTS_PER_PAGE_GRADE_BOOK', 1) @@ -544,9 +528,9 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT kwargs={'course_id': self.course.id} ) response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # Max number of student per page is one. Patched setting MAX_STUDENTS_PER_PAGE_GRADE_BOOK = 1 - self.assertEqual(len(response.mako_context['students']), 1) + assert len(response.mako_context['students']) == 1 def test_open_response_assessment_page(self): """ @@ -583,7 +567,7 @@ class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssT ) response = self.client.get(self.url) # assert we don't get a 500 error - self.assertEqual(200, response.status_code) + assert 200 == response.status_code @ddt.ddt @@ -678,4 +662,4 @@ class TestInstructorDashboardPerformance(ModuleStoreTestCase, LoginEnrollmentTes url = reverse('spoc_gradebook', kwargs={'course_id': self.course.id}) with check_mongo_calls(9): response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 diff --git a/lms/djangoapps/instructor_analytics/tests/test_basic.py b/lms/djangoapps/instructor_analytics/tests/test_basic.py index 99294bd972..d26b330503 100644 --- a/lms/djangoapps/instructor_analytics/tests/test_basic.py +++ b/lms/djangoapps/instructor_analytics/tests/test_basic.py @@ -82,8 +82,8 @@ class TestAnalyticsBasic(ModuleStoreTestCase): response = Mock(module_type='openassessment', student=Mock(username='staff'), state=payload_state) transformed_state = json.loads(get_response_state(response)) - self.assertEqual(transformed_state['saved_files_descriptions'][0], files_descriptions) - self.assertEqual(transformed_state['saved_response']['parts'][0]['text'], saved_response) + assert transformed_state['saved_files_descriptions'][0] == files_descriptions + assert transformed_state['saved_response']['parts'][0]['text'] == saved_response def test_list_problem_responses(self): def result_factory(result_id): @@ -120,20 +120,17 @@ class TestAnalyticsBasic(ModuleStoreTestCase): ) # Check if list_problem_responses returned expected results: - self.assertEqual(len(problem_responses), len(mock_results)) + assert len(problem_responses) == len(mock_results) for mock_result in mock_results: - self.assertIn( - {'username': mock_result.student.username, 'state': mock_result.state}, - problem_responses - ) + assert {'username': mock_result.student.username, 'state': mock_result.state} in problem_responses def test_enrolled_students_features_username(self): - self.assertIn('username', AVAILABLE_FEATURES) + assert 'username' in AVAILABLE_FEATURES userreports = enrolled_students_features(self.course_key, ['username']) - self.assertEqual(len(userreports), len(self.users)) + assert len(userreports) == len(self.users) for userreport in userreports: - self.assertEqual(list(userreport.keys()), ['username']) - self.assertIn(userreport['username'], [user.username for user in self.users]) + assert list(userreport.keys()) == ['username'] + assert userreport['username'] in [user.username for user in self.users] def test_enrolled_students_features_keys(self): query_features = ('username', 'name', 'email', 'city', 'country',) @@ -142,20 +139,20 @@ class TestAnalyticsBasic(ModuleStoreTestCase): user.profile.country = u"Tatooine {}".format(user.id) user.profile.save() for feature in query_features: - self.assertIn(feature, AVAILABLE_FEATURES) + assert feature in AVAILABLE_FEATURES with self.assertNumQueries(1): userreports = enrolled_students_features(self.course_key, query_features) - self.assertEqual(len(userreports), len(self.users)) + assert len(userreports) == len(self.users) userreports = sorted(userreports, key=lambda u: u["username"]) users = sorted(self.users, key=lambda u: u.username) for userreport, user in zip(userreports, users): - self.assertEqual(set(userreport.keys()), set(query_features)) - self.assertEqual(userreport['username'], user.username) - self.assertEqual(userreport['email'], user.email) - self.assertEqual(userreport['name'], user.profile.name) - self.assertEqual(userreport['city'], user.profile.city) - self.assertEqual(userreport['country'], user.profile.country) + assert set(userreport.keys()) == set(query_features) + assert userreport['username'] == user.username + assert userreport['email'] == user.email + assert userreport['name'] == user.profile.name + assert userreport['city'] == user.profile.city + assert userreport['country'] == user.profile.country def test_enrolled_student_with_no_country_city(self): userreports = enrolled_students_features(self.course_key, ('username', 'city', 'country',)) @@ -163,8 +160,8 @@ class TestAnalyticsBasic(ModuleStoreTestCase): # This behaviour is somewhat inconsistent: None string fields # objects are converted to "None", but non-JSON serializable fields # are converted to an empty string. - self.assertEqual(userreport['city'], "None") - self.assertEqual(userreport['country'], "") + assert userreport['city'] == 'None' + assert userreport['country'] == '' def test_enrolled_students_meta_features_keys(self): """ @@ -173,11 +170,11 @@ class TestAnalyticsBasic(ModuleStoreTestCase): query_features = ('meta.position', 'meta.company') with self.assertNumQueries(1): userreports = enrolled_students_features(self.course_key, query_features) - self.assertEqual(len(userreports), len(self.users)) + assert len(userreports) == len(self.users) for userreport in userreports: - self.assertEqual(set(userreport.keys()), set(query_features)) - self.assertIn(userreport['meta.position'], [u"edX expert {}".format(user.id) for user in self.users]) - self.assertIn(userreport['meta.company'], [u"Open edX Inc {}".format(user.id) for user in self.users]) + assert set(userreport.keys()) == set(query_features) + assert userreport['meta.position'] in [u'edX expert {}'.format(user.id) for user in self.users] + assert userreport['meta.company'] in [u'Open edX Inc {}'.format(user.id) for user in self.users] def test_enrolled_students_enrollment_verification(self): """ @@ -185,13 +182,13 @@ class TestAnalyticsBasic(ModuleStoreTestCase): """ query_features = ('enrollment_mode', 'verification_status') userreports = enrolled_students_features(self.course_key, query_features) - self.assertEqual(len(userreports), len(self.users)) + assert len(userreports) == len(self.users) # by default all users should have "audit" as their enrollment mode # and "N/A" as their verification status for userreport in userreports: - self.assertEqual(set(userreport.keys()), set(query_features)) - self.assertIn(userreport['enrollment_mode'], ["audit"]) - self.assertIn(userreport['verification_status'], ["N/A"]) + assert set(userreport.keys()) == set(query_features) + assert userreport['enrollment_mode'] in ['audit'] + assert userreport['verification_status'] in ['N/A'] # make sure that the user report respects whatever value # is returned by verification and enrollment code with patch("common.djangoapps.student.models.CourseEnrollment.enrollment_mode_for_user") as enrollment_patch: @@ -201,11 +198,11 @@ class TestAnalyticsBasic(ModuleStoreTestCase): enrollment_patch.return_value = ["verified"] verify_patch.return_value = "dummy verification status" userreports = enrolled_students_features(self.course_key, query_features) - self.assertEqual(len(userreports), len(self.users)) + assert len(userreports) == len(self.users) for userreport in userreports: - self.assertEqual(set(userreport.keys()), set(query_features)) - self.assertIn(userreport['enrollment_mode'], ["verified"]) - self.assertIn(userreport['verification_status'], ["dummy verification status"]) + assert set(userreport.keys()) == set(query_features) + assert userreport['enrollment_mode'] in ['verified'] + assert userreport['verification_status'] in ['dummy verification status'] def test_enrolled_students_features_keys_cohorted(self): course = CourseFactory.create(org="test", course="course1", display_name="run1") @@ -229,26 +226,26 @@ class TestAnalyticsBasic(ModuleStoreTestCase): # prefetch_related('course_groups'). with self.assertNumQueries(2): userreports = enrolled_students_features(course.id, query_features) - self.assertEqual(len([r for r in userreports if r['username'] in cohorted_usernames]), len(cohorted_students)) - self.assertEqual(len([r for r in userreports if r['username'] == non_cohorted_student.username]), 1) + assert len([r for r in userreports if r['username'] in cohorted_usernames]) == len(cohorted_students) + assert len([r for r in userreports if r['username'] == non_cohorted_student.username]) == 1 for report in userreports: - self.assertEqual(set(report.keys()), set(query_features)) + assert set(report.keys()) == set(query_features) if report['username'] in cohorted_usernames: - self.assertEqual(report['cohort'], cohort.name) + assert report['cohort'] == cohort.name else: - self.assertEqual(report['cohort'], '[unassigned]') + assert report['cohort'] == '[unassigned]' def test_available_features(self): - self.assertEqual(len(AVAILABLE_FEATURES), len(STUDENT_FEATURES + PROFILE_FEATURES)) - self.assertEqual(set(AVAILABLE_FEATURES), set(STUDENT_FEATURES + PROFILE_FEATURES)) + assert len(AVAILABLE_FEATURES) == len((STUDENT_FEATURES + PROFILE_FEATURES)) + assert set(AVAILABLE_FEATURES) == set((STUDENT_FEATURES + PROFILE_FEATURES)) def test_list_may_enroll(self): may_enroll = list_may_enroll(self.course_key, ['email']) - self.assertEqual(len(may_enroll), len(self.students_who_may_enroll) - len(self.users)) + assert len(may_enroll) == (len(self.students_who_may_enroll) - len(self.users)) email_adresses = [student.email for student in self.students_who_may_enroll] for student in may_enroll: - self.assertEqual(list(student.keys()), ['email']) - self.assertIn(student['email'], email_adresses) + assert list(student.keys()) == ['email'] + assert student['email'] in email_adresses def test_get_student_exam_attempt_features(self): query_features = [ @@ -281,6 +278,6 @@ class TestAnalyticsBasic(ModuleStoreTestCase): ) proctored_exam_attempts = get_proctored_exam_results(self.course_key, query_features) - self.assertEqual(len(proctored_exam_attempts), 3) + assert len(proctored_exam_attempts) == 3 for proctored_exam_attempt in proctored_exam_attempts: - self.assertEqual(set(proctored_exam_attempt.keys()), set(query_features)) + assert set(proctored_exam_attempt.keys()) == set(query_features) diff --git a/lms/djangoapps/instructor_analytics/tests/test_csvs.py b/lms/djangoapps/instructor_analytics/tests/test_csvs.py index 58075aaa5c..1b3cdbf5bf 100644 --- a/lms/djangoapps/instructor_analytics/tests/test_csvs.py +++ b/lms/djangoapps/instructor_analytics/tests/test_csvs.py @@ -16,30 +16,28 @@ class TestAnalyticsCSVS(TestCase): datarows = [] res = create_csv_response('robot.csv', header, datarows) - self.assertEqual(res['Content-Type'], 'text/csv') - self.assertEqual(res['Content-Disposition'], u'attachment; filename={0}'.format('robot.csv')) - self.assertEqual(res.content.strip().decode('utf-8'), '"Name","Email"') + assert res['Content-Type'] == 'text/csv' + assert res['Content-Disposition'] == u'attachment; filename={0}'.format('robot.csv') + assert res.content.strip().decode('utf-8') == '"Name","Email"' def test_create_csv_response(self): header = ['Name', 'Email'] datarows = [['Jim', 'jim@edy.org'], ['Jake', 'jake@edy.org'], ['Jeeves', 'jeeves@edy.org']] res = create_csv_response('robot.csv', header, datarows) - self.assertEqual(res['Content-Type'], 'text/csv') - self.assertEqual(res['Content-Disposition'], u'attachment; filename={0}'.format('robot.csv')) - self.assertEqual( - res.content.strip().decode('utf-8'), - '"Name","Email"\r\n"Jim","jim@edy.org"\r\n"Jake","jake@edy.org"\r\n"Jeeves","jeeves@edy.org"' - ) + assert res['Content-Type'] == 'text/csv' + assert res['Content-Disposition'] == u'attachment; filename={0}'.format('robot.csv') + assert res.content.strip().decode('utf-8') ==\ + '"Name","Email"\r\n"Jim","jim@edy.org"\r\n"Jake","jake@edy.org"\r\n"Jeeves","jeeves@edy.org"' def test_create_csv_response_empty(self): header = [] datarows = [] res = create_csv_response('robot.csv', header, datarows) - self.assertEqual(res['Content-Type'], 'text/csv') - self.assertEqual(res['Content-Disposition'], u'attachment; filename={0}'.format('robot.csv')) - self.assertEqual(res.content.strip().decode('utf-8'), '') + assert res['Content-Type'] == 'text/csv' + assert res['Content-Disposition'] == u'attachment; filename={0}'.format('robot.csv') + assert res.content.strip().decode('utf-8') == '' class TestAnalyticsFormatDictlist(TestCase): @@ -68,25 +66,23 @@ class TestAnalyticsFormatDictlist(TestCase): ideal_datarows = [['value-1,1', 'value-1,4'], ['value-2,1', 'value-2,4']] - self.assertEqual(header, ideal_header) - self.assertEqual(datarows, ideal_datarows) + assert header == ideal_header + assert datarows == ideal_datarows def test_format_dictlist_empty(self): header, datarows = format_dictlist([], []) - self.assertEqual(header, []) - self.assertEqual(datarows, []) + assert header == [] + assert datarows == [] def test_create_csv_response(self): header = ['Name', 'Email'] datarows = [['Jim', 'jim@edy.org'], ['Jake', 'jake@edy.org'], ['Jeeves', 'jeeves@edy.org']] res = create_csv_response('robot.csv', header, datarows) - self.assertEqual(res['Content-Type'], 'text/csv') - self.assertEqual(res['Content-Disposition'], u'attachment; filename={0}'.format('robot.csv')) - self.assertEqual( - res.content.strip().decode('utf-8'), - '"Name","Email"\r\n"Jim","jim@edy.org"\r\n"Jake","jake@edy.org"\r\n"Jeeves","jeeves@edy.org"' - ) + assert res['Content-Type'] == 'text/csv' + assert res['Content-Disposition'] == u'attachment; filename={0}'.format('robot.csv') + assert res.content.strip().decode('utf-8') ==\ + '"Name","Email"\r\n"Jim","jim@edy.org"\r\n"Jake","jake@edy.org"\r\n"Jeeves","jeeves@edy.org"' class TestAnalyticsFormatInstances(TestCase): @@ -111,23 +107,19 @@ class TestAnalyticsFormatInstances(TestCase): def test_format_instances_response(self): features = ['a_var', 'c_var', 'd_var'] header, datarows = format_instances(self.instances, features) - self.assertEqual(header, ['a_var', 'c_var', 'd_var']) - self.assertEqual(datarows, [[ - 'aval', - 'cval', - 'dval', - ] for _ in range(len(self.instances))]) + assert header == ['a_var', 'c_var', 'd_var'] + assert datarows == [['aval', 'cval', 'dval'] for _ in range(len(self.instances))] def test_format_instances_response_noinstances(self): features = ['a_var'] header, datarows = format_instances([], features) - self.assertEqual(header, features) - self.assertEqual(datarows, []) + assert header == features + assert datarows == [] def test_format_instances_response_nofeatures(self): header, datarows = format_instances(self.instances, []) - self.assertEqual(header, []) - self.assertEqual(datarows, [[] for _ in range(len(self.instances))]) + assert header == [] + assert datarows == [[] for _ in range(len(self.instances))] def test_format_instances_response_nonexistantfeature(self): with pytest.raises(AttributeError): diff --git a/lms/djangoapps/instructor_analytics/tests/test_distributions.py b/lms/djangoapps/instructor_analytics/tests/test_distributions.py index fb7e941bf3..051eb1e8b5 100644 --- a/lms/djangoapps/instructor_analytics/tests/test_distributions.py +++ b/lms/djangoapps/instructor_analytics/tests/test_distributions.py @@ -29,49 +29,49 @@ class TestAnalyticsDistributions(TestCase): def test_profile_distribution_bad_feature(self): feature = 'robot-not-a-real-feature' - self.assertNotIn(feature, AVAILABLE_PROFILE_FEATURES) + assert feature not in AVAILABLE_PROFILE_FEATURES with pytest.raises(ValueError): profile_distribution(self.course_id, feature) def test_profile_distribution_easy_choice(self): feature = 'gender' - self.assertIn(feature, AVAILABLE_PROFILE_FEATURES) + assert feature in AVAILABLE_PROFILE_FEATURES distribution = profile_distribution(self.course_id, feature) - self.assertEqual(distribution.type, 'EASY_CHOICE') - self.assertEqual(distribution.data['no_data'], 0) - self.assertEqual(distribution.data['m'], len(self.users) / 3) - self.assertEqual(distribution.choices_display_names['m'], 'Male') + assert distribution.type == 'EASY_CHOICE' + assert distribution.data['no_data'] == 0 + assert distribution.data['m'] == (len(self.users) / 3) + assert distribution.choices_display_names['m'] == 'Male' def test_profile_distribution_open_choice(self): feature = 'year_of_birth' - self.assertIn(feature, AVAILABLE_PROFILE_FEATURES) + assert feature in AVAILABLE_PROFILE_FEATURES distribution = profile_distribution(self.course_id, feature) print(distribution) - self.assertEqual(distribution.type, 'OPEN_CHOICE') - self.assertTrue(hasattr(distribution, 'choices_display_names')) - self.assertEqual(distribution.choices_display_names, None) - self.assertNotIn('no_data', distribution.data) - self.assertEqual(distribution.data[1930], 1) + assert distribution.type == 'OPEN_CHOICE' + assert hasattr(distribution, 'choices_display_names') + assert distribution.choices_display_names is None + assert 'no_data' not in distribution.data + assert distribution.data[1930] == 1 def test_gender_count(self): course_enrollments = CourseEnrollment.objects.filter( course_id=self.course_id, user__profile__gender='m' ) distribution = profile_distribution(self.course_id, "gender") - self.assertEqual(distribution.data['m'], len(course_enrollments)) + assert distribution.data['m'] == len(course_enrollments) course_enrollments[0].deactivate() distribution = profile_distribution(self.course_id, "gender") - self.assertEqual(distribution.data['m'], len(course_enrollments) - 1) + assert distribution.data['m'] == (len(course_enrollments) - 1) def test_level_of_education_count(self): course_enrollments = CourseEnrollment.objects.filter( course_id=self.course_id, user__profile__level_of_education='hs' ) distribution = profile_distribution(self.course_id, "level_of_education") - self.assertEqual(distribution.data['hs'], len(course_enrollments)) + assert distribution.data['hs'] == len(course_enrollments) course_enrollments[0].deactivate() distribution = profile_distribution(self.course_id, "level_of_education") - self.assertEqual(distribution.data['hs'], len(course_enrollments) - 1) + assert distribution.data['hs'] == (len(course_enrollments) - 1) class TestAnalyticsDistributionsNoData(TestCase): @@ -97,22 +97,22 @@ class TestAnalyticsDistributionsNoData(TestCase): def test_profile_distribution_easy_choice_nodata(self): feature = 'gender' - self.assertIn(feature, AVAILABLE_PROFILE_FEATURES) + assert feature in AVAILABLE_PROFILE_FEATURES distribution = profile_distribution(self.course_id, feature) print(distribution) - self.assertEqual(distribution.type, 'EASY_CHOICE') - self.assertTrue(hasattr(distribution, 'choices_display_names')) - self.assertNotEqual(distribution.choices_display_names, None) - self.assertIn('no_data', distribution.data) - self.assertEqual(distribution.data['no_data'], len(self.nodata_users)) + assert distribution.type == 'EASY_CHOICE' + assert hasattr(distribution, 'choices_display_names') + assert distribution.choices_display_names is not None + assert 'no_data' in distribution.data + assert distribution.data['no_data'] == len(self.nodata_users) def test_profile_distribution_open_choice_nodata(self): feature = 'year_of_birth' - self.assertIn(feature, AVAILABLE_PROFILE_FEATURES) + assert feature in AVAILABLE_PROFILE_FEATURES distribution = profile_distribution(self.course_id, feature) print(distribution) - self.assertEqual(distribution.type, 'OPEN_CHOICE') - self.assertTrue(hasattr(distribution, 'choices_display_names')) - self.assertEqual(distribution.choices_display_names, None) - self.assertIn('no_data', distribution.data) - self.assertEqual(distribution.data['no_data'], len(self.nodata_users)) + assert distribution.type == 'OPEN_CHOICE' + assert hasattr(distribution, 'choices_display_names') + assert distribution.choices_display_names is None + assert 'no_data' in distribution.data + assert distribution.data['no_data'] == len(self.nodata_users) diff --git a/lms/djangoapps/instructor_task/management/commands/tests/test_fail_old_tasks.py b/lms/djangoapps/instructor_task/management/commands/tests/test_fail_old_tasks.py index f2ffc88aa1..e5f6bbdeb1 100644 --- a/lms/djangoapps/instructor_task/management/commands/tests/test_fail_old_tasks.py +++ b/lms/djangoapps/instructor_task/management/commands/tests/test_fail_old_tasks.py @@ -4,7 +4,7 @@ Tests for failing old tasks from datetime import datetime - +import pytest import ddt import pytz from celery.states import FAILURE @@ -84,9 +84,9 @@ class TestFailOldQueueingTasksCommand(InstructorTaskTestCase): ) type_1_queueing, type_1_progress, type_2_queueing = self.get_tasks() - self.assertEqual(type_1_queueing.task_state, QUEUING) - self.assertEqual(type_2_queueing.task_state, QUEUING) - self.assertEqual(type_1_progress.task_state, PROGRESS) + assert type_1_queueing.task_state == QUEUING + assert type_2_queueing.task_state == QUEUING + assert type_1_progress.task_state == PROGRESS @ddt.data( ('2015-05-05', '2015-05-07', '2015-05-06', FAILURE), @@ -105,9 +105,9 @@ class TestFailOldQueueingTasksCommand(InstructorTaskTestCase): call_command('fail_old_tasks', QUEUING, before=before, after=after) type_1_queueing, type_1_progress, type_2_queueing = self.get_tasks() - self.assertEqual(type_1_queueing.task_state, expected_state) - self.assertEqual(type_2_queueing.task_state, expected_state) - self.assertEqual(type_1_progress.task_state, PROGRESS) + assert type_1_queueing.task_state == expected_state + assert type_2_queueing.task_state == expected_state + assert type_1_progress.task_state == PROGRESS @ddt.data( (PROGRESS, QUEUING, FAILURE), @@ -129,9 +129,9 @@ class TestFailOldQueueingTasksCommand(InstructorTaskTestCase): ) type_1_queueing, type_1_progress, type_2_queueing = self.get_tasks() - self.assertEqual(type_1_queueing.task_state, expected_queueing_state) - self.assertEqual(type_2_queueing.task_state, expected_queueing_state) - self.assertEqual(type_1_progress.task_state, expected_progress_state) + assert type_1_queueing.task_state == expected_queueing_state + assert type_2_queueing.task_state == expected_queueing_state + assert type_1_progress.task_state == expected_progress_state def test_filter_by_task_type(self): """ @@ -147,10 +147,10 @@ class TestFailOldQueueingTasksCommand(InstructorTaskTestCase): task_type="type_1", ) type_1_queueing, type_1_progress, type_2_queueing = self.get_tasks() - self.assertEqual(type_1_queueing.task_state, FAILURE) + assert type_1_queueing.task_state == FAILURE # the other type of task shouldn't be updated - self.assertEqual(type_2_queueing.task_state, QUEUING) - self.assertEqual(type_1_progress.task_state, PROGRESS) + assert type_2_queueing.task_state == QUEUING + assert type_1_progress.task_state == PROGRESS @ddt.data( ('2015-05-05', None), @@ -162,7 +162,7 @@ class TestFailOldQueueingTasksCommand(InstructorTaskTestCase): Test that we get a CommandError when we don't supply before and after dates. """ - with self.assertRaises(CommandError): + with pytest.raises(CommandError): call_command('fail_old_tasks', QUEUING, before=before, after=after) @ddt.data( @@ -174,5 +174,5 @@ class TestFailOldQueueingTasksCommand(InstructorTaskTestCase): Test that the command will throw an error if called with a value that's neither 'QUEUING' nor 'PROGRESS' """ - with self.assertRaises(CommandError): + with pytest.raises(CommandError): call_command('fail_old_tasks', task_type, before='2015-05-15', after='2015-05-05') diff --git a/lms/djangoapps/instructor_task/tests/test_api.py b/lms/djangoapps/instructor_task/tests/test_api.py index 2fffc7aa7e..0295390c38 100644 --- a/lms/djangoapps/instructor_task/tests/test_api.py +++ b/lms/djangoapps/instructor_task/tests/test_api.py @@ -2,7 +2,7 @@ Test for LMS instructor background task queue management """ - +import pytest import ddt from celery.states import FAILURE from mock import MagicMock, Mock, patch @@ -60,7 +60,7 @@ class InstructorTaskReportTest(InstructorTaskTestCase): self._create_success_entry() progress_task_ids = [self._create_progress_entry().task_id for _ in range(1, 5)] task_ids = [instructor_task.task_id for instructor_task in get_running_instructor_tasks(TEST_COURSE_KEY)] - self.assertEqual(set(task_ids), set(progress_task_ids)) + assert set(task_ids) == set(progress_task_ids) def test_get_instructor_task_history(self): # when fetching historical tasks, we get all tasks, including running tasks @@ -71,7 +71,7 @@ class InstructorTaskReportTest(InstructorTaskTestCase): expected_ids.append(self._create_progress_entry().task_id) task_ids = [instructor_task.task_id for instructor_task in get_instructor_task_history(TEST_COURSE_KEY, usage_key=self.problem_url)] - self.assertEqual(set(task_ids), set(expected_ids)) + assert set(task_ids) == set(expected_ids) # make the same call using explicit task_type: task_ids = [instructor_task.task_id for instructor_task in get_instructor_task_history( @@ -79,7 +79,7 @@ class InstructorTaskReportTest(InstructorTaskTestCase): usage_key=self.problem_url, task_type='rescore_problem' )] - self.assertEqual(set(task_ids), set(expected_ids)) + assert set(task_ids) == set(expected_ids) # make the same call using a non-existent task_type: task_ids = [instructor_task.task_id for instructor_task in get_instructor_task_history( @@ -87,7 +87,7 @@ class InstructorTaskReportTest(InstructorTaskTestCase): usage_key=self.problem_url, task_type='dummy_type' )] - self.assertEqual(set(task_ids), set()) + assert set(task_ids) == set() @ddt.ddt @@ -105,13 +105,13 @@ class InstructorTaskModuleSubmitTest(InstructorTaskModuleTestCase): # confirm that a rescore of a non-existent module returns an exception problem_url = InstructorTaskModuleTestCase.problem_location("NonexistentProblem") request = None - with self.assertRaises(ItemNotFoundError): + with pytest.raises(ItemNotFoundError): submit_rescore_problem_for_student(request, problem_url, self.student) - with self.assertRaises(ItemNotFoundError): + with pytest.raises(ItemNotFoundError): submit_rescore_problem_for_all_students(request, problem_url) - with self.assertRaises(ItemNotFoundError): + with pytest.raises(ItemNotFoundError): submit_reset_problem_attempts_for_all_students(request, problem_url) - with self.assertRaises(ItemNotFoundError): + with pytest.raises(ItemNotFoundError): submit_delete_problem_state_for_all_students(request, problem_url) def test_submit_nonrescorable_modules(self): @@ -120,9 +120,9 @@ class InstructorTaskModuleSubmitTest(InstructorTaskModuleTestCase): # where we are creating real modules.) problem_url = self.problem_section.location request = None - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): submit_rescore_problem_for_student(request, problem_url, self.student) - with self.assertRaises(NotImplementedError): + with pytest.raises(NotImplementedError): submit_rescore_problem_for_all_students(request, problem_url) @ddt.data( @@ -170,22 +170,22 @@ class InstructorTaskModuleSubmitTest(InstructorTaskModuleTestCase): error = Exception() apply_async.side_effect = error - with self.assertRaises(QueueConnectionError): + with pytest.raises(QueueConnectionError): instructor_task = task_function(self.create_task_request(self.instructor), location, **params) most_recent_task = InstructorTask.objects.latest('id') - self.assertEqual(most_recent_task.task_state, FAILURE) + assert most_recent_task.task_state == FAILURE # successful submission instructor_task = task_function(self.create_task_request(self.instructor), location, **params) - self.assertEqual(instructor_task.task_type, expected_task_type) + assert instructor_task.task_type == expected_task_type # test resubmitting, by updating the existing record: instructor_task = InstructorTask.objects.get(id=instructor_task.id) instructor_task.task_state = PROGRESS instructor_task.save() - with self.assertRaises(AlreadyRunningError): + with pytest.raises(AlreadyRunningError): task_function(self.create_task_request(self.instructor), location, **params) @@ -223,7 +223,7 @@ class InstructorTaskCourseSubmitTest(TestReportMixin, InstructorTaskCourseTestCa instructor_task = InstructorTask.objects.get(id=instructor_task.id) instructor_task.task_state = PROGRESS instructor_task.save() - with self.assertRaises(AlreadyRunningError): + with pytest.raises(AlreadyRunningError): api_call() def test_submit_bulk_email_all(self): @@ -328,7 +328,7 @@ class InstructorTaskCourseSubmitTest(TestReportMixin, InstructorTaskCourseTestCa """ Raises ValueError when student_set is 'specific_student' and 'specific_student_id' is None. """ - with self.assertRaises(SpecificStudentIdMissingError): + with pytest.raises(SpecificStudentIdMissingError): generate_certificates_for_students( self.create_task_request(self.instructor), self.course.id, @@ -352,7 +352,7 @@ class InstructorTaskCourseSubmitTest(TestReportMixin, InstructorTaskCourseTestCa ) # Validate that record was added to CertificateGenerationHistory - self.assertTrue(certificate_generation_history.exists()) + assert certificate_generation_history.exists() instructor_task = regenerate_certificates( self.create_task_request(self.instructor), @@ -367,4 +367,4 @@ class InstructorTaskCourseSubmitTest(TestReportMixin, InstructorTaskCourseTestCa ) # Validate that record was added to CertificateGenerationHistory - self.assertTrue(certificate_generation_history.exists()) + assert certificate_generation_history.exists() diff --git a/lms/djangoapps/instructor_task/tests/test_base.py b/lms/djangoapps/instructor_task/tests/test_base.py index b12a6ec577..b94460b172 100644 --- a/lms/djangoapps/instructor_task/tests/test_base.py +++ b/lms/djangoapps/instructor_task/tests/test_base.py @@ -367,8 +367,8 @@ class TestReportMixin(object): numeric_expected_rows = [self._extract_and_round_numeric_items(row) for row in expected_rows] if verify_order: - self.assertEqual(csv_rows, expected_rows) - self.assertEqual(numeric_csv_rows, numeric_expected_rows) + assert csv_rows == expected_rows + assert numeric_csv_rows == numeric_expected_rows else: six.assertCountEqual(self, csv_rows, expected_rows) six.assertCountEqual(self, numeric_csv_rows, numeric_expected_rows) diff --git a/lms/djangoapps/instructor_task/tests/test_integration.py b/lms/djangoapps/instructor_task/tests/test_integration.py index a8583194f3..1b3facb8a0 100644 --- a/lms/djangoapps/instructor_task/tests/test_integration.py +++ b/lms/djangoapps/instructor_task/tests/test_integration.py @@ -11,7 +11,7 @@ import json import logging import textwrap from collections import namedtuple - +import pytest import ddt import six from celery.states import FAILURE, SUCCESS @@ -56,18 +56,19 @@ class TestIntegrationTask(InstructorTaskModuleTestCase): def _assert_task_failure(self, entry_id, task_type, problem_url_name, expected_message): """Confirm that expected values are stored in InstructorTask on task failure.""" instructor_task = InstructorTask.objects.get(id=entry_id) - self.assertEqual(instructor_task.task_state, FAILURE) - self.assertEqual(instructor_task.requester.username, 'instructor') - self.assertEqual(instructor_task.task_type, task_type) + assert instructor_task.task_state == FAILURE + assert instructor_task.requester.username == 'instructor' + assert instructor_task.task_type == task_type task_input = json.loads(instructor_task.task_input) - self.assertNotIn('student', task_input) - self.assertEqual(task_input['problem_url'], text_type(InstructorTaskModuleTestCase.problem_location(problem_url_name))) # lint-amnesty, pylint: disable=line-too-long + assert 'student' not in task_input + assert task_input['problem_url'] == text_type(InstructorTaskModuleTestCase.problem_location(problem_url_name)) + # lint-amnesty, pylint: disable=line-too-long status = json.loads(instructor_task.task_output) - self.assertEqual(status['exception'], 'ZeroDivisionError') - self.assertEqual(status['message'], expected_message) + assert status['exception'] == 'ZeroDivisionError' + assert status['message'] == expected_message # check status returned: status = InstructorTaskModuleTestCase.get_task_status(instructor_task.task_id) - self.assertEqual(status['message'], expected_message) + assert status['message'] == expected_message @ddt.ddt @@ -120,26 +121,24 @@ class TestRescoringTask(TestIntegrationTask): Values checked include the number of attempts, the score, and the max score for a problem. """ module = self.get_student_module(user.username, descriptor) - self.assertEqual(module.grade, expected_score) - self.assertEqual(module.max_grade, expected_max_score) + assert module.grade == expected_score + assert module.max_grade == expected_max_score state = json.loads(module.state) attempts = state['attempts'] - self.assertEqual(attempts, expected_attempts) + assert attempts == expected_attempts if attempts > 0: - self.assertIn('correct_map', state) - self.assertIn('student_answers', state) - self.assertGreater(len(state['correct_map']), 0) - self.assertGreater(len(state['student_answers']), 0) + assert 'correct_map' in state + assert 'student_answers' in state + assert len(state['correct_map']) > 0 + assert len(state['student_answers']) > 0 # assume only one problem in the subsection and the grades # are in sync. expected_subsection_grade = expected_score course_grade = CourseGradeFactory().read(user, self.course) - self.assertEqual( - course_grade.graded_subsections_by_format['Homework'][self.problem_section.location].graded_total.earned, - expected_subsection_grade, - ) + assert course_grade.graded_subsections_by_format['Homework'][self.problem_section.location].graded_total.earned\ + == expected_subsection_grade def submit_rescore_all_student_answers(self, instructor, problem_url_name, only_if_higher=False): """Submits the particular problem for rescoring""" @@ -300,16 +299,17 @@ class TestRescoringTask(TestIntegrationTask): # check instructor_task returned instructor_task = InstructorTask.objects.get(id=instructor_task.id) - self.assertEqual(instructor_task.task_state, 'SUCCESS') - self.assertEqual(instructor_task.requester.username, 'instructor') - self.assertEqual(instructor_task.task_type, 'rescore_problem') + assert instructor_task.task_state == 'SUCCESS' + assert instructor_task.requester.username == 'instructor' + assert instructor_task.task_type == 'rescore_problem' task_input = json.loads(instructor_task.task_input) - self.assertNotIn('student', task_input) - self.assertEqual(task_input['problem_url'], text_type(InstructorTaskModuleTestCase.problem_location(problem_url_name))) # lint-amnesty, pylint: disable=line-too-long + assert 'student' not in task_input + assert task_input['problem_url'] == text_type(InstructorTaskModuleTestCase.problem_location(problem_url_name)) + # lint-amnesty, pylint: disable=line-too-long status = json.loads(instructor_task.task_output) - self.assertEqual(status['attempted'], 1) - self.assertEqual(status['succeeded'], 0) - self.assertEqual(status['total'], 1) + assert status['attempted'] == 1 + assert status['succeeded'] == 0 + assert status['total'] == 1 def define_code_response_problem(self, problem_url_name): """ @@ -340,13 +340,13 @@ class TestRescoringTask(TestIntegrationTask): instructor_task = self.submit_rescore_all_student_answers('instructor', problem_url_name) instructor_task = InstructorTask.objects.get(id=instructor_task.id) - self.assertEqual(instructor_task.task_state, FAILURE) + assert instructor_task.task_state == FAILURE status = json.loads(instructor_task.task_output) - self.assertEqual(status['exception'], 'NotImplementedError') - self.assertEqual(status['message'], "Problem's definition does not support rescoring.") + assert status['exception'] == 'NotImplementedError' + assert status['message'] == "Problem's definition does not support rescoring." status = InstructorTaskModuleTestCase.get_task_status(instructor_task.task_id) - self.assertEqual(status['message'], "Problem's definition does not support rescoring.") + assert status['message'] == "Problem's definition does not support rescoring." def define_randomized_custom_response_problem(self, problem_url_name, redefine=False): """ @@ -476,12 +476,12 @@ class TestResetAttemptsTask(TestIntegrationTask): self.submit_student_answer(username, problem_url_name, [OPTION_1, OPTION_1]) for username in self.userlist: - self.assertEqual(self.get_num_attempts(username, descriptor), num_attempts) + assert self.get_num_attempts(username, descriptor) == num_attempts self.reset_problem_attempts('instructor', location) for username in self.userlist: - self.assertEqual(self.get_num_attempts(username, descriptor), 0) + assert self.get_num_attempts(username, descriptor) == 0 def test_reset_failure(self): """Simulate a failure in resetting attempts on a problem""" @@ -501,7 +501,7 @@ class TestResetAttemptsTask(TestIntegrationTask): location = self.problem_section.location instructor_task = self.reset_problem_attempts('instructor', location) instructor_task = InstructorTask.objects.get(id=instructor_task.id) - self.assertEqual(instructor_task.task_state, SUCCESS) + assert instructor_task.task_state == SUCCESS class TestDeleteProblemTask(TestIntegrationTask): @@ -537,12 +537,12 @@ class TestDeleteProblemTask(TestIntegrationTask): self.submit_student_answer(username, problem_url_name, [OPTION_1, OPTION_1]) # confirm that state exists: for username in self.userlist: - self.assertIsNotNone(self.get_student_module(username, descriptor)) + assert self.get_student_module(username, descriptor) is not None # run delete task: self.delete_problem_state('instructor', location) # confirm that no state can be found: for username in self.userlist: - with self.assertRaises(StudentModule.DoesNotExist): + with pytest.raises(StudentModule.DoesNotExist): self.get_student_module(username, descriptor) def test_delete_failure(self): @@ -563,7 +563,7 @@ class TestDeleteProblemTask(TestIntegrationTask): location = self.problem_section.location instructor_task = self.delete_problem_state('instructor', location) instructor_task = InstructorTask.objects.get(id=instructor_task.id) - self.assertEqual(instructor_task.task_state, SUCCESS) + assert instructor_task.task_state == SUCCESS class TestGradeReportConditionalContent(TestReportMixin, TestConditionalContent, TestIntegrationTask): diff --git a/lms/djangoapps/instructor_task/tests/test_models.py b/lms/djangoapps/instructor_task/tests/test_models.py index 324484141e..1891547863 100644 --- a/lms/djangoapps/instructor_task/tests/test_models.py +++ b/lms/djangoapps/instructor_task/tests/test_models.py @@ -6,7 +6,7 @@ Tests for instructor_task/models.py. import copy import time from six import StringIO - +import pytest from django.conf import settings from django.test import SimpleTestCase, TestCase, override_settings from opaque_keys.edx.locator import CourseLocator @@ -25,7 +25,7 @@ class TestInstructorTasksModel(TestCase): Test allowed length of task_input field """ task_input = 's' * TASK_INPUT_LENGTH - with self.assertRaises(AttributeError): + with pytest.raises(AttributeError): InstructorTask.create( course_id='dummy_course_id', task_type='dummy type', @@ -56,7 +56,7 @@ class ReportStoreTestMixin(object): in reverse chronological order. """ report_store = self.create_report_store() # lint-amnesty, pylint: disable=assignment-from-no-return - self.assertEqual(report_store.links_for(self.course_id), []) + assert report_store.links_for(self.course_id) == [] report_store.store(self.course_id, 'old_file', StringIO()) time.sleep(1) # Ensure we have a unique timestamp. @@ -64,10 +64,7 @@ class ReportStoreTestMixin(object): time.sleep(1) # Ensure we have a unique timestamp. report_store.store(self.course_id, 'new_file', StringIO()) - self.assertEqual( - [link[0] for link in report_store.links_for(self.course_id)], - ['new_file', 'middle_file', 'old_file'] - ) + assert [link[0] for link in report_store.links_for(self.course_id)] == ['new_file', 'middle_file', 'old_file'] class LocalFSReportStoreTestCase(ReportStoreTestMixin, TestReportMixin, SimpleTestCase): @@ -137,4 +134,4 @@ class TestS3ReportStorage(TestCase): }): report_store = ReportStore.from_config(config_name="FINANCIAL_REPORTS") # Make sure CUSTOM_DOMAIN from FINANCIAL_REPORTS is used to construct file url - self.assertIn("edx-financial-reports.s3.amazonaws.com", report_store.storage.url("")) + assert 'edx-financial-reports.s3.amazonaws.com' in report_store.storage.url('') diff --git a/lms/djangoapps/instructor_task/tests/test_subtasks.py b/lms/djangoapps/instructor_task/tests/test_subtasks.py index ece5ed4429..b46f09cfde 100644 --- a/lms/djangoapps/instructor_task/tests/test_subtasks.py +++ b/lms/djangoapps/instructor_task/tests/test_subtasks.py @@ -67,9 +67,9 @@ class TestSubtasks(InstructorTaskCourseTestCase): # Check number of items for each subtask mock_create_subtask_fcn_args = mock_create_subtask_fcn.call_args_list - self.assertEqual(len(mock_create_subtask_fcn_args[0][0][0]), 3) - self.assertEqual(len(mock_create_subtask_fcn_args[1][0][0]), 3) - self.assertEqual(len(mock_create_subtask_fcn_args[2][0][0]), 2) + assert len(mock_create_subtask_fcn_args[0][0][0]) == 3 + assert len(mock_create_subtask_fcn_args[1][0][0]) == 3 + assert len(mock_create_subtask_fcn_args[2][0][0]) == 2 def test_queue_subtasks_for_query2(self): """Test queue_subtasks_for_query() if the last subtask needs to accommodate > items_per_task items.""" @@ -79,6 +79,6 @@ class TestSubtasks(InstructorTaskCourseTestCase): # Check number of items for each subtask mock_create_subtask_fcn_args = mock_create_subtask_fcn.call_args_list - self.assertEqual(len(mock_create_subtask_fcn_args[0][0][0]), 3) - self.assertEqual(len(mock_create_subtask_fcn_args[1][0][0]), 3) - self.assertEqual(len(mock_create_subtask_fcn_args[2][0][0]), 5) + assert len(mock_create_subtask_fcn_args[0][0][0]) == 3 + assert len(mock_create_subtask_fcn_args[1][0][0]) == 3 + assert len(mock_create_subtask_fcn_args[2][0][0]) == 5 diff --git a/lms/djangoapps/instructor_task/tests/test_tasks.py b/lms/djangoapps/instructor_task/tests/test_tasks.py index cc810035a0..3c3c0b2409 100644 --- a/lms/djangoapps/instructor_task/tests/test_tasks.py +++ b/lms/djangoapps/instructor_task/tests/test_tasks.py @@ -9,7 +9,7 @@ paths actually work. import json from functools import partial # lint-amnesty, pylint: disable=unused-import from uuid import uuid4 - +import pytest import ddt from celery.states import FAILURE, SUCCESS from django.utils.translation import ugettext_noop @@ -109,19 +109,19 @@ class TestInstructorTasks(InstructorTaskModuleTestCase): def _test_missing_current_task(self, task_class): """Check that a task_class fails when celery doesn't provide a current_task.""" task_entry = self._create_input_entry() - with self.assertRaises(ValueError): + with pytest.raises(ValueError): task_class(task_entry.id, self._get_xmodule_instance_args()) def _test_undefined_course(self, task_class): """Run with celery, but with no course defined.""" task_entry = self._create_input_entry(course_id="bogus/course/id") - with self.assertRaises(ItemNotFoundError): + with pytest.raises(ItemNotFoundError): self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id) def _test_undefined_problem(self, task_class): """Run with celery, but no problem defined.""" task_entry = self._create_input_entry() - with self.assertRaises(ItemNotFoundError): + with pytest.raises(ItemNotFoundError): self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id) def _test_run_with_task(self, task_class, action_name, expected_num_succeeded, @@ -134,16 +134,16 @@ class TestInstructorTasks(InstructorTaskModuleTestCase): expected_total = expected_total \ if expected_total else expected_num_succeeded + expected_num_skipped # check return value - self.assertEqual(status.get('attempted'), expected_attempted) - self.assertEqual(status.get('succeeded'), expected_num_succeeded) - self.assertEqual(status.get('skipped'), expected_num_skipped) - self.assertEqual(status.get('total'), expected_total) - self.assertEqual(status.get('action_name'), action_name) - self.assertGreater(status.get('duration_ms'), 0) + assert status.get('attempted') == expected_attempted + assert status.get('succeeded') == expected_num_succeeded + assert status.get('skipped') == expected_num_skipped + assert status.get('total') == expected_total + assert status.get('action_name') == action_name + assert status.get('duration_ms') > 0 # compare with entry in table: entry = InstructorTask.objects.get(id=task_entry.id) - self.assertEqual(json.loads(entry.task_output), status) - self.assertEqual(entry.task_state, SUCCESS) + assert json.loads(entry.task_output) == status + assert entry.task_state == SUCCESS def _test_run_with_no_state(self, task_class, action_name): """Run with no StudentModules defined for the current problem.""" @@ -186,20 +186,20 @@ class TestInstructorTasks(InstructorTaskModuleTestCase): student=student, module_state_key=self.location) state = json.loads(module.state) - self.assertEqual(state['attempts'], num_attempts) + assert state['attempts'] == num_attempts def _test_run_with_failure(self, task_class, expected_message): """Run a task and trigger an artificial failure with the given message.""" task_entry = self._create_input_entry() self.define_option_problem(PROBLEM_URL_NAME) - with self.assertRaises(TestTaskFailure): + with pytest.raises(TestTaskFailure): self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id, expected_message) # compare with entry in table: entry = InstructorTask.objects.get(id=task_entry.id) - self.assertEqual(entry.task_state, FAILURE) + assert entry.task_state == FAILURE output = json.loads(entry.task_output) - self.assertEqual(output['exception'], 'TestTaskFailure') - self.assertEqual(output['message'], expected_message) + assert output['exception'] == 'TestTaskFailure' + assert output['message'] == expected_message def _test_run_with_long_error_msg(self, task_class): """ @@ -209,16 +209,16 @@ class TestInstructorTasks(InstructorTaskModuleTestCase): task_entry = self._create_input_entry() self.define_option_problem(PROBLEM_URL_NAME) expected_message = "x" * 1500 - with self.assertRaises(TestTaskFailure): + with pytest.raises(TestTaskFailure): self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id, expected_message) # compare with entry in table: entry = InstructorTask.objects.get(id=task_entry.id) - self.assertEqual(entry.task_state, FAILURE) - self.assertGreater(1023, len(entry.task_output)) + assert entry.task_state == FAILURE + assert 1023 > len(entry.task_output) output = json.loads(entry.task_output) - self.assertEqual(output['exception'], 'TestTaskFailure') - self.assertEqual(output['message'], expected_message[:len(output['message']) - 3] + "...") - self.assertNotIn('traceback', output) + assert output['exception'] == 'TestTaskFailure' + assert output['message'] == (expected_message[:(len(output['message']) - 3)] + '...') + assert 'traceback' not in output def _test_run_with_short_error_msg(self, task_class): """ @@ -229,16 +229,16 @@ class TestInstructorTasks(InstructorTaskModuleTestCase): task_entry = self._create_input_entry() self.define_option_problem(PROBLEM_URL_NAME) expected_message = "x" * 900 - with self.assertRaises(TestTaskFailure): + with pytest.raises(TestTaskFailure): self._run_task_with_mock_celery(task_class, task_entry.id, task_entry.task_id, expected_message) # compare with entry in table: entry = InstructorTask.objects.get(id=task_entry.id) - self.assertEqual(entry.task_state, FAILURE) - self.assertGreater(1023, len(entry.task_output)) + assert entry.task_state == FAILURE + assert 1023 > len(entry.task_output) output = json.loads(entry.task_output) - self.assertEqual(output['exception'], 'TestTaskFailure') - self.assertEqual(output['message'], expected_message) - self.assertEqual(output['traceback'][-3:], "...") + assert output['exception'] == 'TestTaskFailure' + assert output['message'] == expected_message + assert output['traceback'][(- 3):] == '...' class TestOverrideScoreInstructorTask(TestInstructorTasks): @@ -247,13 +247,13 @@ class TestOverrideScoreInstructorTask(TestInstructorTasks): """ Check & compare output of the task """ - self.assertEqual(output.get('total'), expected_output.get('total')) - self.assertEqual(output.get('attempted'), expected_output.get('attempted')) - self.assertEqual(output.get('succeeded'), expected_output.get('succeeded')) - self.assertEqual(output.get('skipped'), expected_output.get('skipped')) - self.assertEqual(output.get('failed'), expected_output.get('failed')) - self.assertEqual(output.get('action_name'), expected_output.get('action_name')) - self.assertGreater(output.get('duration_ms'), expected_output.get('duration_ms', 0)) + assert output.get('total') == expected_output.get('total') + assert output.get('attempted') == expected_output.get('attempted') + assert output.get('succeeded') == expected_output.get('succeeded') + assert output.get('skipped') == expected_output.get('skipped') + assert output.get('failed') == expected_output.get('failed') + assert output.get('action_name') == expected_output.get('action_name') + assert output.get('duration_ms') > expected_output.get('duration_ms', 0) def get_task_output(self, task_id): """Get and load instructor task output""" @@ -298,14 +298,14 @@ class TestOverrideScoreInstructorTask(TestInstructorTasks): 'lms.djangoapps.instructor_task.tasks_helper.module_state.get_module_for_descriptor_internal' ) as mock_get_module: mock_get_module.return_value = mock_instance - with self.assertRaises(UpdateProblemModuleStateError): + with pytest.raises(UpdateProblemModuleStateError): self._run_task_with_mock_celery(override_problem_score, task_entry.id, task_entry.task_id) # check values stored in table: entry = InstructorTask.objects.get(id=task_entry.id) output = json.loads(entry.task_output) - self.assertEqual(output['exception'], "UpdateProblemModuleStateError") - self.assertEqual(output['message'], "Scores cannot be overridden for this problem type.") - self.assertGreater(len(output['traceback']), 0) + assert output['exception'] == 'UpdateProblemModuleStateError' + assert output['message'] == 'Scores cannot be overridden for this problem type.' + assert len(output['traceback']) > 0 def test_overriding_unaccessable(self): """ @@ -386,13 +386,13 @@ class TestRescoreInstructorTask(TestInstructorTasks): """ Check & compare output of the task """ - self.assertEqual(output.get('total'), expected_output.get('total')) - self.assertEqual(output.get('attempted'), expected_output.get('attempted')) - self.assertEqual(output.get('succeeded'), expected_output.get('succeeded')) - self.assertEqual(output.get('skipped'), expected_output.get('skipped')) - self.assertEqual(output.get('failed'), expected_output.get('failed')) - self.assertEqual(output.get('action_name'), expected_output.get('action_name')) - self.assertGreater(output.get('duration_ms'), expected_output.get('duration_ms', 0)) + assert output.get('total') == expected_output.get('total') + assert output.get('attempted') == expected_output.get('attempted') + assert output.get('succeeded') == expected_output.get('succeeded') + assert output.get('skipped') == expected_output.get('skipped') + assert output.get('failed') == expected_output.get('failed') + assert output.get('action_name') == expected_output.get('action_name') + assert output.get('duration_ms') > expected_output.get('duration_ms', 0) def get_task_output(self, task_id): """Get and load instructor task output""" @@ -430,17 +430,15 @@ class TestRescoreInstructorTask(TestInstructorTasks): del mock_instance.rescore with patch('lms.djangoapps.instructor_task.tasks_helper.module_state.get_module_for_descriptor_internal') as mock_get_module: # lint-amnesty, pylint: disable=line-too-long mock_get_module.return_value = mock_instance - with self.assertRaises(UpdateProblemModuleStateError): + with pytest.raises(UpdateProblemModuleStateError): self._run_task_with_mock_celery(rescore_problem, task_entry.id, task_entry.task_id) # check values stored in table: entry = InstructorTask.objects.get(id=task_entry.id) output = json.loads(entry.task_output) - self.assertEqual(output['exception'], "UpdateProblemModuleStateError") - self.assertEqual(output['message'], u"Specified module {0} of type {1} does not support rescoring.".format( - self.location, - mock_instance.__class__, - )) - self.assertGreater(len(output['traceback']), 0) + assert output['exception'] == 'UpdateProblemModuleStateError' + assert output['message'] == u'Specified module {0} of type {1} does not support rescoring.'\ + .format(self.location, mock_instance.__class__) + assert len(output['traceback']) > 0 def test_rescoring_unaccessable(self): """ @@ -553,7 +551,7 @@ class TestResetAttemptsInstructorTask(TestInstructorTasks): student=student, module_state_key=self.location) state = json.loads(module.state) - self.assertEqual(state['attempts'], initial_attempts) + assert state['attempts'] == initial_attempts if use_email: student_ident = students[3].email @@ -563,16 +561,16 @@ class TestResetAttemptsInstructorTask(TestInstructorTasks): status = self._run_task_with_mock_celery(reset_problem_attempts, task_entry.id, task_entry.task_id) # check return value - self.assertEqual(status.get('attempted'), 1) - self.assertEqual(status.get('succeeded'), 1) - self.assertEqual(status.get('total'), 1) - self.assertEqual(status.get('action_name'), 'reset') - self.assertGreater(status.get('duration_ms'), 0) + assert status.get('attempted') == 1 + assert status.get('succeeded') == 1 + assert status.get('total') == 1 + assert status.get('action_name') == 'reset' + assert status.get('duration_ms') > 0 # compare with entry in table: entry = InstructorTask.objects.get(id=task_entry.id) - self.assertEqual(json.loads(entry.task_output), status) - self.assertEqual(entry.task_state, SUCCESS) + assert json.loads(entry.task_output) == status + assert entry.task_state == SUCCESS # check that the correct entry was reset for index, student in enumerate(students): module = StudentModule.objects.get(course_id=self.course.id, @@ -580,9 +578,9 @@ class TestResetAttemptsInstructorTask(TestInstructorTasks): module_state_key=self.location) state = json.loads(module.state) if index == 3: - self.assertEqual(state['attempts'], 0) + assert state['attempts'] == 0 else: - self.assertEqual(state['attempts'], initial_attempts) + assert state['attempts'] == initial_attempts def test_reset_with_student_username(self): self._test_reset_with_student(False) @@ -628,7 +626,7 @@ class TestDeleteStateInstructorTask(TestInstructorTasks): self._test_run_with_task(delete_problem_state, 'deleted', num_students) # confirm that no state can be found anymore: for student in students: - with self.assertRaises(StudentModule.DoesNotExist): + with pytest.raises(StudentModule.DoesNotExist): StudentModule.objects.get(course_id=self.course.id, student=student, module_state_key=self.location) diff --git a/lms/djangoapps/instructor_task/tests/test_tasks_helper.py b/lms/djangoapps/instructor_task/tests/test_tasks_helper.py index df9e530fc7..9f05da7570 100644 --- a/lms/djangoapps/instructor_task/tests/test_tasks_helper.py +++ b/lms/djangoapps/instructor_task/tests/test_tasks_helper.py @@ -106,9 +106,9 @@ class InstructorGradeReportTestCase(TestReportMixin, InstructorTaskCourseTestCas with report_store.storage.open(report_path) as csv_file: for row in unicodecsv.DictReader(csv_file): if row.get('Username') == username: - self.assertEqual(row[column_header], expected_cell_content) + assert row[column_header] == expected_cell_content found_user = True - self.assertTrue(found_user) + assert found_user @ddt.ddt @@ -150,7 +150,7 @@ class TestInstructorGradeReport(InstructorGradeReportTestCase): self.assertDictContainsSubset({'attempted': 1, 'succeeded': 0, 'failed': 1}, result) report_store = ReportStore.from_config(config_name='GRADES_DOWNLOAD') - self.assertTrue(any('grade_report_err' in item[0] for item in report_store.links_for(self.course.id))) + assert any((('grade_report_err' in item[0]) for item in report_store.links_for(self.course.id))) def test_cohort_data_in_grading(self): """ @@ -217,7 +217,7 @@ class TestInstructorGradeReport(InstructorGradeReportTestCase): ) _groups = [group.name for group in self.course.user_partitions[0].groups] - self.assertEqual(_groups, user_groups) + assert _groups == user_groups def test_cohort_scheme_partition(self): """ @@ -517,7 +517,7 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): usage_key_str_list=[str(self.course.location)], ) - self.assertEqual(len(student_data), 4) + assert len(student_data) == 4 @patch( 'lms.djangoapps.instructor_task.tasks_helper.grades.list_problem_responses', @@ -536,16 +536,15 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): course_key=self.course.id, usage_key_str_list=[str(problem.location)], ) - self.assertEqual(len(student_data), 1) + assert len(student_data) == 1 self.assertDictContainsSubset({ 'username': 'student', 'location': 'test_course > Section > Subsection > Problem1', 'block_key': 'i4x://edx/1.23x/problem/Problem1', 'title': 'Problem1', }, student_data[0]) - self.assertIn('state', student_data[0]) - self.assertEqual(student_data_keys_list, - ['username', 'title', 'location', 'block_key', 'state']) + assert 'state' in student_data[0] + assert student_data_keys_list == ['username', 'title', 'location', 'block_key', 'state'] mock_list_problem_responses.assert_called_with(self.course.id, ANY, ANY) @patch('xmodule.capa_module.ProblemBlock.generate_report_data', create=True) @@ -567,7 +566,7 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): course_key=self.course.id, usage_key_str_list=[str(self.course.location)], ) - self.assertEqual(len(student_data), 2) + assert len(student_data) == 2 self.assertDictContainsSubset({ 'username': 'student', 'location': 'test_course > Section > Subsection > Problem1', @@ -584,9 +583,8 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): 'some': 'state2', 'more': 'state2!', }, student_data[1]) - self.assertEqual(student_data[0]['state'], student_data[1]['state']) - self.assertEqual(student_data_keys_list, - ['username', 'title', 'location', 'more', 'some', 'block_key', 'state']) + assert student_data[0]['state'] == student_data[1]['state'] + assert student_data_keys_list == ['username', 'title', 'location', 'more', 'some', 'block_key', 'state'] @patch('xmodule.capa_module.ProblemBlock.generate_report_data', create=True) def test_build_student_data_for_block_with_ordered_generate_report_data(self, mock_generate_report_data): @@ -609,7 +607,7 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): course_key=self.course.id, usage_key_str_list=[str(self.course.location)], ) - self.assertEqual(len(student_data), 2) + assert len(student_data) == 2 self.assertDictContainsSubset({ 'username': 'student', 'location': 'test_course > Section > Subsection > Problem1', @@ -626,9 +624,8 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): 'some': 'state2', 'more': 'state2!', }, student_data[1]) - self.assertEqual(student_data[0]['state'], student_data[1]['state']) - self.assertEqual(student_data_keys_list, - ['username', 'title', 'location', 'some', 'more', 'block_key', 'state']) + assert student_data[0]['state'] == student_data[1]['state'] + assert student_data_keys_list == ['username', 'title', 'location', 'some', 'more', 'block_key', 'state'] def test_build_student_data_for_block_with_real_generate_report_data(self): """ @@ -642,7 +639,7 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): course_key=self.course.id, usage_key_str_list=[str(self.course.location)], ) - self.assertEqual(len(student_data), 1) + assert len(student_data) == 1 self.assertDictContainsSubset({ 'username': 'student', 'location': 'test_course > Section > Subsection > Problem1', @@ -653,11 +650,9 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): 'Correct Answer': u'Option 1', 'Question': u'The correct answer is Option 1', }, student_data[0]) - self.assertIn('state', student_data[0]) - self.assertEqual(student_data_keys_list, - ['username', 'title', 'location', - 'Answer', 'Answer ID', 'Correct Answer', 'Question', - 'block_key', 'state']) + assert 'state' in student_data[0] + assert student_data_keys_list == ['username', 'title', 'location', 'Answer', 'Answer ID', 'Correct Answer', + 'Question', 'block_key', 'state'] def test_build_student_data_for_multiple_problems(self): """ @@ -672,7 +667,7 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): course_key=self.course.id, usage_key_str_list=[str(problem1.location), str(problem2.location)], ) - self.assertEqual(len(student_data), 2) + assert len(student_data) == 2 for idx in range(1, 3): self.assertDictContainsSubset({ 'username': 'student', @@ -684,7 +679,7 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): 'Correct Answer': u'Option 1', 'Question': u'The correct answer is Option 1', }, student_data[idx - 1]) - self.assertIn('state', student_data[idx - 1]) + assert 'state' in student_data[(idx - 1)] @ddt.data( (['problem'], 5), @@ -717,7 +712,7 @@ class TestProblemResponsesReport(TestReportMixin, InstructorTaskModuleTestCase): usage_key_str_list=[str(self.course.location)], filter_types=filters, ) - self.assertEqual(len(student_data), filtered_count) + assert len(student_data) == filtered_count @patch('lms.djangoapps.instructor_task.tasks_helper.grades.list_problem_responses') @patch('xmodule.capa_module.ProblemBlock.generate_report_data', create=True) @@ -1076,7 +1071,7 @@ class TestProblemReportSplitTestContent(TestReportMixin, TestConditionalContent, with patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task'): ProblemGradeReport.generate(None, None, self.course.id, None, 'graded') - self.assertEqual(self.get_csv_row_with_headers(), header_row) + assert self.get_csv_row_with_headers() == header_row class TestProblemReportCohortedContent(TestReportMixin, ContentGroupTestCase, InstructorTaskModuleTestCase): @@ -1125,10 +1120,10 @@ class TestProblemReportCohortedContent(TestReportMixin, ContentGroupTestCase, In def test_cohort_content(self): self.submit_student_answer(self.alpha_user.username, u'Problem0', ['Option 1', 'Option 1']) resp = self.submit_student_answer(self.alpha_user.username, u'Problem1', ['Option 1', 'Option 1']) - self.assertEqual(resp.status_code, 404) + assert resp.status_code == 404 resp = self.submit_student_answer(self.beta_user.username, u'Problem0', ['Option 1', 'Option 2']) - self.assertEqual(resp.status_code, 404) + assert resp.status_code == 404 self.submit_student_answer(self.beta_user.username, u'Problem1', ['Option 1', 'Option 2']) with patch('lms.djangoapps.instructor_task.tasks_helper.runner._get_current_task'): @@ -1266,7 +1261,7 @@ class TestCourseSurveyReport(TestReportMixin, InstructorTaskCourseTestCase): # Removing unicode signature (BOM) from the beginning csv_file_data = csv_file_data.decode("utf-8-sig") for data in expected_data: - self.assertIn(data, csv_file_data) + assert data in csv_file_data @ddt.ddt @@ -1286,7 +1281,7 @@ class TestStudentReport(TestReportMixin, InstructorTaskCourseTestCase): report_store = ReportStore.from_config(config_name='GRADES_DOWNLOAD') links = report_store.links_for(self.course.id) - self.assertEqual(len(links), 1) + assert len(links) == 1 self.assertDictContainsSubset({'attempted': 1, 'succeeded': 1, 'failed': 0}, result) @ddt.data([u'student', u'student\xec']) @@ -1348,9 +1343,9 @@ class TestTeamStudentReport(TestReportMixin, InstructorTaskCourseTestCase): with report_store.storage.open(report_path) as csv_file: for row in unicodecsv.DictReader(csv_file): if row.get('username') == username: - self.assertEqual(row['team'], expected_team) + assert row['team'] == expected_team found_user = True - self.assertTrue(found_user) + assert found_user def test_team_column_no_teams(self): self._generate_and_verify_teams_column(self.student1.username, UNAVAILABLE) @@ -1404,7 +1399,7 @@ class TestListMayEnroll(TestReportMixin, InstructorTaskCourseTestCase): report_store = ReportStore.from_config(config_name='GRADES_DOWNLOAD') links = report_store.links_for(self.course.id) - self.assertEqual(len(links), 1) + assert len(links) == 1 self.assertDictContainsSubset({'attempted': 1, 'succeeded': 1, 'failed': 0}, result) def test_unicode_email_addresses(self): @@ -1847,8 +1842,8 @@ class TestGradeReport(TestReportMixin, InstructorTaskModuleTestCase): with patch('lms.djangoapps.grades.course_data.get_course_blocks') as mock_course_blocks: with patch('lms.djangoapps.grades.subsection_grade.get_score') as mock_get_score: CourseGradeReport.generate(None, None, self.course.id, None, 'graded') - self.assertFalse(mock_get_score.called) - self.assertFalse(mock_course_blocks.called) + assert not mock_get_score.called + assert not mock_course_blocks.called @ddt.ddt @@ -1919,9 +1914,9 @@ class TestGradeReportEnrollmentAndCertificateInfo(TestReportMixin, InstructorTas for row in unicodecsv.DictReader(csv_file): if row.get('Username') == username: csv_row_data = [row[column] for column in self.columns_to_check] - self.assertEqual(csv_row_data, expected_data) + assert csv_row_data == expected_data found_user = True - self.assertTrue(found_user) + assert found_user def _create_user_data(self, user_enroll_mode, @@ -2098,16 +2093,12 @@ class TestCertificateGeneration(InstructorTaskModuleTestCase): # the first 3 students (who were whitelisted) have passing # certificate statuses for student in students[:3]: - self.assertIn( - GeneratedCertificate.certificate_for_student(student, self.course.id).status, - CertificateStatuses.PASSED_STATUSES - ) + assert GeneratedCertificate.certificate_for_student(student, self.course.id).status in\ + CertificateStatuses.PASSED_STATUSES # The last 2 students still don't have certs for student in students[3:]: - self.assertIsNone( - GeneratedCertificate.certificate_for_student(student, self.course.id) - ) + assert GeneratedCertificate.certificate_for_student(student, self.course.id) is None @ddt.data( (CertificateStatuses.downloadable, 2), @@ -2158,15 +2149,11 @@ class TestCertificateGeneration(InstructorTaskModuleTestCase): # the first 4 students have passing certificate statuses since # they either were whitelisted or had one before for student in students[:4]: - self.assertIn( - GeneratedCertificate.certificate_for_student(student, self.course.id).status, - CertificateStatuses.PASSED_STATUSES - ) + assert GeneratedCertificate.certificate_for_student(student, self.course.id).status in\ + CertificateStatuses.PASSED_STATUSES # The last student still doesn't have a cert - self.assertIsNone( - GeneratedCertificate.certificate_for_student(students[4], self.course.id) - ) + assert GeneratedCertificate.certificate_for_student(students[4], self.course.id) is None def test_certificate_generation_specific_student(self): """ @@ -2348,15 +2335,15 @@ class TestCertificateGeneration(InstructorTaskModuleTestCase): # Verify from results from database # Certificates are being generated for 2 white-listed students that had statuses in 'deleted'' and 'generating' - self.assertEqual(certificate_statuses.count(CertificateStatuses.generating), 2) + assert certificate_statuses.count(CertificateStatuses.generating) == 2 # 5 students are skipped that had Certificate Status 'downloadable' and 'error' - self.assertEqual(certificate_statuses.count(CertificateStatuses.downloadable), 2) - self.assertEqual(certificate_statuses.count(CertificateStatuses.error), 3) + assert certificate_statuses.count(CertificateStatuses.downloadable) == 2 + assert certificate_statuses.count(CertificateStatuses.error) == 3 # grades will be '0.0' as students are either white-listed or ending in error - self.assertEqual(certificate_grades.count('0.0'), 5) + assert certificate_grades.count('0.0') == 5 # grades will be '-1' for students that were skipped - self.assertEqual(certificate_grades.count(default_grade), 5) + assert certificate_grades.count(default_grade) == 5 def test_certificate_regeneration_with_existing_unavailable_status(self): """ @@ -2448,21 +2435,21 @@ class TestCertificateGeneration(InstructorTaskModuleTestCase): # Verify from results from database # Certificates are being generated for 8 students that had statuses in 'downloadable', 'error' and 'generating' - self.assertEqual(certificate_statuses.count(CertificateStatuses.generating), 8) + assert certificate_statuses.count(CertificateStatuses.generating) == 8 # 2 students are skipped that had Certificate Status 'unavailable' - self.assertEqual(certificate_statuses.count(CertificateStatuses.unavailable), 2) + assert certificate_statuses.count(CertificateStatuses.unavailable) == 2 # grades will be '0.0' as students are white-listed and have not completed any tasks - self.assertEqual(certificate_grades.count('0.0'), 8) + assert certificate_grades.count('0.0') == 8 # grades will be '-1' for students that have not been processed - self.assertEqual(certificate_grades.count(default_grade), 2) + assert certificate_grades.count(default_grade) == 2 # Verify that students with status 'unavailable were skipped unavailable_certificates = \ [cert for cert in generated_certificates if cert.status == CertificateStatuses.unavailable and cert.grade == default_grade] - self.assertEqual(len(unavailable_certificates), 2) + assert len(unavailable_certificates) == 2 def test_certificate_regeneration_for_students(self): """ @@ -2589,7 +2576,7 @@ class TestInstructorOra2Report(SharedModuleStoreTestCase): mock_current_task.return_value = self.current_task response = upload_ora2_data(None, None, self.course.id, None, 'generated') - self.assertEqual(response, UPDATE_STATUS_FAILED) + assert response == UPDATE_STATUS_FAILED def test_report_stores_results(self): with ExitStack() as stack: @@ -2618,7 +2605,7 @@ class TestInstructorOra2Report(SharedModuleStoreTestCase): course_id_string = quote(text_type(self.course.id).replace('/', '_')) filename = u'{}_ORA_data_{}.csv'.format(course_id_string, timestamp_str) - self.assertEqual(return_val, UPDATE_STATUS_SUCCEEDED) + assert return_val == UPDATE_STATUS_SUCCEEDED mock_store_rows.assert_called_once_with(self.course.id, filename, [test_header] + test_rows) @@ -2648,7 +2635,7 @@ class TestInstructorOra2AttachmentsExport(SharedModuleStoreTestCase): mock_collect_data.side_effect = KeyError response = upload_ora2_submission_files(None, None, self.course.id, None, 'compressed') - self.assertEqual(response, UPDATE_STATUS_FAILED) + assert response == UPDATE_STATUS_FAILED def test_export_fails_if_error_on_create_zip_step(self): with ExitStack() as stack: @@ -2667,7 +2654,7 @@ class TestInstructorOra2AttachmentsExport(SharedModuleStoreTestCase): create_zip_mock.side_effect = KeyError response = upload_ora2_submission_files(None, None, self.course.id, None, 'compressed') - self.assertEqual(response, UPDATE_STATUS_FAILED) + assert response == UPDATE_STATUS_FAILED def test_export_fails_if_error_on_upload_step(self): with ExitStack() as stack: @@ -2689,7 +2676,7 @@ class TestInstructorOra2AttachmentsExport(SharedModuleStoreTestCase): upload_mock.side_effect = KeyError response = upload_ora2_submission_files(None, None, self.course.id, None, 'compressed') - self.assertEqual(response, UPDATE_STATUS_FAILED) + assert response == UPDATE_STATUS_FAILED def test_task_stores_zip_with_attachments(self): with ExitStack() as stack: @@ -2714,4 +2701,4 @@ class TestInstructorOra2AttachmentsExport(SharedModuleStoreTestCase): mock_create_zip.assert_called_once() mock_store.assert_called_once() - self.assertEqual(response, UPDATE_STATUS_SUCCEEDED) + assert response == UPDATE_STATUS_SUCCEEDED diff --git a/lms/djangoapps/instructor_task/tests/test_views.py b/lms/djangoapps/instructor_task/tests/test_views.py index a54614f294..65a238325f 100644 --- a/lms/djangoapps/instructor_task/tests/test_views.py +++ b/lms/djangoapps/instructor_task/tests/test_views.py @@ -38,7 +38,7 @@ class InstructorTaskReportTest(InstructorTaskTestCase): request.GET = request.POST = {'task_id': task_id} response = instructor_task_status(request) output = json.loads(response.content.decode('utf-8')) - self.assertEqual(output['task_id'], task_id) + assert output['task_id'] == task_id def test_missing_instructor_task_status(self): task_id = "missing_id" @@ -46,7 +46,7 @@ class InstructorTaskReportTest(InstructorTaskTestCase): request.GET = request.POST = {'task_id': task_id} response = instructor_task_status(request) output = json.loads(response.content.decode('utf-8')) - self.assertEqual(output, {}) + assert output == {} def test_instructor_task_status_list(self): # Fetch status for existing tasks by arg list, as if called from ajax. @@ -59,9 +59,9 @@ class InstructorTaskReportTest(InstructorTaskTestCase): request.GET = request.POST = task_ids_query_dict response = instructor_task_status(request) output = json.loads(response.content.decode('utf-8')) - self.assertEqual(len(output), len(task_ids)) + assert len(output) == len(task_ids) for task_id in task_ids: - self.assertEqual(output[task_id]['task_id'], task_id) + assert output[task_id]['task_id'] == task_id def test_get_status_from_failure(self): # get status for a task that has already failed @@ -69,16 +69,16 @@ class InstructorTaskReportTest(InstructorTaskTestCase): task_id = instructor_task.task_id response = self._get_instructor_task_status(task_id) output = json.loads(response.content.decode('utf-8')) - self.assertEqual(output['message'], TEST_FAILURE_MESSAGE) - self.assertEqual(output['succeeded'], False) - self.assertEqual(output['task_id'], task_id) - self.assertEqual(output['task_state'], FAILURE) - self.assertFalse(output['in_progress']) + assert output['message'] == TEST_FAILURE_MESSAGE + assert output['succeeded'] is False + assert output['task_id'] == task_id + assert output['task_state'] == FAILURE + assert not output['in_progress'] expected_progress = { 'exception': TEST_FAILURE_EXCEPTION, 'message': TEST_FAILURE_MESSAGE, } - self.assertEqual(output['task_progress'], expected_progress) + assert output['task_progress'] == expected_progress def test_get_status_from_success(self): # get status for a task that has already succeeded @@ -86,18 +86,18 @@ class InstructorTaskReportTest(InstructorTaskTestCase): task_id = instructor_task.task_id response = self._get_instructor_task_status(task_id) output = json.loads(response.content.decode('utf-8')) - self.assertEqual(output['message'], "Problem rescored for 2 of 3 students (out of 5)") - self.assertEqual(output['succeeded'], False) - self.assertEqual(output['task_id'], task_id) - self.assertEqual(output['task_state'], SUCCESS) - self.assertFalse(output['in_progress']) + assert output['message'] == 'Problem rescored for 2 of 3 students (out of 5)' + assert output['succeeded'] is False + assert output['task_id'] == task_id + assert output['task_state'] == SUCCESS + assert not output['in_progress'] expected_progress = { 'attempted': 3, 'succeeded': 2, 'total': 5, 'action_name': 'rescored', } - self.assertEqual(output['task_progress'], expected_progress) + assert output['task_progress'] == expected_progress def test_get_status_from_legacy_success(self): # get status for a task that had already succeeded, back at a time @@ -112,12 +112,12 @@ class InstructorTaskReportTest(InstructorTaskTestCase): task_id = instructor_task.task_id response = self._get_instructor_task_status(task_id) output = json.loads(response.content.decode('utf-8')) - self.assertEqual(output['message'], "Problem rescored for 2 of 3 students (out of 5)") - self.assertEqual(output['succeeded'], False) - self.assertEqual(output['task_id'], task_id) - self.assertEqual(output['task_state'], SUCCESS) - self.assertFalse(output['in_progress']) - self.assertEqual(output['task_progress'], legacy_progress) + assert output['message'] == 'Problem rescored for 2 of 3 students (out of 5)' + assert output['succeeded'] is False + assert output['task_id'] == task_id + assert output['task_state'] == SUCCESS + assert not output['in_progress'] + assert output['task_progress'] == legacy_progress def _create_email_subtask_entry(self, total=5, attempted=3, succeeded=2, skipped=0, task_state=PROGRESS): """Create an InstructorTask with subtask defined and email argument.""" @@ -140,11 +140,11 @@ class InstructorTaskReportTest(InstructorTaskTestCase): task_id = instructor_task.task_id response = self._get_instructor_task_status(task_id) output = json.loads(response.content.decode('utf-8')) - self.assertEqual(output['message'], "Progress: emailed 2 of 3 so far (skipping 1) (out of 5)") - self.assertEqual(output['succeeded'], False) - self.assertEqual(output['task_id'], task_id) - self.assertEqual(output['task_state'], PROGRESS) - self.assertTrue(output['in_progress']) + assert output['message'] == 'Progress: emailed 2 of 3 so far (skipping 1) (out of 5)' + assert output['succeeded'] is False + assert output['task_id'] == task_id + assert output['task_state'] == PROGRESS + assert output['in_progress'] expected_progress = { 'attempted': 3, 'succeeded': 2, @@ -152,7 +152,7 @@ class InstructorTaskReportTest(InstructorTaskTestCase): 'total': 5, 'action_name': 'emailed', } - self.assertEqual(output['task_progress'], expected_progress) + assert output['task_progress'] == expected_progress def _test_get_status_from_result(self, task_id, mock_result=None): """ @@ -162,7 +162,7 @@ class InstructorTaskReportTest(InstructorTaskTestCase): mock_result_ctor.return_value = mock_result response = self._get_instructor_task_status(task_id) output = json.loads(response.content.decode('utf-8')) - self.assertEqual(output['task_id'], task_id) + assert output['task_id'] == task_id return output def test_get_status_to_pending(self): @@ -174,9 +174,9 @@ class InstructorTaskReportTest(InstructorTaskTestCase): mock_result.state = PENDING output = self._test_get_status_from_result(task_id, mock_result) for key in ['message', 'succeeded', 'task_progress']: - self.assertNotIn(key, output) - self.assertEqual(output['task_state'], 'PENDING') - self.assertTrue(output['in_progress']) + assert key not in output + assert output['task_state'] == 'PENDING' + assert output['in_progress'] def test_update_progress_to_progress(self): # view task entry for task in progress @@ -192,11 +192,11 @@ class InstructorTaskReportTest(InstructorTaskTestCase): 'action_name': 'rescored', } output = self._test_get_status_from_result(task_id, mock_result) - self.assertEqual(output['message'], "Progress: rescored 4 of 5 so far (out of 10)") - self.assertEqual(output['succeeded'], False) - self.assertEqual(output['task_state'], PROGRESS) - self.assertTrue(output['in_progress']) - self.assertEqual(output['task_progress'], mock_result.result) + assert output['message'] == 'Progress: rescored 4 of 5 so far (out of 10)' + assert output['succeeded'] is False + assert output['task_state'] == PROGRESS + assert output['in_progress'] + assert output['task_progress'] == mock_result.result def test_update_progress_to_failure(self): # view task entry for task in progress that later fails @@ -208,16 +208,16 @@ class InstructorTaskReportTest(InstructorTaskTestCase): mock_result.result = NotImplementedError("This task later failed.") mock_result.traceback = "random traceback" output = self._test_get_status_from_result(task_id, mock_result) - self.assertEqual(output['message'], "This task later failed.") - self.assertEqual(output['succeeded'], False) - self.assertEqual(output['task_state'], FAILURE) - self.assertFalse(output['in_progress']) + assert output['message'] == 'This task later failed.' + assert output['succeeded'] is False + assert output['task_state'] == FAILURE + assert not output['in_progress'] expected_progress = { 'exception': 'NotImplementedError', 'message': "This task later failed.", 'traceback': "random traceback", } - self.assertEqual(output['task_progress'], expected_progress) + assert output['task_progress'] == expected_progress def test_update_progress_to_revoked(self): # view task entry for task in progress that later fails @@ -227,12 +227,12 @@ class InstructorTaskReportTest(InstructorTaskTestCase): mock_result.task_id = task_id mock_result.state = REVOKED output = self._test_get_status_from_result(task_id, mock_result) - self.assertEqual(output['message'], "Task revoked before running") - self.assertEqual(output['succeeded'], False) - self.assertEqual(output['task_state'], REVOKED) - self.assertFalse(output['in_progress']) + assert output['message'] == 'Task revoked before running' + assert output['succeeded'] is False + assert output['task_state'] == REVOKED + assert not output['in_progress'] expected_progress = {'message': "Task revoked before running"} - self.assertEqual(output['task_progress'], expected_progress) + assert output['task_progress'] == expected_progress def _get_output_for_task_success(self, attempted, succeeded, total, student=None): """returns the task_id and the result returned by instructor_task_status().""" @@ -264,127 +264,127 @@ class InstructorTaskReportTest(InstructorTaskTestCase): def test_update_progress_to_success(self): output = self._get_output_for_task_success(10, 8, 10) - self.assertEqual(output['message'], "Problem rescored for 8 of 10 students") - self.assertEqual(output['succeeded'], False) - self.assertEqual(output['task_state'], SUCCESS) - self.assertFalse(output['in_progress']) + assert output['message'] == 'Problem rescored for 8 of 10 students' + assert output['succeeded'] is False + assert output['task_state'] == SUCCESS + assert not output['in_progress'] expected_progress = { 'attempted': 10, 'succeeded': 8, 'total': 10, 'action_name': 'rescored', } - self.assertEqual(output['task_progress'], expected_progress) + assert output['task_progress'] == expected_progress def test_success_messages(self): output = self._get_output_for_task_success(0, 0, 10) - self.assertEqual(output['message'], "Unable to find any students with submissions to be rescored (out of 10)") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Unable to find any students with submissions to be rescored (out of 10)' + assert not output['succeeded'] output = self._get_output_for_task_success(10, 0, 10) - self.assertEqual(output['message'], "Problem failed to be rescored for any of 10 students") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Problem failed to be rescored for any of 10 students' + assert not output['succeeded'] output = self._get_output_for_task_success(10, 8, 10) - self.assertEqual(output['message'], "Problem rescored for 8 of 10 students") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Problem rescored for 8 of 10 students' + assert not output['succeeded'] output = self._get_output_for_task_success(9, 8, 10) - self.assertEqual(output['message'], "Problem rescored for 8 of 9 students (out of 10)") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Problem rescored for 8 of 9 students (out of 10)' + assert not output['succeeded'] output = self._get_output_for_task_success(10, 10, 10) - self.assertEqual(output['message'], "Problem successfully rescored for 10 students") - self.assertTrue(output['succeeded']) + assert output['message'] == 'Problem successfully rescored for 10 students' + assert output['succeeded'] output = self._get_output_for_task_success(0, 0, 1, student=self.student) - self.assertIn("Unable to find submission to be rescored for student", output['message']) - self.assertFalse(output['succeeded']) + assert 'Unable to find submission to be rescored for student' in output['message'] + assert not output['succeeded'] output = self._get_output_for_task_success(1, 0, 1, student=self.student) - self.assertIn("Problem failed to be rescored for student", output['message']) - self.assertFalse(output['succeeded']) + assert 'Problem failed to be rescored for student' in output['message'] + assert not output['succeeded'] output = self._get_output_for_task_success(1, 1, 1, student=self.student) - self.assertIn("Problem successfully rescored for student", output['message']) - self.assertTrue(output['succeeded']) + assert 'Problem successfully rescored for student' in output['message'] + assert output['succeeded'] def test_email_success_messages(self): output = self._get_email_output_for_task_success(0, 0, 10) - self.assertEqual(output['message'], "Unable to find any recipients to be emailed (out of 10)") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Unable to find any recipients to be emailed (out of 10)' + assert not output['succeeded'] output = self._get_email_output_for_task_success(10, 0, 10) - self.assertEqual(output['message'], "Message failed to be emailed for any of 10 recipients ") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Message failed to be emailed for any of 10 recipients ' + assert not output['succeeded'] output = self._get_email_output_for_task_success(10, 8, 10) - self.assertEqual(output['message'], "Message emailed for 8 of 10 recipients") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Message emailed for 8 of 10 recipients' + assert not output['succeeded'] output = self._get_email_output_for_task_success(9, 8, 10) - self.assertEqual(output['message'], "Message emailed for 8 of 9 recipients (out of 10)") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Message emailed for 8 of 9 recipients (out of 10)' + assert not output['succeeded'] output = self._get_email_output_for_task_success(10, 10, 10) - self.assertEqual(output['message'], "Message successfully emailed for 10 recipients") - self.assertTrue(output['succeeded']) + assert output['message'] == 'Message successfully emailed for 10 recipients' + assert output['succeeded'] output = self._get_email_output_for_task_success(0, 0, 10, skipped=3) - self.assertEqual(output['message'], "Unable to find any recipients to be emailed (skipping 3) (out of 10)") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Unable to find any recipients to be emailed (skipping 3) (out of 10)' + assert not output['succeeded'] output = self._get_email_output_for_task_success(10, 0, 10, skipped=3) - self.assertEqual(output['message'], "Message failed to be emailed for any of 10 recipients (skipping 3)") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Message failed to be emailed for any of 10 recipients (skipping 3)' + assert not output['succeeded'] output = self._get_email_output_for_task_success(10, 8, 10, skipped=3) - self.assertEqual(output['message'], "Message emailed for 8 of 10 recipients (skipping 3)") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Message emailed for 8 of 10 recipients (skipping 3)' + assert not output['succeeded'] output = self._get_email_output_for_task_success(9, 8, 10, skipped=3) - self.assertEqual(output['message'], "Message emailed for 8 of 9 recipients (skipping 3) (out of 10)") - self.assertFalse(output['succeeded']) + assert output['message'] == 'Message emailed for 8 of 9 recipients (skipping 3) (out of 10)' + assert not output['succeeded'] output = self._get_email_output_for_task_success(10, 10, 10, skipped=3) - self.assertEqual(output['message'], "Message successfully emailed for 10 recipients (skipping 3)") - self.assertTrue(output['succeeded']) + assert output['message'] == 'Message successfully emailed for 10 recipients (skipping 3)' + assert output['succeeded'] def test_get_info_for_queuing_task(self): # get status for a task that is still running: instructor_task = self._create_entry() succeeded, message = get_task_completion_info(instructor_task) - self.assertFalse(succeeded) - self.assertEqual(message, "No status information available") + assert not succeeded + assert message == 'No status information available' def test_get_info_for_missing_output(self): # check for missing task_output instructor_task = self._create_success_entry() instructor_task.task_output = None succeeded, message = get_task_completion_info(instructor_task) - self.assertFalse(succeeded) - self.assertEqual(message, "No status information available") + assert not succeeded + assert message == 'No status information available' def test_get_info_for_broken_output(self): # check for non-JSON task_output instructor_task = self._create_success_entry() instructor_task.task_output = u"{ bad" succeeded, message = get_task_completion_info(instructor_task) - self.assertFalse(succeeded) - self.assertEqual(message, "No parsable status information available") + assert not succeeded + assert message == 'No parsable status information available' def test_get_info_for_empty_output(self): # check for JSON task_output with missing keys instructor_task = self._create_success_entry() instructor_task.task_output = "{}" succeeded, message = get_task_completion_info(instructor_task) - self.assertFalse(succeeded) - self.assertEqual(message, "No progress status information available") + assert not succeeded + assert message == 'No progress status information available' def test_get_info_for_broken_input(self): # check for non-JSON task_input, but then just ignore it instructor_task = self._create_success_entry() instructor_task.task_input = u"{ bad" succeeded, message = get_task_completion_info(instructor_task) - self.assertFalse(succeeded) - self.assertEqual(message, "Status: rescored 2 of 3 (out of 5)") + assert not succeeded + assert message == 'Status: rescored 2 of 3 (out of 5)'