From 93a4f96e30448fe44f076e4ac1c486b1a84bf7f7 Mon Sep 17 00:00:00 2001 From: Aarif <MrAarif@outlook.com> Date: Mon, 22 Feb 2021 16:19:37 +0500 Subject: [PATCH] replaced unittest assertions pytest assertions (#26575) --- .../announcements/tests/test_announcements.py | 4 +- .../features/calendar_sync/tests/test_api.py | 14 +- .../features/calendar_sync/tests/test_ics.py | 2 +- .../features/calendar_sync/tests/test_init.py | 2 +- .../calendar_sync/tests/test_models.py | 6 +- .../calendar_sync/tests/test_plugins.py | 2 +- .../calendar_sync/tests/test_views.py | 4 +- .../content_type_gating/tests/test_access.py | 36 +--- .../content_type_gating/tests/test_models.py | 90 ++++----- .../tests/test_partitions.py | 18 +- .../tests/test_course_bookmarks.py | 2 +- .../tests/test_access.py | 29 +-- .../tests/test_course_expiration.py | 24 +-- .../tests/test_models.py | 102 +++++------ .../api/v1/tests/test_views.py | 16 +- .../tests/test_course_updates.py | 26 +-- .../tests/views/test_course_dates.py | 2 +- .../tests/views/test_course_home.py | 34 +--- .../tests/views/test_course_outline.py | 70 +++---- .../tests/views/test_course_updates.py | 2 +- .../tests/views/test_welcome_message.py | 10 +- .../discounts/tests/test_applicability.py | 12 +- .../tests/test_discount_restriction_models.py | 13 +- .../features/discounts/tests/test_utils.py | 12 +- .../tests/mixins/enterprise.py | 8 +- .../enterprise_support/tests/test_api.py | 173 +++++++++--------- .../enterprise_support/tests/test_logout.py | 2 +- .../enterprise_support/tests/test_signals.py | 16 +- .../enterprise_support/tests/test_utils.py | 39 ++-- .../tests/views/test_learner_profile.py | 54 ++---- .../tests/test_show_answer_override.py | 8 +- 31 files changed, 366 insertions(+), 466 deletions(-) diff --git a/openedx/features/announcements/tests/test_announcements.py b/openedx/features/announcements/tests/test_announcements.py index 2685c5b9feb..c50ad804221 100644 --- a/openedx/features/announcements/tests/test_announcements.py +++ b/openedx/features/announcements/tests/test_announcements.py @@ -65,12 +65,12 @@ class TestGlobalAnnouncements(TestCase): url = reverse("announcements:page", kwargs={"page": 1}) response = self.client.get(url) data = json.loads(response.content.decode('utf-8')) - self.assertEqual(data['num_pages'], 1) + assert data['num_pages'] == 1 ## double the number of announcements to verify the number of pages increases self.setUpTestData() response = self.client.get(url) data = json.loads(response.content.decode('utf-8')) - self.assertEqual(data['num_pages'], 2) + assert data['num_pages'] == 2 def test_active(self): """ diff --git a/openedx/features/calendar_sync/tests/test_api.py b/openedx/features/calendar_sync/tests/test_api.py index d8abcb5e0b9..b300bab2296 100644 --- a/openedx/features/calendar_sync/tests/test_api.py +++ b/openedx/features/calendar_sync/tests/test_api.py @@ -24,17 +24,17 @@ class TestCalendarSyncAPI(SharedModuleStoreTestCase): self.user = UserFactory(password=TEST_PASSWORD) def test_subscribe_to_calendar(self): - self.assertEqual(UserCalendarSyncConfig.objects.count(), 0) + assert UserCalendarSyncConfig.objects.count() == 0 subscribe_user_to_calendar(self.user, self.course_key) - self.assertEqual(UserCalendarSyncConfig.objects.count(), 1) - self.assertTrue(UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key)) + assert UserCalendarSyncConfig.objects.count() == 1 + assert UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key) def test_unsubscribe_to_calendar(self): - self.assertEqual(UserCalendarSyncConfig.objects.count(), 0) + assert UserCalendarSyncConfig.objects.count() == 0 unsubscribe_user_to_calendar(self.user, self.course_key) - self.assertEqual(UserCalendarSyncConfig.objects.count(), 0) + assert UserCalendarSyncConfig.objects.count() == 0 UserCalendarSyncConfig.objects.create(user=self.user, course_key=self.course_key, enabled=True) - self.assertTrue(UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key)) + assert UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key) unsubscribe_user_to_calendar(self.user, self.course_key) - self.assertFalse(UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key)) + assert not UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key) diff --git a/openedx/features/calendar_sync/tests/test_ics.py b/openedx/features/calendar_sync/tests/test_ics.py index 773a643a0b9..12bc1dff6d1 100644 --- a/openedx/features/calendar_sync/tests/test_ics.py +++ b/openedx/features/calendar_sync/tests/test_ics.py @@ -98,7 +98,7 @@ END:VCALENDAR generated = [ file.decode('utf8').replace('\r\n', '\n') for file in sorted(self.generate_ics(*assignments).values()) ] - self.assertEqual(len(generated), len(assignments)) + assert len(generated) == len(assignments) self.assertListEqual(generated, list(self.expected_ics(*assignments))) def test_generate_ics_for_user_course(self): diff --git a/openedx/features/calendar_sync/tests/test_init.py b/openedx/features/calendar_sync/tests/test_init.py index 47ce2a43473..c2471d9b635 100644 --- a/openedx/features/calendar_sync/tests/test_init.py +++ b/openedx/features/calendar_sync/tests/test_init.py @@ -23,4 +23,4 @@ class TestCalendarSyncInit(TestCase): expected = '{user_id}.{block_key}.{date_type}@{hostname}'.format( user_id=self.user.id, block_key=block_key, date_type=date_type, hostname=hostname ) - self.assertEqual(event_id, expected) + assert event_id == expected diff --git a/openedx/features/calendar_sync/tests/test_models.py b/openedx/features/calendar_sync/tests/test_models.py index cd62653b591..41f4002d632 100644 --- a/openedx/features/calendar_sync/tests/test_models.py +++ b/openedx/features/calendar_sync/tests/test_models.py @@ -24,11 +24,11 @@ class TestUserCalendarSyncConfig(SharedModuleStoreTestCase): def test_is_enabled_for_course(self): # Calendar Sync Config does not exist and returns False - self.assertFalse(UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key)) + assert not UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key) # Default value for enabled is False UserCalendarSyncConfig.objects.create(user=self.user, course_key=self.course_key) - self.assertFalse(UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key)) + assert not UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key) UserCalendarSyncConfig.objects.filter(user=self.user, course_key=self.course_key).update(enabled=True) - self.assertTrue(UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key)) + assert UserCalendarSyncConfig.is_enabled_for_course(self.user, self.course_key) diff --git a/openedx/features/calendar_sync/tests/test_plugins.py b/openedx/features/calendar_sync/tests/test_plugins.py index 52d8132c83e..b2877cf7bca 100644 --- a/openedx/features/calendar_sync/tests/test_plugins.py +++ b/openedx/features/calendar_sync/tests/test_plugins.py @@ -41,4 +41,4 @@ class TestCalendarSyncToggleTool(SharedModuleStoreTestCase): request.user = self.create_user_for_course(self.course, user_type) self.addCleanup(crum.set_current_request, None) crum.set_current_request(request) - self.assertEqual(CalendarSyncToggleTool.is_enabled(request, self.course.id), should_be_enabled) + assert CalendarSyncToggleTool.is_enabled(request, self.course.id) == should_be_enabled diff --git a/openedx/features/calendar_sync/tests/test_views.py b/openedx/features/calendar_sync/tests/test_views.py index 8f70c4832af..77fd708073e 100644 --- a/openedx/features/calendar_sync/tests/test_views.py +++ b/openedx/features/calendar_sync/tests/test_views.py @@ -47,5 +47,5 @@ class TestCalendarSyncView(SharedModuleStoreTestCase, TestCase): @ddt.unpack def test_course_dates_fragment(self, data, expected_status_code, contained_text): response = self.client.post(self.calendar_sync_url, data) - self.assertEqual(response.status_code, expected_status_code) - self.assertIn(contained_text, str(response.content)) + assert response.status_code == expected_status_code + assert contained_text in str(response.content) diff --git a/openedx/features/content_type_gating/tests/test_access.py b/openedx/features/content_type_gating/tests/test_access.py index 4134518e451..fc373a183c8 100644 --- a/openedx/features/content_type_gating/tests/test_access.py +++ b/openedx/features/content_type_gating/tests/test_access.py @@ -565,7 +565,7 @@ class TestProblemTypeAccess(SharedModuleStoreTestCase, MasqueradeMixin): ) self.client.login(username=self.users[user].username, password=TEST_PASSWORD) response = self.client.post(url) - self.assertEqual(response.status_code, status_code) + assert response.status_code == status_code @ddt.data( InstructorFactory, @@ -684,9 +684,9 @@ class TestProblemTypeAccess(SharedModuleStoreTestCase, MasqueradeMixin): block_view_url = reverse('render_xblock', kwargs={'usage_key_string': six.text_type(block.scope_ids.usage_id)}) response = self.client.get(block_view_url) if is_gated: - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 else: - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 @ddt.data( InstructorFactory, @@ -721,7 +721,7 @@ class TestProblemTypeAccess(SharedModuleStoreTestCase, MasqueradeMixin): block = self.blocks_dict['problem'] block_view_url = reverse('render_xblock', kwargs={'usage_key_string': six.text_type(block.scope_ids.usage_id)}) response = self.client.get(block_view_url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 @ddt.data( FORUM_ROLE_COMMUNITY_TA, @@ -1154,20 +1154,10 @@ class TestContentTypeGatingService(ModuleStoreTestCase): ) # The method returns a content type gate for blocks that should be gated - self.assertIn( - 'content-paywall', - ContentTypeGatingService()._content_type_gate_for_block( - self.user, blocks_dict['graded_1'], course['course'].id - ).content - ) + assert 'content-paywall' in ContentTypeGatingService()._content_type_gate_for_block(self.user, blocks_dict['graded_1'], course['course'].id).content # The method returns None for blocks that should not be gated - self.assertEquals( - None, - ContentTypeGatingService()._content_type_gate_for_block( - self.user, blocks_dict['not_graded_1'], course['course'].id - ) - ) + assert ContentTypeGatingService()._content_type_gate_for_block(self.user, blocks_dict['not_graded_1'], course['course'].id) is None @patch.object(ContentTypeGatingService, '_get_user', return_value=UserFactory.build()) def test_check_children_for_content_type_gating_paywall(self, mocked_user): # pylint: disable=unused-argument @@ -1187,12 +1177,7 @@ class TestContentTypeGatingService(ModuleStoreTestCase): ) # The method returns a content type gate for blocks that should be gated - self.assertEquals( - None, - ContentTypeGatingService().check_children_for_content_type_gating_paywall( - blocks_dict['vertical'], course['course'].id - ) - ) + assert ContentTypeGatingService().check_children_for_content_type_gating_paywall(blocks_dict['vertical'], course['course'].id) is None blocks_dict['graded_1'] = ItemFactory.create( parent=blocks_dict['vertical'], @@ -1202,9 +1187,4 @@ class TestContentTypeGatingService(ModuleStoreTestCase): ) # The method returns None for blocks that should not be gated - self.assertIn( - 'content-paywall', - ContentTypeGatingService().check_children_for_content_type_gating_paywall( - blocks_dict['vertical'], course['course'].id - ) - ) + assert 'content-paywall' in ContentTypeGatingService().check_children_for_content_type_gating_paywall(blocks_dict['vertical'], course['course'].id) diff --git a/openedx/features/content_type_gating/tests/test_models.py b/openedx/features/content_type_gating/tests/test_models.py index c60b6ad8a3c..9c4bb7f77b3 100644 --- a/openedx/features/content_type_gating/tests/test_models.py +++ b/openedx/features/content_type_gating/tests/test_models.py @@ -1,3 +1,4 @@ +import pytest import itertools @@ -77,14 +78,14 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): user=user, course_key=course_key, ) - self.assertEqual(not enrolled_before_enabled, enabled) + assert (not enrolled_before_enabled) == enabled def test_enabled_for_enrollment_failure(self): - with self.assertRaises(ValueError): + with pytest.raises(ValueError): ContentTypeGatingConfig.enabled_for_enrollment(None, None) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): ContentTypeGatingConfig.enabled_for_enrollment(Mock(name='user'), None) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): ContentTypeGatingConfig.enabled_for_enrollment(None, Mock(name='course_key')) @ddt.data(True, False) @@ -107,13 +108,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): course_key = self.course_overview.id - self.assertEqual( - not before_enabled, - ContentTypeGatingConfig.enabled_for_course( - course_key=course_key, - target_datetime=target_datetime, - ) - ) + assert (not before_enabled) == ContentTypeGatingConfig.enabled_for_course(course_key=course_key, target_datetime=target_datetime) @ddt.data( # Generate all combinations of setting each configuration level to True/False/None @@ -162,10 +157,10 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): expected_org_setting = self._resolve_settings([global_setting, site_setting, org_setting]) expected_course_setting = self._resolve_settings([global_setting, site_setting, org_setting, course_setting]) - self.assertEqual(expected_global_setting, ContentTypeGatingConfig.current().enabled) - self.assertEqual(expected_site_setting, ContentTypeGatingConfig.current(site=test_site_cfg.site).enabled) - self.assertEqual(expected_org_setting, ContentTypeGatingConfig.current(org=test_course.org).enabled) - self.assertEqual(expected_course_setting, ContentTypeGatingConfig.current(course_key=test_course.id).enabled) + assert expected_global_setting == ContentTypeGatingConfig.current().enabled + assert expected_site_setting == ContentTypeGatingConfig.current(site=test_site_cfg.site).enabled + assert expected_org_setting == ContentTypeGatingConfig.current(org=test_course.org).enabled + assert expected_course_setting == ContentTypeGatingConfig.current(course_key=test_course.id).enabled def test_all_current_course_configs(self): # Set up test objects @@ -197,33 +192,12 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Deliberatly using the last all_configs that was checked after the 3rd pass through the global_settings loop # We should be creating 3^4 courses (3 global values * 3 site values * 3 org values * 3 course values) # Plus 1 for the edX/toy/2012_Fall course - self.assertEqual(len(all_configs), 3**4 + 1) + assert len(all_configs) == ((3 ** 4) + 1) # Point-test some of the final configurations - self.assertEqual( - all_configs[CourseLocator('7-True', 'test_course', 'run-None')], - { - 'enabled': (True, Provenance.org), - 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), Provenance.run), - 'studio_override_enabled': (None, Provenance.default), - } - ) - self.assertEqual( - all_configs[CourseLocator('7-True', 'test_course', 'run-False')], - { - 'enabled': (False, Provenance.run), - 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), Provenance.run), - 'studio_override_enabled': (None, Provenance.default), - } - ) - self.assertEqual( - all_configs[CourseLocator('7-None', 'test_course', 'run-None')], - { - 'enabled': (True, Provenance.site), - 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), Provenance.run), - 'studio_override_enabled': (None, Provenance.default), - } - ) + assert all_configs[CourseLocator('7-True', 'test_course', 'run-None')] == {'enabled': (True, Provenance.org), 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), Provenance.run), 'studio_override_enabled': (None, Provenance.default)} + assert all_configs[CourseLocator('7-True', 'test_course', 'run-False')] == {'enabled': (False, Provenance.run), 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), Provenance.run), 'studio_override_enabled': (None, Provenance.default)} + assert all_configs[CourseLocator('7-None', 'test_course', 'run-None')] == {'enabled': (True, Provenance.site), 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), Provenance.run), 'studio_override_enabled': (None, Provenance.default)} def test_caching_global(self): global_config = ContentTypeGatingConfig(enabled=True, enabled_as_of=datetime(2018, 1, 1)) @@ -233,13 +207,13 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the global value is not retrieved from cache after save with self.assertNumQueries(1): - self.assertTrue(ContentTypeGatingConfig.current().enabled) + assert ContentTypeGatingConfig.current().enabled RequestCache.clear_all_namespaces() # Check that the global value can be retrieved from cache after read with self.assertNumQueries(0): - self.assertTrue(ContentTypeGatingConfig.current().enabled) + assert ContentTypeGatingConfig.current().enabled global_config.enabled = False global_config.save() @@ -248,7 +222,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the global value in cache was deleted on save with self.assertNumQueries(1): - self.assertFalse(ContentTypeGatingConfig.current().enabled) + assert not ContentTypeGatingConfig.current().enabled def test_caching_site(self): site_cfg = SiteConfigurationFactory() @@ -259,13 +233,13 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the site value is not retrieved from cache after save with self.assertNumQueries(1): - self.assertTrue(ContentTypeGatingConfig.current(site=site_cfg.site).enabled) + assert ContentTypeGatingConfig.current(site=site_cfg.site).enabled RequestCache.clear_all_namespaces() # Check that the site value can be retrieved from cache after read with self.assertNumQueries(0): - self.assertTrue(ContentTypeGatingConfig.current(site=site_cfg.site).enabled) + assert ContentTypeGatingConfig.current(site=site_cfg.site).enabled site_config.enabled = False site_config.save() @@ -274,7 +248,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the site value in cache was deleted on save with self.assertNumQueries(1): - self.assertFalse(ContentTypeGatingConfig.current(site=site_cfg.site).enabled) + assert not ContentTypeGatingConfig.current(site=site_cfg.site).enabled global_config = ContentTypeGatingConfig(enabled=True, enabled_as_of=datetime(2018, 1, 1)) global_config.save() @@ -283,7 +257,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the site value is not updated in cache by changing the global value with self.assertNumQueries(0): - self.assertFalse(ContentTypeGatingConfig.current(site=site_cfg.site).enabled) + assert not ContentTypeGatingConfig.current(site=site_cfg.site).enabled def test_caching_org(self): course = CourseOverviewFactory.create(org='test-org') @@ -297,13 +271,13 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the org value is not retrieved from cache after save with self.assertNumQueries(2): - self.assertTrue(ContentTypeGatingConfig.current(org=course.org).enabled) + assert ContentTypeGatingConfig.current(org=course.org).enabled RequestCache.clear_all_namespaces() # Check that the org value can be retrieved from cache after read with self.assertNumQueries(0): - self.assertTrue(ContentTypeGatingConfig.current(org=course.org).enabled) + assert ContentTypeGatingConfig.current(org=course.org).enabled org_config.enabled = False org_config.save() @@ -312,7 +286,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the org value in cache was deleted on save with self.assertNumQueries(2): - self.assertFalse(ContentTypeGatingConfig.current(org=course.org).enabled) + assert not ContentTypeGatingConfig.current(org=course.org).enabled global_config = ContentTypeGatingConfig(enabled=True, enabled_as_of=datetime(2018, 1, 1)) global_config.save() @@ -321,7 +295,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the org value is not updated in cache by changing the global value with self.assertNumQueries(0): - self.assertFalse(ContentTypeGatingConfig.current(org=course.org).enabled) + assert not ContentTypeGatingConfig.current(org=course.org).enabled site_config = ContentTypeGatingConfig(site=site_cfg.site, enabled=True, enabled_as_of=datetime(2018, 1, 1)) site_config.save() @@ -330,7 +304,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the org value is not updated in cache by changing the site value with self.assertNumQueries(0): - self.assertFalse(ContentTypeGatingConfig.current(org=course.org).enabled) + assert not ContentTypeGatingConfig.current(org=course.org).enabled def test_caching_course(self): course = CourseOverviewFactory.create(org='test-org') @@ -344,13 +318,13 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the org value is not retrieved from cache after save with self.assertNumQueries(2): - self.assertTrue(ContentTypeGatingConfig.current(course_key=course.id).enabled) + assert ContentTypeGatingConfig.current(course_key=course.id).enabled RequestCache.clear_all_namespaces() # Check that the org value can be retrieved from cache after read with self.assertNumQueries(0): - self.assertTrue(ContentTypeGatingConfig.current(course_key=course.id).enabled) + assert ContentTypeGatingConfig.current(course_key=course.id).enabled course_config.enabled = False course_config.save() @@ -359,7 +333,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the org value in cache was deleted on save with self.assertNumQueries(2): - self.assertFalse(ContentTypeGatingConfig.current(course_key=course.id).enabled) + assert not ContentTypeGatingConfig.current(course_key=course.id).enabled global_config = ContentTypeGatingConfig(enabled=True, enabled_as_of=datetime(2018, 1, 1)) global_config.save() @@ -368,7 +342,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the org value is not updated in cache by changing the global value with self.assertNumQueries(0): - self.assertFalse(ContentTypeGatingConfig.current(course_key=course.id).enabled) + assert not ContentTypeGatingConfig.current(course_key=course.id).enabled site_config = ContentTypeGatingConfig(site=site_cfg.site, enabled=True, enabled_as_of=datetime(2018, 1, 1)) site_config.save() @@ -377,7 +351,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the org value is not updated in cache by changing the site value with self.assertNumQueries(0): - self.assertFalse(ContentTypeGatingConfig.current(course_key=course.id).enabled) + assert not ContentTypeGatingConfig.current(course_key=course.id).enabled org_config = ContentTypeGatingConfig(org=course.org, enabled=True, enabled_as_of=datetime(2018, 1, 1)) org_config.save() @@ -386,7 +360,7 @@ class TestContentTypeGatingConfig(CacheIsolationTestCase): # Check that the org value is not updated in cache by changing the site value with self.assertNumQueries(0): - self.assertFalse(ContentTypeGatingConfig.current(course_key=course.id).enabled) + assert not ContentTypeGatingConfig.current(course_key=course.id).enabled def _resolve_settings(self, settings): if all(setting is None for setting in settings): diff --git a/openedx/features/content_type_gating/tests/test_partitions.py b/openedx/features/content_type_gating/tests/test_partitions.py index 3de4d021831..e51ecb22619 100644 --- a/openedx/features/content_type_gating/tests/test_partitions.py +++ b/openedx/features/content_type_gating/tests/test_partitions.py @@ -32,21 +32,21 @@ class TestContentTypeGatingPartition(CacheIsolationTestCase): with patch('openedx.features.content_type_gating.partitions.ContentTypeGatingPartitionScheme.create_user_partition') as mock_create: partition = create_content_gating_partition(mock_course) - self.assertEqual(partition, mock_create.return_value) + assert partition == mock_create.return_value def test_create_content_gating_partition_override_only(self): mock_course = Mock(id=self.course_key, user_partitions={}) ContentTypeGatingConfig.objects.create(enabled=False, studio_override_enabled=True) partition = create_content_gating_partition(mock_course) - self.assertIsNotNone(partition) + assert partition is not None def test_create_content_gating_partition_disabled(self): mock_course = Mock(id=self.course_key, user_partitions={}) ContentTypeGatingConfig.objects.create(enabled=False, studio_override_enabled=False) partition = create_content_gating_partition(mock_course) - self.assertIsNone(partition) + assert partition is None def test_create_content_gating_partition_no_scheme_installed(self): mock_course = Mock(id=self.course_key, user_partitions={}) @@ -55,7 +55,7 @@ class TestContentTypeGatingPartition(CacheIsolationTestCase): with patch('openedx.features.content_type_gating.partitions.UserPartition.get_scheme', side_effect=UserPartitionError): partition = create_content_gating_partition(mock_course) - self.assertIsNone(partition) + assert partition is None def test_create_content_gating_partition_partition_id_used(self): mock_course = Mock(id=self.course_key, user_partitions={Mock(name='partition', id=CONTENT_GATING_PARTITION_ID): object()}) @@ -64,7 +64,7 @@ class TestContentTypeGatingPartition(CacheIsolationTestCase): with patch('openedx.features.content_type_gating.partitions.LOG') as mock_log: partition = create_content_gating_partition(mock_course) mock_log.warning.assert_called() - self.assertIsNone(partition) + assert partition is None def test_access_denied_fragment_for_masquerading(self): """ @@ -93,7 +93,7 @@ class TestContentTypeGatingPartition(CacheIsolationTestCase): ): fragment = partition.access_denied_fragment(mock_block, global_staff, LIMITED_ACCESS, [FULL_ACCESS]) - self.assertIsNotNone(fragment) + assert fragment is not None def test_access_denied_fragment_for_full_access_users(self): """ @@ -115,9 +115,9 @@ class TestContentTypeGatingPartition(CacheIsolationTestCase): return_value=mock_request ): fragment = partition.access_denied_fragment(mock_block, global_staff, FULL_ACCESS, 'test_allowed_group') - self.assertIsNone(fragment) + assert fragment is None message = partition.access_denied_message(mock_block.scope_ids.usage_id, global_staff, FULL_ACCESS, 'test_allowed_group') - self.assertIsNone(message) + assert message is None def test_access_denied_fragment_for_null_request(self): """ @@ -142,4 +142,4 @@ class TestContentTypeGatingPartition(CacheIsolationTestCase): ): fragment = partition.access_denied_fragment(mock_block, global_staff, LIMITED_ACCESS, [FULL_ACCESS]) - self.assertIsNotNone(fragment) + assert fragment is not None diff --git a/openedx/features/course_bookmarks/tests/test_course_bookmarks.py b/openedx/features/course_bookmarks/tests/test_course_bookmarks.py index c183477352f..e71fc909c7c 100644 --- a/openedx/features/course_bookmarks/tests/test_course_bookmarks.py +++ b/openedx/features/course_bookmarks/tests/test_course_bookmarks.py @@ -43,4 +43,4 @@ class TestCourseBookmarksTool(SharedModuleStoreTestCase): def test_bookmarks_tool_is_enabled(self, user_type, should_be_enabled): request = RequestFactory().request() request.user = self.create_user_for_course(self.course, user_type) - self.assertEqual(CourseBookmarksTool.is_enabled(request, self.course.id), should_be_enabled) + assert CourseBookmarksTool.is_enabled(request, self.course.id) == should_be_enabled diff --git a/openedx/features/course_duration_limits/tests/test_access.py b/openedx/features/course_duration_limits/tests/test_access.py index 89f2ab56da3..8ce1e90b047 100644 --- a/openedx/features/course_duration_limits/tests/test_access.py +++ b/openedx/features/course_duration_limits/tests/test_access.py @@ -39,10 +39,10 @@ class TestAccess(CacheIsolationTestCase): def assertDateInMessage(self, date, message): # lint-amnesty, pylint: disable=missing-function-docstring # First, check that the formatted version is in there - self.assertIn(strftime_localized(date, 'SHORT_DATE'), message) + assert strftime_localized(date, 'SHORT_DATE') in message # But also that the machine-readable version is in there - self.assertIn('data-datetime="%s"' % date.isoformat(), message) + assert 'data-datetime="%s"' % date.isoformat() in message def test_get_access_expiration_data(self): enrollment = CourseEnrollmentFactory() @@ -62,15 +62,16 @@ class TestAccess(CacheIsolationTestCase): ) expiration_date = get_user_course_expiration_date(user, overview) - self.assertIsNotNone(expiration_date) + assert expiration_date is not None data = get_access_expiration_data(user, overview) - self.assertEqual(data, { - 'expiration_date': expiration_date, - 'masquerading_expired_course': False, - 'upgrade_deadline': upgrade_deadline, - 'upgrade_url': '/dashboard', - }) + assert data == \ + { + 'expiration_date': expiration_date, + 'masquerading_expired_course': False, + 'upgrade_deadline': upgrade_deadline, + 'upgrade_url': '/dashboard' + } @ddt.data( *itertools.product( @@ -118,12 +119,12 @@ class TestAccess(CacheIsolationTestCase): ) duration_limit_upgrade_deadline = get_user_course_expiration_date(enrollment.user, enrollment.course) - self.assertIsNotNone(duration_limit_upgrade_deadline) + assert duration_limit_upgrade_deadline is not None message = generate_course_expired_message(enrollment.user, enrollment.course) self.assertDateInMessage(duration_limit_upgrade_deadline, message) - self.assertIn('data-timezone="Asia/Tokyo"', message) + assert 'data-timezone="Asia/Tokyo"' in message soft_upgradeable = schedule_upgrade_deadline is not None and now < schedule_upgrade_deadline upgradeable = course_upgrade_deadline is None or now < course_upgrade_deadline @@ -134,7 +135,7 @@ class TestAccess(CacheIsolationTestCase): elif upgradeable and has_upgrade_deadline: self.assertDateInMessage(course_upgrade_deadline, message) else: - self.assertNotIn("Upgrade by", message) + assert 'Upgrade by' not in message def test_schedule_start_date_in_past(self): """ @@ -164,5 +165,5 @@ class TestAccess(CacheIsolationTestCase): expected_course_expiration_date = content_availability_date + access_duration duration_limit_upgrade_deadline = get_user_course_expiration_date(enrollment.user, enrollment.course) - self.assertIsNotNone(duration_limit_upgrade_deadline) - self.assertEqual(duration_limit_upgrade_deadline, expected_course_expiration_date) + assert duration_limit_upgrade_deadline is not None + assert duration_limit_upgrade_deadline == expected_course_expiration_date diff --git a/openedx/features/course_duration_limits/tests/test_course_expiration.py b/openedx/features/course_duration_limits/tests/test_course_expiration.py index 0324182fedb..9d6f084e6db 100644 --- a/openedx/features/course_duration_limits/tests/test_course_expiration.py +++ b/openedx/features/course_duration_limits/tests/test_course_expiration.py @@ -67,7 +67,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): """Tests that verified enrollments do not have an expiration""" CourseEnrollment.enroll(self.user, self.course.id, CourseMode.VERIFIED) result = get_user_course_expiration_date(self.user, CourseOverview.get_from_id(self.course.id)) - self.assertEqual(result, None) + assert result is None @mock.patch("openedx.core.djangoapps.course_date_signals.utils.get_course_run_details") @ddt.data( @@ -106,7 +106,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): self.user, CourseOverview.get_from_id(self.course.id), ) - self.assertEqual(result, enrollment.created + access_duration) + assert result == (enrollment.created + access_duration) @mock.patch("openedx.core.djangoapps.course_date_signals.utils.get_course_run_details") def test_content_availability_date(self, mock_get_course_run_details): @@ -129,7 +129,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): self.user, CourseOverview.get_from_id(past_course.id), ) - self.assertEqual(result, None) + assert result is None add_course_mode(past_course, mode_slug=CourseMode.AUDIT) add_course_mode(past_course, upgrade_deadline_expired=False) @@ -138,7 +138,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): CourseOverview.get_from_id(past_course.id), ) content_availability_date = enrollment.created - self.assertEqual(result, content_availability_date + access_duration) + assert result == (content_availability_date + access_duration) # Content availability date is course start date start_date = now() + timedelta(weeks=10) @@ -153,7 +153,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): self.user, CourseOverview.get_from_id(future_course.id), ) - self.assertEqual(result, None) + assert result is None add_course_mode(future_course, mode_slug=CourseMode.AUDIT) add_course_mode(future_course, upgrade_deadline_expired=False) @@ -162,7 +162,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): CourseOverview.get_from_id(future_course.id), ) content_availability_date = start_date.replace(microsecond=0) - self.assertEqual(result, content_availability_date + access_duration) + assert result == (content_availability_date + access_duration) @mock.patch("openedx.core.djangoapps.course_date_signals.utils.get_course_run_details") def test_expired_upgrade_deadline(self, mock_get_course_run_details): @@ -187,7 +187,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): CourseOverview.get_from_id(course.id), ) content_availability_date = enrollment.created - self.assertEqual(result, content_availability_date + access_duration) + assert result == (content_availability_date + access_duration) @mock.patch("openedx.core.djangoapps.course_date_signals.utils.get_course_run_details") @ddt.data( @@ -238,7 +238,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): course_home_url = reverse('openedx.course_experience.course_home', args=[six.text_type(self.course.id)]) response = self.client.get(course_home_url, follow=True) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 six.assertCountEqual(self, response.redirect_chain, []) banner_text = 'You lose all access to this course, including your progress,' if show_expiration_banner: @@ -275,7 +275,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): course_home_url = reverse('openedx.course_experience.course_home', args=[six.text_type(self.course.id)]) response = self.client.get(course_home_url, follow=True) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 six.assertCountEqual(self, response.redirect_chain, []) banner_text = 'You lose all access to this course, including your progress,' self.assertNotContains(response, banner_text) @@ -311,7 +311,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): course_home_url = reverse('openedx.course_experience.course_home', args=[six.text_type(self.course.id)]) response = self.client.get(course_home_url, follow=True) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 six.assertCountEqual(self, response.redirect_chain, []) banner_text = 'This learner does not have access to this course. Their access expired on' self.assertContains(response, banner_text) @@ -362,7 +362,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): course_home_url = reverse('openedx.course_experience.course_home', args=[six.text_type(self.course.id)]) response = self.client.get(course_home_url, follow=True) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 six.assertCountEqual(self, response.redirect_chain, []) banner_text = 'This learner does not have access to this course. Their access expired on' self.assertNotContains(response, banner_text) @@ -411,7 +411,7 @@ class CourseExpirationTestCase(ModuleStoreTestCase, MasqueradeMixin): course_home_url = reverse('openedx.course_experience.course_home', args=[six.text_type(self.course.id)]) response = self.client.get(course_home_url, follow=True) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 six.assertCountEqual(self, response.redirect_chain, []) banner_text = 'This learner does not have access to this course. Their access expired on' self.assertNotContains(response, banner_text) diff --git a/openedx/features/course_duration_limits/tests/test_models.py b/openedx/features/course_duration_limits/tests/test_models.py index 4e72e4a5806..5f3878aa2ef 100644 --- a/openedx/features/course_duration_limits/tests/test_models.py +++ b/openedx/features/course_duration_limits/tests/test_models.py @@ -2,11 +2,11 @@ Tests of CourseDurationLimitConfig. """ - import itertools from datetime import datetime, timedelta import ddt +import pytest import pytz from django.utils import timezone from edx_django_utils.cache import RequestCache @@ -14,12 +14,12 @@ from mock import Mock from opaque_keys.edx.locator import CourseLocator from common.djangoapps.course_modes.tests.factories import CourseModeFactory +from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory from openedx.core.djangoapps.config_model_utils.models import Provenance from openedx.core.djangoapps.content.course_overviews.tests.factories import CourseOverviewFactory from openedx.core.djangoapps.site_configuration.tests.factories import SiteConfigurationFactory from openedx.core.djangolib.testing.utils import CacheIsolationTestCase from openedx.features.course_duration_limits.models import CourseDurationLimitConfig -from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory @ddt.ddt @@ -78,17 +78,17 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): with self.assertNumQueries(query_count): enabled = CourseDurationLimitConfig.enabled_for_enrollment(user, self.course_overview) - self.assertEqual(not enrolled_before_enabled, enabled) + assert (not enrolled_before_enabled) == enabled def test_enabled_for_enrollment_failure(self): - with self.assertRaises(ValueError): + with pytest.raises(ValueError): CourseDurationLimitConfig.enabled_for_enrollment(None, None) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): CourseDurationLimitConfig.enabled_for_enrollment( Mock(name='user'), None ) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): CourseDurationLimitConfig.enabled_for_enrollment( None, Mock(name='course_key') @@ -114,12 +114,8 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): course_key = self.course_overview.id - self.assertEqual( - not before_enabled, - CourseDurationLimitConfig.enabled_for_course( - course_key=course_key, - target_datetime=target_datetime, - ) + assert (not before_enabled) == CourseDurationLimitConfig.enabled_for_course( + course_key=course_key, target_datetime=target_datetime ) @ddt.data( @@ -174,10 +170,10 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): expected_org_setting = self._resolve_settings([global_setting, site_setting, org_setting]) expected_course_setting = self._resolve_settings([global_setting, site_setting, org_setting, course_setting]) - self.assertEqual(expected_global_setting, CourseDurationLimitConfig.current().enabled) - self.assertEqual(expected_site_setting, CourseDurationLimitConfig.current(site=test_site_cfg.site).enabled) - self.assertEqual(expected_org_setting, CourseDurationLimitConfig.current(org=test_course.org).enabled) - self.assertEqual(expected_course_setting, CourseDurationLimitConfig.current(course_key=test_course.id).enabled) + assert expected_global_setting == CourseDurationLimitConfig.current().enabled + assert expected_site_setting == CourseDurationLimitConfig.current(site=test_site_cfg.site).enabled + assert expected_org_setting == CourseDurationLimitConfig.current(org=test_course.org).enabled + assert expected_course_setting == CourseDurationLimitConfig.current(course_key=test_course.id).enabled def test_all_current_course_configs(self): # Set up test objects @@ -215,30 +211,24 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Deliberatly using the last all_configs that was checked after the 3rd pass through the global_settings loop # We should be creating 3^4 courses (3 global values * 3 site values * 3 org values * 3 course values) # Plus 1 for the edX/toy/2012_Fall course - self.assertEqual(len(all_configs), 3**4 + 1) + assert len(all_configs) == ((3 ** 4) + 1) # Point-test some of the final configurations - self.assertEqual( - all_configs[CourseLocator('7-True', 'test_course', 'run-None')], - { - 'enabled': (True, Provenance.org), - 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), Provenance.run), - } - ) - self.assertEqual( - all_configs[CourseLocator('7-True', 'test_course', 'run-False')], - { - 'enabled': (False, Provenance.run), - 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), Provenance.run), - } - ) - self.assertEqual( - all_configs[CourseLocator('7-None', 'test_course', 'run-None')], - { - 'enabled': (True, Provenance.site), - 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), Provenance.run), - } - ) + assert all_configs[CourseLocator('7-True', 'test_course', 'run-None')] == { + 'enabled': (True, Provenance.org), + 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), + Provenance.run) + } + assert all_configs[CourseLocator('7-True', 'test_course', 'run-False')] == { + 'enabled': (False, Provenance.run), + 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), + Provenance.run) + } + assert all_configs[CourseLocator('7-None', 'test_course', 'run-None')] == { + 'enabled': (True, Provenance.site), + 'enabled_as_of': (datetime(2018, 1, 1, 0, tzinfo=pytz.UTC), + Provenance.run) + } def test_caching_global(self): global_config = CourseDurationLimitConfig(enabled=True, enabled_as_of=datetime(2018, 1, 1, tzinfo=pytz.UTC)) @@ -248,13 +238,13 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the global value is not retrieved from cache after save with self.assertNumQueries(1): - self.assertTrue(CourseDurationLimitConfig.current().enabled) + assert CourseDurationLimitConfig.current().enabled RequestCache.clear_all_namespaces() # Check that the global value can be retrieved from cache after read with self.assertNumQueries(0): - self.assertTrue(CourseDurationLimitConfig.current().enabled) + assert CourseDurationLimitConfig.current().enabled global_config.enabled = False global_config.save() @@ -263,7 +253,7 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the global value in cache was deleted on save with self.assertNumQueries(1): - self.assertFalse(CourseDurationLimitConfig.current().enabled) + assert not CourseDurationLimitConfig.current().enabled def test_caching_site(self): site_cfg = SiteConfigurationFactory() @@ -274,13 +264,13 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the site value is not retrieved from cache after save with self.assertNumQueries(1): - self.assertTrue(CourseDurationLimitConfig.current(site=site_cfg.site).enabled) + assert CourseDurationLimitConfig.current(site=site_cfg.site).enabled RequestCache.clear_all_namespaces() # Check that the site value can be retrieved from cache after read with self.assertNumQueries(0): - self.assertTrue(CourseDurationLimitConfig.current(site=site_cfg.site).enabled) + assert CourseDurationLimitConfig.current(site=site_cfg.site).enabled site_config.enabled = False site_config.save() @@ -289,7 +279,7 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the site value in cache was deleted on save with self.assertNumQueries(1): - self.assertFalse(CourseDurationLimitConfig.current(site=site_cfg.site).enabled) + assert not CourseDurationLimitConfig.current(site=site_cfg.site).enabled global_config = CourseDurationLimitConfig(enabled=True, enabled_as_of=datetime(2018, 1, 1, tzinfo=pytz.UTC)) global_config.save() @@ -298,7 +288,7 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the site value is not updated in cache by changing the global value with self.assertNumQueries(0): - self.assertFalse(CourseDurationLimitConfig.current(site=site_cfg.site).enabled) + assert not CourseDurationLimitConfig.current(site=site_cfg.site).enabled def test_caching_org(self): course = CourseOverviewFactory.create(org='test-org') @@ -312,13 +302,13 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the org value is not retrieved from cache after save with self.assertNumQueries(2): - self.assertTrue(CourseDurationLimitConfig.current(org=course.org).enabled) + assert CourseDurationLimitConfig.current(org=course.org).enabled RequestCache.clear_all_namespaces() # Check that the org value can be retrieved from cache after read with self.assertNumQueries(0): - self.assertTrue(CourseDurationLimitConfig.current(org=course.org).enabled) + assert CourseDurationLimitConfig.current(org=course.org).enabled org_config.enabled = False org_config.save() @@ -327,7 +317,7 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the org value in cache was deleted on save with self.assertNumQueries(2): - self.assertFalse(CourseDurationLimitConfig.current(org=course.org).enabled) + assert not CourseDurationLimitConfig.current(org=course.org).enabled global_config = CourseDurationLimitConfig(enabled=True, enabled_as_of=datetime(2018, 1, 1, tzinfo=pytz.UTC)) global_config.save() @@ -336,7 +326,7 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the org value is not updated in cache by changing the global value with self.assertNumQueries(0): - self.assertFalse(CourseDurationLimitConfig.current(org=course.org).enabled) + assert not CourseDurationLimitConfig.current(org=course.org).enabled site_config = CourseDurationLimitConfig(site=site_cfg.site, enabled=True, enabled_as_of=datetime(2018, 1, 1, tzinfo=pytz.UTC)) # lint-amnesty, pylint: disable=line-too-long site_config.save() @@ -345,7 +335,7 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the org value is not updated in cache by changing the site value with self.assertNumQueries(0): - self.assertFalse(CourseDurationLimitConfig.current(org=course.org).enabled) + assert not CourseDurationLimitConfig.current(org=course.org).enabled def test_caching_course(self): course = CourseOverviewFactory.create(org='test-org') @@ -359,13 +349,13 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the org value is not retrieved from cache after save with self.assertNumQueries(2): - self.assertTrue(CourseDurationLimitConfig.current(course_key=course.id).enabled) + assert CourseDurationLimitConfig.current(course_key=course.id).enabled RequestCache.clear_all_namespaces() # Check that the org value can be retrieved from cache after read with self.assertNumQueries(0): - self.assertTrue(CourseDurationLimitConfig.current(course_key=course.id).enabled) + assert CourseDurationLimitConfig.current(course_key=course.id).enabled course_config.enabled = False course_config.save() @@ -374,7 +364,7 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the org value in cache was deleted on save with self.assertNumQueries(2): - self.assertFalse(CourseDurationLimitConfig.current(course_key=course.id).enabled) + assert not CourseDurationLimitConfig.current(course_key=course.id).enabled global_config = CourseDurationLimitConfig(enabled=True, enabled_as_of=datetime(2018, 1, 1, tzinfo=pytz.UTC)) global_config.save() @@ -383,7 +373,7 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the org value is not updated in cache by changing the global value with self.assertNumQueries(0): - self.assertFalse(CourseDurationLimitConfig.current(course_key=course.id).enabled) + assert not CourseDurationLimitConfig.current(course_key=course.id).enabled site_config = CourseDurationLimitConfig(site=site_cfg.site, enabled=True, enabled_as_of=datetime(2018, 1, 1, tzinfo=pytz.UTC)) # lint-amnesty, pylint: disable=line-too-long site_config.save() @@ -392,7 +382,7 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the org value is not updated in cache by changing the site value with self.assertNumQueries(0): - self.assertFalse(CourseDurationLimitConfig.current(course_key=course.id).enabled) + assert not CourseDurationLimitConfig.current(course_key=course.id).enabled org_config = CourseDurationLimitConfig(org=course.org, enabled=True, enabled_as_of=datetime(2018, 1, 1, tzinfo=pytz.UTC)) # lint-amnesty, pylint: disable=line-too-long org_config.save() @@ -401,7 +391,7 @@ class TestCourseDurationLimitConfig(CacheIsolationTestCase): # Check that the org value is not updated in cache by changing the site value with self.assertNumQueries(0): - self.assertFalse(CourseDurationLimitConfig.current(course_key=course.id).enabled) + assert not CourseDurationLimitConfig.current(course_key=course.id).enabled def _resolve_settings(self, settings): if all(setting is None for setting in settings): diff --git a/openedx/features/course_experience/api/v1/tests/test_views.py b/openedx/features/course_experience/api/v1/tests/test_views.py index 6704c624fa8..87cc854be3b 100644 --- a/openedx/features/course_experience/api/v1/tests/test_views.py +++ b/openedx/features/course_experience/api/v1/tests/test_views.py @@ -32,10 +32,10 @@ class ResetCourseDeadlinesViewTests(EventTestMixin, BaseCourseHomeTests, Masquer CourseEnrollment.enroll(self.user, self.course.id, CourseMode.VERIFIED) # Test correct post body response = self.client.post(reverse('course-experience-reset-course-deadlines'), {'course_key': self.course.id}) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 # Test body with incorrect body param (course_key is required) response = self.client.post(reverse('course-experience-reset-course-deadlines'), {'course': self.course.id}) - self.assertEqual(response.status_code, 400) + assert response.status_code == 400 self.assert_no_events_were_emitted() def test_reset_deadlines_with_masquerade(self): @@ -61,9 +61,9 @@ class ResetCourseDeadlinesViewTests(EventTestMixin, BaseCourseHomeTests, Masquer return_value=(True, False)): self.client.post(reverse('course-experience-reset-course-deadlines'), {'course_key': course.id}) updated_schedule = Schedule.objects.get(id=student_schedule.id) - self.assertEqual(updated_schedule.start_date.date(), datetime.datetime.today().date()) + assert updated_schedule.start_date.date() == datetime.datetime.today().date() updated_staff_schedule = Schedule.objects.get(id=staff_schedule.id) - self.assertEqual(updated_staff_schedule.start_date, staff_schedule.start_date) + assert updated_staff_schedule.start_date == staff_schedule.start_date self.assert_event_emitted( 'edx.ui.lms.reset_deadlines.clicked', courserun_key=str(course.id), @@ -76,11 +76,11 @@ class ResetCourseDeadlinesViewTests(EventTestMixin, BaseCourseHomeTests, Masquer def test_post_unauthenticated_user(self): self.client.logout() response = self.client.post(reverse('course-experience-reset-course-deadlines'), {'course_key': self.course.id}) - self.assertEqual(response.status_code, 401) + assert response.status_code == 401 def test_mobile_get_banner_info(self): response = self.client.get(reverse('course-experience-course-deadlines-mobile', args=[self.course.id])) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'missed_deadlines') self.assertContains(response, 'missed_gated_content') self.assertContains(response, 'content_type_gating_enabled') @@ -89,9 +89,9 @@ class ResetCourseDeadlinesViewTests(EventTestMixin, BaseCourseHomeTests, Masquer def test_mobile_get_unknown_course(self): url = reverse('course-experience-course-deadlines-mobile', args=['course-v1:unknown+course+2T2020']) response = self.client.get(url) - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 def test_mobile_get_unauthenticated_user(self): self.client.logout() response = self.client.get(reverse('course-experience-course-deadlines-mobile', args=[self.course.id])) - self.assertEqual(response.status_code, 401) + assert response.status_code == 401 diff --git a/openedx/features/course_experience/tests/test_course_updates.py b/openedx/features/course_experience/tests/test_course_updates.py index 76467881522..accad1734f0 100644 --- a/openedx/features/course_experience/tests/test_course_updates.py +++ b/openedx/features/course_experience/tests/test_course_updates.py @@ -55,35 +55,35 @@ class TestCourseUpdatesUtils(BaseCourseUpdatesTestCase): course=self.course.id.course, run=self.course.id.run, ) - self.assertEqual(updates[0]['content'], expected) + assert updates[0]['content'] == expected def test_ordered_update_includes_dismissed_updates(self): """Ordered update list should still have dismissed updates.""" self.create_course_update('Dismissed') dismiss_current_update_for_user(self.request, self.course) updates = get_ordered_updates(self.request, self.course) - self.assertEqual(len(updates), 1) + assert len(updates) == 1 def test_get_current_update_is_newest(self): """Tests that the current update is also the newest.""" self.create_course_update('Oldest', date='January 1, 1900') self.create_course_update('New', date='January 1, 2017') self.create_course_update('Oldish', date='January 1, 2000') - self.assertEqual(get_current_update_for_user(self.request, self.course), 'New') + assert get_current_update_for_user(self.request, self.course) == 'New' def test_get_current_update_when_dismissed(self): """Tests that a dismissed update is not returned.""" self.create_course_update('Dismissed') dismiss_current_update_for_user(self.request, self.course) - self.assertIsNone(get_current_update_for_user(self.request, self.course)) + assert get_current_update_for_user(self.request, self.course) is None def test_get_current_update_when_dismissed_but_edited(self): """Tests that a dismissed but edited update is returned.""" self.create_course_update('Original') dismiss_current_update_for_user(self.request, self.course) - self.assertIsNone(get_current_update_for_user(self.request, self.course)) + assert get_current_update_for_user(self.request, self.course) is None self.edit_course_update(1, content='Edited') - self.assertIsNotNone(get_current_update_for_user(self.request, self.course)) + assert get_current_update_for_user(self.request, self.course) is not None def test_get_current_update_remembers_dismissals(self): """Tests that older dismissed updates are remembered.""" @@ -94,21 +94,21 @@ class TestCourseUpdatesUtils(BaseCourseUpdatesTestCase): dismiss_current_update_for_user(self.request, self.course) self.create_course_update('Fourth') - self.assertEqual(get_current_update_for_user(self.request, self.course), 'Fourth') + assert get_current_update_for_user(self.request, self.course) == 'Fourth' self.edit_course_update(4, deleted=True) - self.assertIsNone(get_current_update_for_user(self.request, self.course)) + assert get_current_update_for_user(self.request, self.course) is None self.edit_course_update(3, deleted=True) - self.assertIsNone(get_current_update_for_user(self.request, self.course)) + assert get_current_update_for_user(self.request, self.course) is None self.edit_course_update(2, deleted=True) - self.assertEqual(get_current_update_for_user(self.request, self.course), 'First') + assert get_current_update_for_user(self.request, self.course) == 'First' def test_legacy_ignore_all_support(self): """Storing 'False' as the dismissal ignores all updates.""" self.create_course_update('First') - self.assertEqual(get_current_update_for_user(self.request, self.course), 'First') + assert get_current_update_for_user(self.request, self.course) == 'First' set_course_tag(self.user, self.course.id, self.UPDATES_TAG, 'False') - self.assertIsNone(get_current_update_for_user(self.request, self.course)) + assert get_current_update_for_user(self.request, self.course) is None def test_dismissal_hashing(self): """Confirm that the stored dismissal values are what we expect, to catch accidentally changing formats.""" @@ -118,4 +118,4 @@ class TestCourseUpdatesUtils(BaseCourseUpdatesTestCase): dismiss_current_update_for_user(self.request, self.course) tag = get_course_tag(self.user, self.course.id, self.UPDATES_TAG) - self.assertEqual(tag, '7fb55ed0b7a30342ba6da306428cae04,c22cf8376b1893dcfcef0649fe1a7d87') + assert tag == '7fb55ed0b7a30342ba6da306428cae04,c22cf8376b1893dcfcef0649fe1a7d87' diff --git a/openedx/features/course_experience/tests/views/test_course_dates.py b/openedx/features/course_experience/tests/views/test_course_dates.py index ef27c0eac94..ea0c359da6a 100644 --- a/openedx/features/course_experience/tests/views/test_course_dates.py +++ b/openedx/features/course_experience/tests/views/test_course_dates.py @@ -45,4 +45,4 @@ class TestCourseDatesFragmentView(ModuleStoreTestCase): self.client.logout() response = self.client.get(self.dates_fragment_url) - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 diff --git a/openedx/features/course_experience/tests/views/test_course_home.py b/openedx/features/course_experience/tests/views/test_course_home.py index 367660dab52..874b9b71c57 100644 --- a/openedx/features/course_experience/tests/views/test_course_home.py +++ b/openedx/features/course_experience/tests/views/test_course_home.py @@ -228,7 +228,7 @@ class TestCourseHomePage(CourseHomePageTestCase): # lint-amnesty, pylint: disab with override_flag(COURSE_PRE_START_ACCESS_FLAG.name, True): url = course_home_url(future_course) response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 @ddt.ddt @@ -458,11 +458,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase): # ensure that the user who has indefinite access self.client.login(username=user.username, password=self.TEST_PASSWORD) response = self.client.get(url) - self.assertEqual( - response.status_code, - 200, - "Should not expire access for user", - ) + assert response.status_code == 200, 'Should not expire access for user' @mock.patch.dict(settings.FEATURES, {'DISABLE_START_DATES': False}) @ddt.data( @@ -492,11 +488,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase): # ensure that the user has indefinite access self.client.login(username=user.username, password=self.TEST_PASSWORD) response = self.client.get(url) - self.assertEqual( - response.status_code, - 200, - "Should not expire access for user", - ) + assert response.status_code == 200, 'Should not expire access for user' @ddt.data( FORUM_ROLE_COMMUNITY_TA, @@ -518,11 +510,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase): # ensure the user has indefinite access self.client.login(username=user.username, password=self.TEST_PASSWORD) response = self.client.get(url) - self.assertEqual( - response.status_code, - 200, - "Should not expire access for user" - ) + assert response.status_code == 200, 'Should not expire access for user' @mock.patch.dict(settings.FEATURES, {'DISABLE_START_DATES': False}) @ddt.data( @@ -548,11 +536,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase): # ensure that the user who has indefinite access self.client.login(username=user.username, password=self.TEST_PASSWORD) response = self.client.get(url) - self.assertEqual( - response.status_code, - 200, - "Should not expire access for user", - ) + assert response.status_code == 200, 'Should not expire access for user' @mock.patch.dict(settings.FEATURES, {'DISABLE_START_DATES': False}) def test_expired_course(self): @@ -620,7 +604,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase): audit_only_course = CourseFactory.create() self.create_user_for_course(audit_only_course, CourseUserType.ENROLLED) response = self.client.get(course_home_url(audit_only_course)) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, TEST_COURSE_TOOLS) self.assertNotContains(response, TEST_BANNER_CLASS) @@ -650,7 +634,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase): response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 @mock.patch.dict(settings.FEATURES, {'DISABLE_START_DATES': False}) @mock.patch("common.djangoapps.util.date_utils.strftime_localized") @@ -683,7 +667,7 @@ class TestCourseHomePageAccess(CourseHomePageTestCase): url = course_home_url_from_string('not/a/course') response = self.client.get(url) - self.assertEqual(response.status_code, 404) + assert response.status_code == 404 @override_waffle_flag(COURSE_PRE_START_ACCESS_FLAG, active=True) def test_masters_course_message(self): @@ -935,7 +919,7 @@ class CourseHomeFragmentViewTests(ModuleStoreTestCase): self.assert_upgrade_message_not_displayed() def test_no_upgrade_message_if_not_enrolled(self): - self.assertEqual(len(CourseEnrollment.enrollments_for_user(self.user)), 0) + assert len(CourseEnrollment.enrollments_for_user(self.user)) == 0 self.assert_upgrade_message_not_displayed() def test_no_upgrade_message_if_verified_track(self): diff --git a/openedx/features/course_experience/tests/views/test_course_outline.py b/openedx/features/course_experience/tests/views/test_course_outline.py index 4f8e6123ffb..825cdfca27f 100644 --- a/openedx/features/course_experience/tests/views/test_course_outline.py +++ b/openedx/features/course_experience/tests/views/test_course_outline.py @@ -156,17 +156,17 @@ class TestCourseOutlinePage(SharedModuleStoreTestCase, MasqueradeMixin): ) response = self.client.get(url) - self.assertTrue(course.children) + assert course.children for chapter in course_block_tree['children']: self.assertContains(response, chapter['display_name']) - self.assertTrue(chapter['children']) + assert chapter['children'] for sequential in chapter['children']: self.assertContains(response, sequential['display_name']) if sequential['graded']: print(sequential) self.assertContains(response, sequential['due'].strftime(u'%Y-%m-%d %H:%M:%S')) self.assertContains(response, sequential['format']) - self.assertTrue(sequential['children']) + assert sequential['children'] def test_num_graded_problems(self): course = CourseFactory.create() @@ -258,9 +258,9 @@ class TestCourseOutlinePage(SharedModuleStoreTestCase, MasqueradeMixin): post_dict = {'course_id': str(course.id)} self.client.post(reverse(RESET_COURSE_DEADLINES_NAME), post_dict) updated_schedule = Schedule.objects.get(id=student_schedule.id) - self.assertEqual(updated_schedule.start_date.date(), datetime.datetime.today().date()) + assert updated_schedule.start_date.date() == datetime.datetime.today().date() updated_staff_schedule = Schedule.objects.get(id=staff_schedule.id) - self.assertEqual(updated_staff_schedule.start_date, staff_schedule.start_date) + assert updated_staff_schedule.start_date == staff_schedule.start_date @override_experiment_waffle_flag(RELATIVE_DATES_FLAG, active=True) def test_reset_course_deadlines_masquerade_generic_student(self): @@ -283,9 +283,9 @@ class TestCourseOutlinePage(SharedModuleStoreTestCase, MasqueradeMixin): post_dict = {'course_id': str(course.id)} self.client.post(reverse(RESET_COURSE_DEADLINES_NAME), post_dict) updated_student_schedule = Schedule.objects.get(id=student_schedule.id) - self.assertEqual(updated_student_schedule.start_date, student_schedule.start_date) + assert updated_student_schedule.start_date == student_schedule.start_date updated_staff_schedule = Schedule.objects.get(id=staff_schedule.id) - self.assertEqual(updated_staff_schedule.start_date.date(), datetime.date.today()) + assert updated_staff_schedule.start_date.date() == datetime.date.today() class TestCourseOutlinePageWithPrerequisites(SharedModuleStoreTestCase, MilestonesTestCaseMixin): @@ -377,25 +377,25 @@ class TestCourseOutlinePageWithPrerequisites(SharedModuleStoreTestCase, Mileston self.setup_gated_section(self.course_blocks['gated_content'], self.course_blocks['prerequisite']) response = self.client.get(course_home_url(course)) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 response_content = pq(response.content) # check lock icon is present lock_icon = response_content('.fa-lock') - self.assertTrue(lock_icon, "lock icon is not present, but should be") + assert lock_icon, 'lock icon is not present, but should be' subsection = lock_icon.parents('.subsection-text') # check that subsection-title-name is the display name gated_subsection_title = self.course_blocks['gated_content'].display_name - self.assertIn(gated_subsection_title, subsection.children('.subsection-title').html()) + assert gated_subsection_title in subsection.children('.subsection-title').html() # check that it says prerequisite required - self.assertIn("Prerequisite:", subsection.children('.details').html()) + assert 'Prerequisite:' in subsection.children('.details').html() # check that there is not a screen reader message - self.assertFalse(subsection.children('.sr')) + assert not subsection.children('.sr') def test_content_unlocked(self): """ @@ -414,13 +414,13 @@ class TestCourseOutlinePageWithPrerequisites(SharedModuleStoreTestCase, Mileston ) response = self.client.get(course_home_url(course)) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 response_content = pq(response.content) # check unlock icon is not present unlock_icon = response_content('.fa-unlock') - self.assertFalse(unlock_icon, "unlock icon is present, yet shouldn't be.") + assert not unlock_icon, "unlock icon is present, yet shouldn't be." gated_subsection_title = self.course_blocks['gated_content'].display_name every_subsection_on_outline = response_content('.subsection-title') @@ -433,8 +433,8 @@ class TestCourseOutlinePageWithPrerequisites(SharedModuleStoreTestCase, Mileston says_prerequisite_required = "Prerequisite:" in subsection_contents # check that subsection-title-name is the display name of gated content section - self.assertTrue(subsection_has_gated_text) - self.assertFalse(says_prerequisite_required) + assert subsection_has_gated_text + assert not says_prerequisite_required class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleTestMixin): @@ -510,7 +510,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT 'section': sequential.url_name, } ) - self.assertEqual(200, self.client.get(last_accessed_url).status_code) + assert 200 == self.client.get(last_accessed_url).status_code @override_waffle_switch(ENABLE_COMPLETION_TRACKING_SWITCH, active=True) def complete_sequential(self, course, sequential): @@ -540,7 +540,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT :return: response object """ response = self.client.get(course_home_url(course)) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'Start Course', count=start_count) self.assertContains(response, 'Resume Course', count=resume_count) return response @@ -556,7 +556,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT response = self.client.get(course_home_url(course)) content = pq(response.content) - self.assertEqual(len(content('.fa-check')), 0) + assert len(content('.fa-check')) == 0 self.complete_sequential(self.course, vertical) @@ -564,7 +564,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT content = pq(response.content) # Subsection should be checked - self.assertEqual(len(content('.fa-check')), 1) + assert len(content('.fa-check')) == 1 def test_start_course(self): """ @@ -580,7 +580,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT content = pq(response.content) vertical = course.children[0].children[0].children[0] - self.assertTrue(content('.action-resume-course').attr('href').endswith('/vertical/' + vertical.url_name)) + assert content('.action-resume-course').attr('href').endswith(('/vertical/' + vertical.url_name)) @override_settings(LMS_BASE='test_url:9999') def test_resume_course_with_completion_api(self): @@ -600,7 +600,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT # Test for 'resume' link URL - should be vertical 1 content = pq(response.content) - self.assertTrue(content('.action-resume-course').attr('href').endswith('/vertical/' + vertical1.url_name)) + assert content('.action-resume-course').attr('href').endswith(('/vertical/' + vertical1.url_name)) self.complete_sequential(self.course, vertical2) # Test for 'resume' link @@ -608,7 +608,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT # Test for 'resume' link URL - should be vertical 2 content = pq(response.content) - self.assertTrue(content('.action-resume-course').attr('href').endswith('/vertical/' + vertical2.url_name)) + assert content('.action-resume-course').attr('href').endswith(('/vertical/' + vertical2.url_name)) # visit sequential 1, make sure 'Resume Course' URL is robust against 'Last Visited' # (even though I visited seq1/vert1, 'Resume Course' still points to seq2/vert2) @@ -617,7 +617,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT # Test for 'resume' link URL - should be vertical 2 (last completed block, NOT last visited) response = self.visit_course_home(course, resume_count=1) content = pq(response.content) - self.assertTrue(content('.action-resume-course').attr('href').endswith('/vertical/' + vertical2.url_name)) + assert content('.action-resume-course').attr('href').endswith(('/vertical/' + vertical2.url_name)) def test_resume_course_deleted_sequential(self): """ @@ -629,7 +629,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT # first navigate to a sequential to make it the last accessed chapter = course.children[0] - self.assertGreaterEqual(len(chapter.children), 2) + assert len(chapter.children) >= 2 sequential = chapter.children[0] sequential2 = chapter.children[1] self.complete_sequential(course, sequential) @@ -643,7 +643,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT response = self.visit_course_home(course, resume_count=1) content = pq(response.content) - self.assertTrue(content('.action-resume-course').attr('href').endswith('/sequential/' + sequential2.url_name)) + assert content('.action-resume-course').attr('href').endswith(('/sequential/' + sequential2.url_name)) def test_resume_course_deleted_sequentials(self): """ @@ -655,7 +655,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT # first navigate to a sequential to make it the last accessed chapter = course.children[0] - self.assertEqual(len(chapter.children), 2) + assert len(chapter.children) == 2 sequential = chapter.children[0] self.complete_sequential(course, sequential) @@ -681,7 +681,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT response = self.visit_course_home(course, start_count=1, resume_count=0) content = pq(response.content) vertical = course.children[0].children[0].children[0] - self.assertTrue(content('.action-resume-course').attr('href').endswith('/vertical/' + vertical.url_name)) + assert content('.action-resume-course').attr('href').endswith(('/vertical/' + vertical.url_name)) @override_waffle_switch(ENABLE_COMPLETION_TRACKING_SWITCH, active=True) def test_course_outline_auto_open(self): @@ -705,12 +705,12 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT response_content = self.client.get(course_home_url(course)).content stripped_response = text_type(re.sub(b"\\s+", b"", response_content), "utf-8") - self.assertIn(get_sequential_button(text_type(chapter1.location), False), stripped_response) - self.assertIn(get_sequential_button(text_type(chapter2.location), True), stripped_response) + assert get_sequential_button(text_type(chapter1.location), False) in stripped_response + assert get_sequential_button(text_type(chapter2.location), True) in stripped_response content = pq(response_content) button = content('#expand-collapse-outline-all-button') - self.assertEqual('Expand All', button.children()[0].text) + assert 'Expand All' == button.children()[0].text def test_user_enrolled_after_completion_collection(self): """ @@ -722,7 +722,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT switch, _ = Switch.objects.get_or_create(name=switch_name) # pylint: disable=protected-access - self.assertEqual(switch.created, view._completion_data_collection_start()) + assert switch.created == view._completion_data_collection_start() switch.delete() @@ -734,7 +734,7 @@ class TestCourseOutlineResumeCourse(SharedModuleStoreTestCase, CompletionWaffleT view = CourseOutlineFragmentView() # pylint: disable=protected-access - self.assertEqual(DEFAULT_COMPLETION_TRACKING_START, view._completion_data_collection_start()) + assert DEFAULT_COMPLETION_TRACKING_START == view._completion_data_collection_start() class TestCourseOutlinePreview(SharedModuleStoreTestCase, MasqueradeMixin): @@ -773,11 +773,11 @@ class TestCourseOutlinePreview(SharedModuleStoreTestCase, MasqueradeMixin): self.client.login(username=staff_user.username, password='test') url = course_home_url(course) response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'Future Chapter') # Verify that staff masquerading as a learner see the future chapter. self.update_masquerade(course=course, role='student') response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'Future Chapter') diff --git a/openedx/features/course_experience/tests/views/test_course_updates.py b/openedx/features/course_experience/tests/views/test_course_updates.py index d0ae2996f31..a3abea4b3db 100644 --- a/openedx/features/course_experience/tests/views/test_course_updates.py +++ b/openedx/features/course_experience/tests/views/test_course_updates.py @@ -36,7 +36,7 @@ class TestCourseUpdatesPage(BaseCourseUpdatesTestCase): self.create_course_update('Second Message') url = course_updates_url(self.course) response = self.client.get(url) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'First Message') self.assertContains(response, 'Second Message') diff --git a/openedx/features/course_experience/tests/views/test_welcome_message.py b/openedx/features/course_experience/tests/views/test_welcome_message.py index 805ae431c23..e94d3322302 100644 --- a/openedx/features/course_experience/tests/views/test_welcome_message.py +++ b/openedx/features/course_experience/tests/views/test_welcome_message.py @@ -57,24 +57,24 @@ class TestWelcomeMessageView(BaseCourseUpdatesTestCase): self.create_course_update('Second Update', date='January 1, 2017') self.create_course_update('Retroactive Update', date='January 1, 2010') response = self.client.get(url_generator(self.course)) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'Second Update') self.assertContains(response, 'Dismiss') @ddt.data(welcome_message_url, latest_update_url) def test_empty_message(self, url_generator): response = self.client.get(url_generator(self.course)) - self.assertEqual(response.status_code, 204) + assert response.status_code == 204 def test_dismiss_welcome_message(self): # Latest update is dimssed in JS and has no server/backend component. self.create_course_update('First Update') response = self.client.get(welcome_message_url(self.course)) - self.assertEqual(response.status_code, 200) + assert response.status_code == 200 self.assertContains(response, 'First Update') self.client.post(dismiss_message_url(self.course)) response = self.client.get(welcome_message_url(self.course)) - self.assertNotIn('First Update', response) - self.assertEqual(response.status_code, 204) + assert 'First Update' not in response + assert response.status_code == 204 diff --git a/openedx/features/discounts/tests/test_applicability.py b/openedx/features/discounts/tests/test_applicability.py index 21b9d2c2543..1a6a584ec17 100644 --- a/openedx/features/discounts/tests/test_applicability.py +++ b/openedx/features/discounts/tests/test_applicability.py @@ -54,7 +54,7 @@ class TestApplicability(ModuleStoreTestCase): def test_can_receive_discount(self): # Right now, no one should be able to receive the discount applicability = can_receive_discount(user=self.user, course=self.course) - self.assertEqual(applicability, False) + assert applicability is False @override_waffle_flag(DISCOUNT_APPLICABILITY_FLAG, active=True) def test_can_receive_discount_course_requirements(self): @@ -68,22 +68,22 @@ class TestApplicability(ModuleStoreTestCase): ) applicability = can_receive_discount(user=self.user, course=self.course) - self.assertEqual(applicability, True) + assert applicability is True no_verified_mode_course = CourseFactory(end=now() + timedelta(days=30)) applicability = can_receive_discount(user=self.user, course=no_verified_mode_course) - self.assertEqual(applicability, False) + assert applicability is False course_that_has_ended = CourseFactory(end=now() - timedelta(days=30)) applicability = can_receive_discount(user=self.user, course=course_that_has_ended) - self.assertEqual(applicability, False) + assert applicability is False disabled_course = CourseFactory() CourseModeFactory.create(course_id=disabled_course.id, mode_slug='verified') # lint-amnesty, pylint: disable=no-member disabled_course_overview = CourseOverview.get_from_id(disabled_course.id) # lint-amnesty, pylint: disable=no-member DiscountRestrictionConfig.objects.create(disabled=True, course=disabled_course_overview) applicability = can_receive_discount(user=self.user, course=disabled_course) - self.assertEqual(applicability, False) + assert applicability is False @ddt.data(*( [[]] + @@ -149,7 +149,7 @@ class TestApplicability(ModuleStoreTestCase): ) applicability = can_receive_discount(user=self.user, course=self.course) - self.assertEqual(applicability, False) + assert applicability is False @override_waffle_flag(DISCOUNT_APPLICABILITY_FLAG, active=True) def test_holdback_denies_discount(self): diff --git a/openedx/features/discounts/tests/test_discount_restriction_models.py b/openedx/features/discounts/tests/test_discount_restriction_models.py index f5db7a17c58..12714c44533 100644 --- a/openedx/features/discounts/tests/test_discount_restriction_models.py +++ b/openedx/features/discounts/tests/test_discount_restriction_models.py @@ -37,10 +37,7 @@ class TestDiscountRestrictionConfig(CacheIsolationTestCase): ) course_key = self.course_overview.id - self.assertEqual( - disabled, - DiscountRestrictionConfig.current(course_key=course_key).disabled - ) + assert disabled == DiscountRestrictionConfig.current(course_key=course_key).disabled @ddt.data( # Generate all combinations of setting each configuration level to True/False/None @@ -88,10 +85,10 @@ class TestDiscountRestrictionConfig(CacheIsolationTestCase): expected_org_setting = self._resolve_settings([global_setting, site_setting, org_setting]) expected_course_setting = self._resolve_settings([global_setting, site_setting, org_setting, course_setting]) - self.assertEqual(expected_global_setting, DiscountRestrictionConfig.current().disabled) - self.assertEqual(expected_site_setting, DiscountRestrictionConfig.current(site=test_site_cfg.site).disabled) - self.assertEqual(expected_org_setting, DiscountRestrictionConfig.current(org=test_course.org).disabled) - self.assertEqual(expected_course_setting, DiscountRestrictionConfig.current(course_key=test_course.id).disabled) + assert expected_global_setting == DiscountRestrictionConfig.current().disabled + assert expected_site_setting == DiscountRestrictionConfig.current(site=test_site_cfg.site).disabled + assert expected_org_setting == DiscountRestrictionConfig.current(org=test_course.org).disabled + assert expected_course_setting == DiscountRestrictionConfig.current(course_key=test_course.id).disabled def _resolve_settings(self, settings): if all(setting is None for setting in settings): diff --git a/openedx/features/discounts/tests/test_utils.py b/openedx/features/discounts/tests/test_utils.py index 098c9d01197..695b001df8c 100644 --- a/openedx/features/discounts/tests/test_utils.py +++ b/openedx/features/discounts/tests/test_utils.py @@ -72,22 +72,22 @@ class TestOfferData(TestCase): CourseEnrollment.enroll(self.user, self.overview.id, CourseMode.AUDIT) def test_happy_path(self): - self.assertEqual(utils.generate_offer_data(self.user, self.overview), { + assert utils.generate_offer_data(self.user, self.overview) == { 'code': 'EDXWELCOME', 'expiration_date': get_discount_expiration_date(self.user, self.overview), 'original_price': '$149', 'discounted_price': '$126.65', 'percentage': 15, - 'upgrade_url': '/dashboard', - }) + 'upgrade_url': '/dashboard' + } def test_spanish_code(self): with override_lang('es-419'): - self.assertEqual(utils.generate_offer_data(self.user, self.overview)['code'], 'BIENVENIDOAEDX') + assert utils.generate_offer_data(self.user, self.overview)['code'] == 'BIENVENIDOAEDX' def test_anonymous(self): - self.assertIsNone(utils.generate_offer_data(AnonymousUser(), self.overview)) + assert utils.generate_offer_data(AnonymousUser(), self.overview) is None @patch('openedx.features.discounts.utils.can_receive_discount', return_value=False) def test_no_discount(self, _mock): - self.assertIsNone(utils.generate_offer_data(self.user, self.overview)) + assert utils.generate_offer_data(self.user, self.overview) is None diff --git a/openedx/features/enterprise_support/tests/mixins/enterprise.py b/openedx/features/enterprise_support/tests/mixins/enterprise.py index 45c1be021fd..6febb21e8ea 100644 --- a/openedx/features/enterprise_support/tests/mixins/enterprise.py +++ b/openedx/features/enterprise_support/tests/mixins/enterprise.py @@ -279,15 +279,15 @@ class EnterpriseTestConsentRequired(SimpleTestCase): response = client.get(url) while(response.status_code == 302 and 'grant_data_sharing_permissions' not in response.url): response = client.get(response.url) - self.assertEqual(response.status_code, 302) - self.assertIn('grant_data_sharing_permissions', response.url) + assert response.status_code == 302 + assert 'grant_data_sharing_permissions' in response.url # Ensure that when consent is not necessary, the user continues through to the requested page. mock_consent_necessary.return_value = False response = client.get(url) - self.assertEqual(response.status_code, status_code) + assert response.status_code == status_code # If we were expecting a redirect, ensure it's not to the data sharing permission page if status_code == 302: - self.assertNotIn('grant_data_sharing_permissions', response.url) + assert 'grant_data_sharing_permissions' not in response.url return response diff --git a/openedx/features/enterprise_support/tests/test_api.py b/openedx/features/enterprise_support/tests/test_api.py index 8249a322ca1..4b3ffe9f6d2 100644 --- a/openedx/features/enterprise_support/tests/test_api.py +++ b/openedx/features/enterprise_support/tests/test_api.py @@ -1,11 +1,10 @@ """ Test the enterprise support APIs. """ - - import ddt import httpretty import mock +import pytest from consent.models import DataSharingConsent from django.conf import settings from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user @@ -14,21 +13,23 @@ from django.http import HttpResponseRedirect from django.test.utils import override_settings from django.urls import reverse from edx_django_utils.cache import get_cache_key +from enterprise.models import EnterpriseCustomerUser # lint-amnesty, pylint: disable=wrong-import-order from six.moves.urllib.parse import parse_qs from slumber.exceptions import HttpClientError +from common.djangoapps.student.tests.factories import UserFactory from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory from openedx.core.djangolib.testing.utils import CacheIsolationTestCase, skip_unless_lms from openedx.features.enterprise_support.api import ( activate_learner_enterprise, _CACHE_MISS, ENTERPRISE_CUSTOMER_KEY_NAME, - EnterpriseApiException, - add_enterprise_customer_to_session, ConsentApiClient, ConsentApiServiceClient, EnterpriseApiClient, + EnterpriseApiException, EnterpriseApiServiceClient, + add_enterprise_customer_to_session, consent_needed_for_course, data_sharing_consent_required, enterprise_customer_for_request, @@ -43,18 +44,15 @@ from openedx.features.enterprise_support.api import ( get_enterprise_learner_data_from_db, get_enterprise_learner_portal_enabled_message, insert_enterprise_pipeline_elements, - unlink_enterprise_user_from_idp, + unlink_enterprise_user_from_idp ) from openedx.features.enterprise_support.tests import FEATURES_WITH_ENTERPRISE_ENABLED from openedx.features.enterprise_support.tests.factories import ( EnterpriseCustomerIdentityProviderFactory, - EnterpriseCustomerUserFactory, + EnterpriseCustomerUserFactory ) from openedx.features.enterprise_support.tests.mixins.enterprise import EnterpriseServiceMockMixin from openedx.features.enterprise_support.utils import clear_data_consent_share_cache -from common.djangoapps.student.tests.factories import UserFactory - -from enterprise.models import EnterpriseCustomerUser # lint-amnesty, pylint: disable=wrong-import-order class MockEnrollment(mock.MagicMock): @@ -95,7 +93,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): mocked_jwt_builder.assert_called_once_with(enterprise_service_user) # pylint: disable=protected-access - self.assertEqual(enterprise_api_service_client.client._store['session'].auth.token, 'test-token') + assert enterprise_api_service_client.client._store['session'].auth.token == 'test-token' def _assert_api_client_with_user(self, api_client, mocked_jwt_builder): """ @@ -112,7 +110,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): mocked_jwt_builder.assert_called_once_with(dummy_enterprise_user) # pylint: disable=protected-access - self.assertEqual(enterprise_api_service_client.client._store['session'].auth.token, 'test-token') + assert enterprise_api_service_client.client._store['session'].auth.token == 'test-token' return enterprise_api_service_client def _assert_get_enterprise_customer(self, api_client, enterprise_api_data_for_mock): @@ -132,12 +130,12 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): DRY method to verify that get enterprise customer response is cached. """ cached_enterprise_customer = cache.get(cache_key) - self.assertIsNone(cached_enterprise_customer) + assert cached_enterprise_customer is None enterprise_customer = api_client.get_enterprise_customer(enterprise_customer_data['uuid']) - self.assertEqual(enterprise_customer_data, enterprise_customer) + assert enterprise_customer_data == enterprise_customer cached_enterprise_customer = cache.get(cache_key) - self.assertEqual(cached_enterprise_customer, enterprise_customer) + assert cached_enterprise_customer == enterprise_customer @httpretty.activate @mock.patch('openedx.features.enterprise_support.api.create_jwt_for_user') @@ -188,7 +186,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): consent_granted = True if should_raise_http_error: - with self.assertRaises(EnterpriseApiException): + with pytest.raises(EnterpriseApiException): api_client.post_enterprise_course_enrollment(username, course_id, consent_granted) else: api_client.post_enterprise_course_enrollment(username, course_id, consent_granted) @@ -206,8 +204,8 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): mock_request = mock.Mock() actual_result = enterprise_customer_from_api(mock_request) - self.assertIsNone(actual_result) - self.assertFalse(mock_client_class.called) + assert actual_result is None + assert not mock_client_class.called @httpretty.activate @mock.patch('openedx.features.enterprise_support.api.create_jwt_for_user') @@ -256,26 +254,26 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): # test that consent is not required for a non-enterprise customer self.mock_consent_not_required(user.username, course_id, ec_uuid) - self.assertFalse(consent_needed_for_course(request, user, course_id)) + assert not consent_needed_for_course(request, user, course_id) # test required and missing consent for example now he becomes a enterprise customer self.mock_consent_missing(user.username, course_id, ec_uuid) # still result should be False as it has been stored in cache "Not to show consent", so it will confirm that # cache is working fine - self.assertFalse(consent_needed_for_course(request, user, course_id)) + assert not consent_needed_for_course(request, user, course_id) # Removing cache clear_data_consent_share_cache(user.id, course_id) # Now test again - self.assertTrue(consent_needed_for_course(request, user, course_id)) + assert consent_needed_for_course(request, user, course_id) # test after consent permission is granted self.mock_consent_get(user.username, course_id, ec_uuid) - self.assertFalse(consent_needed_for_course(request, user, course_id)) + assert not consent_needed_for_course(request, user, course_id) # test when the enrollment already exists without a consent record existing. clear_data_consent_share_cache(user.id, course_id) self.mock_consent_missing(user.username, course_id, ec_uuid) - self.assertFalse(consent_needed_for_course(request, user, course_id, enrollment_exists=True)) + assert not consent_needed_for_course(request, user, course_id, enrollment_exists=True) @httpretty.activate @mock.patch('openedx.features.enterprise_support.api.get_enterprise_learner_data_from_db') @@ -295,7 +293,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): # test that consent is not required for a non-enterprise customer self.mock_consent_not_required(user.username, course_id, ec_uuid) - self.assertFalse(consent_needed_for_course(request, user, course_id)) + assert not consent_needed_for_course(request, user, course_id) @httpretty.activate @mock.patch('enterprise.models.EnterpriseCustomer.catalog_contains_course') @@ -313,13 +311,13 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): ) data_sharing_consent.save() consent_required = get_consent_required_courses(user, [course_id]) - self.assertIn(course_id, consent_required) + assert course_id in consent_required # now grant consent and call our method again data_sharing_consent.granted = True data_sharing_consent.save() consent_required = get_consent_required_courses(user, [course_id]) - self.assertNotIn(course_id, consent_required) + assert course_id not in consent_required def test_consent_not_required_for_non_enterprise_user(self): user = UserFactory() @@ -336,9 +334,9 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): mock_endpoint = getattr(api_client.client, 'enterprise-learner') user = mock.Mock(is_authenticated=False) - self.assertIsNone(api_client.fetch_enterprise_learner_data(user)) + assert api_client.fetch_enterprise_learner_data(user) is None - self.assertFalse(mock_endpoint.called) + assert not mock_endpoint.called @mock.patch('openedx.features.enterprise_support.api.create_jwt_for_user') def test_fetch_enterprise_learner_data(self, mock_jwt_builder): @@ -365,7 +363,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): user = mock.Mock(is_authenticated=True, username='spongebob') - self.assertIsNone(api_client.fetch_enterprise_learner_data(user)) + assert api_client.fetch_enterprise_learner_data(user) is None mock_endpoint.return_value.get.assert_called_once_with(username=user.username) @@ -430,7 +428,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): # expected enterprise customer against the requesting user. self.mock_get_enterprise_customer('real-ent-uuid', {'real': 'enterprisecustomer'}, 200) enterprise_customer = enterprise_customer_for_request(dummy_request) - self.assertEqual(enterprise_customer, {'real': 'enterprisecustomer'}) + assert enterprise_customer == {'real': 'enterprisecustomer'} httpretty.reset() @@ -439,7 +437,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): del dummy_request.session['enterprise_customer'] self.mock_get_enterprise_customer('real-ent-uuid', {'detail': 'Not found.'}, 404) enterprise_customer = enterprise_customer_for_request(dummy_request) - self.assertIsNone(enterprise_customer) + assert enterprise_customer is None httpretty.reset() @@ -455,7 +453,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): user=self.user ) enterprise_customer = enterprise_customer_for_request(mock_request) - self.assertEqual(enterprise_customer, {'real': 'enterprisecustomer'}) + assert enterprise_customer == {'real': 'enterprisecustomer'} # Verify that the method `enterprise_customer_for_request` returns # expected enterprise customer against the requesting user even if @@ -468,7 +466,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): user=self.user ) enterprise_customer = enterprise_customer_for_request(mock_request) - self.assertEqual(enterprise_customer, {'real': 'enterprisecustomer'}) + assert enterprise_customer == {'real': 'enterprisecustomer'} # Verify that the method `enterprise_customer_for_request` returns # expected enterprise customer against the requesting user if @@ -482,7 +480,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): user=self.user ) enterprise_customer = enterprise_customer_for_request(mock_request) - self.assertEqual(enterprise_customer, {'real': 'enterprisecustomer'}) + assert enterprise_customer == {'real': 'enterprisecustomer'} # Verify that we can still get enterprise customer from enterprise # learner API even if we are unable to get it from preferred sources, @@ -497,7 +495,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): site=1 ) enterprise_customer = enterprise_customer_for_request(mock_request) - self.assertEqual(enterprise_customer, {'real': 'enterprisecustomer'}) + assert enterprise_customer == {'real': 'enterprisecustomer'} def test_enterprise_customer_for_request_with_session(self): """ @@ -511,10 +509,10 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): 'openedx.features.enterprise_support.api.enterprise_customer_from_api', return_value=enterprise_data ): - self.assertEqual(dummy_request.session.get('enterprise_customer'), None) + assert dummy_request.session.get('enterprise_customer') is None enterprise_customer = enterprise_customer_for_request(dummy_request) - self.assertEqual(enterprise_customer, enterprise_data) - self.assertEqual(dummy_request.session.get('enterprise_customer'), enterprise_data) + assert enterprise_customer == enterprise_data + assert dummy_request.session.get('enterprise_customer') == enterprise_data # Verify enterprise customer data fetched from session for subsequent calls with mock.patch( @@ -525,9 +523,9 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): return_value=enterprise_data ) as mock_enterprise_customer_from_session: enterprise_customer = enterprise_customer_for_request(dummy_request) - self.assertEqual(enterprise_customer, enterprise_data) - self.assertEqual(mock_enterprise_customer_from_api.called, False) - self.assertEqual(mock_enterprise_customer_from_session.called, True) + assert enterprise_customer == enterprise_data + assert mock_enterprise_customer_from_api.called is False + assert mock_enterprise_customer_from_session.called is True # Verify enterprise customer data fetched from session for subsequent calls # with unauthenticated user in SAML case @@ -541,9 +539,9 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): return_value=enterprise_data ) as mock_enterprise_customer_from_session: enterprise_customer = enterprise_customer_for_request(dummy_request) - self.assertEqual(enterprise_customer, enterprise_data) - self.assertEqual(mock_enterprise_customer_from_api.called, False) - self.assertEqual(mock_enterprise_customer_from_session.called, True) + assert enterprise_customer == enterprise_data + assert mock_enterprise_customer_from_api.called is False + assert mock_enterprise_customer_from_session.called is True def check_data_sharing_consent(self, consent_required=False, consent_url=None): """ @@ -566,12 +564,12 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): # If consent required, then the response should be a redirect to the consent URL, and the view function would # not be called. if consent_required: - self.assertIsInstance(response, HttpResponseRedirect) - self.assertEqual(response.url, consent_url) # pylint: disable=no-member + assert isinstance(response, HttpResponseRedirect) + assert response.url == consent_url # pylint: disable=no-member # Otherwise, the view function should have been called with the expected arguments. else: - self.assertEqual(response, (args, kwargs)) + assert response == (args, kwargs) @mock.patch('openedx.features.enterprise_support.api.enterprise_enabled') @mock.patch('openedx.features.enterprise_support.api.consent_needed_for_course') @@ -666,7 +664,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): actual_url = get_enterprise_consent_url(request_mock, course_id, return_to=return_to) actual_url_args = parse_qs(actual_url.split('/enterprise/grant_data_sharing_permissions?')[1]) - self.assertEqual(actual_url_args, expected_url_args) + assert actual_url_args == expected_url_args @ddt.data( (False, {'real': 'enterprise', 'uuid': ''}, 'course', [], [], "", ""), @@ -746,13 +744,13 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): ) if notification_message and notification_title: - self.assertIn(notification_title, notification_string) - self.assertIn(notification_message, notification_string) + assert notification_title in notification_string + assert notification_message in notification_string elif expected_substrings: for substr in expected_substrings: - self.assertIn(substr, notification_string) + assert substr in notification_string else: - self.assertEqual(notification_string, '') + assert notification_string == '' @override_settings(FEATURES=dict(ENABLE_ENTERPRISE_INTEGRATION=False)) def test_utils_with_enterprise_disabled(self): @@ -760,21 +758,22 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): Test that disabling the enterprise integration flag causes the utilities to return the expected default values. """ - self.assertFalse(enterprise_enabled()) - self.assertEqual(insert_enterprise_pipeline_elements(None), None) + assert not enterprise_enabled() + assert insert_enterprise_pipeline_elements(None) is None def test_utils_with_enterprise_enabled(self): """ Test that enabling enterprise integration (which is currently on by default) causes the the utilities to return the expected values. """ - self.assertTrue(enterprise_enabled()) + assert enterprise_enabled() pipeline = ['abc', 'social_core.pipeline.social_auth.load_extra_data', 'def'] insert_enterprise_pipeline_elements(pipeline) - self.assertEqual(pipeline, ['abc', - 'enterprise.tpa_pipeline.handle_enterprise_logistration', - 'social_core.pipeline.social_auth.load_extra_data', - 'def']) + assert pipeline == \ + [ + 'abc', 'enterprise.tpa_pipeline.handle_enterprise_logistration', + 'social_core.pipeline.social_auth.load_extra_data', 'def' + ] @mock.patch('openedx.features.enterprise_support.api.get_enterprise_learner_data_from_db') def test_enterprise_learner_portal_message_cache_miss_no_customer(self, mock_learner_data_from_db): @@ -787,7 +786,7 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): mock_learner_data_from_db.return_value = None actual_result = get_enterprise_learner_portal_enabled_message(mock_request) - self.assertIsNone(actual_result) + assert actual_result is None mock_learner_data_from_db.assert_called_once_with(mock_request.user) @mock.patch('openedx.features.enterprise_support.api.get_enterprise_learner_data_from_db') @@ -812,8 +811,8 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): ] actual_result = get_enterprise_learner_portal_enabled_message(mock_request) - self.assertIn('custom dashboard for learning', actual_result) - self.assertIn('Best Corp', actual_result) + assert 'custom dashboard for learning' in actual_result + assert 'Best Corp' in actual_result mock_learner_data_from_db.assert_called_once_with(mock_request.user) # assert we cached the enterprise customer data in the request session after fetching it assert mock_request.session.get(ENTERPRISE_CUSTOMER_KEY_NAME) == mock_enterprise_customer @@ -829,8 +828,8 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): }) actual_result = get_enterprise_learner_portal_enabled_message(mock_request) - self.assertIsNone(actual_result) - self.assertFalse(mock_learner_data_from_db.called) + assert actual_result is None + assert not mock_learner_data_from_db.called @ddt.data(True, False) @mock.patch('openedx.features.enterprise_support.api.get_enterprise_learner_data_from_db') @@ -855,11 +854,11 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): actual_result = get_enterprise_learner_portal_enabled_message(mock_request) if not enable_learner_portal: - self.assertIsNone(actual_result) + assert actual_result is None else: - self.assertIn('custom dashboard for learning', actual_result) - self.assertIn('Best Corp', actual_result) - self.assertFalse(mock_learner_data_from_db.called) + assert 'custom dashboard for learning' in actual_result + assert 'Best Corp' in actual_result + assert not mock_learner_data_from_db.called @mock.patch('openedx.features.enterprise_support.api.get_partial_pipeline', return_value=None) def test_customer_uuid_for_request_sso_provider_id_customer_exists(self, mock_partial_pipeline): @@ -874,9 +873,9 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): actual_uuid = enterprise_customer_uuid_for_request(mock_request) expected_uuid = mock_customer.uuid - self.assertEqual(expected_uuid, actual_uuid) + assert expected_uuid == actual_uuid mock_partial_pipeline.assert_called_once_with(mock_request) - self.assertNotIn(ENTERPRISE_CUSTOMER_KEY_NAME, mock_request.session) + assert ENTERPRISE_CUSTOMER_KEY_NAME not in mock_request.session @mock.patch('openedx.features.enterprise_support.api.get_enterprise_learner_data_from_db') @mock.patch('openedx.features.enterprise_support.api.get_partial_pipeline', return_value=None) @@ -897,9 +896,9 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): actual_uuid = enterprise_customer_uuid_for_request(mock_request) - self.assertEqual(actual_uuid, enterprise_customer_uuid) + assert actual_uuid == enterprise_customer_uuid mock_partial_pipeline.assert_called_once_with(mock_request) - self.assertIn(ENTERPRISE_CUSTOMER_KEY_NAME, mock_request.session) + assert ENTERPRISE_CUSTOMER_KEY_NAME in mock_request.session @mock.patch('openedx.features.enterprise_support.api.get_partial_pipeline', return_value=None) def test_enterprise_uuid_for_request_from_query_params(self, mock_partial_pipeline): @@ -912,9 +911,9 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): actual_uuid = enterprise_customer_uuid_for_request(mock_request) - self.assertEqual(expected_uuid, actual_uuid) + assert expected_uuid == actual_uuid mock_partial_pipeline.assert_called_once_with(mock_request) - self.assertNotIn(ENTERPRISE_CUSTOMER_KEY_NAME, mock_request.session) + assert ENTERPRISE_CUSTOMER_KEY_NAME not in mock_request.session @mock.patch('openedx.features.enterprise_support.api.get_partial_pipeline', return_value=None) def test_enterprise_uuid_for_request_from_cookies(self, mock_partial_pipeline): @@ -927,9 +926,9 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): actual_uuid = enterprise_customer_uuid_for_request(mock_request) - self.assertEqual(expected_uuid, actual_uuid) + assert expected_uuid == actual_uuid mock_partial_pipeline.assert_called_once_with(mock_request) - self.assertNotIn(ENTERPRISE_CUSTOMER_KEY_NAME, mock_request.session) + assert ENTERPRISE_CUSTOMER_KEY_NAME not in mock_request.session @mock.patch('openedx.features.enterprise_support.api.get_partial_pipeline', return_value=None) def test_enterprise_uuid_for_request_from_session(self, mock_partial_pipeline): @@ -942,9 +941,9 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): actual_uuid = enterprise_customer_uuid_for_request(mock_request) - self.assertEqual(expected_uuid, actual_uuid) + assert expected_uuid == actual_uuid mock_partial_pipeline.assert_called_once_with(mock_request) - self.assertEqual({'uuid': expected_uuid}, mock_request.session.get(ENTERPRISE_CUSTOMER_KEY_NAME)) + assert {'uuid': expected_uuid} == mock_request.session.get(ENTERPRISE_CUSTOMER_KEY_NAME) @mock.patch('openedx.features.enterprise_support.api.get_enterprise_learner_data_from_db') @mock.patch('openedx.features.enterprise_support.api.get_partial_pipeline', return_value=None) @@ -961,10 +960,10 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): actual_uuid = enterprise_customer_uuid_for_request(mock_request) expected_uuid = 'my-uuid' - self.assertEqual(expected_uuid, actual_uuid) + assert expected_uuid == actual_uuid mock_partial_pipeline.assert_called_once_with(mock_request) mock_data_from_db.assert_called_once_with(mock_request.user) - self.assertEqual({'uuid': 'my-uuid'}, mock_request.session[ENTERPRISE_CUSTOMER_KEY_NAME]) + assert {'uuid': 'my-uuid'} == mock_request.session[ENTERPRISE_CUSTOMER_KEY_NAME] @ddt.data(True, False) @mock.patch('openedx.features.enterprise_support.api.get_enterprise_learner_data_from_db', return_value=None) @@ -984,15 +983,15 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): actual_uuid = enterprise_customer_uuid_for_request(mock_request) - self.assertIsNone(actual_uuid) + assert actual_uuid is None mock_partial_pipeline.assert_called_once_with(mock_request) if is_user_authenticated: mock_data_from_db.assert_called_once_with(mock_request.user) - self.assertIsNone(mock_request.session[ENTERPRISE_CUSTOMER_KEY_NAME]) + assert mock_request.session[ENTERPRISE_CUSTOMER_KEY_NAME] is None else: - self.assertFalse(mock_data_from_db.called) - self.assertNotIn(ENTERPRISE_CUSTOMER_KEY_NAME, mock_request.session) + assert not mock_data_from_db.called + assert ENTERPRISE_CUSTOMER_KEY_NAME not in mock_request.session def test_enterprise_customer_from_session(self): mock_request = mock.Mock( @@ -1009,13 +1008,13 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): # set enterprise customer info with authenticate user add_enterprise_customer_to_session(mock_request, enterprise_customer) - self.assertEqual(mock_request.session[ENTERPRISE_CUSTOMER_KEY_NAME], enterprise_customer) + assert mock_request.session[ENTERPRISE_CUSTOMER_KEY_NAME] == enterprise_customer # Now try to set info with un-authenticated user mock_request.user.is_authenticated = False add_enterprise_customer_to_session(mock_request, None) # verify that existing session value should not be updated for un-authenticate user - self.assertEqual(mock_request.session[ENTERPRISE_CUSTOMER_KEY_NAME], enterprise_customer) + assert mock_request.session[ENTERPRISE_CUSTOMER_KEY_NAME] == enterprise_customer def test_get_consent_notification_data_no_overrides(self): enterprise_customer = { @@ -1025,8 +1024,8 @@ class TestEnterpriseApi(EnterpriseServiceMockMixin, CacheIsolationTestCase): title_template, message_template = get_consent_notification_data(enterprise_customer) - self.assertIsNone(title_template) - self.assertIsNone(message_template) + assert title_template is None + assert message_template is None @mock.patch('openedx.features.enterprise_support.api.DataSharingConsentTextOverrides') def test_get_consent_notification_data(self, mock_override_model): diff --git a/openedx/features/enterprise_support/tests/test_logout.py b/openedx/features/enterprise_support/tests/test_logout.py index d3e17956beb..851a5054d65 100644 --- a/openedx/features/enterprise_support/tests/test_logout.py +++ b/openedx/features/enterprise_support/tests/test_logout.py @@ -55,7 +55,7 @@ class EnterpriseLogoutTests(EnterpriseServiceMockMixin, CacheIsolationTestCase, logout_path=reverse('logout'), redirect_url=redirect_url ) - self.assertTrue(enterprise_enabled()) + assert enterprise_enabled() response = self.client.get(url, HTTP_HOST='testserver') expected = { 'enterprise_target': enterprise_target, diff --git a/openedx/features/enterprise_support/tests/test_signals.py b/openedx/features/enterprise_support/tests/test_signals.py index 475f174f37c..bd6ff4c93e4 100644 --- a/openedx/features/enterprise_support/tests/test_signals.py +++ b/openedx/features/enterprise_support/tests/test_signals.py @@ -97,10 +97,10 @@ class EnterpriseSupportSignals(SharedModuleStoreTestCase): """ self._create_dsc_cache(self.user.id, self.course_id) - self.assertTrue(self._is_dsc_cache_found(self.user.id, self.course_id)) + assert self._is_dsc_cache_found(self.user.id, self.course_id) self._create_enterprise_enrollment(self.user.id, self.course_id) - self.assertFalse(self._is_dsc_cache_found(self.user.id, self.course_id)) + assert not self._is_dsc_cache_found(self.user.id, self.course_id) def test_signal_update_dsc_cache_on_enterprise_customer_update(self): """ @@ -110,13 +110,13 @@ class EnterpriseSupportSignals(SharedModuleStoreTestCase): self._create_enterprise_enrollment(self.user.id, self.course_id) self._create_dsc_cache(self.user.id, self.course_id) - self.assertTrue(self._is_dsc_cache_found(self.user.id, self.course_id)) + assert self._is_dsc_cache_found(self.user.id, self.course_id) # updating enable_data_sharing_consent flag self.enterprise_customer.enable_data_sharing_consent = False self.enterprise_customer.save() - self.assertFalse(self._is_dsc_cache_found(self.user.id, self.course_id)) + assert not self._is_dsc_cache_found(self.user.id, self.course_id) def _create_enrollment_to_refund(self, no_of_days_placed=10, enterprise_enrollment_exists=True): """Create enrollment to refund. """ @@ -158,7 +158,7 @@ class EnterpriseSupportSignals(SharedModuleStoreTestCase): enrollment = self._create_enrollment_to_refund(no_of_days_placed, enterprise_enrollment_exists) with patch('openedx.features.enterprise_support.signals.ecommerce_api_client') as mock_ecommerce_api_client: enrollment.update_enrollment(is_active=False, skip_refund=skip_refund) - self.assertEqual(mock_ecommerce_api_client.called, api_called) + assert mock_ecommerce_api_client.called == api_called @ddt.data( (HttpClientError, 'INFO'), @@ -174,7 +174,7 @@ class EnterpriseSupportSignals(SharedModuleStoreTestCase): client_instance.enterprise.coupons.create_refunded_voucher.post.side_effect = mock_error() with LogCapture(LOGGER_NAME) as logger: enrollment.update_enrollment(is_active=False) - self.assertEqual(mock_ecommerce_api_client.called, True) + assert mock_ecommerce_api_client.called is True logger.check( ( LOGGER_NAME, @@ -197,7 +197,7 @@ class EnterpriseSupportSignals(SharedModuleStoreTestCase): course_key = CourseKey.from_string(self.course_id) COURSE_GRADE_NOW_PASSED.disconnect(dispatch_uid='new_passing_learner') COURSE_GRADE_NOW_PASSED.send(sender=None, user=self.user, course_id=course_key) - self.assertFalse(mock_task_apply.called) + assert not mock_task_apply.called self._create_enterprise_enrollment(self.user.id, self.course_id) task_kwargs = { @@ -225,7 +225,7 @@ class EnterpriseSupportSignals(SharedModuleStoreTestCase): subsection_id='subsection_id', subsection_grade=1.0 ) - self.assertFalse(mock_task_apply.called) + assert not mock_task_apply.called self._create_enterprise_enrollment(self.user.id, self.course_id) task_kwargs = { diff --git a/openedx/features/enterprise_support/tests/test_utils.py b/openedx/features/enterprise_support/tests/test_utils.py index c5e95849103..7a66df628c6 100644 --- a/openedx/features/enterprise_support/tests/test_utils.py +++ b/openedx/features/enterprise_support/tests/test_utils.py @@ -149,7 +149,7 @@ class TestEnterpriseUtils(TestCase): assert 'pied-piper' == actual_result['enterprise_name'] expected_logo_url = branding_configuration.get('logo', '') assert expected_logo_url == actual_result['enterprise_logo_url'] - self.assertIn('pied-piper', str(actual_result['enterprise_branded_welcome_string'])) + assert 'pied-piper' in str(actual_result['enterprise_branded_welcome_string']) @ddt.data( ('notfoundpage', 0), @@ -165,7 +165,7 @@ class TestEnterpriseUtils(TestCase): 'openedx.features.enterprise_support.api.enterprise_customer_for_request' ) as mock_customer_request: self.client.get(resource) - self.assertEqual(mock_customer_request.call_count, expected_calls) + assert mock_customer_request.call_count == expected_calls @mock.patch('openedx.features.enterprise_support.utils.configuration_helpers.get_value') def test_enterprise_fields_only(self, mock_get_value): @@ -202,21 +202,12 @@ class TestEnterpriseUtils(TestCase): # This will directly modify context update_third_party_auth_context_for_enterprise(request, context, enterprise_customer) - self.assertIn( - 'We are sorry, you are not authorized', - str(context['data']['third_party_auth']['errorMessage']) - ) - self.assertIn( - 'Widget error.', - str(context['data']['third_party_auth']['errorMessage']) - ) + assert 'We are sorry, you are not authorized' in str(context['data']['third_party_auth']['errorMessage']) + assert 'Widget error.' in str(context['data']['third_party_auth']['errorMessage']) assert [] == context['data']['third_party_auth']['providers'] assert [] == context['data']['third_party_auth']['secondaryProviders'] - self.assertFalse(context['data']['third_party_auth']['autoSubmitRegForm']) - self.assertIn( - 'Just a couple steps', - str(context['data']['third_party_auth']['autoRegisterWelcomeMessage']) - ) + assert not context['data']['third_party_auth']['autoSubmitRegForm'] + assert 'Just a couple steps' in str(context['data']['third_party_auth']['autoRegisterWelcomeMessage']) assert 'Continue' == str(context['data']['third_party_auth']['registerFormSubmitButtonText']) mock_tpa.pipeline.get.assert_called_once_with(request) @@ -423,11 +414,11 @@ class TestEnterpriseUtils(TestCase): request.GET = {'enterprise_customer': uuid.uuid4()} portal = get_enterprise_learner_portal(request) - self.assertIsNone(portal) + assert portal is None def test_get_enterprise_learner_generic_name_404_pages(self): request = mock.Mock(view_name='404') - self.assertIsNone(get_enterprise_learner_generic_name(request)) + assert get_enterprise_learner_generic_name(request) is None @mock.patch('openedx.features.enterprise_support.api.enterprise_customer_for_request') def test_get_enterprise_learner_generic_name_with_replacement(self, mock_customer_for_request): @@ -454,27 +445,27 @@ class TestEnterpriseUtils(TestCase): 'django.core.cache.cache.set' ) as mock_cache_set: EnterpriseCustomerUserFactory.create(active=True, user_id=self.user.id) - self.assertTrue(is_enterprise_learner(self.user)) + assert is_enterprise_learner(self.user) - self.assertTrue(mock_cache_set.called) + assert mock_cache_set.called def test_is_enterprise_learner_no_enterprise_user(self): with mock.patch( 'django.core.cache.cache.set' ) as mock_cache_set: - self.assertFalse(is_enterprise_learner(self.user)) + assert not is_enterprise_learner(self.user) - self.assertFalse(mock_cache_set.called) + assert not mock_cache_set.called @mock.patch('openedx.features.enterprise_support.utils.reverse') def test_get_enterprise_slug_login_url_no_reverse_match(self, mock_reverse): mock_reverse.side_effect = NoReverseMatch - self.assertIsNone(get_enterprise_slug_login_url()) + assert get_enterprise_slug_login_url() is None mock_reverse.assert_called_once_with('enterprise_slug_login') @mock.patch('openedx.features.enterprise_support.utils.reverse') def test_get_enterprise_slug_login_url_with_match(self, mock_reverse): - self.assertIsNotNone(get_enterprise_slug_login_url()) + assert get_enterprise_slug_login_url() is not None mock_reverse.assert_called_once_with('enterprise_slug_login') def test_fetch_enterprise_customer_by_id(self): @@ -511,4 +502,4 @@ class TestEnterpriseUtils(TestCase): mock_tpa.pipeline.AUTH_ENTRY_LOGIN, redirect_url=redirect_url, ) - self.assertFalse(mock_next_login_url.called) + assert not mock_next_login_url.called diff --git a/openedx/features/learner_profile/tests/views/test_learner_profile.py b/openedx/features/learner_profile/tests/views/test_learner_profile.py index 31d51fd3b92..5dd04009f50 100644 --- a/openedx/features/learner_profile/tests/views/test_learner_profile.py +++ b/openedx/features/learner_profile/tests/views/test_learner_profile.py @@ -68,45 +68,29 @@ class LearnerProfileViewTest(SiteMixin, UrlResetMixin, ModuleStoreTestCase): context = learner_profile_context(request, self.USERNAME, self.user.is_staff) - self.assertEqual( - context['data']['default_public_account_fields'], - settings.ACCOUNT_VISIBILITY_CONFIGURATION['public_fields'] - ) + assert context['data']['default_public_account_fields'] == \ + settings.ACCOUNT_VISIBILITY_CONFIGURATION['public_fields'] - self.assertEqual( - context['data']['accounts_api_url'], - reverse("accounts_api", kwargs={'username': self.user.username}) - ) + assert context['data']['accounts_api_url'] == \ + reverse('accounts_api', kwargs={'username': self.user.username}) - self.assertEqual( - context['data']['preferences_api_url'], - reverse('preferences_api', kwargs={'username': self.user.username}) - ) + assert context['data']['preferences_api_url'] == \ + reverse('preferences_api', kwargs={'username': self.user.username}) - self.assertEqual( - context['data']['profile_image_upload_url'], - reverse("profile_image_upload", kwargs={'username': self.user.username}) - ) + assert context['data']['profile_image_upload_url'] == \ + reverse('profile_image_upload', kwargs={'username': self.user.username}) - self.assertEqual( - context['data']['profile_image_remove_url'], - reverse('profile_image_remove', kwargs={'username': self.user.username}) - ) + assert context['data']['profile_image_remove_url'] == \ + reverse('profile_image_remove', kwargs={'username': self.user.username}) - self.assertEqual( - context['data']['profile_image_max_bytes'], - settings.PROFILE_IMAGE_MAX_BYTES - ) + assert context['data']['profile_image_max_bytes'] == settings.PROFILE_IMAGE_MAX_BYTES - self.assertEqual( - context['data']['profile_image_min_bytes'], - settings.PROFILE_IMAGE_MIN_BYTES - ) + assert context['data']['profile_image_min_bytes'] == settings.PROFILE_IMAGE_MIN_BYTES - self.assertEqual(context['data']['account_settings_page_url'], reverse('account_settings')) + assert context['data']['account_settings_page_url'] == reverse('account_settings') for attribute in self.CONTEXT_DATA: - self.assertIn(attribute, context['data']) + assert attribute in context['data'] def test_view(self): """ @@ -149,7 +133,7 @@ class LearnerProfileViewTest(SiteMixin, UrlResetMixin, ModuleStoreTestCase): """ profile_path = reverse('learner_profile', kwargs={'username': "no_such_user"}) response = self.client.get(path=profile_path) - self.assertEqual(404, response.status_code) + assert 404 == response.status_code def _create_certificate(self, course_key=None, enrollment_mode=CourseMode.HONOR, status='downloadable'): """Simulate that the user has a generated certificate. """ @@ -189,7 +173,7 @@ class LearnerProfileViewTest(SiteMixin, UrlResetMixin, ModuleStoreTestCase): cert.save() # Ensure that this test is actually using both passing and non-passing certs. - self.assertEqual(is_passing_status(cert.status), is_passed_status) + assert is_passing_status(cert.status) == is_passed_status response = self.client.get('/u/{username}'.format(username=self.user.username)) @@ -261,15 +245,15 @@ class LearnerProfileViewTest(SiteMixin, UrlResetMixin, ModuleStoreTestCase): user_is_staff = True context = learner_profile_context(request, profile_username, user_is_staff) - self.assertIn('achievements_fragment', context) + assert 'achievements_fragment' in context user_is_staff = False context = learner_profile_context(request, profile_username, user_is_staff) - self.assertNotIn('achievements_fragment', context) + assert 'achievements_fragment' not in context profile_username = self.user.username context = learner_profile_context(request, profile_username, user_is_staff) - self.assertIn('achievements_fragment', context) + assert 'achievements_fragment' in context @mock.patch.dict(settings.FEATURES, {'CERTIFICATES_HTML_VIEW': True}) def test_certificate_visibility_with_no_cert_config(self): diff --git a/openedx/features/personalized_learner_schedules/show_answer/tests/test_show_answer_override.py b/openedx/features/personalized_learner_schedules/show_answer/tests/test_show_answer_override.py index d439d253df7..50eb16423fd 100644 --- a/openedx/features/personalized_learner_schedules/show_answer/tests/test_show_answer_override.py +++ b/openedx/features/personalized_learner_schedules/show_answer/tests/test_show_answer_override.py @@ -40,7 +40,7 @@ class ShowAnswerFieldOverrideTest(ModuleStoreTestCase): # Instructor paced course will just have the default value ip_course = self.setup_course() course_module = self.get_course_module(ip_course) - self.assertEqual(course_module.showanswer, SHOWANSWER.FINISHED) + assert course_module.showanswer == SHOWANSWER.FINISHED # This should be updated to not explicitly add in the showanswer so it can test the # default case of never touching showanswer. Reference ticket AA-307 (if that's closed, @@ -48,9 +48,9 @@ class ShowAnswerFieldOverrideTest(ModuleStoreTestCase): sp_course = self.setup_course(self_paced=True, showanswer=SHOWANSWER.FINISHED) course_module = self.get_course_module(sp_course) if active: - self.assertEqual(course_module.showanswer, SHOWANSWER.AFTER_ALL_ATTEMPTS_OR_CORRECT) + assert course_module.showanswer == SHOWANSWER.AFTER_ALL_ATTEMPTS_OR_CORRECT else: - self.assertEqual(course_module.showanswer, SHOWANSWER.FINISHED) + assert course_module.showanswer == SHOWANSWER.FINISHED @ddt.data( (SHOWANSWER.ATTEMPTED, SHOWANSWER.ATTEMPTED_NO_PAST_DUE), @@ -67,4 +67,4 @@ class ShowAnswerFieldOverrideTest(ModuleStoreTestCase): def test_get(self, initial_value, expected_final_value): course = self.setup_course(self_paced=True, showanswer=initial_value) course_module = self.get_course_module(course) - self.assertEqual(course_module.showanswer, expected_final_value) + assert course_module.showanswer == expected_final_value -- GitLab