From f35ff6a1ebb2d0365d71260d6a08face081d8f8d Mon Sep 17 00:00:00 2001 From: Aarif Date: Thu, 18 Feb 2021 19:13:47 +0500 Subject: [PATCH] replaced unittest assertions pytest assertions (#26540) --- lms/djangoapps/badges/api/tests.py | 26 +- .../backends/tests/test_badgr_backend.py | 83 ++--- .../events/tests/test_course_complete.py | 27 +- .../badges/events/tests/test_course_meta.py | 20 +- lms/djangoapps/badges/models.py | 1 + lms/djangoapps/badges/tests/test_models.py | 77 ++--- lms/djangoapps/branding/tests/test_api.py | 20 +- lms/djangoapps/branding/tests/test_models.py | 10 +- lms/djangoapps/branding/tests/test_page.py | 64 ++-- lms/djangoapps/branding/tests/test_views.py | 82 ++--- .../bulk_email/tests/test_course_optout.py | 34 +- lms/djangoapps/bulk_email/tests/test_email.py | 113 +++--- .../bulk_email/tests/test_err_handling.py | 48 +-- lms/djangoapps/bulk_email/tests/test_forms.py | 64 ++-- .../bulk_email/tests/test_models.py | 105 +++--- .../bulk_email/tests/test_signals.py | 10 +- lms/djangoapps/bulk_email/tests/test_tasks.py | 76 ++--- lms/djangoapps/bulk_email/tests/test_views.py | 13 +- .../bulk_enroll/tests/test_views.py | 90 ++--- lms/djangoapps/ccx/api/v0/tests/test_views.py | 273 +++++++-------- .../ccx/tests/test_ccx_modulestore.py | 24 +- lms/djangoapps/ccx/tests/test_models.py | 30 +- lms/djangoapps/ccx/tests/test_overrides.py | 8 +- lms/djangoapps/ccx/tests/test_tasks.py | 10 +- lms/djangoapps/ccx/tests/test_utils.py | 152 ++++----- lms/djangoapps/ccx/tests/test_views.py | 322 ++++++++---------- 26 files changed, 827 insertions(+), 955 deletions(-) diff --git a/lms/djangoapps/badges/api/tests.py b/lms/djangoapps/badges/api/tests.py index 3cf16cd610..8a91327b42 100644 --- a/lms/djangoapps/badges/api/tests.py +++ b/lms/djangoapps/badges/api/tests.py @@ -43,19 +43,19 @@ class UserAssertionTestCase(UrlResetMixin, ModuleStoreTestCase, ApiTestCase): """ Check a JSON response against a known badge class. """ - self.assertEqual(badge_class.issuing_component, json_class['issuing_component']) - self.assertEqual(badge_class.slug, json_class['slug']) - self.assertIn(badge_class.image.url, json_class['image_url']) - self.assertEqual(badge_class.description, json_class['description']) - self.assertEqual(badge_class.criteria, json_class['criteria']) - self.assertEqual(badge_class.course_id and six.text_type(badge_class.course_id), json_class['course_id']) + assert badge_class.issuing_component == json_class['issuing_component'] + assert badge_class.slug == json_class['slug'] + assert badge_class.image.url in json_class['image_url'] + assert badge_class.description == json_class['description'] + assert badge_class.criteria == json_class['criteria'] + assert (badge_class.course_id and six.text_type(badge_class.course_id)) == json_class['course_id'] def check_assertion_structure(self, assertion, json_assertion): """ Check a JSON response against a known assertion object. """ - self.assertEqual(assertion.image_url, json_assertion['image_url']) - self.assertEqual(assertion.assertion_url, json_assertion['assertion_url']) + assert assertion.image_url == json_assertion['image_url'] + assert assertion.assertion_url == json_assertion['assertion_url'] self.check_class_structure(assertion.badge_class, json_assertion['badge_class']) def get_course_id(self, wildcard, badge_class): @@ -105,7 +105,7 @@ class TestUserBadgeAssertions(UserAssertionTestCase): for dummy in range(3): self.create_badge_class(False) response = self.get_json(self.url()) - self.assertEqual(len(response['results']), 4) + assert len(response['results']) == 4 def test_assertion_structure(self): badge_class = self.create_badge_class(False) @@ -134,10 +134,10 @@ class TestUserCourseBadgeAssertions(UserAssertionTestCase): for dummy in range(6): BadgeAssertionFactory.create(badge_class=badge_class) response = self.get_json(self.url(), data={'course_id': str(course_key)}) - self.assertEqual(len(response['results']), 3) + assert len(response['results']) == 3 unused_course = CourseFactory.create() response = self.get_json(self.url(), data={'course_id': str(unused_course.location.course_key)}) - self.assertEqual(len(response['results']), 0) + assert len(response['results']) == 0 def test_assertion_structure(self): """ @@ -187,14 +187,14 @@ class TestUserBadgeAssertionsByClass(UserAssertionTestCase): expected_length = 4 else: expected_length = 3 - self.assertEqual(len(response['results']), expected_length) + assert len(response['results']) == expected_length unused_class = self.create_badge_class(check_course, slug='unused_slug', issuing_component='unused_component') response = self.get_json( self.url(), data=self.get_qs_args(check_course, wildcard, unused_class), ) - self.assertEqual(len(response['results']), 0) + assert len(response['results']) == 0 def check_badge_class_assertion(self, check_course, wildcard, badge_class): """ diff --git a/lms/djangoapps/badges/backends/tests/test_badgr_backend.py b/lms/djangoapps/badges/backends/tests/test_badgr_backend.py index 2177fb1d9d..39a09bf428 100644 --- a/lms/djangoapps/badges/backends/tests/test_badgr_backend.py +++ b/lms/djangoapps/badges/backends/tests/test_badgr_backend.py @@ -72,22 +72,20 @@ class BadgrBackendTestCase(ModuleStoreTestCase, EventTrackingTestCase): """ Make sure the handler generates the correct URLs for different API tasks. """ - self.assertEqual(self.handler._base_url, 'https://example.com/v1/issuer/issuers/test-issuer') # lint-amnesty, pylint: disable=no-member - self.assertEqual(self.handler._badge_create_url, 'https://example.com/v1/issuer/issuers/test-issuer/badges') # lint-amnesty, pylint: disable=no-member - self.assertEqual( - self.handler._badge_url('test_slug_here'), # lint-amnesty, pylint: disable=no-member - 'https://example.com/v1/issuer/issuers/test-issuer/badges/test_slug_here' - ) - self.assertEqual( - self.handler._assertion_url('another_test_slug'), # lint-amnesty, pylint: disable=no-member - 'https://example.com/v1/issuer/issuers/test-issuer/badges/another_test_slug/assertions' - ) + assert self.handler._base_url == 'https://example.com/v1/issuer/issuers/test-issuer' + # lint-amnesty, pylint: disable=no-member + assert self.handler._badge_create_url == 'https://example.com/v1/issuer/issuers/test-issuer/badges' + # lint-amnesty, pylint: disable=no-member + assert self.handler._badge_url('test_slug_here') ==\ + 'https://example.com/v1/issuer/issuers/test-issuer/badges/test_slug_here' + assert self.handler._assertion_url('another_test_slug') ==\ + 'https://example.com/v1/issuer/issuers/test-issuer/badges/another_test_slug/assertions' def check_headers(self, headers): """ Verify the a headers dict from a requests call matches the proper auth info. """ - self.assertEqual(headers, {'Authorization': 'Token 12345'}) + assert headers == {'Authorization': 'Token 12345'} def test_get_headers(self): """ @@ -102,20 +100,16 @@ class BadgrBackendTestCase(ModuleStoreTestCase, EventTrackingTestCase): """ self.handler._create_badge(self.badge_class) args, kwargs = post.call_args - self.assertEqual(args[0], 'https://example.com/v1/issuer/issuers/test-issuer/badges') - self.assertEqual(kwargs['files']['image'][0], self.badge_class.image.name) - self.assertIsInstance(kwargs['files']['image'][1], ImageFieldFile) - self.assertEqual(kwargs['files']['image'][2], 'image/png') + assert args[0] == 'https://example.com/v1/issuer/issuers/test-issuer/badges' + assert kwargs['files']['image'][0] == self.badge_class.image.name + assert isinstance(kwargs['files']['image'][1], ImageFieldFile) + assert kwargs['files']['image'][2] == 'image/png' self.check_headers(kwargs['headers']) - self.assertEqual( - kwargs['data'], - { - 'name': 'Test Badge', + assert kwargs['data'] ==\ + {'name': 'Test Badge', 'slug': EXAMPLE_SLUG, 'criteria': 'https://example.com/syllabus', - 'description': "Yay! It's a test badge.", - } - ) + 'description': "Yay! It's a test badge."} def test_ensure_badge_created_cache(self): """ @@ -124,7 +118,7 @@ class BadgrBackendTestCase(ModuleStoreTestCase, EventTrackingTestCase): BadgrBackend.badges.append(EXAMPLE_SLUG) self.handler._create_badge = Mock() self.handler._ensure_badge_created(self.badge_class) # lint-amnesty, pylint: disable=no-member - self.assertFalse(self.handler._create_badge.called) + assert not self.handler._create_badge.called @ddt.unpack @ddt.data( @@ -133,38 +127,35 @@ class BadgrBackendTestCase(ModuleStoreTestCase, EventTrackingTestCase): ('no_course_badge_class', 'test_componenttest_slug') ) def test_slugs(self, badge_class_type, slug): - self.assertEqual(self.handler._slugify(getattr(self, badge_class_type)), slug) # lint-amnesty, pylint: disable=no-member + assert self.handler._slugify(getattr(self, badge_class_type)) == slug + # lint-amnesty, pylint: disable=no-member @patch('requests.get') def test_ensure_badge_created_checks(self, get): response = Mock() response.status_code = 200 get.return_value = response - self.assertNotIn('test_componenttest_slug', BadgrBackend.badges) + assert 'test_componenttest_slug' not in BadgrBackend.badges self.handler._create_badge = Mock() self.handler._ensure_badge_created(self.badge_class) # lint-amnesty, pylint: disable=no-member - self.assertTrue(get.called) + assert get.called args, kwargs = get.call_args - self.assertEqual( - args[0], - 'https://example.com/v1/issuer/issuers/test-issuer/badges/' + - EXAMPLE_SLUG - ) + assert args[0] == ('https://example.com/v1/issuer/issuers/test-issuer/badges/' + EXAMPLE_SLUG) self.check_headers(kwargs['headers']) - self.assertIn(EXAMPLE_SLUG, BadgrBackend.badges) - self.assertFalse(self.handler._create_badge.called) + assert EXAMPLE_SLUG in BadgrBackend.badges + assert not self.handler._create_badge.called @patch('requests.get') def test_ensure_badge_created_creates(self, get): response = Mock() response.status_code = 404 get.return_value = response - self.assertNotIn(EXAMPLE_SLUG, BadgrBackend.badges) + assert EXAMPLE_SLUG not in BadgrBackend.badges self.handler._create_badge = Mock() self.handler._ensure_badge_created(self.badge_class) # lint-amnesty, pylint: disable=no-member - self.assertTrue(self.handler._create_badge.called) - self.assertEqual(self.handler._create_badge.call_args, call(self.badge_class)) - self.assertIn(EXAMPLE_SLUG, BadgrBackend.badges) + assert self.handler._create_badge.called + assert self.handler._create_badge.call_args == call(self.badge_class) + assert EXAMPLE_SLUG in BadgrBackend.badges @patch('requests.post') def test_badge_creation_event(self, post): @@ -180,21 +171,13 @@ class BadgrBackendTestCase(ModuleStoreTestCase, EventTrackingTestCase): self.recreate_tracker() self.handler._create_assertion(self.badge_class, self.user, 'https://example.com/irrefutable_proof') # lint-amnesty, pylint: disable=no-member args, kwargs = post.call_args - self.assertEqual( - args[0], - 'https://example.com/v1/issuer/issuers/test-issuer/badges/' + - EXAMPLE_SLUG + - '/assertions' - ) + assert args[0] == (('https://example.com/v1/issuer/issuers/test-issuer/badges/' + EXAMPLE_SLUG) + '/assertions') self.check_headers(kwargs['headers']) assertion = BadgeAssertion.objects.get(user=self.user, badge_class__course_id=self.course.location.course_key) - self.assertEqual(assertion.data, result) - self.assertEqual(assertion.image_url, 'http://www.example.com/example.png') - self.assertEqual(assertion.assertion_url, 'http://www.example.com/example') - self.assertEqual(kwargs['data'], { - 'email': 'example@example.com', - 'evidence': 'https://example.com/irrefutable_proof' - }) + assert assertion.data == result + assert assertion.image_url == 'http://www.example.com/example.png' + assert assertion.assertion_url == 'http://www.example.com/example' + assert kwargs['data'] == {'email': 'example@example.com', 'evidence': 'https://example.com/irrefutable_proof'} assert_event_matches({ 'name': 'edx.badge.assertion.created', 'data': { diff --git a/lms/djangoapps/badges/events/tests/test_course_complete.py b/lms/djangoapps/badges/events/tests/test_course_complete.py index 921b7f87a4..6506b10de4 100644 --- a/lms/djangoapps/badges/events/tests/test_course_complete.py +++ b/lms/djangoapps/badges/events/tests/test_course_complete.py @@ -31,33 +31,22 @@ class CourseCompleteTestCase(ModuleStoreTestCase): Verify slug generation is working as expected. If this test fails, the algorithm has changed, and it will cause the handler to lose track of all badges it made in the past. """ - self.assertEqual( - course_complete.course_slug(self.course_key, 'honor'), - 'edxcourse_testtest_run_honor_fc5519b' - ) - self.assertEqual( - course_complete.course_slug(self.course_key, 'verified'), - 'edxcourse_testtest_run_verified_a199ec0' - ) + assert course_complete.course_slug(self.course_key, 'honor') == 'edxcourse_testtest_run_honor_fc5519b' + assert course_complete.course_slug(self.course_key, 'verified') == 'edxcourse_testtest_run_verified_a199ec0' def test_dated_description(self): """ Verify that a course with start/end dates contains a description with them. """ - self.assertEqual( - course_complete.badge_description(self.course, 'honor'), - 'Completed the course "Badged" (honor, 2015-05-19 - 2015-05-20)' - ) + assert course_complete.badge_description(self.course, 'honor') ==\ + 'Completed the course "Badged" (honor, 2015-05-19 - 2015-05-20)' def test_self_paced_description(self): """ Verify that a badge created for a course with no end date gets a different description. """ self.course.end = None - self.assertEqual( - course_complete.badge_description(self.course, 'honor'), - 'Completed the course "Badged" (honor)' - ) + assert course_complete.badge_description(self.course, 'honor') == 'Completed the course "Badged" (honor)' def test_evidence_url(self): """ @@ -76,7 +65,5 @@ class CourseCompleteTestCase(ModuleStoreTestCase): name=user.profile.name, verify_uuid=uuid4().hex ) - self.assertEqual( - 'https://edx.org/certificates/{}?evidence_visit=1'.format(cert.verify_uuid), - course_complete.evidence_url(user.id, self.course_key) - ) + assert f'https://edx.org/certificates/{cert.verify_uuid}?evidence_visit=1' ==\ + course_complete.evidence_url(user.id, self.course_key) diff --git a/lms/djangoapps/badges/events/tests/test_course_meta.py b/lms/djangoapps/badges/events/tests/test_course_meta.py index d77202d99b..e1007b5fcb 100644 --- a/lms/djangoapps/badges/events/tests/test_course_meta.py +++ b/lms/djangoapps/badges/events/tests/test_course_meta.py @@ -51,7 +51,7 @@ class CourseEnrollmentBadgeTest(ModuleStoreTestCase): user = UserFactory() course = CourseFactory() CourseEnrollment.enroll(user, course_key=course.location.course_key) - self.assertFalse(user.badgeassertion_set.all()) + assert not user.badgeassertion_set.all() @unpack @data((1, 3), (2, 5), (3, 8)) @@ -64,8 +64,8 @@ class CourseEnrollmentBadgeTest(ModuleStoreTestCase): for course in courses: CourseEnrollment.enroll(user, course_key=course.location.course_key) assertions = user.badgeassertion_set.all().order_by('id') - self.assertEqual(user.badgeassertion_set.all().count(), checkpoint) - self.assertEqual(assertions[checkpoint - 1].badge_class, self.badge_classes[checkpoint - 1]) + assert user.badgeassertion_set.all().count() == checkpoint + assert assertions[(checkpoint - 1)].badge_class == self.badge_classes[(checkpoint - 1)] @ddt @@ -104,7 +104,7 @@ class CourseCompletionBadgeTest(ModuleStoreTestCase): GeneratedCertificate( user=user, course_id=course.location.course_key, status=CertificateStatuses.downloadable ).save() - self.assertFalse(user.badgeassertion_set.all()) + assert not user.badgeassertion_set.all() @unpack @data((1, 2), (2, 6), (3, 9)) @@ -119,8 +119,8 @@ class CourseCompletionBadgeTest(ModuleStoreTestCase): user=user, course_id=course.location.course_key, status=CertificateStatuses.downloadable ).save() assertions = user.badgeassertion_set.all().order_by('id') - self.assertEqual(user.badgeassertion_set.all().count(), checkpoint) - self.assertEqual(assertions[checkpoint - 1].badge_class, self.badge_classes[checkpoint - 1]) + assert user.badgeassertion_set.all().count() == checkpoint + assert assertions[(checkpoint - 1)].badge_class == self.badge_classes[(checkpoint - 1)] @patch.dict(settings.FEATURES, {'ENABLE_OPENBADGES': True}) @@ -161,7 +161,7 @@ class CourseGroupBadgeTest(ModuleStoreTestCase): GeneratedCertificate( user=user, course_id=course.location.course_key, status=CertificateStatuses.downloadable ).save() - self.assertFalse(user.badgeassertion_set.all()) + assert not user.badgeassertion_set.all() def test_group_matches(self): """ @@ -176,9 +176,9 @@ class CourseGroupBadgeTest(ModuleStoreTestCase): ).save() # We don't award badges until all three are set. if i + 1 == len(course_keys): - self.assertTrue(badge_class.get_for_user(user)) + assert badge_class.get_for_user(user) else: - self.assertFalse(badge_class.get_for_user(user)) + assert not badge_class.get_for_user(user) classes = [badge.badge_class.id for badge in user.badgeassertion_set.all()] source_classes = [badge.id for badge in self.badge_classes] - self.assertEqual(classes, source_classes) + assert classes == source_classes diff --git a/lms/djangoapps/badges/models.py b/lms/djangoapps/badges/models.py index 623ab49726..96673197fb 100644 --- a/lms/djangoapps/badges/models.py +++ b/lms/djangoapps/badges/models.py @@ -76,6 +76,7 @@ class BadgeClass(models.Model): cls, slug, issuing_component, display_name=None, description=None, criteria=None, image_file_handle=None, mode='', course_id=None, create=True ): + # TODO method should be renamed to getorcreate instead """ Looks up a badge class by its slug, issuing component, and course_id and returns it should it exist. If it does not exist, and create is True, creates it according to the arguments. Otherwise, returns None. diff --git a/lms/djangoapps/badges/tests/test_models.py b/lms/djangoapps/badges/tests/test_models.py index 0b9258a3c5..3e9ae7f7de 100644 --- a/lms/djangoapps/badges/tests/test_models.py +++ b/lms/djangoapps/badges/tests/test_models.py @@ -2,7 +2,7 @@ Tests for the Badges app models. """ - +import pytest from django.core.exceptions import ValidationError from django.core.files.images import ImageFile from django.core.files.storage import default_storage @@ -49,19 +49,15 @@ class BadgeImageConfigurationTest(TestCase): Verify that creating two configurations as default is not permitted. """ CourseCompleteImageConfiguration(mode='test', icon=get_image('good'), default=True).save() - self.assertRaises( - ValidationError, - CourseCompleteImageConfiguration(mode='test2', icon=get_image('good'), default=True).full_clean - ) + pytest.raises(ValidationError, CourseCompleteImageConfiguration(mode='test2', icon=get_image('good'), + default=True).full_clean) def test_runs_validator(self): """ Verify that the image validator is triggered when cleaning the model. """ - self.assertRaises( - ValidationError, - CourseCompleteImageConfiguration(mode='test2', icon=get_image('unbalanced')).full_clean - ) + pytest.raises(ValidationError, CourseCompleteImageConfiguration(mode='test2', icon=get_image('unbalanced')) + .full_clean) class DummyBackend(object): @@ -97,7 +93,7 @@ class BadgeClassTest(ModuleStoreTestCase): """ Verify the BadgeClass fetches the backend properly. """ - self.assertIsInstance(BadgeClass().backend, DummyBackend) + assert isinstance(BadgeClass().backend, DummyBackend) def test_get_badge_class_preexisting(self): """ @@ -110,11 +106,11 @@ class BadgeClassTest(ModuleStoreTestCase): criteria='test', display_name='Testola', image_file_handle=get_image('good') ) # These defaults are set on the factory. - self.assertEqual(badge_class.criteria, 'https://example.com/syllabus') - self.assertEqual(badge_class.display_name, 'Test Badge') - self.assertEqual(badge_class.description, "Yay! It's a test badge.") + assert badge_class.criteria == 'https://example.com/syllabus' + assert badge_class.display_name == 'Test Badge' + assert badge_class.description == "Yay! It's a test badge." # File name won't always be the same. - self.assertEqual(badge_class.image.path, premade_badge_class.image.path) + assert badge_class.image.path == premade_badge_class.image.path def test_unique_for_course(self): """ @@ -131,8 +127,8 @@ class BadgeClassTest(ModuleStoreTestCase): criteria='test', display_name='Testola', image_file_handle=get_image('good'), course_id=course_key, ) - self.assertNotEqual(badge_class.id, course_badge_class.id) - self.assertEqual(course_badge_class.id, premade_badge_class.id) + assert badge_class.id != course_badge_class.id + assert course_badge_class.id == premade_badge_class.id def test_get_badge_class_course_disabled(self): """ @@ -140,7 +136,7 @@ class BadgeClassTest(ModuleStoreTestCase): exception. """ course_key = CourseFactory.create(metadata={'issue_badges': False}).location.course_key - with self.assertRaises(CourseBadgesDisabledError): + with pytest.raises(CourseBadgesDisabledError): BadgeClass.get_badge_class( slug='test_slug', issuing_component='test_component', description='Attempted override', criteria='test', display_name='Testola', image_file_handle=get_image('good'), @@ -157,13 +153,13 @@ class BadgeClassTest(ModuleStoreTestCase): image_file_handle=get_image('good') ) # This should have been saved before being passed back. - self.assertTrue(badge_class.id) - self.assertEqual(badge_class.slug, 'new_slug') - self.assertEqual(badge_class.issuing_component, 'new_component') - self.assertEqual(badge_class.description, 'This is a test') - self.assertEqual(badge_class.criteria, 'https://example.com/test_criteria') - self.assertEqual(badge_class.display_name, 'Super Badge') - self.assertTrue('good' in badge_class.image.name.rsplit('/', 1)[-1]) # lint-amnesty, pylint: disable=wrong-assert-type + assert badge_class.id + assert badge_class.slug == 'new_slug' + assert badge_class.issuing_component == 'new_component' + assert badge_class.description == 'This is a test' + assert badge_class.criteria == 'https://example.com/test_criteria' + assert badge_class.display_name == 'Super Badge' + assert 'good' in badge_class.image.name.rsplit('/', 1)[(- 1)] def test_get_badge_class_nocreate(self): """ @@ -172,19 +168,20 @@ class BadgeClassTest(ModuleStoreTestCase): badge_class = BadgeClass.get_badge_class( slug='new_slug', issuing_component='new_component', create=False ) - self.assertIsNone(badge_class) + assert badge_class is None # Run this twice to verify there wasn't a background creation of the badge. badge_class = BadgeClass.get_badge_class( slug='new_slug', issuing_component='new_component', description=None, criteria=None, display_name=None, image_file_handle=None, create=False ) - self.assertIsNone(badge_class) + assert badge_class is None def test_get_badge_class_image_validate(self): """ Verify handing a broken image to get_badge_class raises a validation error upon creation. """ + # TODO Test should be updated, this doc doesn't makes sense, the object eventually gets created self.assertRaises( ValidationError, BadgeClass.get_badge_class, @@ -197,12 +194,9 @@ class BadgeClassTest(ModuleStoreTestCase): """ Verify handing incomplete data for required fields when making a badge class raises an Integrity error. """ - self.assertRaises( - IntegrityError, - BadgeClass.get_badge_class, - slug='new_slug', issuing_component='new_component', - image_file_handle=get_image('good') - ) + image = get_image('good') + pytest.raises(IntegrityError, BadgeClass.get_badge_class, slug='new_slug', issuing_component='new_component', + image_file_handle=image) def test_get_for_user(self): """ @@ -210,9 +204,9 @@ class BadgeClassTest(ModuleStoreTestCase): """ user = UserFactory.create() badge_class = BadgeClassFactory.create() - self.assertFalse(badge_class.get_for_user(user)) + assert not badge_class.get_for_user(user) assertion = BadgeAssertionFactory.create(badge_class=badge_class, user=user) - self.assertEqual(list(badge_class.get_for_user(user)), [assertion]) + assert list(badge_class.get_for_user(user)) == [assertion] @override_settings(BADGING_BACKEND='lms.djangoapps.badges.backends.badgr.BadgrBackend', BADGR_API_TOKEN='test') @patch('lms.djangoapps.badges.backends.badgr.BadgrBackend.award') @@ -223,20 +217,15 @@ class BadgeClassTest(ModuleStoreTestCase): user = UserFactory.create() badge_class = BadgeClassFactory.create() badge_class.award(user, evidence_url='http://example.com/evidence') - self.assertTrue(mock_award.called) + assert mock_award.called mock_award.assert_called_with(badge_class, user, evidence_url='http://example.com/evidence') def test_runs_validator(self): """ Verify that the image validator is triggered when cleaning the model. """ - self.assertRaises( - ValidationError, - BadgeClass( - slug='test', issuing_component='test2', criteria='test3', - description='test4', image=get_image('unbalanced') - ).full_clean - ) + pytest.raises(ValidationError, BadgeClass(slug='test', issuing_component='test2', criteria='test3', + description='test4', image=get_image('unbalanced')).full_clean) class BadgeAssertionTest(ModuleStoreTestCase): @@ -262,12 +251,12 @@ class BadgeAssertionTest(ModuleStoreTestCase): assertions.sort() assertions_for_user = [badge.id for badge in BadgeAssertion.assertions_for_user(user)] assertions_for_user.sort() - self.assertEqual(assertions_for_user, assertions) + assert assertions_for_user == assertions course_scoped_assertions = [ badge.id for badge in BadgeAssertion.assertions_for_user(user, course_id=course_key) ] course_scoped_assertions.sort() - self.assertEqual(course_scoped_assertions, course_assertions) + assert course_scoped_assertions == course_assertions class ValidBadgeImageTest(TestCase): diff --git a/lms/djangoapps/branding/tests/test_api.py b/lms/djangoapps/branding/tests/test_api.py index d2d6ffdc3f..0dcd981456 100644 --- a/lms/djangoapps/branding/tests/test_api.py +++ b/lms/djangoapps/branding/tests/test_api.py @@ -34,11 +34,11 @@ class TestHeader(TestCase): with mock.patch('lms.djangoapps.branding.api.staticfiles_storage.url', return_value=cdn_url): logo_url = get_logo_url() - self.assertEqual(logo_url, cdn_url) + assert logo_url == cdn_url def test_home_url(self): expected_url = get_home_url() - self.assertEqual(reverse('dashboard'), expected_url) + assert reverse('dashboard') == expected_url class TestFooter(TestCase): @@ -169,7 +169,7 @@ class TestFooter(TestCase): 'text': 'Take free online courses at edX.org', }, } - self.assertEqual(actual_footer, expected_footer) + assert actual_footer == expected_footer @with_site_configuration(configuration=test_config_disabled_contact_us) def test_get_footer_disabled_contact_form(self): @@ -177,8 +177,8 @@ class TestFooter(TestCase): Test retrieving the footer with disabled contact form. """ actual_footer = get_footer(is_secure=True) - self.assertEqual(any(l['name'] == 'contact' for l in actual_footer['connect_links']), False) - self.assertEqual(any(l['name'] == 'contact' for l in actual_footer['navigation_links']), False) + assert any(((l['name'] == 'contact') for l in actual_footer['connect_links'])) is False + assert any(((l['name'] == 'contact') for l in actual_footer['navigation_links'])) is False @with_site_configuration(configuration=test_config_custom_url_contact_us) def test_get_footer_custom_contact_url(self): @@ -187,13 +187,7 @@ class TestFooter(TestCase): """ actual_footer = get_footer(is_secure=True) contact_us_link = [l for l in actual_footer['connect_links'] if l['name'] == 'contact'][0] - self.assertEqual( - contact_us_link['url'], - test_config_custom_url_contact_us['CONTACT_US_CUSTOM_LINK'] - ) + assert contact_us_link['url'] == test_config_custom_url_contact_us['CONTACT_US_CUSTOM_LINK'] navigation_link_contact_us = [l for l in actual_footer['navigation_links'] if l['name'] == 'contact'][0] - self.assertEqual( - navigation_link_contact_us['url'], - test_config_custom_url_contact_us['CONTACT_US_CUSTOM_LINK'] - ) + assert navigation_link_contact_us['url'] == test_config_custom_url_contact_us['CONTACT_US_CUSTOM_LINK'] diff --git a/lms/djangoapps/branding/tests/test_models.py b/lms/djangoapps/branding/tests/test_models.py index 710c0c23b1..9493e44e04 100644 --- a/lms/djangoapps/branding/tests/test_models.py +++ b/lms/djangoapps/branding/tests/test_models.py @@ -2,7 +2,7 @@ Tests for the Video Branding configuration. """ - +import pytest from django.core.exceptions import ValidationError from django.test import TestCase @@ -30,14 +30,14 @@ class BrandingInfoConfigTest(TestCase): Tests creation of configuration. """ self.config.save() - self.assertEqual(self.config.configuration, self.configuration_string) + assert self.config.configuration == self.configuration_string def test_clean_bad_json(self): """ Tests if bad Json string was given. """ self.config = BrandingInfoConfig(configuration='{"bad":"test"') - self.assertRaises(ValidationError, self.config.clean) + pytest.raises(ValidationError, self.config.clean) def test_get(self): """ @@ -52,7 +52,7 @@ class BrandingInfoConfigTest(TestCase): "logo_tag": "Video hosted by XuetangX.com" } } - self.assertEqual(self.config.get_config(), expected_config) + assert self.config.get_config() == expected_config def test_get_not_enabled(self): """ @@ -60,4 +60,4 @@ class BrandingInfoConfigTest(TestCase): """ self.config.enabled = False self.config.save() - self.assertEqual(self.config.get_config(), {}) + assert self.config.get_config() == {} diff --git a/lms/djangoapps/branding/tests/test_page.py b/lms/djangoapps/branding/tests/test_page.py index 1f6a09235b..a8bcc01ac1 100644 --- a/lms/djangoapps/branding/tests/test_page.py +++ b/lms/djangoapps/branding/tests/test_page.py @@ -61,17 +61,17 @@ class AnonymousIndexPageTest(ModuleStoreTestCase): """ self.client.logout() response = self.client.get(reverse('root')) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 @override_settings(FEATURES=FEATURES_WITH_STARTDATE) def test_anon_user_with_startdate_index(self): response = self.client.get('/') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 @override_settings(FEATURES=FEATURES_WO_STARTDATE) def test_anon_user_no_startdate_index(self): response = self.client.get('/') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 @override_settings(X_FRAME_OPTIONS='ALLOW') def test_allow_x_frame_options(self): @@ -81,7 +81,7 @@ class AnonymousIndexPageTest(ModuleStoreTestCase): # check to see that the override value is honored resp = self.client.get('/') - self.assertEqual(resp['X-Frame-Options'], 'ALLOW') + assert resp['X-Frame-Options'] == 'ALLOW' def test_deny_x_frame_options(self): """ @@ -90,7 +90,7 @@ class AnonymousIndexPageTest(ModuleStoreTestCase): # check to see that the default setting is to DENY iframing resp = self.client.get('/') - self.assertEqual(resp['X-Frame-Options'], 'DENY') + assert resp['X-Frame-Options'] == 'DENY' def test_edge_redirect_to_login(self): """ @@ -105,9 +105,9 @@ class AnonymousIndexPageTest(ModuleStoreTestCase): response = index(request) # Response should be instance of HttpResponseRedirect. - self.assertIsInstance(response, HttpResponseRedirect) + assert isinstance(response, HttpResponseRedirect) # Location should be "/login". - self.assertEqual(response._headers.get("location")[1], "/login") # pylint: disable=protected-access + assert response._headers.get('location')[1] == '/login' # pylint: disable=protected-access class PreRequisiteCourseCatalog(ModuleStoreTestCase, LoginEnrollmentTestCase, MilestonesTestCaseMixin): @@ -199,13 +199,13 @@ class IndexPageCourseCardsSortingTests(ModuleStoreTestCase): feature flag settings """ response = self.client.get('/') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # assert that the course discovery UI is not present self.assertNotContains(response, 'Search for a course') # check the /courses view response = self.client.get(reverse('courses')) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # assert that the course discovery UI is not present self.assertNotContains(response, 'Search for a course') @@ -223,13 +223,13 @@ class IndexPageCourseCardsSortingTests(ModuleStoreTestCase): feature flag settings """ response = self.client.get('/') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # assert that the course discovery UI is not present self.assertContains(response, 'Search for a course') # check the /courses view response = self.client.get(reverse('courses')) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # assert that the course discovery UI is present self.assertContains(response, 'Search for a course') @@ -241,25 +241,25 @@ class IndexPageCourseCardsSortingTests(ModuleStoreTestCase): @patch.dict('django.conf.settings.FEATURES', {'ENABLE_COURSE_DISCOVERY': False}) def test_course_cards_sorted_by_default_sorting(self): response = self.client.get('/') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 ((template, context), _) = RENDER_MOCK.call_args # pylint: disable=unpacking-non-sequence - self.assertEqual(template, 'index.html') + assert template == 'index.html' # by default the courses will be sorted by their creation dates, earliest first. - self.assertEqual(context['courses'][0].id, self.starting_earlier.id) - self.assertEqual(context['courses'][1].id, self.starting_later.id) - self.assertEqual(context['courses'][2].id, self.course_with_default_start_date.id) + assert context['courses'][0].id == self.starting_earlier.id + assert context['courses'][1].id == self.starting_later.id + assert context['courses'][2].id == self.course_with_default_start_date.id # check the /courses view response = self.client.get(reverse('courses')) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 ((template, context), _) = RENDER_MOCK.call_args # pylint: disable=unpacking-non-sequence - self.assertEqual(template, 'courseware/courses.html') + assert template == 'courseware/courses.html' # by default the courses will be sorted by their creation dates, earliest first. - self.assertEqual(context['courses'][0].id, self.starting_earlier.id) - self.assertEqual(context['courses'][1].id, self.starting_later.id) - self.assertEqual(context['courses'][2].id, self.course_with_default_start_date.id) + assert context['courses'][0].id == self.starting_earlier.id + assert context['courses'][1].id == self.starting_later.id + assert context['courses'][2].id == self.course_with_default_start_date.id @patch('common.djangoapps.student.views.management.render_to_response', RENDER_MOCK) @patch('lms.djangoapps.courseware.views.views.render_to_response', RENDER_MOCK) @@ -267,25 +267,25 @@ class IndexPageCourseCardsSortingTests(ModuleStoreTestCase): @patch.dict('django.conf.settings.FEATURES', {'ENABLE_COURSE_DISCOVERY': False}) def test_course_cards_sorted_by_start_date_disabled(self): response = self.client.get('/') - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 ((template, context), _) = RENDER_MOCK.call_args # pylint: disable=unpacking-non-sequence - self.assertEqual(template, 'index.html') + assert template == 'index.html' # now the courses will be sorted by their announcement dates. - self.assertEqual(context['courses'][0].id, self.starting_later.id) - self.assertEqual(context['courses'][1].id, self.starting_earlier.id) - self.assertEqual(context['courses'][2].id, self.course_with_default_start_date.id) + assert context['courses'][0].id == self.starting_later.id + assert context['courses'][1].id == self.starting_earlier.id + assert context['courses'][2].id == self.course_with_default_start_date.id # check the /courses view as well response = self.client.get(reverse('courses')) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 ((template, context), _) = RENDER_MOCK.call_args # pylint: disable=unpacking-non-sequence - self.assertEqual(template, 'courseware/courses.html') + assert template == 'courseware/courses.html' # now the courses will be sorted by their announcement dates. - self.assertEqual(context['courses'][0].id, self.starting_later.id) - self.assertEqual(context['courses'][1].id, self.starting_earlier.id) - self.assertEqual(context['courses'][2].id, self.course_with_default_start_date.id) + assert context['courses'][0].id == self.starting_later.id + assert context['courses'][1].id == self.starting_earlier.id + assert context['courses'][2].id == self.course_with_default_start_date.id class IndexPageProgramsTests(SiteMixin, ModuleStoreTestCase): @@ -300,5 +300,5 @@ class IndexPageProgramsTests(SiteMixin, ModuleStoreTestCase): for url, dotted_path in views: with patch(dotted_path) as mock_get_programs_with_type: response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 mock_get_programs_with_type.assert_called_once() diff --git a/lms/djangoapps/branding/tests/test_views.py b/lms/djangoapps/branding/tests/test_views.py index 4b6877d184..9ec3b723a0 100644 --- a/lms/djangoapps/branding/tests/test_views.py +++ b/lms/djangoapps/branding/tests/test_views.py @@ -29,7 +29,7 @@ class TestFooter(CacheIsolationTestCase): def test_feature_flag(self, accepts): self._set_feature_flag(False) resp = self._get_footer(accepts=accepts) - self.assertEqual(resp.status_code, 404) + assert resp.status_code == 404 @ddt.data( # Open source version @@ -48,7 +48,7 @@ class TestFooter(CacheIsolationTestCase): with with_comprehensive_theme_context(theme): resp = self._get_footer(accepts=accepts) - self.assertEqual(resp["Content-Type"], content_type) + assert resp['Content-Type'] == content_type self.assertContains(resp, content) @mock.patch.dict(settings.FEATURES, {'ENABLE_FOOTER_MOBILE_APP_LINKS': True}) @@ -58,52 +58,52 @@ class TestFooter(CacheIsolationTestCase): with with_comprehensive_theme_context(theme): resp = self._get_footer() - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 json_data = json.loads(resp.content.decode('utf-8')) - self.assertTrue(isinstance(json_data, dict)) + assert isinstance(json_data, dict) # Logo - self.assertIn("logo_image", json_data) + assert 'logo_image' in json_data # Links - self.assertIn("navigation_links", json_data) + assert 'navigation_links' in json_data for link in json_data["navigation_links"]: - self.assertIn("name", link) - self.assertIn("title", link) - self.assertIn("url", link) + assert 'name' in link + assert 'title' in link + assert 'url' in link # Social links - self.assertIn("social_links", json_data) + assert 'social_links' in json_data for link in json_data["social_links"]: - self.assertIn("name", link) - self.assertIn("title", link) - self.assertIn("url", link) - self.assertIn("icon-class", link) - self.assertIn("action", link) + assert 'name' in link + assert 'title' in link + assert 'url' in link + assert 'icon-class' in link + assert 'action' in link # Mobile links - self.assertIn("mobile_links", json_data) + assert 'mobile_links' in json_data for link in json_data["mobile_links"]: - self.assertIn("name", link) - self.assertIn("title", link) - self.assertIn("url", link) - self.assertIn("image", link) + assert 'name' in link + assert 'title' in link + assert 'url' in link + assert 'image' in link # Legal links - self.assertIn("legal_links", json_data) + assert 'legal_links' in json_data for link in json_data["legal_links"]: - self.assertIn("name", link) - self.assertIn("title", link) - self.assertIn("url", link) + assert 'name' in link + assert 'title' in link + assert 'url' in link # OpenEdX - self.assertIn("openedx_link", json_data) - self.assertIn("url", json_data["openedx_link"]) - self.assertIn("title", json_data["openedx_link"]) - self.assertIn("image", json_data["openedx_link"]) + assert 'openedx_link' in json_data + assert 'url' in json_data['openedx_link'] + assert 'title' in json_data['openedx_link'] + assert 'image' in json_data['openedx_link'] # Copyright - self.assertIn("copyright", json_data) + assert 'copyright' in json_data def test_absolute_urls_with_cdn(self): self._set_feature_flag(True) @@ -117,13 +117,13 @@ class TestFooter(CacheIsolationTestCase): with mock.patch('lms.djangoapps.branding.api.staticfiles_storage.url', return_value=cdn_url): resp = self._get_footer() - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 json_data = json.loads(resp.content.decode('utf-8')) - self.assertEqual(json_data["logo_image"], cdn_url) + assert json_data['logo_image'] == cdn_url for link in json_data["mobile_links"]: - self.assertEqual(link["url"], cdn_url) + assert link['url'] == cdn_url @ddt.data( ("en", "registered trademarks"), @@ -136,11 +136,11 @@ class TestFooter(CacheIsolationTestCase): # Load the footer with the specified language resp = self._get_footer(params={'language': language}) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 json_data = json.loads(resp.content.decode('utf-8')) # Verify that the translation occurred - self.assertIn(expected_copyright, json_data['copyright']) + assert expected_copyright in json_data['copyright'] @ddt.data( # OpenEdX @@ -227,7 +227,7 @@ class TestFooter(CacheIsolationTestCase): } resp = self._get_footer(accepts="text/html", params=params) - self.assertEqual(resp.status_code, 200) + assert resp.status_code == 200 if include_language_selector: selected_language = language if language else 'en' @@ -238,7 +238,7 @@ class TestFooter(CacheIsolationTestCase): def test_no_supported_accept_type(self): self._set_feature_flag(True) resp = self._get_footer(accepts="application/x-shockwave-flash") - self.assertEqual(resp.status_code, 406) + assert resp.status_code == 406 def _set_feature_flag(self, enabled): """Enable or disable the feature flag for the branding API end-points. """ @@ -261,16 +261,16 @@ class TestFooter(CacheIsolationTestCase): """ Verify that the language selector is present and correctly configured.""" # Verify the selector is included content = response.content.decode(response.charset) - self.assertIn('footer-language-selector', content) + assert 'footer-language-selector' in content # Verify the correct language is selected - self.assertIn(u'