replaced unittest assertions pytest assertions (#26554)

This commit is contained in:
Aarif
2021-02-18 18:06:13 +05:00
committed by GitHub
parent 1ead9f684c
commit d2644e2dc2
35 changed files with 578 additions and 789 deletions

View File

@@ -44,7 +44,7 @@ class QueryStringAssertionMixin(object):
if expected_component == 'query':
self.assert_query_string_equal(expected_value, parsed_url.query)
else:
self.assertEqual(expected_value, getattr(parsed_url, expected_component))
assert expected_value == getattr(parsed_url, expected_component)
def assert_query_string_parameters_equal(self, url, **kwargs):
"""
@@ -61,7 +61,7 @@ class QueryStringAssertionMixin(object):
parsed_url = urlparse(url)
parsed_qs = parse_qs(parsed_url.query)
for expected_key, expected_value in kwargs.items():
self.assertEqual(parsed_qs[expected_key], [str(expected_value)])
assert parsed_qs[expected_key] == [str(expected_value)]
class EmailTemplateTagMixin(object):

View File

@@ -25,6 +25,6 @@ class TestAbsoluteUrl(TestCase): # lint-amnesty, pylint: disable=missing-class-
"""
with patch("openedx.core.djangoapps.site_configuration.helpers.get_value", return_value=from_address):
ace_message_type = BaseMessageType()
self.assertEqual('from_address' in ace_message_type.options, has_from_address)
assert ('from_address' in ace_message_type.options) == has_from_address
if from_address:
self.assertEqual(ace_message_type.options.get('from_address'), from_address)
assert ace_message_type.options.get('from_address') == from_address

View File

@@ -1,6 +1,7 @@
# pylint: disable=missing-docstring
import pytest
from django.template import VariableDoesNotExist
from django.test import override_settings
@@ -24,16 +25,16 @@ class TestAbsoluteUrl(CacheIsolationTestCase):
def test_absolute_url(self):
absolute = ensure_url_is_absolute(self.site, '/foo/bar')
self.assertEqual(absolute, 'https://example.com/foo/bar')
assert absolute == 'https://example.com/foo/bar'
def test_absolute_url_domain_lstrip(self):
self.site.domain = 'example.com/'
absolute = ensure_url_is_absolute(self.site, 'foo/bar')
self.assertEqual(absolute, 'https://example.com/foo/bar')
assert absolute == 'https://example.com/foo/bar'
def test_absolute_url_already_absolute(self):
absolute = ensure_url_is_absolute(self.site, 'https://some-cdn.com/foo/bar')
self.assertEqual(absolute, 'https://some-cdn.com/foo/bar')
assert absolute == 'https://some-cdn.com/foo/bar'
@skip_unless_lms
@@ -54,13 +55,13 @@ class TestLinkTrackingTag(QueryStringAssertionMixin, EmailTemplateTagMixin, Cach
def test_missing_request(self):
self.mock_get_current_request.return_value = None
with self.assertRaises(VariableDoesNotExist):
with pytest.raises(VariableDoesNotExist):
with_link_tracking(self.context, 'http://example.com/foo')
def test_missing_message(self):
del self.context['message']
with self.assertRaises(VariableDoesNotExist):
with pytest.raises(VariableDoesNotExist):
with_link_tracking(self.context, 'http://example.com/foo')
def test_course_id(self):
@@ -111,13 +112,13 @@ class TestGoogleAnalyticsPixelTag(QueryStringAssertionMixin, EmailTemplateTagMix
def test_missing_request(self):
self.mock_get_current_request.return_value = None
with self.assertRaises(VariableDoesNotExist):
with pytest.raises(VariableDoesNotExist):
google_analytics_tracking_pixel(self.context)
def test_missing_message(self):
del self.context['message']
with self.assertRaises(VariableDoesNotExist):
with pytest.raises(VariableDoesNotExist):
google_analytics_tracking_pixel(self.context)
def test_course_id(self):
@@ -138,9 +139,9 @@ class TestGoogleAnalyticsPixelTag(QueryStringAssertionMixin, EmailTemplateTagMix
def test_html_emitted(self):
result_html = google_analytics_tracking_pixel(self.context)
self.assertIn('<img src', result_html)
assert '<img src' in result_html
@override_settings(GOOGLE_ANALYTICS_TRACKING_ID=None)
def test_no_html_emitted_if_not_enabled(self):
result_html = google_analytics_tracking_pixel(self.context)
self.assertEqual('', result_html)
assert '' == result_html

View File

@@ -20,11 +20,11 @@ class TestCampaignTrackingInfo(QueryStringAssertionMixin, TestCase):
def test_default_campaign_info(self):
campaign = CampaignTrackingInfo()
self.assertEqual(campaign.source, DEFAULT_CAMPAIGN_SOURCE)
self.assertEqual(campaign.medium, DEFAULT_CAMPAIGN_MEDIUM)
self.assertIsNone(campaign.campaign)
self.assertIsNone(campaign.term)
self.assertIsNone(campaign.content)
assert campaign.source == DEFAULT_CAMPAIGN_SOURCE
assert campaign.medium == DEFAULT_CAMPAIGN_MEDIUM
assert campaign.campaign is None
assert campaign.term is None
assert campaign.content is None
def test_to_query_string(self):
campaign = CampaignTrackingInfo(
@@ -76,7 +76,7 @@ class TestGoogleAnalyticsTrackingPixel(QueryStringAssertionMixin, CacheIsolation
@override_settings(GOOGLE_ANALYTICS_TRACKING_ID='UA-123456-1')
def test_default_parameters(self):
pixel = GoogleAnalyticsTrackingPixel()
self.assertIsNotNone(pixel.generate_image_url())
assert pixel.generate_image_url() is not None
self.assert_url_components_equal(
pixel.generate_image_url(),
scheme='https',
@@ -105,7 +105,7 @@ class TestGoogleAnalyticsTrackingPixel(QueryStringAssertionMixin, CacheIsolation
document_host='test_host.com',
client_id='123456.123456',
)
self.assertIsNotNone(pixel.generate_image_url())
assert pixel.generate_image_url() is not None
self.assert_url_components_equal(
pixel.generate_image_url(),
scheme='https',
@@ -117,7 +117,7 @@ class TestGoogleAnalyticsTrackingPixel(QueryStringAssertionMixin, CacheIsolation
def test_missing_settings(self):
pixel = GoogleAnalyticsTrackingPixel()
self.assertIsNone(pixel.generate_image_url())
assert pixel.generate_image_url() is None
@override_settings(GOOGLE_ANALYTICS_TRACKING_ID='UA-123456-1')
def test_site_config_override(self):
@@ -135,7 +135,7 @@ class TestGoogleAnalyticsTrackingPixel(QueryStringAssertionMixin, CacheIsolation
)
def test_custom_dimension(self):
pixel = GoogleAnalyticsTrackingPixel(user_id=10, campaign_source=None, campaign_medium=None)
self.assertIsNotNone(pixel.generate_image_url())
assert pixel.generate_image_url() is not None
self.assert_url_components_equal(
pixel.generate_image_url(),
query='v=1&t=event&ec=email&ea=edx.bi.email.opened&cid={cid}&tid=UA-123456-1&cd40=10&uid=10'.format(
@@ -149,7 +149,7 @@ class TestGoogleAnalyticsTrackingPixel(QueryStringAssertionMixin, CacheIsolation
)
def test_custom_dimension_without_user_id(self):
pixel = GoogleAnalyticsTrackingPixel(campaign_source=None, campaign_medium=None)
self.assertIsNotNone(pixel.generate_image_url())
assert pixel.generate_image_url() is not None
self.assert_url_components_equal(
pixel.generate_image_url(),
query='v=1&t=event&ec=email&ea=edx.bi.email.opened&cid={cid}&tid=UA-123456-1'.format(
@@ -161,11 +161,11 @@ class TestGoogleAnalyticsTrackingPixel(QueryStringAssertionMixin, CacheIsolation
def test_course_id(self):
course_id = 'foo/bar/baz'
pixel = GoogleAnalyticsTrackingPixel(course_id=course_id)
self.assertIsNotNone(pixel.generate_image_url())
assert pixel.generate_image_url() is not None
self.assert_query_string_parameters_equal(pixel.generate_image_url(), el=course_id)
@override_settings(GOOGLE_ANALYTICS_TRACKING_ID='UA-123456-1')
def test_course_id_with_event_label(self):
pixel = GoogleAnalyticsTrackingPixel(course_id='foo/bar/baz', event_label='test_label')
self.assertIsNotNone(pixel.generate_image_url())
assert pixel.generate_image_url() is not None
self.assert_query_string_parameters_equal(pixel.generate_image_url(), el='test_label')

View File

@@ -2,7 +2,7 @@
Tests for bookmarks api.
"""
import pytest
import ddt
import six
from django.conf import settings
@@ -33,7 +33,7 @@ class BookmarkApiEventTestMixin(object):
"""
Assert no events were emitted.
"""
self.assertFalse(mock_tracker.called)
assert not mock_tracker.called
@ddt.ddt
@@ -64,7 +64,7 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
Verifies that get_bookmark raises error as expected.
"""
with self.assertNumQueries(1):
with self.assertRaises(ObjectDoesNotExist):
with pytest.raises(ObjectDoesNotExist):
api.get_bookmark(user=self.other_user, usage_key=self.vertical_1.location)
@ddt.data(
@@ -79,7 +79,7 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
# Without course key.
with self.assertNumQueries(1):
bookmarks_data = api.get_bookmarks(user=self.user)
self.assertEqual(len(bookmarks_data), count + 5)
assert len(bookmarks_data) == (count + 5)
# Assert them in ordered manner.
self.assert_bookmark_data_is_valid(bookmarks[-1], bookmarks_data[0])
self.assert_bookmark_data_is_valid(self.bookmark_1, bookmarks_data[-1])
@@ -88,36 +88,36 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
# Without course key, with optional fields.
with self.assertNumQueries(1):
bookmarks_data = api.get_bookmarks(user=self.user, fields=self.ALL_FIELDS)
self.assertEqual(len(bookmarks_data), count + 5)
assert len(bookmarks_data) == (count + 5)
self.assert_bookmark_data_is_valid(bookmarks[-1], bookmarks_data[0])
self.assert_bookmark_data_is_valid(self.bookmark_1, bookmarks_data[-1])
# With course key.
with self.assertNumQueries(1):
bookmarks_data = api.get_bookmarks(user=self.user, course_key=course.id)
self.assertEqual(len(bookmarks_data), count)
assert len(bookmarks_data) == count
self.assert_bookmark_data_is_valid(bookmarks[-1], bookmarks_data[0])
self.assert_bookmark_data_is_valid(bookmarks[0], bookmarks_data[-1])
# With course key, with optional fields.
with self.assertNumQueries(1):
bookmarks_data = api.get_bookmarks(user=self.user, course_key=course.id, fields=self.ALL_FIELDS)
self.assertEqual(len(bookmarks_data), count)
assert len(bookmarks_data) == count
self.assert_bookmark_data_is_valid(bookmarks[-1], bookmarks_data[0])
self.assert_bookmark_data_is_valid(bookmarks[0], bookmarks_data[-1])
# Without Serialized.
with self.assertNumQueries(1):
bookmarks = api.get_bookmarks(user=self.user, course_key=course.id, serialized=False)
self.assertEqual(len(bookmarks), count)
self.assertIs(bookmarks.model, Bookmark)
assert len(bookmarks) == count
assert bookmarks.model is Bookmark
@patch('openedx.core.djangoapps.bookmarks.api.tracker.emit')
def test_create_bookmark(self, mock_tracker):
"""
Verifies that create_bookmark create & returns data as expected.
"""
self.assertEqual(len(api.get_bookmarks(user=self.user, course_key=self.course.id)), 4)
assert len(api.get_bookmarks(user=self.user, course_key=self.course.id)) == 4
with self.assertNumQueries(9):
bookmark_data = api.create_bookmark(user=self.user, usage_key=self.vertical_2.location)
@@ -131,14 +131,14 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
component_usage_id=six.text_type(self.vertical_2.location),
)
self.assertEqual(len(api.get_bookmarks(user=self.user, course_key=self.course.id)), 5)
assert len(api.get_bookmarks(user=self.user, course_key=self.course.id)) == 5
@patch('openedx.core.djangoapps.bookmarks.api.tracker.emit')
def test_create_bookmark_do_not_create_duplicates(self, mock_tracker):
"""
Verifies that create_bookmark do not create duplicate bookmarks.
"""
self.assertEqual(len(api.get_bookmarks(user=self.user, course_key=self.course.id)), 4)
assert len(api.get_bookmarks(user=self.user, course_key=self.course.id)) == 4
with self.assertNumQueries(9):
bookmark_data = api.create_bookmark(user=self.user, usage_key=self.vertical_2.location)
@@ -152,15 +152,15 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
component_usage_id=six.text_type(self.vertical_2.location),
)
self.assertEqual(len(api.get_bookmarks(user=self.user, course_key=self.course.id)), 5)
assert len(api.get_bookmarks(user=self.user, course_key=self.course.id)) == 5
mock_tracker.reset_mock()
with self.assertNumQueries(5):
bookmark_data_2 = api.create_bookmark(user=self.user, usage_key=self.vertical_2.location)
self.assertEqual(len(api.get_bookmarks(user=self.user, course_key=self.course.id)), 5)
self.assertEqual(bookmark_data, bookmark_data_2)
assert len(api.get_bookmarks(user=self.user, course_key=self.course.id)) == 5
assert bookmark_data == bookmark_data_2
self.assert_no_events_were_emitted(mock_tracker)
@@ -170,7 +170,7 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
Verifies that create_bookmark raises error as expected.
"""
with self.assertNumQueries(0):
with self.assertRaises(ItemNotFoundError):
with pytest.raises(ItemNotFoundError):
api.create_bookmark(user=self.user, usage_key=UsageKey.from_string('i4x://brb/100/html/340ef1771a0940'))
self.assert_no_events_were_emitted(mock_tracker)
@@ -186,27 +186,27 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
max_bookmarks = settings.MAX_BOOKMARKS_PER_COURSE
__, blocks, __ = self.create_course_with_bookmarks_count(max_bookmarks)
with self.assertNumQueries(1):
with self.assertRaises(BookmarksLimitReachedError):
with pytest.raises(BookmarksLimitReachedError):
api.create_bookmark(user=self.user, usage_key=blocks[-1].location)
self.assert_no_events_were_emitted(mock_tracker)
# if user tries to create bookmark in another course it should succeed
self.assertEqual(len(api.get_bookmarks(user=self.user, course_key=self.other_course.id)), 1)
assert len(api.get_bookmarks(user=self.user, course_key=self.other_course.id)) == 1
api.create_bookmark(user=self.user, usage_key=self.other_chapter_1.location)
self.assertEqual(len(api.get_bookmarks(user=self.user, course_key=self.other_course.id)), 2)
assert len(api.get_bookmarks(user=self.user, course_key=self.other_course.id)) == 2
# if another user tries to create bookmark it should succeed
self.assertEqual(len(api.get_bookmarks(user=self.other_user, course_key=blocks[-1].location.course_key)), 0)
assert len(api.get_bookmarks(user=self.other_user, course_key=blocks[(- 1)].location.course_key)) == 0
api.create_bookmark(user=self.other_user, usage_key=blocks[-1].location)
self.assertEqual(len(api.get_bookmarks(user=self.other_user, course_key=blocks[-1].location.course_key)), 1)
assert len(api.get_bookmarks(user=self.other_user, course_key=blocks[(- 1)].location.course_key)) == 1
@patch('openedx.core.djangoapps.bookmarks.api.tracker.emit')
def test_delete_bookmark(self, mock_tracker):
"""
Verifies that delete_bookmark removes bookmark as expected.
"""
self.assertEqual(len(api.get_bookmarks(user=self.user)), 5)
assert len(api.get_bookmarks(user=self.user)) == 5
with self.assertNumQueries(3):
api.delete_bookmark(user=self.user, usage_key=self.sequential_1.location)
@@ -221,13 +221,13 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
)
bookmarks_data = api.get_bookmarks(user=self.user)
self.assertEqual(len(bookmarks_data), 4)
self.assertNotEqual(six.text_type(self.sequential_1.location), bookmarks_data[0]['usage_id'])
self.assertNotEqual(six.text_type(self.sequential_1.location), bookmarks_data[1]['usage_id'])
assert len(bookmarks_data) == 4
assert six.text_type(self.sequential_1.location) != bookmarks_data[0]['usage_id']
assert six.text_type(self.sequential_1.location) != bookmarks_data[1]['usage_id']
@patch('openedx.core.djangoapps.bookmarks.api.tracker.emit')
def test_delete_bookmarks_with_vertical_block_type(self, mock_tracker):
self.assertEqual(len(api.get_bookmarks(user=self.user)), 5)
assert len(api.get_bookmarks(user=self.user)) == 5
api.delete_bookmarks(usage_key=self.vertical_3.location)
@@ -240,7 +240,7 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
component_usage_id=six.text_type(self.vertical_3.location),
)
self.assertEqual(len(api.get_bookmarks(self.user)), 4)
assert len(api.get_bookmarks(self.user)) == 4
@patch('openedx.core.djangoapps.bookmarks.api.modulestore')
@patch('openedx.core.djangoapps.bookmarks.api.tracker.emit')
@@ -251,8 +251,8 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
api.delete_bookmarks(usage_key=self.chapter_2.location)
self.assertEqual(mocked_modulestore.call_count, 2)
self.assertEqual(mocked_modulestore().get_item.call_count, 2)
assert mocked_modulestore.call_count == 2
assert mocked_modulestore().get_item.call_count == 2
mocked_modulestore().get_item().get_children.assert_called()
self.assert_bookmark_event_emitted(
mock_tracker,
@@ -262,7 +262,7 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
component_type=self.chapter_2.location.block_type,
component_usage_id=six.text_type(self.chapter_2.location),
)
self.assertEqual(len(api.get_bookmarks(self.user)), 4)
assert len(api.get_bookmarks(self.user)) == 4
@patch('openedx.core.djangoapps.bookmarks.api.tracker.emit')
def test_delete_bookmark_raises_error(self, mock_tracker):
@@ -270,7 +270,7 @@ class BookmarksAPITests(BookmarkApiEventTestMixin, BookmarksTestsBase):
Verifies that delete_bookmark raises error as expected.
"""
with self.assertNumQueries(1):
with self.assertRaises(ObjectDoesNotExist):
with pytest.raises(ObjectDoesNotExist):
api.delete_bookmark(user=self.other_user, usage_key=self.vertical_1.location)
self.assert_no_events_were_emitted(mock_tracker)

View File

@@ -219,30 +219,30 @@ class BookmarksTestsBase(ModuleStoreTestCase):
"""
Assert that the attributes of the bookmark model were set correctly.
"""
self.assertEqual(bookmark.user, bookmark_data['user'])
self.assertEqual(bookmark.course_key, bookmark_data['course_key'])
self.assertEqual(text_type(bookmark.usage_key), text_type(bookmark_data['usage_key']))
self.assertEqual(bookmark.resource_id, u"{},{}".format(bookmark_data['user'], bookmark_data['usage_key']))
self.assertEqual(bookmark.display_name, bookmark_data['display_name'])
self.assertEqual(bookmark.path, self.path)
self.assertIsNotNone(bookmark.created)
assert bookmark.user == bookmark_data['user']
assert bookmark.course_key == bookmark_data['course_key']
assert text_type(bookmark.usage_key) == text_type(bookmark_data['usage_key'])
assert bookmark.resource_id == u'{},{}'.format(bookmark_data['user'], bookmark_data['usage_key'])
assert bookmark.display_name == bookmark_data['display_name']
assert bookmark.path == self.path
assert bookmark.created is not None
self.assertEqual(bookmark.xblock_cache.course_key, bookmark_data['course_key'])
self.assertEqual(bookmark.xblock_cache.display_name, bookmark_data['display_name'])
assert bookmark.xblock_cache.course_key == bookmark_data['course_key']
assert bookmark.xblock_cache.display_name == bookmark_data['display_name']
def assert_bookmark_data_is_valid(self, bookmark, bookmark_data, check_optional_fields=False):
"""
Assert that the bookmark data matches the data in the model.
"""
self.assertEqual(bookmark_data['id'], bookmark.resource_id)
self.assertEqual(bookmark_data['course_id'], text_type(bookmark.course_key))
self.assertEqual(bookmark_data['usage_id'], text_type(bookmark.usage_key))
self.assertEqual(bookmark_data['block_type'], text_type(bookmark.usage_key.block_type))
self.assertIsNotNone(bookmark_data['created'])
assert bookmark_data['id'] == bookmark.resource_id
assert bookmark_data['course_id'] == text_type(bookmark.course_key)
assert bookmark_data['usage_id'] == text_type(bookmark.usage_key)
assert bookmark_data['block_type'] == text_type(bookmark.usage_key.block_type)
assert bookmark_data['created'] is not None
if check_optional_fields:
self.assertEqual(bookmark_data['display_name'], bookmark.display_name)
self.assertEqual(bookmark_data['path'], bookmark.path)
assert bookmark_data['display_name'] == bookmark.display_name
assert bookmark_data['path'] == bookmark.path
@ddt.ddt
@@ -304,9 +304,9 @@ class BookmarkModelTests(BookmarksTestsBase):
with check_mongo_calls(expected_mongo_calls):
bookmark, __ = Bookmark.create(bookmark_data)
self.assertEqual(bookmark.path, expected_path)
self.assertIsNotNone(bookmark.xblock_cache)
self.assertEqual(bookmark.xblock_cache.paths, [])
assert bookmark.path == expected_path
assert bookmark.xblock_cache is not None
assert bookmark.xblock_cache.paths == []
def test_create_bookmark_success(self):
"""
@@ -320,14 +320,14 @@ class BookmarkModelTests(BookmarksTestsBase):
bookmark_data_different_values['display_name'] = 'Introduction Video'
bookmark2, __ = Bookmark.create(bookmark_data_different_values)
# The bookmark object already created should have been returned without modifications.
self.assertEqual(bookmark, bookmark2)
self.assertEqual(bookmark.xblock_cache, bookmark2.xblock_cache)
assert bookmark == bookmark2
assert bookmark.xblock_cache == bookmark2.xblock_cache
self.assert_bookmark_model_is_valid(bookmark2, bookmark_data)
bookmark_data_different_user = self.get_bookmark_data(self.vertical_2)
bookmark_data_different_user['user'] = UserFactory.create()
bookmark3, __ = Bookmark.create(bookmark_data_different_user)
self.assertNotEqual(bookmark, bookmark3)
assert bookmark != bookmark3
self.assert_bookmark_model_is_valid(bookmark3, bookmark_data_different_user)
def test_create_bookmark_successfully_with_display_name_none(self):
@@ -359,15 +359,15 @@ class BookmarkModelTests(BookmarksTestsBase):
bookmark_data = self.get_bookmark_data(html)
bookmark, __ = Bookmark.create(bookmark_data)
self.assertIsNotNone(bookmark.xblock_cache)
assert bookmark.xblock_cache is not None
modification_datetime = datetime.datetime.now(pytz.utc) + datetime.timedelta(seconds=seconds_delta)
with freeze_time(modification_datetime):
bookmark.xblock_cache.paths = paths
bookmark.xblock_cache.save()
self.assertEqual(bookmark.path, block_path)
self.assertEqual(mock_get_path.call_count, get_path_call_count)
assert bookmark.path == block_path
assert mock_get_path.call_count == get_path_call_count
@ddt.data(
(ModuleStoreEnum.Type.mongo, 2, 2, 2),
@@ -401,7 +401,7 @@ class BookmarkModelTests(BookmarksTestsBase):
with check_mongo_calls(expected_mongo_calls):
path = Bookmark.get_path(block.location)
self.assertEqual(len(path), depth - 2)
assert len(path) == (depth - 2)
def test_get_path_in_case_of_exceptions(self):
@@ -410,7 +410,7 @@ class BookmarkModelTests(BookmarksTestsBase):
# Block does not exist
usage_key = UsageKey.from_string('i4x://edX/apis/html/interactive')
usage_key.replace(course_key=self.course.id)
self.assertEqual(Bookmark.get_path(usage_key), [])
assert Bookmark.get_path(usage_key) == []
# Block is an orphan
self.other_sequential_1.children = []
@@ -419,16 +419,16 @@ class BookmarkModelTests(BookmarksTestsBase):
bookmark_data = self.get_bookmark_data(self.other_vertical_2, user=user)
bookmark, __ = Bookmark.create(bookmark_data)
self.assertEqual(bookmark.path, [])
self.assertIsNotNone(bookmark.xblock_cache)
self.assertEqual(bookmark.xblock_cache.paths, [])
assert bookmark.path == []
assert bookmark.xblock_cache is not None
assert bookmark.xblock_cache.paths == []
# Parent block could not be retrieved
with mock.patch('openedx.core.djangoapps.bookmarks.models.search.path_to_location') as mock_path_to_location:
mock_path_to_location.return_value = [usage_key]
bookmark_data = self.get_bookmark_data(self.other_sequential_1, user=user)
bookmark, __ = Bookmark.create(bookmark_data)
self.assertEqual(bookmark.path, [])
assert bookmark.path == []
@ddt.ddt
@@ -454,11 +454,11 @@ class XBlockCacheModelTest(ModuleStoreTestCase):
"""
Assert that the XBlockCache object values match.
"""
self.assertEqual(xblock_cache.usage_key, data['usage_key'])
self.assertEqual(xblock_cache.course_key, data['usage_key'].course_key)
self.assertEqual(xblock_cache.display_name, data['display_name'])
self.assertEqual(xblock_cache._paths, data['_paths']) # pylint: disable=protected-access
self.assertEqual(xblock_cache.paths, [parse_path_data(path) for path in data['_paths']])
assert xblock_cache.usage_key == data['usage_key']
assert xblock_cache.course_key == data['usage_key'].course_key
assert xblock_cache.display_name == data['display_name']
assert xblock_cache._paths == data['_paths'] # pylint: disable=protected-access
assert xblock_cache.paths == [parse_path_data(path) for path in data['_paths']]
@ddt.data(
(
@@ -503,11 +503,11 @@ class XBlockCacheModelTest(ModuleStoreTestCase):
'display_name': 'The end.',
'_paths': original_paths,
})
self.assertEqual(xblock_cache.paths, [parse_path_data(path) for path in original_paths])
assert xblock_cache.paths == [parse_path_data(path) for path in original_paths]
xblock_cache.paths = [parse_path_data(path) for path in updated_paths]
xblock_cache.save()
xblock_cache = XBlockCache.objects.get(id=xblock_cache.id)
self.assertEqual(xblock_cache._paths, updated_paths) # pylint: disable=protected-access
self.assertEqual(xblock_cache.paths, [parse_path_data(path) for path in updated_paths])
assert xblock_cache._paths == updated_paths # pylint: disable=protected-access
assert xblock_cache.paths == [parse_path_data(path) for path in updated_paths]

View File

@@ -29,7 +29,7 @@ class BookmarksServiceTests(BookmarksTestsBase):
with self.assertNumQueries(1):
bookmarks_data = self.bookmark_service.bookmarks(course_key=self.course.id)
self.assertEqual(len(bookmarks_data), 4)
assert len(bookmarks_data) == 4
self.assert_bookmark_data_is_valid(self.bookmark_4, bookmarks_data[0])
self.assert_bookmark_data_is_valid(self.bookmark_3, bookmarks_data[1])
self.assert_bookmark_data_is_valid(self.bookmark_2, bookmarks_data[2])
@@ -40,25 +40,25 @@ class BookmarksServiceTests(BookmarksTestsBase):
Verifies is_bookmarked returns Bool as expected.
"""
with self.assertNumQueries(1):
self.assertTrue(self.bookmark_service.is_bookmarked(usage_key=self.sequential_1.location))
self.assertFalse(self.bookmark_service.is_bookmarked(usage_key=self.vertical_2.location))
self.assertTrue(self.bookmark_service.is_bookmarked(usage_key=self.sequential_2.location))
assert self.bookmark_service.is_bookmarked(usage_key=self.sequential_1.location)
assert not self.bookmark_service.is_bookmarked(usage_key=self.vertical_2.location)
assert self.bookmark_service.is_bookmarked(usage_key=self.sequential_2.location)
self.bookmark_service.set_bookmarked(usage_key=self.chapter_1.location)
with self.assertNumQueries(0):
self.assertTrue(self.bookmark_service.is_bookmarked(usage_key=self.chapter_1.location))
self.assertFalse(self.bookmark_service.is_bookmarked(usage_key=self.vertical_2.location))
assert self.bookmark_service.is_bookmarked(usage_key=self.chapter_1.location)
assert not self.bookmark_service.is_bookmarked(usage_key=self.vertical_2.location)
# Removing a bookmark should result in the cache being updated on the next request
self.bookmark_service.unset_bookmarked(usage_key=self.chapter_1.location)
with self.assertNumQueries(0):
self.assertFalse(self.bookmark_service.is_bookmarked(usage_key=self.chapter_1.location))
self.assertFalse(self.bookmark_service.is_bookmarked(usage_key=self.vertical_2.location))
assert not self.bookmark_service.is_bookmarked(usage_key=self.chapter_1.location)
assert not self.bookmark_service.is_bookmarked(usage_key=self.vertical_2.location)
# Get bookmark that does not exist.
bookmark_service = BookmarksService(self.other_user)
with self.assertNumQueries(1):
self.assertFalse(bookmark_service.is_bookmarked(usage_key=self.sequential_1.location))
assert not bookmark_service.is_bookmarked(usage_key=self.sequential_1.location)
def test_set_bookmarked(self):
"""
@@ -66,21 +66,19 @@ class BookmarksServiceTests(BookmarksTestsBase):
"""
# Assert False for item that does not exist.
with self.assertNumQueries(0):
self.assertFalse(
self.bookmark_service.set_bookmarked(usage_key=UsageKey.from_string("i4x://ed/ed/ed/interactive"))
)
assert not self.bookmark_service\
.set_bookmarked(usage_key=UsageKey.from_string('i4x://ed/ed/ed/interactive'))
with self.assertNumQueries(9):
self.assertTrue(self.bookmark_service.set_bookmarked(usage_key=self.vertical_2.location))
assert self.bookmark_service.set_bookmarked(usage_key=self.vertical_2.location)
def test_unset_bookmarked(self):
"""
Verifies unset_bookmarked returns Bool as expected.
"""
with self.assertNumQueries(1):
self.assertFalse(
self.bookmark_service.unset_bookmarked(usage_key=UsageKey.from_string("i4x://ed/ed/ed/interactive"))
)
assert not self.bookmark_service\
.unset_bookmarked(usage_key=UsageKey.from_string('i4x://ed/ed/ed/interactive'))
with self.assertNumQueries(3):
self.assertTrue(self.bookmark_service.unset_bookmarked(usage_key=self.sequential_1.location))
assert self.bookmark_service.unset_bookmarked(usage_key=self.sequential_1.location)

View File

@@ -124,7 +124,7 @@ class XBlockCacheTaskTests(BookmarksTestsBase):
with check_mongo_calls(expected_mongo_calls):
blocks_data = _calculate_course_xblocks_data(course.id)
self.assertGreater(len(blocks_data), children_per_block ** depth)
assert len(blocks_data) > (children_per_block ** depth)
@ddt.data(
('course',),
@@ -142,9 +142,7 @@ class XBlockCacheTaskTests(BookmarksTestsBase):
for usage_key, __ in expected_cache_data.items():
for path_index, path in enumerate(blocks_data[six.text_type(usage_key)]['paths']):
for path_item_index, path_item in enumerate(path):
self.assertEqual(
path_item['usage_key'], expected_cache_data[usage_key][path_index][path_item_index]
)
assert path_item['usage_key'] == expected_cache_data[usage_key][path_index][path_item_index]
@ddt.data(
('course', 36),
@@ -165,9 +163,7 @@ class XBlockCacheTaskTests(BookmarksTestsBase):
xblock_cache = XBlockCache.objects.get(usage_key=usage_key)
for path_index, path in enumerate(xblock_cache.paths):
for path_item_index, path_item in enumerate(path):
self.assertEqual(
path_item.usage_key, expected_cache_data[usage_key][path_index][path_item_index + 1]
)
assert path_item.usage_key == expected_cache_data[usage_key][path_index][(path_item_index + 1)]
with self.assertNumQueries(3):
_update_xblocks_cache(course.id)
@@ -199,7 +195,5 @@ class XBlockCacheTaskTests(BookmarksTestsBase):
xblock_cache = XBlockCache.objects.get(usage_key=usage_key)
for path_index, path in enumerate(xblock_cache.paths):
for path_item_index, path_item in enumerate(path):
self.assertEqual(
path_item.usage_key,
self.course_expected_cache_data[usage_key][path_index][path_item_index + 1]
)
assert path_item.usage_key == \
self.course_expected_cache_data[usage_key][path_index][(path_item_index + 1)]

View File

@@ -43,7 +43,7 @@ class BookmarksViewsTestsBase(BookmarksTestsBase, BookmarkApiEventTestMixin):
"""
url = url + '?' + query_parameters if query_parameters else url
response = client.get(url)
self.assertEqual(expected_status, response.status_code)
assert expected_status == response.status_code
return response
def send_post(self, client, url, data, content_type='application/json', expected_status=201):
@@ -51,7 +51,7 @@ class BookmarksViewsTestsBase(BookmarksTestsBase, BookmarkApiEventTestMixin):
Helper method for sending a POST to the server. Verifies the expected status and returns the response.
"""
response = client.post(url, data=json.dumps(data), content_type=content_type)
self.assertEqual(expected_status, response.status_code)
assert expected_status == response.status_code
return response
def send_delete(self, client, url, expected_status=204):
@@ -59,7 +59,7 @@ class BookmarksViewsTestsBase(BookmarksTestsBase, BookmarkApiEventTestMixin):
Helper method for sending a DELETE to the server. Verifies the expected status and returns the response.
"""
response = client.delete(url)
self.assertEqual(expected_status, response.status_code)
assert expected_status == response.status_code
return response
@@ -104,9 +104,9 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
)
bookmarks_data = response.data['results']
self.assertEqual(len(bookmarks_data), len(bookmarks))
self.assertEqual(response.data['count'], len(bookmarks))
self.assertEqual(response.data['num_pages'], 1)
assert len(bookmarks_data) == len(bookmarks)
assert response.data['count'] == len(bookmarks)
assert response.data['num_pages'] == 1
# As bookmarks are sorted by -created so we will compare in that order.
self.assert_bookmark_data_is_valid(bookmarks[-1], bookmarks_data[0], check_optional_fields=check_all_fields)
@@ -147,11 +147,11 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
bookmarks_data = response.data['results']
# Pagination assertions.
self.assertEqual(response.data['count'], bookmarks_count)
self.assertIn('page=2&page_size={}'.format(page_size), response.data['next'])
self.assertEqual(response.data['num_pages'], bookmarks_count / page_size)
assert response.data['count'] == bookmarks_count
assert 'page=2&page_size={}'.format(page_size) in response.data['next']
assert response.data['num_pages'] == (bookmarks_count / page_size)
self.assertEqual(len(bookmarks_data), min(bookmarks_count, page_size))
assert len(bookmarks_data) == min(bookmarks_count, page_size)
self.assert_bookmark_data_is_valid(bookmarks[-1], bookmarks_data[0])
self.assert_bookmark_event_emitted(
@@ -177,8 +177,8 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
)
bookmarks_data = response.data['results']
self.assertEqual(len(bookmarks_data), 0)
self.assertFalse(mock_tracker.emit.called)
assert len(bookmarks_data) == 0
assert not mock_tracker.emit.called
@patch('eventtracking.tracker.emit')
def test_get_all_bookmarks_when_course_id_not_given(self, mock_tracker):
@@ -191,7 +191,7 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
url=reverse('bookmarks')
)
bookmarks_data = response.data['results']
self.assertEqual(len(bookmarks_data), 5)
assert len(bookmarks_data) == 5
self.assert_bookmark_data_is_valid(self.other_bookmark_1, bookmarks_data[0])
self.assert_bookmark_data_is_valid(self.bookmark_4, bookmarks_data[1])
self.assert_bookmark_data_is_valid(self.bookmark_3, bookmarks_data[2])
@@ -236,12 +236,12 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
)
# Assert Newly created bookmark.
self.assertEqual(response.data['id'], '%s,%s' % (self.user.username, six.text_type(self.vertical_2.location)))
self.assertEqual(response.data['course_id'], self.course_id)
self.assertEqual(response.data['usage_id'], six.text_type(self.vertical_2.location))
self.assertIsNotNone(response.data['created'])
self.assertEqual(len(response.data['path']), 2)
self.assertEqual(response.data['display_name'], self.vertical_2.display_name)
assert response.data['id'] == ('%s,%s' % (self.user.username, six.text_type(self.vertical_2.location)))
assert response.data['course_id'] == self.course_id
assert response.data['usage_id'] == six.text_type(self.vertical_2.location)
assert response.data['created'] is not None
assert len(response.data['path']) == 2
assert response.data['display_name'] == self.vertical_2.display_name
def test_post_bookmark_with_invalid_data(self):
"""
@@ -258,7 +258,7 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
data={'usage_id': 'invalid'},
expected_status=400
)
self.assertEqual(response.data['user_message'], u'An error has occurred. Please try again.')
assert response.data['user_message'] == u'An error has occurred. Please try again.'
# Send data without usage_id.
response = self.send_post(
@@ -267,8 +267,8 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
data={'course_id': 'invalid'},
expected_status=400
)
self.assertEqual(response.data['user_message'], u'An error has occurred. Please try again.')
self.assertEqual(response.data['developer_message'], u'Parameter usage_id not provided.')
assert response.data['user_message'] == u'An error has occurred. Please try again.'
assert response.data['developer_message'] == u'Parameter usage_id not provided.'
# Send empty data dictionary.
with self.assertNumQueries(9): # No queries for bookmark table.
@@ -278,8 +278,8 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
data={},
expected_status=400
)
self.assertEqual(response.data['user_message'], u'An error has occurred. Please try again.')
self.assertEqual(response.data['developer_message'], u'No data provided.')
assert response.data['user_message'] == u'An error has occurred. Please try again.'
assert response.data['developer_message'] == u'No data provided.'
def test_post_bookmark_for_non_existing_block(self):
"""
@@ -291,14 +291,9 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
data={'usage_id': 'i4x://arbi/100/html/340ef1771a094090ad260ec940d04a21'},
expected_status=400
)
self.assertEqual(
response.data['user_message'],
u'An error has occurred. Please try again.'
)
self.assertEqual(
response.data['developer_message'],
u'Block with usage_id: i4x://arbi/100/html/340ef1771a094090ad260ec940d04a21 not found.'
)
assert response.data['user_message'] == u'An error has occurred. Please try again.'
assert response.data['developer_message'] ==\
u'Block with usage_id: i4x://arbi/100/html/340ef1771a094090ad260ec940d04a21 not found.'
@patch('django.conf.settings.MAX_BOOKMARKS_PER_COURSE', 5)
def test_post_bookmark_when_max_bookmarks_already_exist(self):
@@ -314,24 +309,20 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
data={'usage_id': six.text_type(blocks[-1].location)},
expected_status=400
)
self.assertEqual(
response.data['user_message'],
u'You can create up to {0} bookmarks.'
u' You must remove some bookmarks before you can add new ones.'.format(max_bookmarks)
)
self.assertEqual(
response.data['developer_message'],
u'You can create up to {0} bookmarks.'
u' You must remove some bookmarks before you can add new ones.'.format(max_bookmarks)
)
assert response.data['user_message'] == u'You can create up to {0} bookmarks.' \
u' You must remove some bookmarks before you can add new ones.'\
.format(max_bookmarks)
assert response.data['developer_message'] == u'You can create up to {0} bookmarks.' \
u' You must remove some bookmarks before you can add new ones.'\
.format(max_bookmarks)
def test_unsupported_methods(self):
"""
Test that DELETE and PUT are not supported.
"""
self.client.login(username=self.user.username, password=self.TEST_PASSWORD)
self.assertEqual(405, self.client.put(reverse('bookmarks')).status_code)
self.assertEqual(405, self.client.delete(reverse('bookmarks')).status_code)
assert 405 == self.client.put(reverse('bookmarks')).status_code
assert 405 == self.client.delete(reverse('bookmarks')).status_code
@patch('eventtracking.tracker.emit')
@ddt.unpack
@@ -397,7 +388,7 @@ class BookmarksDetailViewTests(BookmarksViewsTestsBase):
query_parameters=query_params
)
data = response.data
self.assertIsNotNone(data)
assert data is not None
self.assert_bookmark_data_is_valid(self.bookmark_1, data, check_optional_fields=check_optional_fields)
def test_get_bookmark_that_belongs_to_other_user(self):
@@ -438,14 +429,10 @@ class BookmarksDetailViewTests(BookmarksViewsTestsBase):
),
expected_status=404
)
self.assertEqual(
response.data['user_message'],
'Bookmark with usage_id: i4x://arbi/100/html/340ef1771a0940 does not exist.'
)
self.assertEqual(
response.data['developer_message'],
'Bookmark with usage_id: i4x://arbi/100/html/340ef1771a0940 does not exist.'
)
assert response.data['user_message'] ==\
'Bookmark with usage_id: i4x://arbi/100/html/340ef1771a0940 does not exist.'
assert response.data['developer_message'] ==\
'Bookmark with usage_id: i4x://arbi/100/html/340ef1771a0940 does not exist.'
def test_get_bookmark_with_invalid_usage_id(self):
"""
@@ -459,7 +446,7 @@ class BookmarksDetailViewTests(BookmarksViewsTestsBase):
),
expected_status=404
)
self.assertEqual(response.data['user_message'], u'Invalid usage_id: i4x.')
assert response.data['user_message'] == u'Invalid usage_id: i4x.'
def test_anonymous_access(self):
"""
@@ -484,7 +471,7 @@ class BookmarksDetailViewTests(BookmarksViewsTestsBase):
query_parameters = 'course_id={}'.format(six.moves.urllib.parse.quote(self.course_id))
response = self.send_get(client=self.client, url=reverse('bookmarks'), query_parameters=query_parameters)
bookmarks_data = response.data['results']
self.assertEqual(len(bookmarks_data), 4)
assert len(bookmarks_data) == 4
self.send_delete(
client=self.client,
@@ -496,7 +483,7 @@ class BookmarksDetailViewTests(BookmarksViewsTestsBase):
response = self.send_get(client=self.client, url=reverse('bookmarks'), query_parameters=query_parameters)
bookmarks_data = response.data['results']
self.assertEqual(len(bookmarks_data), 3)
assert len(bookmarks_data) == 3
def test_delete_bookmark_that_belongs_to_other_user(self):
"""
@@ -523,14 +510,10 @@ class BookmarksDetailViewTests(BookmarksViewsTestsBase):
),
expected_status=404
)
self.assertEqual(
response.data['user_message'],
u'Bookmark with usage_id: i4x://arbi/100/html/340ef1771a0940 does not exist.'
)
self.assertEqual(
response.data['developer_message'],
'Bookmark with usage_id: i4x://arbi/100/html/340ef1771a0940 does not exist.'
)
assert response.data['user_message'] ==\
u'Bookmark with usage_id: i4x://arbi/100/html/340ef1771a0940 does not exist.'
assert response.data['developer_message'] ==\
'Bookmark with usage_id: i4x://arbi/100/html/340ef1771a0940 does not exist.'
def test_delete_bookmark_with_invalid_usage_id(self):
"""
@@ -544,7 +527,7 @@ class BookmarksDetailViewTests(BookmarksViewsTestsBase):
),
expected_status=404
)
self.assertEqual(response.data['user_message'], u'Invalid usage_id: i4x.')
assert response.data['user_message'] == u'Invalid usage_id: i4x.'
def test_unsupported_methods(self):
"""
@@ -552,5 +535,5 @@ class BookmarksDetailViewTests(BookmarksViewsTestsBase):
"""
url = reverse('bookmarks_detail', kwargs={'username': self.user.username, 'usage_id': 'i4x'})
self.client.login(username=self.user.username, password=self.TEST_PASSWORD)
self.assertEqual(405, self.client.put(url).status_code)
self.assertEqual(405, self.client.post(url).status_code)
assert 405 == self.client.put(url).status_code
assert 405 == self.client.post(url).status_code

View File

@@ -3,7 +3,7 @@ Test cases for cache_programs command.
"""
import json
import pytest
import httpretty
from django.core.cache import cache
from django.core.management import call_command
@@ -80,7 +80,7 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
'status': ['active', 'retired'],
'uuids_only': ['1']
}
self.assertEqual(request.querystring, expected)
assert request.querystring == expected
return (200, headers, json.dumps(self.uuids))
@@ -99,7 +99,7 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
expected = {
'exclude_utm': ['1'],
}
self.assertEqual(request.querystring, expected)
assert request.querystring == expected
return (200, headers, json.dumps(program))
@@ -119,7 +119,7 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
'exclude_utm': ['1'],
'page': [str(page_number)],
}
self.assertEqual(request.querystring, expected)
assert request.querystring == expected
body = {
'count': len(pathways),
@@ -165,18 +165,12 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
call_command('cache_programs')
cached_uuids = cache.get(SITE_PROGRAM_UUIDS_CACHE_KEY_TPL.format(domain=self.site_domain))
self.assertEqual(
set(cached_uuids),
set(self.uuids)
)
assert set(cached_uuids) == set(self.uuids)
program_keys = list(programs.keys())
cached_programs = cache.get_many(program_keys)
# Verify that the keys were all cache hits.
self.assertEqual(
set(cached_programs),
set(programs)
)
assert set(cached_programs) == set(programs)
# We can't use a set comparison here because these values are dictionaries
# and aren't hashable. We've already verified that all programs came out
@@ -185,7 +179,7 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
for key, program in cached_programs.items():
# cached programs have a pathways field added to them, remove before comparing
del program['pathway_ids']
self.assertEqual(program, programs[key])
assert program == programs[key]
# the courses in the child program's first curriculum (the active one)
# should point to both the child program and the first program
@@ -193,8 +187,8 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
for course in self.child_program['curricula'][0]['courses']:
for course_run in course['course_runs']:
course_run_cache_key = COURSE_PROGRAMS_CACHE_KEY_TPL.format(course_run_id=course_run['key'])
self.assertIn(self.programs[0]['uuid'], cache.get(course_run_cache_key))
self.assertIn(self.child_program['uuid'], cache.get(course_run_cache_key))
assert self.programs[0]['uuid'] in cache.get(course_run_cache_key)
assert self.child_program['uuid'] in cache.get(course_run_cache_key)
# for each program, assert that the program's UUID is in a cached list of
# program UUIDS by program type and a cached list of UUIDs by authoring organization
@@ -207,14 +201,14 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
program_type_slug_cache_key = PROGRAMS_BY_TYPE_SLUG_CACHE_KEY_TPL.format(
site_id=self.site.id, program_slug=program_type_slug
)
self.assertIn(program['uuid'], cache.get(program_type_cache_key))
self.assertIn(program['uuid'], cache.get(program_type_slug_cache_key))
assert program['uuid'] in cache.get(program_type_cache_key)
assert program['uuid'] in cache.get(program_type_slug_cache_key)
for organization in program['authoring_organizations']:
organization_cache_key = PROGRAMS_BY_ORGANIZATION_CACHE_KEY_TPL.format(
org_key=organization['key']
)
self.assertIn(program['uuid'], cache.get(organization_cache_key))
assert program['uuid'] in cache.get(organization_cache_key)
def test_handle_pathways(self):
"""
@@ -242,16 +236,10 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
cached_pathway_keys = cache.get(SITE_PATHWAY_IDS_CACHE_KEY_TPL.format(domain=self.site_domain))
pathway_keys = list(pathways.keys())
self.assertEqual(
set(cached_pathway_keys),
set(pathway_keys)
)
assert set(cached_pathway_keys) == set(pathway_keys)
cached_pathways = cache.get_many(pathway_keys)
self.assertEqual(
set(cached_pathways),
set(pathways)
)
assert set(cached_pathways) == set(pathways)
# We can't use a set comparison here because these values are dictionaries
# and aren't hashable. We've already verified that all pathways came out
@@ -262,7 +250,7 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
pathways[key]['program_uuids'] = [program['uuid'] for program in pathways[key]['programs']]
del pathways[key]['programs']
self.assertEqual(pathway, pathways[key])
assert pathway == pathways[key]
def test_pathways_multiple_pages(self):
"""
@@ -296,16 +284,10 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
pathway_keys = list(pathways_dict.keys())
cached_pathway_keys = cache.get(SITE_PATHWAY_IDS_CACHE_KEY_TPL.format(domain=self.site_domain))
self.assertEqual(
set(cached_pathway_keys),
set(pathway_keys)
)
assert set(cached_pathway_keys) == set(pathway_keys)
cached_pathways = cache.get_many(pathway_keys)
self.assertEqual(
set(cached_pathways),
set(pathways_dict)
)
assert set(cached_pathways) == set(pathways_dict)
# We can't use a set comparison here because these values are dictionaries
# and aren't hashable. We've already verified that all pathways came out
@@ -316,18 +298,18 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
pathways_dict[key]['program_uuids'] = [program['uuid'] for program in pathways_dict[key]['programs']]
del pathways_dict[key]['programs']
self.assertEqual(pathway, pathways_dict[key])
assert pathway == pathways_dict[key]
def test_handle_missing_service_user(self):
"""
Verify that the command raises an exception when run without a service
user, and that program UUIDs are not cached.
"""
with self.assertRaises(Exception):
with pytest.raises(Exception):
call_command('cache_programs')
cached_uuids = cache.get(SITE_PROGRAM_UUIDS_CACHE_KEY_TPL.format(domain=self.site_domain))
self.assertEqual(cached_uuids, None)
assert cached_uuids is None
def test_handle_missing_uuids(self):
"""
@@ -336,12 +318,12 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
"""
UserFactory(username=self.catalog_integration.service_username)
with self.assertRaises(SystemExit) as context:
with pytest.raises(SystemExit) as context:
call_command('cache_programs')
self.assertEqual(context.exception.code, 1)
assert context.value.code == 1
cached_uuids = cache.get(SITE_PROGRAM_UUIDS_CACHE_KEY_TPL.format(domain=self.site_domain))
self.assertEqual(cached_uuids, [])
assert cached_uuids == []
def test_handle_missing_pathways(self):
"""
@@ -359,12 +341,12 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
program = programs[PROGRAM_CACHE_KEY_TPL.format(uuid=uuid)]
self.mock_detail(uuid, program)
with self.assertRaises(SystemExit) as context:
with pytest.raises(SystemExit) as context:
call_command('cache_programs')
self.assertEqual(context.exception.code, 1)
assert context.value.code == 1
cached_pathways = cache.get(SITE_PATHWAY_IDS_CACHE_KEY_TPL.format(domain=self.site_domain))
self.assertEqual(cached_pathways, [])
assert cached_pathways == []
def test_handle_missing_programs(self):
"""
@@ -387,26 +369,20 @@ class TestCachePrograms(CatalogIntegrationMixin, CacheIsolationTestCase, SiteMix
program = partial_programs[PROGRAM_CACHE_KEY_TPL.format(uuid=uuid)]
self.mock_detail(uuid, program)
with self.assertRaises(SystemExit) as context:
with pytest.raises(SystemExit) as context:
call_command('cache_programs')
self.assertEqual(context.exception.code, 1)
assert context.value.code == 1
cached_uuids = cache.get(SITE_PROGRAM_UUIDS_CACHE_KEY_TPL.format(domain=self.site_domain))
self.assertEqual(
set(cached_uuids),
set(self.uuids)
)
assert set(cached_uuids) == set(self.uuids)
program_keys = list(all_programs.keys())
cached_programs = cache.get_many(program_keys)
# One of the cache keys should result in a cache miss.
self.assertEqual(
set(cached_programs),
set(partial_programs)
)
assert set(cached_programs) == set(partial_programs)
for key, program in cached_programs.items():
# cached programs have a pathways field added to them, remove before comparing
del program['pathway_ids']
self.assertEqual(program, partial_programs[key])
assert program == partial_programs[key]

View File

@@ -2,6 +2,7 @@
Test cases for catalog_integrations command.
"""
import pytest
from django.test import TestCase # lint-amnesty, pylint: disable=unused-import
from django.core.management import call_command, CommandError
@@ -18,14 +19,14 @@ class TestCreateCatalogIntegrations(CatalogIntegrationMixin, CacheIsolationTestC
''' Test that required values are supplied '''
# test without service_username
with self.assertRaises(CommandError):
with pytest.raises(CommandError):
call_command(
"create_catalog_integrations",
"--internal_api_url", self.catalog_integration_defaults['internal_api_url'],
)
# test without internal_api_url
with self.assertRaises(CommandError):
with pytest.raises(CommandError):
call_command(
"create_catalog_integrations",
"--service_username", self.catalog_integration_defaults['service_username'],
@@ -46,24 +47,12 @@ class TestCreateCatalogIntegrations(CatalogIntegrationMixin, CacheIsolationTestC
current = CatalogIntegration.current()
# assert current has changed
self.assertNotEqual(
initial,
current
)
assert initial != current
self.assertEqual(
current.enabled,
False
)
self.assertEqual(
current.internal_api_url,
self.catalog_integration_defaults['internal_api_url']
)
assert current.enabled is False
assert current.internal_api_url == self.catalog_integration_defaults['internal_api_url']
self.assertEqual(
current.service_username,
self.catalog_integration_defaults['service_username']
)
assert current.service_username == self.catalog_integration_defaults['service_username']
def test_with_optional(self):
''' Test with optionals arguments supplied'''
@@ -80,24 +69,12 @@ class TestCreateCatalogIntegrations(CatalogIntegrationMixin, CacheIsolationTestC
current = CatalogIntegration.current()
# assert current has changed
self.assertNotEqual(
initial,
current
)
assert initial != current
self.assertEqual(
current.enabled,
True
)
self.assertEqual(
current.internal_api_url,
self.catalog_integration_defaults['internal_api_url']
)
assert current.enabled is True
assert current.internal_api_url == self.catalog_integration_defaults['internal_api_url']
self.assertEqual(
current.service_username,
self.catalog_integration_defaults['service_username']
)
assert current.service_username == self.catalog_integration_defaults['service_username']
# test with all args
call_command(
@@ -113,35 +90,14 @@ class TestCreateCatalogIntegrations(CatalogIntegrationMixin, CacheIsolationTestC
current = CatalogIntegration.current()
# assert current has changed
self.assertNotEqual(
initial,
current
)
assert initial != current
self.assertEqual(
current.enabled,
True
)
self.assertEqual(
current.internal_api_url,
self.catalog_integration_defaults['internal_api_url']
)
assert current.enabled is True
assert current.internal_api_url == self.catalog_integration_defaults['internal_api_url']
self.assertEqual(
current.service_username,
self.catalog_integration_defaults['service_username']
)
assert current.service_username == self.catalog_integration_defaults['service_username']
self.assertEqual(
current.cache_ttl,
500
)
assert current.cache_ttl == 500
self.assertEqual(
current.long_term_cache_ttl,
500
)
self.assertEqual(
current.page_size,
500
)
assert current.long_term_cache_ttl == 500
assert current.page_size == 500

View File

@@ -55,15 +55,9 @@ class TestSyncCourseRunsCommand(ModuleStoreTestCase):
updated_course_overview_value = getattr(updated_course_overview, course_overview_field_name)
# course overview value matches catalog value
self.assertEqual(
updated_course_overview_value,
self.catalog_course_run.get(catalog_field_name), # lint-amnesty, pylint: disable=no-member
)
assert updated_course_overview_value == self.catalog_course_run.get(catalog_field_name) # pylint: disable=no-member, line-too-long
# new value doesn't match old value
self.assertNotEqual(
updated_course_overview_value,
previous_course_overview_value,
)
assert updated_course_overview_value != previous_course_overview_value
@mock.patch(COMMAND_MODULE + '.log.info')
def test_course_overview_does_not_exist(self, mock_log_info, mock_catalog_course_runs):
@@ -80,7 +74,7 @@ class TestSyncCourseRunsCommand(ModuleStoreTestCase):
nonexistent_course_run['key'],
)
updated_marketing_url = CourseOverview.objects.get(id=self.course.id).marketing_url
self.assertEqual(updated_marketing_url, 'test_marketing_url')
assert updated_marketing_url == 'test_marketing_url'
@mock.patch(COMMAND_MODULE + '.log.info')
def test_starting_and_ending_logs(self, mock_log_info, mock_catalog_course_runs):

View File

@@ -19,7 +19,7 @@ class TestCatalogIntegration(mixins.CatalogIntegrationMixin, CacheIsolationTestC
def assert_get_internal_api_url_value(self, expected):
""" Asserts the value of get_internal_api_url matches the expected value. """
catalog_integration = self.create_catalog_integration()
self.assertEqual(catalog_integration.get_internal_api_url(), expected)
assert catalog_integration.get_internal_api_url() == expected
@ddt.data(
(0, False),
@@ -29,14 +29,14 @@ class TestCatalogIntegration(mixins.CatalogIntegrationMixin, CacheIsolationTestC
def test_cache_control(self, cache_ttl, is_cache_enabled):
"""Test the behavior of the property controlling whether API responses are cached."""
catalog_integration = self.create_catalog_integration(cache_ttl=cache_ttl)
self.assertEqual(catalog_integration.is_cache_enabled, is_cache_enabled)
assert catalog_integration.is_cache_enabled == is_cache_enabled
@override_settings(COURSE_CATALOG_API_URL=COURSE_CATALOG_API_URL)
def test_get_internal_api_url(self):
""" Requests made without a microsite should return the value from settings. """
self.assert_get_internal_api_url_value(COURSE_CATALOG_API_URL)
catalog_integration = self.create_catalog_integration()
self.assertEqual(catalog_integration.get_internal_api_url(), COURSE_CATALOG_API_URL)
assert catalog_integration.get_internal_api_url() == COURSE_CATALOG_API_URL
@override_settings(COURSE_CATALOG_API_URL=COURSE_CATALOG_API_URL)
@with_site_configuration(configuration={})

View File

@@ -88,7 +88,7 @@ class TestGetPrograms(CacheIsolationTestCase):
# When called before UUIDs are cached, the function should return an
# empty list and log a warning.
with with_site_configuration_context(domain=self.site.name, configuration={'COURSE_CATALOG_API_URL': 'foo'}):
self.assertEqual(get_programs(site=self.site), [])
assert get_programs(site=self.site) == []
mock_warning.assert_called_once_with(
u'Failed to get program UUIDs from the cache for site {}.'.format(self.site.domain)
)
@@ -105,10 +105,8 @@ class TestGetPrograms(CacheIsolationTestCase):
# The 2 cached programs should be returned while info and warning
# messages should be logged for the missing one.
self.assertEqual(
set(program['uuid'] for program in actual_programs),
set(program['uuid'] for program in partial_programs.values())
)
assert set((program['uuid'] for program in actual_programs)) == \
set((program['uuid'] for program in partial_programs.values()))
mock_info.assert_called_with('Failed to get details for 1 programs. Retrying.')
mock_warning.assert_called_with(
u'Failed to get details for program {uuid} from the cache.'.format(uuid=programs[2]['uuid'])
@@ -121,7 +119,7 @@ class TestGetPrograms(CacheIsolationTestCase):
# the data itself.
for program in actual_programs:
key = PROGRAM_CACHE_KEY_TPL.format(uuid=program['uuid'])
self.assertEqual(program, partial_programs[key])
assert program == partial_programs[key]
# Cache details for all 3 programs.
all_programs = {
@@ -132,15 +130,13 @@ class TestGetPrograms(CacheIsolationTestCase):
actual_programs = get_programs(site=self.site)
# All 3 programs should be returned.
self.assertEqual(
set(program['uuid'] for program in actual_programs),
set(program['uuid'] for program in all_programs.values())
)
self.assertFalse(mock_warning.called)
assert set((program['uuid'] for program in actual_programs)) ==\
set((program['uuid'] for program in all_programs.values()))
assert not mock_warning.called
for program in actual_programs:
key = PROGRAM_CACHE_KEY_TPL.format(uuid=program['uuid'])
self.assertEqual(program, all_programs[key])
assert program == all_programs[key]
@mock.patch(UTILS_MODULE + '.cache')
def test_get_many_with_missing(self, mock_cache, mock_warning, mock_info):
@@ -169,22 +165,20 @@ class TestGetPrograms(CacheIsolationTestCase):
# All 3 cached programs should be returned. An info message should be
# logged about the one that was initially missing, but the code should
# be able to stitch together all the details.
self.assertEqual(
set(program['uuid'] for program in actual_programs),
set(program['uuid'] for program in all_programs.values())
)
self.assertFalse(mock_warning.called)
assert set((program['uuid'] for program in actual_programs)) ==\
set((program['uuid'] for program in all_programs.values()))
assert not mock_warning.called
mock_info.assert_called_with('Failed to get details for 1 programs. Retrying.')
for program in actual_programs:
key = PROGRAM_CACHE_KEY_TPL.format(uuid=program['uuid'])
self.assertEqual(program, all_programs[key])
assert program == all_programs[key]
def test_get_one(self, mock_warning, _mock_info):
expected_program = ProgramFactory()
expected_uuid = expected_program['uuid']
self.assertEqual(get_programs(uuid=expected_uuid), None)
assert get_programs(uuid=expected_uuid) is None
mock_warning.assert_called_once_with(
u'Failed to get details for program {uuid} from the cache.'.format(uuid=expected_uuid)
)
@@ -197,14 +191,14 @@ class TestGetPrograms(CacheIsolationTestCase):
)
actual_program = get_programs(uuid=expected_uuid)
self.assertEqual(actual_program, expected_program)
self.assertFalse(mock_warning.called)
assert actual_program == expected_program
assert not mock_warning.called
def test_get_from_course(self, mock_warning, _mock_info):
expected_program = ProgramFactory()
expected_course = expected_program['courses'][0]['course_runs'][0]['key']
self.assertEqual(get_programs(course=expected_course), [])
assert get_programs(course=expected_course) == []
cache.set(
COURSE_PROGRAMS_CACHE_KEY_TPL.format(course_run_id=expected_course),
@@ -218,8 +212,8 @@ class TestGetPrograms(CacheIsolationTestCase):
)
actual_program = get_programs(course=expected_course)
self.assertEqual(actual_program, [expected_program])
self.assertFalse(mock_warning.called)
assert actual_program == [expected_program]
assert not mock_warning.called
def test_get_via_uuids(self, mock_warning, _mock_info):
first_program = ProgramFactory()
@@ -246,7 +240,7 @@ class TestGetPrograms(CacheIsolationTestCase):
expected_program = ProgramFactory()
expected_catalog_course = expected_program['courses'][0]
self.assertEqual(get_programs(catalog_course_uuid=expected_catalog_course['uuid']), [])
assert get_programs(catalog_course_uuid=expected_catalog_course['uuid']) == []
cache.set(
CATALOG_COURSE_PROGRAMS_CACHE_KEY_TPL.format(course_uuid=expected_catalog_course['uuid']),
@@ -261,8 +255,8 @@ class TestGetPrograms(CacheIsolationTestCase):
actual_program = get_programs(catalog_course_uuid=expected_catalog_course['uuid'])
self.assertEqual(actual_program, [expected_program])
self.assertFalse(mock_warning.called)
assert actual_program == [expected_program]
assert not mock_warning.called
@skip_unless_lms
@@ -286,7 +280,7 @@ class TestGetPathways(CacheIsolationTestCase):
# When called before pathways are cached, the function should return an
# empty list and log a warning.
self.assertEqual(get_pathways(self.site), [])
assert get_pathways(self.site) == []
mock_warning.assert_called_once_with('Failed to get credit pathway ids from the cache.')
mock_warning.reset_mock()
@@ -301,10 +295,8 @@ class TestGetPathways(CacheIsolationTestCase):
# The 2 cached pathways should be returned while info and warning
# messages should be logged for the missing one.
self.assertEqual(
set(pathway['id'] for pathway in actual_pathways),
set(pathway['id'] for pathway in partial_pathways.values())
)
assert set((pathway['id'] for pathway in actual_pathways)) ==\
set((pathway['id'] for pathway in partial_pathways.values()))
mock_info.assert_called_with('Failed to get details for 1 pathways. Retrying.')
mock_warning.assert_called_with(
u'Failed to get details for credit pathway {id} from the cache.'.format(id=pathways[2]['id'])
@@ -317,7 +309,7 @@ class TestGetPathways(CacheIsolationTestCase):
# the data itself.
for pathway in actual_pathways:
key = PATHWAY_CACHE_KEY_TPL.format(id=pathway['id'])
self.assertEqual(pathway, partial_pathways[key])
assert pathway == partial_pathways[key]
# Cache details for all 3 pathways.
all_pathways = {
@@ -328,15 +320,13 @@ class TestGetPathways(CacheIsolationTestCase):
actual_pathways = get_pathways(self.site)
# All 3 pathways should be returned.
self.assertEqual(
set(pathway['id'] for pathway in actual_pathways),
set(pathway['id'] for pathway in all_pathways.values())
)
self.assertFalse(mock_warning.called)
assert set((pathway['id'] for pathway in actual_pathways)) ==\
set((pathway['id'] for pathway in all_pathways.values()))
assert not mock_warning.called
for pathway in actual_pathways:
key = PATHWAY_CACHE_KEY_TPL.format(id=pathway['id'])
self.assertEqual(pathway, all_pathways[key])
assert pathway == all_pathways[key]
@mock.patch(UTILS_MODULE + '.cache')
def test_get_many_with_missing(self, mock_cache, mock_warning, mock_info):
@@ -364,22 +354,20 @@ class TestGetPathways(CacheIsolationTestCase):
# All 3 cached pathways should be returned. An info message should be
# logged about the one that was initially missing, but the code should
# be able to stitch together all the details.
self.assertEqual(
set(pathway['id'] for pathway in actual_pathways),
set(pathway['id'] for pathway in all_pathways.values())
)
self.assertFalse(mock_warning.called)
assert set((pathway['id'] for pathway in actual_pathways)) ==\
set((pathway['id'] for pathway in all_pathways.values()))
assert not mock_warning.called
mock_info.assert_called_with('Failed to get details for 1 pathways. Retrying.')
for pathway in actual_pathways:
key = PATHWAY_CACHE_KEY_TPL.format(id=pathway['id'])
self.assertEqual(pathway, all_pathways[key])
assert pathway == all_pathways[key]
def test_get_one(self, mock_warning, _mock_info):
expected_pathway = PathwayFactory()
expected_id = expected_pathway['id']
self.assertEqual(get_pathways(self.site, pathway_id=expected_id), None)
assert get_pathways(self.site, pathway_id=expected_id) is None
mock_warning.assert_called_once_with(
u'Failed to get details for credit pathway {id} from the cache.'.format(id=expected_id)
)
@@ -392,8 +380,8 @@ class TestGetPathways(CacheIsolationTestCase):
)
actual_pathway = get_pathways(self.site, pathway_id=expected_id)
self.assertEqual(actual_pathway, expected_pathway)
self.assertFalse(mock_warning.called)
assert actual_pathway == expected_pathway
assert not mock_warning.called
@mock.patch(UTILS_MODULE + '.get_edx_api_data')
@@ -407,16 +395,16 @@ class TestGetProgramTypes(CatalogIntegrationMixin, TestCase):
# Catalog integration is disabled.
data = get_program_types()
self.assertEqual(data, [])
assert data == []
catalog_integration = self.create_catalog_integration()
UserFactory(username=catalog_integration.service_username)
data = get_program_types()
self.assertEqual(data, program_types)
assert data == program_types
program = program_types[0]
data = get_program_types(name=program['name'])
self.assertEqual(data, program)
assert data == program
@mock.patch(UTILS_MODULE + '.get_edx_api_data')
@@ -434,12 +422,12 @@ class TestGetCurrency(CatalogIntegrationMixin, TestCase):
# Catalog integration is disabled.
data = get_currency_data()
self.assertEqual(data, [])
assert data == []
catalog_integration = self.create_catalog_integration()
UserFactory(username=catalog_integration.service_username)
data = get_currency_data()
self.assertEqual(data, currency_data)
assert data == currency_data
@mock.patch(UTILS_MODULE + '.get_currency_data')
@@ -460,7 +448,7 @@ class TestGetLocalizedPriceText(TestCase):
'country_code': 'CA'
}
expected_result = '$20 CAD'
self.assertEqual(get_localized_price_text(10, request), expected_result)
assert get_localized_price_text(10, request) == expected_result
@skip_unless_lms
@@ -482,16 +470,16 @@ class TestGetCourseRuns(CatalogIntegrationMixin, CacheIsolationTestCase):
args, kwargs = call_args
for arg in (self.catalog_integration, 'course_runs'):
self.assertIn(arg, args)
assert arg in args
self.assertEqual(kwargs['api']._store['base_url'], self.catalog_integration.get_internal_api_url()) # pylint: disable=protected-access
assert kwargs['api']._store['base_url'] == self.catalog_integration.get_internal_api_url() # pylint: disable=protected-access, line-too-long
querystring = {
'page_size': 20,
'exclude_utm': 1,
}
self.assertEqual(kwargs['querystring'], querystring)
assert kwargs['querystring'] == querystring
return args, kwargs
@@ -503,8 +491,8 @@ class TestGetCourseRuns(CatalogIntegrationMixin, CacheIsolationTestCase):
self.clear_caches()
data = get_course_runs()
self.assertFalse(mock_get_edx_api_data.called)
self.assertEqual(data, [])
assert not mock_get_edx_api_data.called
assert data == []
@mock.patch(UTILS_MODULE + '.logger.error')
def test_service_user_missing(self, mock_log_error, mock_get_edx_api_data):
@@ -518,8 +506,8 @@ class TestGetCourseRuns(CatalogIntegrationMixin, CacheIsolationTestCase):
u'Catalog service user with username [%s] does not exist. Course runs will not be retrieved.',
catalog_integration.service_username,
)
self.assertFalse(mock_get_edx_api_data.called)
self.assertEqual(data, [])
assert not mock_get_edx_api_data.called
assert data == []
def test_get_course_runs(self, mock_get_edx_api_data):
"""
@@ -529,9 +517,9 @@ class TestGetCourseRuns(CatalogIntegrationMixin, CacheIsolationTestCase):
mock_get_edx_api_data.return_value = catalog_course_runs
data = get_course_runs()
self.assertTrue(mock_get_edx_api_data.called)
assert mock_get_edx_api_data.called
self.assert_contract(mock_get_edx_api_data.call_args)
self.assertEqual(data, catalog_course_runs)
assert data == catalog_course_runs
def test_get_course_runs_by_course(self, mock_get_edx_api_data):
"""
@@ -542,8 +530,8 @@ class TestGetCourseRuns(CatalogIntegrationMixin, CacheIsolationTestCase):
mock_get_edx_api_data.return_value = catalog_course
data = get_course_runs_for_course(course_uuid=str(catalog_course['uuid']))
self.assertTrue(mock_get_edx_api_data.called)
self.assertEqual(data, catalog_course_runs)
assert mock_get_edx_api_data.called
assert data == catalog_course_runs
@skip_unless_lms
@@ -567,8 +555,8 @@ class TestGetCourseOwners(CatalogIntegrationMixin, TestCase):
mock_get_edx_api_data.return_value = catalog_course
data = get_owners_for_course(course_uuid=str(catalog_course['uuid']))
self.assertTrue(mock_get_edx_api_data.called)
self.assertEqual(data, catalog_course['owners'])
assert mock_get_edx_api_data.called
assert data == catalog_course['owners']
@skip_unless_lms
@@ -602,7 +590,7 @@ class TestSessionEntitlement(CatalogIntegrationMixin, TestCase):
)
session_entitlements = get_visible_sessions_for_entitlement(entitlement)
self.assertEqual(session_entitlements, [catalog_course_run])
assert session_entitlements == [catalog_course_run]
def test_get_visible_sessions_for_entitlement_expired_mode(self, mock_get_edx_api_data):
"""
@@ -627,7 +615,7 @@ class TestSessionEntitlement(CatalogIntegrationMixin, TestCase):
)
session_entitlements = get_visible_sessions_for_entitlement(entitlement)
self.assertEqual(session_entitlements, [catalog_course_run])
assert session_entitlements == [catalog_course_run]
def test_unpublished_sessions_for_entitlement_when_enrolled(self, mock_get_edx_api_data):
"""
@@ -653,7 +641,7 @@ class TestSessionEntitlement(CatalogIntegrationMixin, TestCase):
)
session_entitlements = get_visible_sessions_for_entitlement(entitlement)
self.assertEqual(session_entitlements, [catalog_course_run])
assert session_entitlements == [catalog_course_run]
def test_unpublished_sessions_for_entitlement(self, mock_get_edx_api_data):
"""
@@ -676,7 +664,7 @@ class TestSessionEntitlement(CatalogIntegrationMixin, TestCase):
)
session_entitlements = get_visible_sessions_for_entitlement(entitlement)
self.assertEqual(session_entitlements, [])
assert session_entitlements == []
@skip_unless_lms
@@ -702,8 +690,8 @@ class TestGetCourseRunDetails(CatalogIntegrationMixin, TestCase):
}
mock_get_edx_api_data.return_value = course_run_details
data = get_course_run_details(course_run['key'], ['content_language', 'weeks_to_complete', 'max_effort'])
self.assertTrue(mock_get_edx_api_data.called)
self.assertEqual(data, course_run_details)
assert mock_get_edx_api_data.called
assert data == course_run_details
class TestProgramCourseRunCrawling(TestCase):
@@ -793,13 +781,13 @@ class TestProgramCourseRunCrawling(TestCase):
program = {
'title': 'notice that I do not have a curriculum',
}
self.assertEqual([], child_programs(program))
assert [] == child_programs(program)
def test_child_programs_no_children(self):
self.assertEqual([], child_programs(self.empty_program))
assert [] == child_programs(self.empty_program)
def test_child_programs_one_child(self):
self.assertEqual([self.grandchild_1], child_programs(self.simple_program))
assert [self.grandchild_1] == child_programs(self.simple_program)
def test_child_programs_many_children(self):
expected_children = [
@@ -809,13 +797,13 @@ class TestProgramCourseRunCrawling(TestCase):
self.grandchild_2,
self.grandchild_3,
]
self.assertEqual(expected_children, child_programs(self.complex_program))
assert expected_children == child_programs(self.complex_program)
def test_course_run_keys_for_program_no_courses(self):
self.assertEqual(set(), course_run_keys_for_program(self.empty_program))
assert set() == course_run_keys_for_program(self.empty_program)
def test_course_run_keys_for_program_one_course(self):
self.assertEqual({'course-run-1'}, course_run_keys_for_program(self.simple_program))
assert {'course-run-1'} == course_run_keys_for_program(self.simple_program)
def test_course_run_keys_for_program_many_courses(self):
expected_course_runs = {
@@ -823,12 +811,12 @@ class TestProgramCourseRunCrawling(TestCase):
'course-run-3',
'course-run-4',
}
self.assertEqual(expected_course_runs, course_run_keys_for_program(self.complex_program))
assert expected_course_runs == course_run_keys_for_program(self.complex_program)
def test_is_course_run_in_program(self):
self.assertTrue(is_course_run_in_program('course-run-4', self.complex_program))
self.assertFalse(is_course_run_in_program('course-run-5', self.complex_program))
self.assertFalse(is_course_run_in_program('course-run-4', self.simple_program))
assert is_course_run_in_program('course-run-4', self.complex_program)
assert not is_course_run_in_program('course-run-5', self.complex_program)
assert not is_course_run_in_program('course-run-4', self.simple_program)
@skip_unless_lms
@@ -913,33 +901,33 @@ class TestGetProgramsByType(CacheIsolationTestCase):
def test_get_bachelors_programs(self):
expected_programs = [self.bachelors_program]
self.assertEqual(expected_programs, get_programs_by_type(self.site, 'bachelors'))
self.assertEqual(expected_programs, get_programs_by_type_slug(self.site, 'bachelors'))
assert expected_programs == get_programs_by_type(self.site, 'bachelors')
assert expected_programs == get_programs_by_type_slug(self.site, 'bachelors')
def test_get_no_such_type_programs(self):
expected_programs = []
self.assertEqual(expected_programs, get_programs_by_type(self.site, 'doctorate'))
self.assertEqual(expected_programs, get_programs_by_type_slug(self.site, 'doctorate'))
assert expected_programs == get_programs_by_type(self.site, 'doctorate')
assert expected_programs == get_programs_by_type_slug(self.site, 'doctorate')
def test_get_masters_programs_other_site(self):
expected_programs = [self.masters_program_other_site]
self.assertEqual(expected_programs, get_programs_by_type(self.other_site, 'masters'))
self.assertEqual(expected_programs, get_programs_by_type_slug(self.other_site, 'masters'))
assert expected_programs == get_programs_by_type(self.other_site, 'masters')
assert expected_programs == get_programs_by_type_slug(self.other_site, 'masters')
def test_get_programs_null_type(self):
expected_programs = [self.no_type_program]
self.assertEqual(expected_programs, get_programs_by_type(self.site, None))
self.assertEqual(expected_programs, get_programs_by_type_slug(self.site, None))
assert expected_programs == get_programs_by_type(self.site, None)
assert expected_programs == get_programs_by_type_slug(self.site, None)
def test_get_programs_false_type(self):
expected_programs = []
self.assertEqual(expected_programs, get_programs_by_type(self.site, False))
self.assertEqual(expected_programs, get_programs_by_type_slug(self.site, False))
assert expected_programs == get_programs_by_type(self.site, False)
assert expected_programs == get_programs_by_type_slug(self.site, False)
def test_normalize_program_type(self):
self.assertEqual('none', normalize_program_type(None))
self.assertEqual('false', normalize_program_type(False))
self.assertEqual('true', normalize_program_type(True))
self.assertEqual('', normalize_program_type(''))
self.assertEqual('masters', normalize_program_type('Masters'))
self.assertEqual('masters', normalize_program_type('masters'))
assert 'none' == normalize_program_type(None)
assert 'false' == normalize_program_type(False)
assert 'true' == normalize_program_type(True)
assert '' == normalize_program_type('')
assert 'masters' == normalize_program_type('Masters')
assert 'masters' == normalize_program_type('masters')

View File

@@ -4,7 +4,7 @@ Unit tests for the API module
import datetime
import pytest
import mock
import pytz
import six.moves.urllib.parse # lint-amnesty, pylint: disable=import-error, wrong-import-order
@@ -104,8 +104,8 @@ class APIsTestCase(SharedModuleStoreTestCase):
Test for an invalid course key
"""
missing_course_key = CourseKey.from_string('course-v1:FakeOrganization+CN999+CR-FALL99')
self.assertIsNone(ccxconapi.course_info_to_ccxcon(missing_course_key))
self.assertEqual(mock_post.call_count, 0)
assert ccxconapi.course_info_to_ccxcon(missing_course_key) is None
assert mock_post.call_count == 0
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.fetch_token', fetch_token_mock)
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.post')
@@ -115,8 +115,8 @@ class APIsTestCase(SharedModuleStoreTestCase):
"""
self.course.enable_ccx = False
self.mstore.update_item(self.course, self.instructor.id)
self.assertIsNone(ccxconapi.course_info_to_ccxcon(self.course_key))
self.assertEqual(mock_post.call_count, 0)
assert ccxconapi.course_info_to_ccxcon(self.course_key) is None
assert mock_post.call_count == 0
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.fetch_token', fetch_token_mock)
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.post')
@@ -127,13 +127,13 @@ class APIsTestCase(SharedModuleStoreTestCase):
# no connector at all
self.course.ccx_connector = ""
self.mstore.update_item(self.course, self.instructor.id)
self.assertIsNone(ccxconapi.course_info_to_ccxcon(self.course_key))
self.assertEqual(mock_post.call_count, 0)
assert ccxconapi.course_info_to_ccxcon(self.course_key) is None
assert mock_post.call_count == 0
# invalid url
self.course.ccx_connector = "www.foo"
self.mstore.update_item(self.course, self.instructor.id)
self.assertIsNone(ccxconapi.course_info_to_ccxcon(self.course_key))
self.assertEqual(mock_post.call_count, 0)
assert ccxconapi.course_info_to_ccxcon(self.course_key) is None
assert mock_post.call_count == 0
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.fetch_token', fetch_token_mock)
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.post')
@@ -143,8 +143,8 @@ class APIsTestCase(SharedModuleStoreTestCase):
"""
self.course.ccx_connector = "https://www.foo.com"
self.mstore.update_item(self.course, self.instructor.id)
self.assertIsNone(ccxconapi.course_info_to_ccxcon(self.course_key))
self.assertEqual(mock_post.call_count, 0)
assert ccxconapi.course_info_to_ccxcon(self.course_key) is None
assert mock_post.call_count == 0
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.fetch_token', fetch_token_mock)
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.post')
@@ -158,14 +158,12 @@ class APIsTestCase(SharedModuleStoreTestCase):
ccxconapi.course_info_to_ccxcon(self.course_key)
self.assertEqual(mock_post.call_count, 1)
assert mock_post.call_count == 1
k_args, k_kwargs = mock_post.call_args
# no args used for the call
self.assertEqual(k_args, tuple())
self.assertEqual(
k_kwargs.get('url'),
six.moves.urllib.parse.urljoin(self.course.ccx_connector, ccxconapi.CCXCON_COURSEXS_URL)
)
assert k_args == tuple()
assert k_kwargs.get('url') ==\
six.moves.urllib.parse.urljoin(self.course.ccx_connector, ccxconapi.CCXCON_COURSEXS_URL)
# second call with different status code
mock_response.status_code = 200
@@ -173,14 +171,12 @@ class APIsTestCase(SharedModuleStoreTestCase):
ccxconapi.course_info_to_ccxcon(self.course_key)
self.assertEqual(mock_post.call_count, 2)
assert mock_post.call_count == 2
k_args, k_kwargs = mock_post.call_args
# no args used for the call
self.assertEqual(k_args, tuple())
self.assertEqual(
k_kwargs.get('url'),
six.moves.urllib.parse.urljoin(self.course.ccx_connector, ccxconapi.CCXCON_COURSEXS_URL)
)
assert k_args == tuple()
assert k_kwargs.get('url') ==\
six.moves.urllib.parse.urljoin(self.course.ccx_connector, ccxconapi.CCXCON_COURSEXS_URL)
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.fetch_token', fetch_token_mock)
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.post')
@@ -192,7 +188,7 @@ class APIsTestCase(SharedModuleStoreTestCase):
mock_response.status_code = 500
mock_post.return_value = mock_response
with self.assertRaises(ccxconapi.CCXConnServerError):
with pytest.raises(ccxconapi.CCXConnServerError):
ccxconapi.course_info_to_ccxcon(self.course_key)
@mock.patch('requests_oauthlib.oauth2_session.OAuth2Session.fetch_token', fetch_token_mock)
@@ -206,4 +202,4 @@ class APIsTestCase(SharedModuleStoreTestCase):
for status_code in (204, 300, 304, 400, 404):
mock_response.status_code = status_code
mock_post.return_value = mock_response
self.assertIsNone(ccxconapi.course_info_to_ccxcon(self.course_key))
assert ccxconapi.course_info_to_ccxcon(self.course_key) is None

View File

@@ -37,10 +37,10 @@ class CCXConTaskTestCase(TestCase):
course_id = u'course-v1:OrgFoo+CN199+CR-FALL01'
tasks.update_ccxcon.delay(course_id)
self.assertEqual(mock_citc.call_count, 6)
assert mock_citc.call_count == 6
course_key = CourseKey.from_string(course_id)
for call in mock_citc.call_args_list:
c_args, c_kwargs = call
self.assertEqual(c_kwargs, {})
self.assertEqual(len(c_args), 1)
self.assertEqual(c_args[0], course_key)
assert c_kwargs == {}
assert len(c_args) == 1
assert c_args[0] == course_key

View File

@@ -97,7 +97,7 @@ class CertificatesApiTestCase(TestCase):
@ddt.data(True, False)
def test_auto_certificate_generation_enabled(self, feature_enabled):
with configure_waffle_namespace(feature_enabled):
self.assertEqual(feature_enabled, api.auto_certificate_generation_enabled())
assert feature_enabled == api.auto_certificate_generation_enabled()
@ddt.data(
(True, True, False), # feature enabled and self-paced should return False
@@ -111,7 +111,7 @@ class CertificatesApiTestCase(TestCase):
):
self.course.self_paced = is_self_paced
with configure_waffle_namespace(feature_enabled):
self.assertEqual(expected_value, api.can_show_certificate_available_date_field(self.course))
assert expected_value == api.can_show_certificate_available_date_field(self.course)
@ddt.data(
(CourseMode.VERIFIED, CertificateStatuses.downloadable, True),
@@ -126,7 +126,7 @@ class CertificatesApiTestCase(TestCase):
self.certificate.mode = CourseMode.VERIFIED
self.certificate.status = certificate_status
self.assertEqual(expected_value, api.is_certificate_valid(self.certificate))
assert expected_value == api.is_certificate_valid(self.certificate)
@ddt.data(
(CourseMode.VERIFIED, CertificateStatuses.downloadable, True),
@@ -141,7 +141,7 @@ class CertificatesApiTestCase(TestCase):
self.certificate.mode = CourseMode.VERIFIED
self.certificate.status = certificate_status
self.assertEqual(expected_value, api.is_certificate_valid(self.certificate))
assert expected_value == api.is_certificate_valid(self.certificate)
@ddt.data(
(True, True, False), # feature enabled and self-paced should return False
@@ -157,17 +157,17 @@ class CertificatesApiTestCase(TestCase):
with configure_waffle_namespace(feature_enabled):
# With no available_date set, both return modified_date
self.assertEqual(self.certificate.modified_date, api.available_date_for_certificate(self.course, self.certificate))
self.assertEqual(self.certificate.modified_date, api.display_date_for_certificate(self.course, self.certificate))
assert self.certificate.modified_date == api.available_date_for_certificate(self.course, self.certificate)
assert self.certificate.modified_date == api.display_date_for_certificate(self.course, self.certificate)
# With an available date set in the past, both return the available date (if configured)
self.course.certificate_available_date = datetime(2017, 2, 1, tzinfo=pytz.UTC)
maybe_avail = self.course.certificate_available_date if uses_avail_date else self.certificate.modified_date
self.assertEqual(maybe_avail, api.available_date_for_certificate(self.course, self.certificate))
self.assertEqual(maybe_avail, api.display_date_for_certificate(self.course, self.certificate))
assert maybe_avail == api.available_date_for_certificate(self.course, self.certificate)
assert maybe_avail == api.display_date_for_certificate(self.course, self.certificate)
# With a future available date, they each return a different date
self.course.certificate_available_date = datetime.max.replace(tzinfo=pytz.UTC)
maybe_avail = self.course.certificate_available_date if uses_avail_date else self.certificate.modified_date
self.assertEqual(maybe_avail, api.available_date_for_certificate(self.course, self.certificate))
self.assertEqual(self.certificate.modified_date, api.display_date_for_certificate(self.course, self.certificate))
assert maybe_avail == api.available_date_for_certificate(self.course, self.certificate)
assert self.certificate.modified_date == api.display_date_for_certificate(self.course, self.certificate)

View File

@@ -4,7 +4,7 @@ Tests for generate_course_blocks management command.
import itertools
import pytest
import ddt
from django.core.management.base import CommandError
from mock import patch
@@ -42,28 +42,28 @@ class TestGenerateCourseBlocks(ModuleStoreTestCase):
Assert courses don't exist in the course block cache.
"""
for course_key in course_keys:
self.assertFalse(is_course_in_block_structure_cache(course_key, self.store))
assert not is_course_in_block_structure_cache(course_key, self.store)
def _assert_courses_in_block_cache(self, *course_keys):
"""
Assert courses exist in course block cache.
"""
for course_key in course_keys:
self.assertTrue(is_course_in_block_structure_cache(course_key, self.store))
assert is_course_in_block_structure_cache(course_key, self.store)
def _assert_courses_not_in_block_storage(self, *course_keys):
"""
Assert courses don't exist in course block storage.
"""
for course_key in course_keys:
self.assertFalse(is_course_in_block_structure_storage(course_key, self.store))
assert not is_course_in_block_structure_storage(course_key, self.store)
def _assert_courses_in_block_storage(self, *course_keys):
"""
Assert courses exist in course block storage.
"""
for course_key in course_keys:
self.assertTrue(is_course_in_block_structure_storage(course_key, self.store))
assert is_course_in_block_structure_storage(course_key, self.store)
def _assert_message_presence_in_logs(self, message, mock_log, expected_presence=True):
"""
@@ -71,9 +71,9 @@ class TestGenerateCourseBlocks(ModuleStoreTestCase):
"""
message_present = any([message in call_args[0][0] for call_args in mock_log.warning.call_args_list])
if expected_presence:
self.assertTrue(message_present)
assert message_present
else:
self.assertFalse(message_present)
assert not message_present
@ddt.data(True, False)
def test_all_courses(self, force_update):
@@ -84,7 +84,7 @@ class TestGenerateCourseBlocks(ModuleStoreTestCase):
'openedx.core.djangoapps.content.block_structure.factory.BlockStructureFactory.create_from_modulestore'
) as mock_update_from_store:
self.command.handle(all_courses=True, force_update=force_update)
self.assertEqual(mock_update_from_store.call_count, self.num_courses if force_update else 0)
assert mock_update_from_store.call_count == (self.num_courses if force_update else 0)
def test_one_course(self):
self._assert_courses_not_in_block_cache(*self.course_keys)
@@ -121,23 +121,15 @@ class TestGenerateCourseBlocks(ModuleStoreTestCase):
self.command.handle(**command_options)
self.assertEqual(
mock_tasks.update_course_in_cache_v2.apply_async.call_count,
self.num_courses if enqueue_task and force_update else 0,
)
self.assertEqual(
mock_tasks.get_course_in_cache_v2.apply_async.call_count,
self.num_courses if enqueue_task and not force_update else 0,
)
assert mock_tasks.update_course_in_cache_v2.apply_async.call_count ==\
(self.num_courses if (enqueue_task and force_update) else 0)
assert mock_tasks.get_course_in_cache_v2.apply_async.call_count ==\
(self.num_courses if (enqueue_task and (not force_update)) else 0)
self.assertEqual(
mock_api.update_course_in_cache.call_count,
self.num_courses if not enqueue_task and force_update else 0,
)
self.assertEqual(
mock_api.get_course_in_cache.call_count,
self.num_courses if not enqueue_task and not force_update else 0,
)
assert mock_api.update_course_in_cache.call_count ==\
(self.num_courses if ((not enqueue_task) and force_update) else 0)
assert mock_api.get_course_in_cache.call_count ==\
(self.num_courses if (not enqueue_task and not force_update) else 0)
if enqueue_task:
if force_update:
@@ -146,21 +138,21 @@ class TestGenerateCourseBlocks(ModuleStoreTestCase):
task_action = mock_tasks.get_course_in_cache_v2
task_options = task_action.apply_async.call_args[1]
if routing_key:
self.assertEqual(task_options['routing_key'], routing_key)
assert task_options['routing_key'] == routing_key
else:
self.assertNotIn('routing_key', task_options)
assert 'routing_key' not in task_options
@patch('openedx.core.djangoapps.content.block_structure.management.commands.generate_course_blocks.log')
def test_not_found_key(self, mock_log):
self.command.handle(courses=['fake/course/id'])
self.assertTrue(mock_log.exception.called)
assert mock_log.exception.called
def test_invalid_key(self):
with self.assertRaises(CommandError):
with pytest.raises(CommandError):
self.command.handle(courses=['not/found'])
def test_no_params(self):
with self.assertRaises(CommandError):
with pytest.raises(CommandError):
self.command.handle(all_courses=False)
def test_no_course_mode(self):

View File

@@ -304,29 +304,21 @@ class ChildrenMapTestMixin(object):
for block_key, children in enumerate(children_map):
# Verify presence
self.assertEqual(
self.block_key_factory(block_key) in block_structure,
block_key not in missing_blocks,
u'Expected presence in block_structure for block_key {} to match absence in missing_blocks.'.format(
six.text_type(block_key)
),
)
assert (self.block_key_factory(block_key) in block_structure) == (block_key not in missing_blocks),\
u'Expected presence in block_structure for block_key {} to match absence in missing_blocks.'\
.format(six.text_type(block_key))
# Verify children
if block_key not in missing_blocks:
self.assertEqual(
set(block_structure.get_children(self.block_key_factory(block_key))),
set(self.block_key_factory(child) for child in children),
)
assert set(block_structure.get_children(self.block_key_factory(block_key))) ==\
set((self.block_key_factory(child) for child in children))
# Verify parents
parents_map = self.get_parents_map(children_map)
for block_key, parents in enumerate(parents_map):
if block_key not in missing_blocks:
self.assertEqual(
set(block_structure.get_parents(self.block_key_factory(block_key))),
set(self.block_key_factory(parent) for parent in parents),
)
assert set(block_structure.get_parents(self.block_key_factory(block_key))) ==\
set((self.block_key_factory(parent) for parent in parents))
class UsageKeyFactoryMixin(object):

View File

@@ -46,8 +46,8 @@ class TestBlockStructure(TestCase, ChildrenMapTestMixin):
# __contains__
for node in range(len(children_map)):
self.assertIn(node, block_structure)
self.assertNotIn(len(children_map) + 1, block_structure)
assert node in block_structure
assert (len(children_map) + 1) not in block_structure
@ddt.ddt
@@ -107,21 +107,12 @@ class TestBlockStructureData(TestCase, ChildrenMapTestMixin):
# verify transformer data
for t_info in transformers_info:
self.assertEqual(
block_structure._get_transformer_data_version(t_info.transformer),
MockTransformer.WRITE_VERSION
)
assert block_structure._get_transformer_data_version(t_info.transformer) == MockTransformer.WRITE_VERSION
for key, val in t_info.structure_wide_data:
self.assertEqual(
block_structure.get_transformer_data(t_info.transformer, key),
val,
)
assert block_structure.get_transformer_data(t_info.transformer, key) == val
for block, block_data in six.iteritems(t_info.block_specific_data):
for key, val in block_data:
self.assertEqual(
block_structure.get_transformer_block_field(block, t_info.transformer, key),
val,
)
assert block_structure.get_transformer_block_field(block, t_info.transformer, key) == val
def test_xblock_data(self):
# block test cases
@@ -147,7 +138,7 @@ class TestBlockStructureData(TestCase, ChildrenMapTestMixin):
for block in blocks:
bs_block = block_structure[block.location]
for field in fields:
self.assertIsNone(getattr(bs_block, field, None))
assert getattr(bs_block, field, None) is None
# collect fields
block_structure._collect_requested_xblock_fields()
@@ -156,10 +147,7 @@ class TestBlockStructureData(TestCase, ChildrenMapTestMixin):
for block in blocks:
bs_block = block_structure[block.location]
for field in fields:
self.assertEqual(
getattr(bs_block, field, None),
block.field_map.get(field),
)
assert getattr(bs_block, field, None) == block.field_map.get(field)
def test_xblock_field_override(self):
# block field override test cases
@@ -185,20 +173,14 @@ class TestBlockStructureData(TestCase, ChildrenMapTestMixin):
# verify values of collected fields
bs_block = block_structure[block.location]
for field in fields:
self.assertEqual(
getattr(bs_block, field, None),
block.field_map.get(field),
)
assert getattr(bs_block, field, None) == block.field_map.get(field)
block_structure.override_xblock_field(
block.location,
"due",
override_due_date
)
self.assertEqual(
block_structure.get_xblock_field(block.location, "due", None),
override_due_date
)
assert block_structure.get_xblock_field(block.location, 'due', None) == override_due_date
@ddt.data(
*itertools.product(
@@ -288,12 +270,12 @@ class TestBlockStructureData(TestCase, ChildrenMapTestMixin):
# create a new copy of the structure and verify they are equivalent
new_copy = block_structure.copy()
self.assertEqual(block_structure.root_block_usage_key, new_copy.root_block_usage_key)
assert block_structure.root_block_usage_key == new_copy.root_block_usage_key
for block in block_structure:
self.assertIn(block, new_copy)
self.assertEqual(block_structure.get_parents(block), new_copy.get_parents(block))
self.assertEqual(block_structure.get_children(block), new_copy.get_children(block))
self.assertEqual(_get_value(block_structure), _get_value(new_copy))
assert block in new_copy
assert block_structure.get_parents(block) == new_copy.get_parents(block)
assert block_structure.get_children(block) == new_copy.get_children(block)
assert _get_value(block_structure) == _get_value(new_copy)
# verify edits to original block structure do not affect the copy
block_structure.remove_block(2, keep_descendants=True)
@@ -301,8 +283,8 @@ class TestBlockStructureData(TestCase, ChildrenMapTestMixin):
self.assert_block_structure(new_copy, [[1], [2], [3], []])
_set_value(block_structure, 'edit1')
self.assertEqual(_get_value(block_structure), 'edit1')
self.assertEqual(_get_value(new_copy), 'original_value')
assert _get_value(block_structure) == 'edit1'
assert _get_value(new_copy) == 'original_value'
# verify edits to copy do not affect the original
new_copy.remove_block(3, keep_descendants=True)
@@ -310,5 +292,5 @@ class TestBlockStructureData(TestCase, ChildrenMapTestMixin):
self.assert_block_structure(new_copy, [[1], [2], [], []], missing_blocks=[3])
_set_value(new_copy, 'edit2')
self.assertEqual(_get_value(block_structure), 'edit1')
self.assertEqual(_get_value(new_copy), 'edit2')
assert _get_value(block_structure) == 'edit1'
assert _get_value(new_copy) == 'edit2'

View File

@@ -2,7 +2,7 @@
Tests for block_structure_factory.py
"""
import pytest
from django.test import TestCase
from xmodule.modulestore.exceptions import ItemNotFoundError
@@ -30,7 +30,7 @@ class TestBlockStructureFactory(TestCase, ChildrenMapTestMixin):
self.assert_block_structure(block_structure, self.children_map)
def test_from_modulestore_fail(self):
with self.assertRaises(ItemNotFoundError):
with pytest.raises(ItemNotFoundError):
BlockStructureFactory.create_from_modulestore(
root_block_usage_key=len(self.children_map) + 1,
modulestore=self.modulestore,
@@ -48,7 +48,7 @@ class TestBlockStructureFactory(TestCase, ChildrenMapTestMixin):
def test_from_cache_none(self):
store = BlockStructureStore(MockCache())
with self.assertRaises(BlockStructureNotFound):
with pytest.raises(BlockStructureNotFound):
BlockStructureFactory.create_from_store(
root_block_usage_key=0,
block_structure_store=store,

View File

@@ -2,7 +2,7 @@
Tests for manager.py
"""
import pytest
import ddt
import six
from django.test import TestCase
@@ -126,7 +126,7 @@ class TestBlockStructureManager(UsageKeyFactoryMixin, ChildrenMapTestMixin, Test
self.assert_block_structure(block_structure, self.children_map)
TestTransformer1.assert_collected(block_structure)
if expect_modulestore_called:
self.assertGreater(self.modulestore.get_items_call_count, 0)
assert self.modulestore.get_items_call_count > 0
else:
assert self.modulestore.get_items_call_count == 0
expected_count = 1 if expect_cache_updated else 0
@@ -170,7 +170,7 @@ class TestBlockStructureManager(UsageKeyFactoryMixin, ChildrenMapTestMixin, Test
def test_get_transformed_with_nonexistent_starting_block(self):
with mock_registered_transformers(self.registered_transformers):
with self.assertRaises(UsageKeyNotInBlockStructure):
with pytest.raises(UsageKeyNotInBlockStructure):
self.bs_manager.get_transformed(self.transformers, starting_block_usage_key=100)
def test_get_collected_cached(self):
@@ -181,7 +181,7 @@ class TestBlockStructureManager(UsageKeyFactoryMixin, ChildrenMapTestMixin, Test
def test_get_collected_error_raised(self):
with override_waffle_switch(RAISE_ERROR_WHEN_NOT_FOUND, active=True):
with mock_registered_transformers(self.registered_transformers):
with self.assertRaises(BlockStructureNotFound):
with pytest.raises(BlockStructureNotFound):
self.bs_manager.get_collected()
@ddt.data(True, False)

View File

@@ -3,7 +3,7 @@ Unit tests for Block Structure models.
"""
# pylint: disable=protected-access
import pytest
import errno
from itertools import product
from uuid import uuid4
@@ -44,17 +44,17 @@ class BlockStructureModelTestCase(TestCase):
on the given bsm are as expected.
"""
for field_name, field_value in six.iteritems(self.params):
self.assertEqual(field_value, getattr(bsm, field_name))
assert field_value == getattr(bsm, field_name)
self.assertEqual(bsm.get_serialized_data().decode('utf-8'), expected_serialized_data)
self.assertIn(_directory_name(self.usage_key), bsm.data.name)
assert bsm.get_serialized_data().decode('utf-8') == expected_serialized_data
assert _directory_name(self.usage_key) in bsm.data.name
def _assert_file_count_equal(self, expected_count):
"""
Asserts the number of files for self.usage_key
is as expected.
"""
self.assertEqual(len(BlockStructureModel._get_all_files(self.usage_key)), expected_count)
assert len(BlockStructureModel._get_all_files(self.usage_key)) == expected_count
def _create_bsm_params(self):
"""
@@ -75,11 +75,11 @@ class BlockStructureModelTestCase(TestCase):
"""
bsm, created = BlockStructureModel.update_or_create(serialized_data, **self.params)
if mock_log:
self.assertEqual("Created" if expect_created else "Updated", mock_log.info.call_args[0][1])
self.assertEqual(len(serialized_data), mock_log.info.call_args[0][6])
assert ('Created' if expect_created else 'Updated') == mock_log.info.call_args[0][1]
assert len(serialized_data) == mock_log.info.call_args[0][6]
self._assert_bsm_fields(bsm, serialized_data)
if expect_created is not None:
self.assertEqual(created, expect_created)
assert created == expect_created
return bsm
@patch('openedx.core.djangoapps.content.block_structure.models.log')
@@ -88,9 +88,9 @@ class BlockStructureModelTestCase(TestCase):
serialized_data = 'initial data'
# shouldn't already exist
with self.assertRaises(BlockStructureNotFound):
with pytest.raises(BlockStructureNotFound):
BlockStructureModel.get(self.usage_key)
self.assertIn("BlockStructure: Not found in table;", mock_log.info.call_args[0][0])
assert 'BlockStructure: Not found in table;' in mock_log.info.call_args[0][0]
# create an entry
bsm = self._verify_update_or_create_call(serialized_data, mock_log, expect_created=True)
@@ -98,13 +98,13 @@ class BlockStructureModelTestCase(TestCase):
# get entry
found_bsm = BlockStructureModel.get(self.usage_key)
self._assert_bsm_fields(found_bsm, serialized_data)
self.assertIn("Read", mock_log.info.call_args[0][1])
assert 'Read' in mock_log.info.call_args[0][1]
# update entry
self.params.update(dict(data_version='new version'))
updated_serialized_data = 'updated data'
updated_bsm = self._verify_update_or_create_call(updated_serialized_data, mock_log, expect_created=False)
self.assertNotEqual(bsm.data.name, updated_bsm.data.name)
assert bsm.data.name != updated_bsm.data.name
# old files not pruned
self._assert_file_count_equal(2)
@@ -123,7 +123,7 @@ class BlockStructureModelTestCase(TestCase):
self._verify_update_or_create_call('test data', expect_created=True)
self._verify_update_or_create_call('updated data', expect_created=False)
self.assertIn('BlockStructure: Exception when deleting old files', mock_log.exception.call_args[0][0])
assert 'BlockStructure: Exception when deleting old files' in mock_log.exception.call_args[0][0]
self._assert_file_count_equal(2) # old files not pruned
@ddt.data(
@@ -159,7 +159,7 @@ class BlockStructureModelTestCase(TestCase):
def test_error_handling(self, error_raised_in_operation, errno_raised, message_raised,
expected_error_raised, is_read_operation):
bs_model, _ = BlockStructureModel.update_or_create('test data', **self.params)
with self.assertRaises(expected_error_raised):
with pytest.raises(expected_error_raised):
with _storage_error_handling(bs_model, 'operation', is_read_operation):
if errno_raised is not None: # lint-amnesty, pylint: disable=no-else-raise
raise error_raised_in_operation(errno_raised, message_raised)

View File

@@ -2,7 +2,7 @@
Unit tests for the Course Blocks signals
"""
import pytest
import ddt
from edx_toggles.toggles.testutils import override_waffle_switch
from mock import patch
@@ -35,21 +35,15 @@ class CourseBlocksSignalTest(ModuleStoreTestCase):
# Course exists in cache initially
bs_manager = get_block_structure_manager(self.course.id)
orig_block_structure = bs_manager.get_collected()
self.assertTrue(is_course_in_block_structure_cache(self.course.id, self.store))
self.assertNotEqual(
test_display_name,
orig_block_structure.get_xblock_field(self.course_usage_key, 'display_name')
)
assert is_course_in_block_structure_cache(self.course.id, self.store)
assert test_display_name != orig_block_structure.get_xblock_field(self.course_usage_key, 'display_name')
self.course.display_name = test_display_name
self.store.update_item(self.course, self.user.id)
# Cached version of course has been updated
updated_block_structure = bs_manager.get_collected()
self.assertEqual(
test_display_name,
updated_block_structure.get_xblock_field(self.course_usage_key, 'display_name')
)
assert test_display_name == updated_block_structure.get_xblock_field(self.course_usage_key, 'display_name')
@ddt.data(True, False)
@patch('openedx.core.djangoapps.content.block_structure.manager.BlockStructureManager.clear')
@@ -60,18 +54,18 @@ class CourseBlocksSignalTest(ModuleStoreTestCase):
self.course.display_name = test_display_name
self.store.update_item(self.course, self.user.id)
self.assertEqual(mock_bs_manager_clear.called, invalidate_cache_enabled)
assert mock_bs_manager_clear.called == invalidate_cache_enabled
def test_course_delete(self):
bs_manager = get_block_structure_manager(self.course.id)
self.assertIsNotNone(bs_manager.get_collected())
self.assertTrue(is_course_in_block_structure_cache(self.course.id, self.store))
assert bs_manager.get_collected() is not None
assert is_course_in_block_structure_cache(self.course.id, self.store)
self.store.delete_course(self.course.id, self.user.id)
with self.assertRaises(ItemNotFoundError):
with pytest.raises(ItemNotFoundError):
bs_manager.get_collected()
self.assertFalse(is_course_in_block_structure_cache(self.course.id, self.store))
assert not is_course_in_block_structure_cache(self.course.id, self.store)
@ddt.data(
(CourseLocator(org='org', course='course', run='run'), True),
@@ -81,4 +75,4 @@ class CourseBlocksSignalTest(ModuleStoreTestCase):
@patch('openedx.core.djangoapps.content.block_structure.tasks.update_course_in_cache_v2.apply_async')
def test_update_only_for_courses(self, key, expect_update_called, mock_update):
update_block_structure_on_course_publish(sender=None, course_key=key)
self.assertEqual(mock_update.called, expect_update_called)
assert mock_update.called == expect_update_called

View File

@@ -2,7 +2,7 @@
Tests for block_structure/cache.py
"""
import pytest
import ddt
from edx_toggles.toggles.testutils import override_waffle_switch
@@ -49,7 +49,7 @@ class TestBlockStructureStore(UsageKeyFactoryMixin, ChildrenMapTestMixin, CacheI
@ddt.data(True, False)
def test_get_none(self, with_storage_backing):
with override_waffle_switch(STORAGE_BACKING_FOR_CACHE, active=with_storage_backing):
with self.assertRaises(BlockStructureNotFound):
with pytest.raises(BlockStructureNotFound):
self.store.get(self.block_structure.root_block_usage_key)
@ddt.data(True, False)
@@ -57,7 +57,7 @@ class TestBlockStructureStore(UsageKeyFactoryMixin, ChildrenMapTestMixin, CacheI
with override_waffle_switch(STORAGE_BACKING_FOR_CACHE, active=with_storage_backing):
self.store.add(self.block_structure)
stored_value = self.store.get(self.block_structure.root_block_usage_key)
self.assertIsNotNone(stored_value)
assert stored_value is not None
self.assert_block_structure(stored_value, self.children_map)
@ddt.data(True, False)
@@ -65,13 +65,13 @@ class TestBlockStructureStore(UsageKeyFactoryMixin, ChildrenMapTestMixin, CacheI
with override_waffle_switch(STORAGE_BACKING_FOR_CACHE, active=with_storage_backing):
self.store.add(self.block_structure)
self.store.delete(self.block_structure.root_block_usage_key)
with self.assertRaises(BlockStructureNotFound):
with pytest.raises(BlockStructureNotFound):
self.store.get(self.block_structure.root_block_usage_key)
def test_uncached_without_storage(self):
self.store.add(self.block_structure)
self.mock_cache.map.clear()
with self.assertRaises(BlockStructureNotFound):
with pytest.raises(BlockStructureNotFound):
self.store.get(self.block_structure.root_block_usage_key)
def test_uncached_with_storage(self):

View File

@@ -22,4 +22,4 @@ class UpdateCourseInCacheTaskTest(ModuleStoreTestCase):
"""
mock_update.side_effect = Exception("WHAMMY")
update_course_in_cache_v2.apply(kwargs=dict(course_id="invalid_course_key raises exception 12345 meow"))
self.assertTrue(mock_retry.called)
assert mock_retry.called

View File

@@ -71,13 +71,13 @@ class TransformerRegistryTestCase(TestCase):
# hash with TestTransformer1
with mock_registered_transformers([TestTransformer1]):
version_hash_1 = TransformerRegistry.get_write_version_hash()
self.assertEqual(version_hash_1, '+2nc5o2YRerVfAtItQBQ/6jVkkw=')
assert version_hash_1 == '+2nc5o2YRerVfAtItQBQ/6jVkkw='
# should return the same value again
self.assertEqual(version_hash_1, TransformerRegistry.get_write_version_hash())
assert version_hash_1 == TransformerRegistry.get_write_version_hash()
# hash with TestTransformer1 and TestTransformer2
with mock_registered_transformers([TestTransformer1, TestTransformer2]):
version_hash_2 = TransformerRegistry.get_write_version_hash()
self.assertEqual(version_hash_2, '5GwhvmSM9hknjUslzPnKDA5QaCo=')
self.assertNotEqual(version_hash_1, version_hash_2)
assert version_hash_2 == '5GwhvmSM9hknjUslzPnKDA5QaCo='
assert version_hash_1 != version_hash_2

View File

@@ -2,7 +2,7 @@
Tests for transformers.py
"""
import pytest
from unittest import TestCase
from mock import MagicMock, patch
@@ -38,21 +38,15 @@ class TestBlockStructureTransformers(ChildrenMapTestMixin, TestCase):
def test_add_registered(self):
self.add_mock_transformer()
self.assertIn(
self.registered_transformers[0],
self.transformers._transformers['no_filter'] # pylint: disable=protected-access
)
self.assertIn(
self.registered_transformers[1],
self.transformers._transformers['supports_filter'] # pylint: disable=protected-access
)
assert self.registered_transformers[0] in self.transformers._transformers['no_filter'] # pylint: disable=protected-access, line-too-long
assert self.registered_transformers[1] in self.transformers._transformers['supports_filter'] # pylint: disable=protected-access, line-too-long
def test_add_unregistered(self):
with self.assertRaises(TransformerException):
with pytest.raises(TransformerException):
self.transformers += [self.UnregisteredTransformer()]
self.assertEqual(self.transformers._transformers['no_filter'], []) # pylint: disable=protected-access
self.assertEqual(self.transformers._transformers['supports_filter'], []) # pylint: disable=protected-access
assert self.transformers._transformers['no_filter'] == [] # pylint: disable=protected-access
assert self.transformers._transformers['supports_filter'] == [] # pylint: disable=protected-access
def test_collect(self):
with mock_registered_transformers(self.registered_transformers):
@@ -60,7 +54,7 @@ class TestBlockStructureTransformers(ChildrenMapTestMixin, TestCase):
'openedx.core.djangoapps.content.block_structure.tests.helpers.MockTransformer.collect'
) as mock_collect_call:
BlockStructureTransformers.collect(block_structure=MagicMock())
self.assertTrue(mock_collect_call.called)
assert mock_collect_call.called
def test_transform(self):
self.add_mock_transformer()
@@ -69,7 +63,7 @@ class TestBlockStructureTransformers(ChildrenMapTestMixin, TestCase):
'openedx.core.djangoapps.content.block_structure.tests.helpers.MockTransformer.transform'
) as mock_transform_call:
self.transformers.transform(block_structure=MagicMock())
self.assertTrue(mock_transform_call.called)
assert mock_transform_call.called
def test_verify_versions(self):
block_structure = self.create_block_structure(
@@ -78,7 +72,7 @@ class TestBlockStructureTransformers(ChildrenMapTestMixin, TestCase):
)
with mock_registered_transformers(self.registered_transformers):
with self.assertRaises(TransformerDataIncompatible):
with pytest.raises(TransformerDataIncompatible):
self.transformers.verify_versions(block_structure)
self.transformers.collect(block_structure)
self.assertTrue(self.transformers.verify_versions(block_structure))
assert self.transformers.verify_versions(block_structure)

View File

@@ -2,7 +2,7 @@
Tests that the generate_course_overview management command actually generates course overviews.
"""
import pytest
import six
from django.core.management.base import CommandError
from mock import patch
@@ -33,7 +33,7 @@ class TestGenerateCourseOverview(ModuleStoreTestCase):
"""
course_keys = CourseOverview.get_all_course_keys()
for expected_course_key in courses:
self.assertNotIn(expected_course_key, course_keys)
assert expected_course_key not in course_keys
def _assert_courses_in_overview(self, *courses):
"""
@@ -41,7 +41,7 @@ class TestGenerateCourseOverview(ModuleStoreTestCase):
"""
course_keys = CourseOverview.get_all_course_keys()
for expected_course_key in courses:
self.assertIn(expected_course_key, course_keys)
assert expected_course_key in course_keys
def test_generate_all(self):
"""
@@ -77,14 +77,14 @@ class TestGenerateCourseOverview(ModuleStoreTestCase):
self.command.handle(six.text_type(self.course_key_1), all_courses=False, force_update=True)
self.command.handle(six.text_type(self.course_key_2), all_courses=False, force_update=False)
self.assertEqual(CourseOverview.get_from_id(self.course_key_1).display_name, updated_course_name)
self.assertNotEqual(CourseOverview.get_from_id(self.course_key_2).display_name, updated_course_name)
assert CourseOverview.get_from_id(self.course_key_1).display_name == updated_course_name
assert CourseOverview.get_from_id(self.course_key_2).display_name != updated_course_name
def test_invalid_key(self):
"""
Test that CommandError is raised for invalid key.
"""
with self.assertRaises(CommandError):
with pytest.raises(CommandError):
self.command.handle('not/found', all_courses=False)
@patch('openedx.core.djangoapps.content.course_overviews.models.log')
@@ -93,13 +93,13 @@ class TestGenerateCourseOverview(ModuleStoreTestCase):
Test keys not found are logged.
"""
self.command.handle('fake/course/id', all_courses=False)
self.assertTrue(mock_log.exception.called)
assert mock_log.exception.called
def test_no_params(self):
"""
Test exception raised when no parameters are specified.
"""
with self.assertRaises(CommandError):
with pytest.raises(CommandError):
self.command.handle(all_courses=False)
@patch('openedx.core.djangoapps.content.course_overviews.tasks.async_course_overview_update')
@@ -107,13 +107,7 @@ class TestGenerateCourseOverview(ModuleStoreTestCase):
self.command.handle(all_courses=True, force_update=True, routing_key='my-routing-key', chunk_size=10000)
called_kwargs = mock_async_task.apply_async.call_args_list[0][1]
self.assertEqual(
sorted([six.text_type(self.course_key_1), six.text_type(self.course_key_2)]),
sorted(called_kwargs.pop('args'))
)
self.assertEqual({
'kwargs': {'force_update': True},
'routing_key': 'my-routing-key'
}, called_kwargs
)
self.assertEqual(1, mock_async_task.apply_async.call_count)
assert sorted([six.text_type(self.course_key_1), six.text_type(self.course_key_2)]) ==\
sorted(called_kwargs.pop('args'))
assert {'kwargs': {'force_update': True}, 'routing_key': 'my-routing-key'} == called_kwargs
assert 1 == mock_async_task.apply_async.call_count

View File

@@ -115,10 +115,10 @@ class TestSimulatePublish(SharedModuleStoreTestCase):
courses=[six.text_type(self.course_key_1), six.text_type(self.course_key_2)]
)
)
self.assertIn(self.course_key_1, self.received_1)
self.assertIn(self.course_key_2, self.received_1)
self.assertNotIn(self.course_key_3, self.received_1)
self.assertEqual(self.received_1, self.received_2)
assert self.course_key_1 in self.received_1
assert self.course_key_2 in self.received_1
assert self.course_key_3 not in self.received_1
assert self.received_1 == self.received_2
def test_specific_receivers(self):
"""Test sending only to specific receivers."""
@@ -127,14 +127,14 @@ class TestSimulatePublish(SharedModuleStoreTestCase):
receivers=[name_from_fn(self.sample_receiver_1)]
)
)
self.assertIn(self.course_key_1, self.received_1)
self.assertIn(self.course_key_2, self.received_1)
self.assertIn(self.course_key_3, self.received_1)
self.assertEqual(self.received_2, [])
assert self.course_key_1 in self.received_1
assert self.course_key_2 in self.received_1
assert self.course_key_3 in self.received_1
assert self.received_2 == []
def test_course_overviews(self):
"""Integration test with CourseOverviews."""
self.assertEqual(CourseOverview.objects.all().count(), 0)
assert CourseOverview.objects.all().count() == 0
# pylint: disable=protected-access
self.command.handle(
**self.options(
@@ -143,9 +143,9 @@ class TestSimulatePublish(SharedModuleStoreTestCase):
]
)
)
self.assertEqual(CourseOverview.objects.all().count(), 3)
self.assertEqual(self.received_1, [])
self.assertEqual(self.received_2, [])
assert CourseOverview.objects.all().count() == 3
assert self.received_1 == []
assert self.received_2 == []
def sample_receiver_1(self, sender, course_key, **kwargs): # pylint: disable=unused-argument
"""Custom receiver for testing."""

View File

@@ -2,7 +2,7 @@
Tests for course_overviews app.
"""
import pytest
import datetime
import itertools
import math
@@ -135,8 +135,8 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
course_value = getattr(course, attribute_name)
cache_miss_value = getattr(course_overview_cache_miss, attribute_name)
cache_hit_value = getattr(course_overview_cache_hit, attribute_name)
self.assertEqual(course_value, cache_miss_value)
self.assertEqual(cache_miss_value, cache_hit_value)
assert course_value == cache_miss_value
assert cache_miss_value == cache_hit_value
# Test if return values for all methods are equal between the three objects
methods_to_test = [
@@ -150,8 +150,8 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
course_value = getattr(course, method_name)(*method_args)
cache_miss_value = getattr(course_overview_cache_miss, method_name)(*method_args)
cache_hit_value = getattr(course_overview_cache_hit, method_name)(*method_args)
self.assertEqual(course_value, cache_miss_value)
self.assertEqual(cache_miss_value, cache_hit_value)
assert course_value == cache_miss_value
assert cache_miss_value == cache_hit_value
# Other values to test
@@ -197,14 +197,14 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
course_value = course_accessor(course, attribute_name)
cache_miss_value = course_overview_accessor(course_overview_cache_miss, attribute_name)
cache_hit_value = course_overview_accessor(course_overview_cache_hit, attribute_name)
self.assertEqual(course_value, cache_miss_value)
self.assertEqual(cache_miss_value, cache_hit_value)
assert course_value == cache_miss_value
assert cache_miss_value == cache_hit_value
# test tabs for both cached miss and cached hit courses
for course_overview in [course_overview_cache_miss, course_overview_cache_hit]:
course_overview_tabs = course_overview.tab_set.all()
course_resp_tabs = {tab.tab_id for tab in course_overview_tabs}
self.assertEqual(self.COURSE_OVERVIEW_TABS, course_resp_tabs)
assert self.COURSE_OVERVIEW_TABS == course_resp_tabs
@ddt.data(*itertools.product(
[
@@ -290,9 +290,9 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
course_overview = CourseOverview.get_from_id(course.id)
if catalog_integration_enabled:
self.assertNotEqual(course_overview.language, course.language)
assert course_overview.language != course.language
else:
self.assertEqual(course_overview.language, course.language)
assert course_overview.language == course.language
@ddt.data(
('fa', 'fa-ir', 'fa'),
@@ -307,7 +307,7 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
def test_closest_released_language(self, released_languages, course_language, expected_language):
DarkLangConfig(released_languages=released_languages, enabled=True, changed_by=self.user).save()
course_overview = CourseOverviewFactory.create(language=course_language)
self.assertEqual(course_overview.closest_released_language, expected_language)
assert course_overview.closest_released_language == expected_language
@ddt.data(ModuleStoreEnum.Type.split, ModuleStoreEnum.Type.mongo)
def test_get_non_existent_course(self, modulestore_type):
@@ -320,7 +320,7 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
course in.
"""
store = modulestore()._get_modulestore_by_type(modulestore_type) # pylint: disable=protected-access
with self.assertRaises(CourseOverview.DoesNotExist):
with pytest.raises(CourseOverview.DoesNotExist):
CourseOverview.get_from_id(store.make_course_key('Non', 'Existent', 'Course'))
@ddt.data(ModuleStoreEnum.Type.split, ModuleStoreEnum.Type.mongo)
@@ -331,8 +331,8 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
"""
course = CourseFactory.create(default_store=modulestore_type)
CourseOverview.get_from_id(course.id) # Ensure course in cached in CourseOverviews
self.assertTrue(CourseOverview.objects.filter(id=course.id).exists())
self.assertTrue(CourseOverview.course_exists(course.id))
assert CourseOverview.objects.filter(id=course.id).exists()
assert CourseOverview.course_exists(course.id)
@ddt.data(ModuleStoreEnum.Type.split, ModuleStoreEnum.Type.mongo)
def test_course_without_overview_exists(self, modulestore_type):
@@ -342,8 +342,8 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
"""
course = CourseFactory.create(default_store=modulestore_type)
CourseOverview.objects.filter(id=course.id).delete()
self.assertTrue(CourseOverview.course_exists(course.id))
self.assertFalse(CourseOverview.objects.filter(id=course.id).exists())
assert CourseOverview.course_exists(course.id)
assert not CourseOverview.objects.filter(id=course.id).exists()
@ddt.data(ModuleStoreEnum.Type.split, ModuleStoreEnum.Type.mongo)
def test_nonexistent_course_does_not_exists(self, modulestore_type):
@@ -352,7 +352,7 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
"""
store = modulestore()._get_modulestore_by_type(modulestore_type) # pylint: disable=protected-access
course_id = store.make_course_key('Non', 'Existent', 'Course')
self.assertFalse(CourseOverview.course_exists(course_id))
assert not CourseOverview.course_exists(course_id)
def test_get_errored_course(self):
"""
@@ -364,7 +364,7 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
# This mock makes it so when the module store tries to load course data,
# an exception is thrown, which causes get_course to return an ErrorBlock,
# which causes get_from_id to raise an IOError.
with self.assertRaises(IOError):
with pytest.raises(IOError):
CourseOverview.load_from_module_store(self.store.make_course_key('Non', 'Existent', 'Course'))
def test_malformed_grading_policy(self):
@@ -377,10 +377,10 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
"""
course = CourseFactory.create()
course._grading_policy['GRADE_CUTOFFS'] = {} # pylint: disable=protected-access
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
__ = course.lowest_passing_grade
course_overview = CourseOverview._create_or_update(course) # pylint: disable=protected-access
self.assertEqual(course_overview.lowest_passing_grade, None)
assert course_overview.lowest_passing_grade is None
@ddt.data((ModuleStoreEnum.Type.mongo, 4, 4), (ModuleStoreEnum.Type.split, 3, 3))
@ddt.unpack
@@ -447,7 +447,7 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
# Verify the CourseOverview is loaded successfully both times,
# including after an IntegrityError exception the 2nd time.
for _ in range(2):
self.assertIsInstance(CourseOverview.get_from_id(course.id), CourseOverview)
assert isinstance(CourseOverview.get_from_id(course.id), CourseOverview)
def test_course_overview_version_update(self):
"""
@@ -460,7 +460,7 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
with mock.patch('openedx.core.djangoapps.content.course_overviews.models.CourseOverview.VERSION', new=10):
# This will create a version 10 CourseOverview
overview_v10 = CourseOverview.get_from_id(course.id)
self.assertEqual(overview_v10.version, 10)
assert overview_v10.version == 10
# Now we're going to muck with the values and manually save it as v09
overview_v10.version = 9
@@ -470,7 +470,7 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
# that this entry will be deleted() and that we'll get back a new
# entry with version = 10 again.
updated_overview = CourseOverview.get_from_id(course.id)
self.assertEqual(updated_overview.version, 10)
assert updated_overview.version == 10
# Now we're going to muck with this and set it a version higher in
# the database.
@@ -480,7 +480,7 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
# Because CourseOverview is encountering a version *higher* than it
# knows how to write, it's not going to overwrite what's there.
unmodified_overview = CourseOverview.get_from_id(course.id)
self.assertEqual(unmodified_overview.version, 11)
assert unmodified_overview.version == 11
def test_update_select_courses(self):
course_ids = [CourseFactory.create().id for __ in range(3)]
@@ -489,20 +489,17 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
'openedx.core.djangoapps.content.course_overviews.models.CourseOverview.get_from_id'
) as mock_get_from_id:
CourseOverview.update_select_courses(select_course_ids)
self.assertEqual(mock_get_from_id.call_count, len(select_course_ids))
assert mock_get_from_id.call_count == len(select_course_ids)
def test_get_all_courses(self):
course_ids = [CourseFactory.create(emit_signals=True).id for __ in range(3)]
self.assertEqual(
{course_overview.id for course_overview in CourseOverview.get_all_courses()},
set(course_ids),
)
assert {course_overview.id for course_overview in CourseOverview.get_all_courses()} == set(course_ids)
with mock.patch(
'openedx.core.djangoapps.content.course_overviews.models.CourseOverview.get_from_id'
) as mock_get_from_id:
CourseOverview.get_all_courses()
self.assertFalse(mock_get_from_id.called)
assert not mock_get_from_id.called
def test_get_all_courses_by_org(self):
org_courses = [] # list of lists of courses
@@ -512,21 +509,15 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
for __ in range(3)
])
self.assertEqual(
{c.id for c in CourseOverview.get_all_courses()},
{c.id for c in org_courses[0] + org_courses[1] + org_courses[2]},
)
assert {c.id for c in CourseOverview.get_all_courses()} ==\
{c.id for c in org_courses[0] + org_courses[1] + org_courses[2]}
self.assertEqual(
{c.id for c in CourseOverview.get_all_courses(orgs=['test_org_1', 'test_org_2'])},
{c.id for c in org_courses[1] + org_courses[2]},
)
assert {c.id for c in CourseOverview.get_all_courses(orgs=['test_org_1', 'test_org_2'])} ==\
{c.id for c in org_courses[1] + org_courses[2]}
# Test case-insensitivity.
self.assertEqual(
{c.id for c in CourseOverview.get_all_courses(orgs=['TEST_ORG_1', 'TEST_ORG_2'])},
{c.id for c in org_courses[1] + org_courses[2]},
)
assert {c.id for c in CourseOverview.get_all_courses(orgs=['TEST_ORG_1', 'TEST_ORG_2'])} ==\
{c.id for c in org_courses[1] + org_courses[2]}
def test_get_all_courses_by_mobile_available(self):
mobile_course = CourseFactory.create(emit_signals=True)
@@ -540,16 +531,8 @@ class CourseOverviewTestCase(CatalogIntegrationMixin, ModuleStoreTestCase, Cache
)
for filter_, expected_courses in test_cases:
self.assertEqual(
{
course_overview.id
for course_overview in
CourseOverview.get_all_courses(filter_=filter_)
},
expected_courses,
u"testing CourseOverview.get_all_courses with filter_={}"
.format(filter_),
)
assert {course_overview.id for course_overview in CourseOverview.get_all_courses(filter_=filter_)} ==\
expected_courses, u'testing CourseOverview.get_all_courses with filter_={}'.format(filter_)
def test_get_from_ids(self):
"""
@@ -661,7 +644,7 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
# Even though there was no source image to generate, we should still
# have a CourseOverviewImageSet object associated with this overview.
self.assertTrue(hasattr(course_overview, 'image_set'))
assert hasattr(course_overview, 'image_set')
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_disabled_no_prior_data(self, modulestore_type):
@@ -680,7 +663,7 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
course_overview = self._assert_image_urls_all_default(modulestore_type, fake_course_image)
# Because we are disabled, no image set should have been generated.
self.assertFalse(hasattr(course_overview, 'image_set'))
assert not hasattr(course_overview, 'image_set')
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_disabled_with_prior_data(self, modulestore_type):
@@ -706,7 +689,7 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
course_overview_before = CourseOverview.get_from_id(course.id)
# This initial seeding should create an entry for the image_set.
self.assertTrue(hasattr(course_overview_before, 'image_set'))
assert hasattr(course_overview_before, 'image_set')
# Now just throw in some fake data to this image set, something that
# couldn't possibly work.
@@ -721,22 +704,15 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
course_overview_after = CourseOverview.get_from_id(course.id)
# Assert that the data still exists for debugging purposes
self.assertTrue(hasattr(course_overview_after, 'image_set'))
assert hasattr(course_overview_after, 'image_set')
image_set = course_overview_after.image_set
self.assertEqual(image_set.small_url, broken_small_url)
self.assertEqual(image_set.large_url, broken_large_url)
assert image_set.small_url == broken_small_url
assert image_set.large_url == broken_large_url
# But because we've disabled it, asking for image_urls should give us
# the raw source image for all resolutions, and not our broken images.
expected_url = course_image_url(course)
self.assertEqual(
course_overview_after.image_urls,
{
'raw': expected_url,
'small': expected_url,
'large': expected_url
}
)
assert course_overview_after.image_urls == {'raw': expected_url, 'small': expected_url, 'large': expected_url}
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_cdn(self, modulestore_type):
@@ -755,14 +731,14 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
expected_path_start = "/asset-v1:"
for url in overview.image_urls.values():
self.assertTrue(url.startswith(expected_path_start))
assert url.startswith(expected_path_start)
# Now enable the CDN...
AssetBaseUrlConfig.objects.create(enabled=True, base_url='fakecdn.edx.org')
expected_cdn_url = "//fakecdn.edx.org" + expected_path_start
for url in overview.image_urls.values():
self.assertTrue(url.startswith(expected_cdn_url))
assert url.startswith(expected_cdn_url)
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_cdn_with_external_image(self, modulestore_type):
@@ -784,10 +760,10 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
}
modified_urls = overview.apply_cdn_to_urls(start_urls)
self.assertEqual(modified_urls['raw'], start_urls['raw'])
self.assertNotEqual(modified_urls['small'], start_urls['small'])
self.assertTrue(modified_urls['small'].startswith(expected_cdn_url))
self.assertEqual(modified_urls['large'], start_urls['large'])
assert modified_urls['raw'] == start_urls['raw']
assert modified_urls['small'] != start_urls['small']
assert modified_urls['small'].startswith(expected_cdn_url)
assert modified_urls['large'] == start_urls['large']
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_cdn_with_a_single_external_image(self, modulestore_type):
@@ -808,8 +784,8 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
start_url = "/static/overview.png"
modified_url = overview.apply_cdn_to_url(start_url)
self.assertNotEqual(start_url, modified_url)
self.assertTrue(modified_url.startswith(expected_cdn_url))
assert start_url != modified_url
assert modified_url.startswith(expected_cdn_url)
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_error_generating_thumbnails(self, modulestore_type):
@@ -839,9 +815,9 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
# Now an image set does exist, even though it only has blank values for
# the small and large urls.
self.assertTrue(hasattr(course_overview, 'image_set'))
self.assertEqual(course_overview.image_set.small_url, '')
self.assertEqual(course_overview.image_set.large_url, '')
assert hasattr(course_overview, 'image_set')
assert course_overview.image_set.small_url == ''
assert course_overview.image_set.large_url == ''
# The next time we create a CourseOverview, the images are explicitly
# *not* regenerated.
@@ -896,25 +872,25 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
# that, then switch config back over to True and it should lazily
# create the image_set on the next get_from_id() call.
if create_after_overview:
self.assertFalse(hasattr(course_overview, 'image_set'))
assert not hasattr(course_overview, 'image_set')
self.set_config(enabled=True)
course_overview = CourseOverview.get_from_id(course.id)
self.assertTrue(hasattr(course_overview, 'image_set'))
assert hasattr(course_overview, 'image_set')
image_urls = course_overview.image_urls
config = CourseOverviewImageConfig.current()
# Make sure the thumbnail names come out as expected...
self.assertTrue(image_urls['raw'].endswith('big_course_image.jpeg'))
self.assertTrue(image_urls['small'].endswith('big_course_image-jpeg-{}x{}.jpg'.format(*config.small)))
self.assertTrue(image_urls['large'].endswith('big_course_image-jpeg-{}x{}.jpg'.format(*config.large)))
assert image_urls['raw'].endswith('big_course_image.jpeg')
assert image_urls['small'].endswith('big_course_image-jpeg-{}x{}.jpg'.format(*config.small))
assert image_urls['large'].endswith('big_course_image-jpeg-{}x{}.jpg'.format(*config.large))
# Now make sure our thumbnails are of the sizes we expect...
for image_url, expected_size in [(image_urls['small'], config.small), (image_urls['large'], config.large)]:
image_key = StaticContent.get_location_from_path(image_url)
image_content = AssetManager.find(image_key)
image = Image.open(BytesIO(image_content.data))
self.assertEqual(image.size, expected_size)
assert image.size == expected_size
@ddt.data(
(800, 400), # Larger than both, correct ratio
@@ -968,7 +944,7 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
image = Image.open(BytesIO(image_content.data))
# Naming convention for thumbnail
self.assertTrue(image_url.endswith('src_course_image-png-{}x{}.jpg'.format(*target)))
assert image_url.endswith('src_course_image-png-{}x{}.jpg'.format(*target))
# Actual thumbnail data
src_x, src_y = src_dimensions
@@ -979,12 +955,12 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
# the right thing in terms of handling aspect ratio. We're just
# going to make sure that small images aren't blown up, and that
# we never exceed our target sizes
self.assertLessEqual(image_x, target_x)
self.assertLessEqual(image_y, target_y)
assert image_x <= target_x
assert image_y <= target_y
if src_x < target_x and src_y < target_y:
self.assertEqual(src_x, image_x)
self.assertEqual(src_y, image_y)
assert src_x == image_x
assert src_y == image_y
def test_image_creation_race_condition(self):
"""
@@ -1001,7 +977,7 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
# First create our CourseOverview
overview = CourseOverview.get_from_id(course.id)
self.assertFalse(hasattr(overview, 'image_set'))
assert not hasattr(overview, 'image_set')
# Now create an ImageSet by hand...
CourseOverviewImageSet.objects.create(course_overview=overview)
@@ -1010,7 +986,7 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
# thrown and suppressed in create()
self.set_config(True)
CourseOverviewImageSet.create(overview)
self.assertTrue(hasattr(overview, 'image_set'))
assert hasattr(overview, 'image_set')
# The following is actually very important for this test because
# set_config() does a model insert after create_for_course() has caught
@@ -1041,13 +1017,13 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
# Create course overview with image set.
overview = CourseOverview.get_from_id(course.id)
self.assertTrue(hasattr(overview, 'image_set'))
assert hasattr(overview, 'image_set')
# Make sure the thumbnail names come out as expected...
image_urls = overview.image_urls
self.assertTrue(image_urls['raw'].endswith('src_course_image.png'))
self.assertTrue(image_urls['small'].endswith('src_course_image-png-{}x{}.jpg'.format(*config.small)))
self.assertTrue(image_urls['large'].endswith('src_course_image-png-{}x{}.jpg'.format(*config.large)))
assert image_urls['raw'].endswith('src_course_image.png')
assert image_urls['small'].endswith('src_course_image-png-{}x{}.jpg'.format(*config.small))
assert image_urls['large'].endswith('src_course_image-png-{}x{}.jpg'.format(*config.large))
# Update course image on the course descriptor This fires a
# course_published signal, this will be caught in signals.py,
@@ -1060,9 +1036,9 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
# Get latest course overview and make sure the thumbnail names are correctly updated..
image_urls = CourseOverview.objects.get(id=overview.id).image_urls
self.assertTrue(image_urls['raw'].endswith('src_course_image1.png'))
self.assertTrue(image_urls['small'].endswith('src_course_image1-png-{}x{}.jpg'.format(*config.small)))
self.assertTrue(image_urls['large'].endswith('src_course_image1-png-{}x{}.jpg'.format(*config.large)))
assert image_urls['raw'].endswith('src_course_image1.png')
assert image_urls['small'].endswith('src_course_image1-png-{}x{}.jpg'.format(*config.small))
assert image_urls['large'].endswith('src_course_image1-png-{}x{}.jpg'.format(*config.large))
def _assert_image_urls_all_default(self, modulestore_type, raw_course_image_name, expected_url=None):
"""
@@ -1084,14 +1060,7 @@ class CourseOverviewImageSetTestCase(ModuleStoreTestCase):
course_overview = CourseOverview.get_from_id(course.id)
# All the URLs that come back should be for the expected_url
self.assertEqual(
course_overview.image_urls,
{
'raw': expected_url,
'small': expected_url,
'large': expected_url,
}
)
assert course_overview.image_urls == {'raw': expected_url, 'small': expected_url, 'large': expected_url}
return course_overview
@@ -1128,5 +1097,5 @@ class CourseOverviewTabTestCase(ModuleStoreTestCase):
# Asserts that the tabs deletion is properly rolled back to a save point and
# the course overview is not updated.
actual_tabs = {tab.tab_id for tab in course_overview.tab_set.all()}
self.assertEqual(actual_tabs, expected_tabs)
self.assertNotEqual(course_overview.display_name, course.display_name)
assert actual_tabs == expected_tabs
assert course_overview.display_name != course.display_name

View File

@@ -1,7 +1,7 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import datetime
import pytest
import ddt
from mock import patch
@@ -52,7 +52,7 @@ class CourseOverviewSignalsTestCase(ModuleStoreTestCase):
# Create a course where mobile_available is True.
course = CourseFactory.create(mobile_available=True, default_store=modulestore_type)
course_overview_1 = CourseOverview.get_from_id(course.id)
self.assertTrue(course_overview_1.mobile_available)
assert course_overview_1.mobile_available
# Set mobile_available to False and update the course.
# This fires a course_published signal, which should be caught in signals.py, which should in turn
@@ -63,10 +63,10 @@ class CourseOverviewSignalsTestCase(ModuleStoreTestCase):
# Make sure that when we load the CourseOverview again, mobile_available is updated.
course_overview_2 = CourseOverview.get_from_id(course.id)
self.assertFalse(course_overview_2.mobile_available)
assert not course_overview_2.mobile_available
# Verify that when the course is deleted, the corresponding CourseOverview is deleted as well.
with self.assertRaises(CourseOverview.DoesNotExist):
with pytest.raises(CourseOverview.DoesNotExist):
self.store.delete_course(course.id, ModuleStoreEnum.UserID.test)
CourseOverview.get_from_id(course.id)
@@ -76,12 +76,12 @@ class CourseOverviewSignalsTestCase(ModuleStoreTestCase):
# changing display name doesn't fire the signal
course.display_name = course.display_name + u'changed'
self.store.update_item(course, ModuleStoreEnum.UserID.test)
self.assertFalse(mock_signal.called)
assert not mock_signal.called
# changing the given field fires the signal
setattr(course, field_name, changed_value)
self.store.update_item(course, ModuleStoreEnum.UserID.test)
self.assertTrue(mock_signal.called)
assert mock_signal.called
@patch('openedx.core.djangoapps.content.course_overviews.signals.COURSE_START_DATE_CHANGED.send')
def test_start_changed(self, mock_signal):

View File

@@ -26,9 +26,9 @@ class BatchedAsyncCourseOverviewUpdateTests(ModuleStoreTestCase): # lint-amnest
)
called_args, called_kwargs = mock_update_courses.call_args_list[0]
self.assertEqual(sorted([self.course_1.id, self.course_2.id, self.course_3.id]), sorted(called_args[0]))
self.assertEqual({'force_update': True}, called_kwargs)
self.assertEqual(1, mock_update_courses.call_count)
assert sorted([self.course_1.id, self.course_2.id, self.course_3.id]) == sorted(called_args[0])
assert {'force_update': True} == called_kwargs
assert 1 == mock_update_courses.call_count
@mock.patch('openedx.core.djangoapps.content.course_overviews.models.CourseOverview.update_select_courses')
def test_enqueue_specific_courses_in_two_batches(self, mock_update_courses):

View File

@@ -43,18 +43,16 @@ class TestCourseOutlineData(TestCase):
def test_deprecated_course_key(self):
"""Old-Mongo style, "Org/Course/Run" keys are not supported."""
old_course_key = CourseKey.from_string("OpenEdX/TestCourse/TestRun")
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
attr.evolve(self.course_outline, course_key=old_course_key)
def test_sequence_building(self):
"""Make sure sequences were set correctly from sections data."""
for section in self.course_outline.sections:
for seq in section.sequences:
self.assertEqual(seq, self.course_outline.sequences[seq.usage_key])
self.assertEqual(
sum(len(section.sequences) for section in self.course_outline.sections),
len(self.course_outline.sequences),
)
assert seq == self.course_outline.sequences[seq.usage_key]
assert sum((len(section.sequences) for section in self.course_outline.sections)) ==\
len(self.course_outline.sequences)
def test_duplicate_sequence(self):
"""We don't support DAGs. Sequences can only be in one Section."""
@@ -62,7 +60,7 @@ class TestCourseOutlineData(TestCase):
section_with_dupe_seq = attr.evolve(
self.course_outline.sections[1], title="Chapter 2 dupe",
)
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
attr.evolve(
self.course_outline,
sections=self.course_outline.sections + [section_with_dupe_seq]
@@ -70,7 +68,7 @@ class TestCourseOutlineData(TestCase):
def test_size(self):
"""Limit how large a CourseOutline is allowed to be."""
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
attr.evolve(
self.course_outline,
sections=generate_sections(self.course_key, [1001])

View File

@@ -4,7 +4,7 @@ models for this app.
"""
from datetime import datetime, timezone
from mock import patch
import pytest
import attr
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, User # lint-amnesty, pylint: disable=imported-auth-user
@@ -64,12 +64,12 @@ class CourseOutlineTestCase(CacheIsolationTestCase):
def test_deprecated_course_key(self):
"""Don't allow Old Mongo Courses at all."""
old_course_key = CourseKey.from_string("Org/Course/Run")
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
outline = get_course_outline(old_course_key) # lint-amnesty, pylint: disable=unused-variable
def test_simple_roundtrip(self):
"""Happy path for writing/reading-back a course outline."""
with self.assertRaises(CourseOutlineData.DoesNotExist):
with pytest.raises(CourseOutlineData.DoesNotExist):
course_outline = get_course_outline(self.course_key) # lint-amnesty, pylint: disable=unused-variable
replace_course_outline(self.course_outline)
@@ -79,8 +79,8 @@ class CourseOutlineTestCase(CacheIsolationTestCase):
def test_empty_course(self):
"""Empty Courses are a common case (when authoring just starts)."""
empty_outline = attr.evolve(self.course_outline, sections=[])
self.assertFalse(empty_outline.sections)
self.assertFalse(empty_outline.sequences)
assert not empty_outline.sections
assert not empty_outline.sequences
replace_course_outline(empty_outline)
assert empty_outline == get_course_outline(self.course_key)
@@ -1197,15 +1197,11 @@ class SequentialVisibilityTestCase(CacheIsolationTestCase):
with self.subTest(user=user):
user_course_outline = get_user_course_outline(self.course_key, user, self.course_access_time)
self.assertEqual(len(user_course_outline.sections), 3)
self.assertEqual(len(user_course_outline.sequences), 6)
self.assertTrue(
all([
seq.usage_key in user_course_outline.accessible_sequences
for seq in user_course_outline.sequences.values()
]),
"Sequences should be accessible to all users for a public course"
)
assert len(user_course_outline.sections) == 3
assert len(user_course_outline.sequences) == 6
assert all([(seq.usage_key in user_course_outline.accessible_sequences) for seq in
user_course_outline.sequences.values()]),\
'Sequences should be accessible to all users for a public course'
@override_waffle_flag(COURSE_ENABLE_UNENROLLED_ACCESS_FLAG, active=True)
def test_public_outline_course_outline(self):
@@ -1220,8 +1216,8 @@ class SequentialVisibilityTestCase(CacheIsolationTestCase):
with self.subTest(user=user):
user_course_outline = get_user_course_outline(self.course_key, user, self.course_access_time)
self.assertEqual(len(user_course_outline.sections), 3)
self.assertEqual(len(user_course_outline.sequences), 6)
assert len(user_course_outline.sections) == 3
assert len(user_course_outline.sequences) == 6
is_sequence_accessible = [
seq.usage_key in user_course_outline.accessible_sequences
@@ -1229,16 +1225,12 @@ class SequentialVisibilityTestCase(CacheIsolationTestCase):
]
if user in [self.anonymous_user, self.unenrolled_student]:
self.assertTrue(
all(not is_accessible for is_accessible in is_sequence_accessible),
"Sequences shouldn't be accessible to anonymous or non-enrolled students "
"for a public_outline course"
)
assert all(((not is_accessible) for is_accessible in is_sequence_accessible)),\
"Sequences shouldn't be accessible to anonymous or " \
"non-enrolled students for a public_outline course"
else:
self.assertTrue(
all(is_sequence_accessible),
"Sequences should be accessible to enrolled, staff users for a public_outline course"
)
assert all(is_sequence_accessible),\
'Sequences should be accessible to enrolled, staff users for a public_outline course'
@override_waffle_flag(COURSE_ENABLE_UNENROLLED_ACCESS_FLAG, active=True)
def test_private_course_outline(self):
@@ -1259,15 +1251,11 @@ class SequentialVisibilityTestCase(CacheIsolationTestCase):
]
if user in [self.anonymous_user, self.unenrolled_student]:
self.assertTrue(
len(user_course_outline.sections) == len(user_course_outline.sequences) == 0,
"No section of a private course should be visible to anonymous or non-enrolled student"
)
assert (len(user_course_outline.sections) == len(user_course_outline.sequences) == 0),\
'No section of a private course should be visible to anonymous or non-enrolled student'
else:
# Enrolled or Staff User
self.assertEqual(len(user_course_outline.sections), 3)
self.assertEqual(len(user_course_outline.sequences), 6)
self.assertTrue(
all(is_sequence_accessible),
"Sequences should be accessible to enrolled, staff users for a public_outline course"
)
assert len(user_course_outline.sections) == 3
assert len(user_course_outline.sequences) == 6
assert all(is_sequence_accessible),\
'Sequences should be accessible to enrolled, staff users for a public_outline course'