replaced unittest assertions pytest assertions (#26547)
This commit is contained in:
@@ -92,7 +92,7 @@ class TestProgramListing(ProgramsApiConfigMixin, SharedModuleStoreTestCase):
|
||||
subset_keys = set(subset.keys())
|
||||
intersection = {key: superset[key] for key in superset_keys & subset_keys}
|
||||
|
||||
self.assertEqual(subset, intersection)
|
||||
assert subset == intersection
|
||||
|
||||
def test_login_required(self, mock_get_programs):
|
||||
"""
|
||||
@@ -112,7 +112,7 @@ class TestProgramListing(ProgramsApiConfigMixin, SharedModuleStoreTestCase):
|
||||
self.client.login(username=self.user.username, password=self.password)
|
||||
|
||||
response = self.client.get(self.url)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_404_if_disabled(self, _mock_get_programs):
|
||||
"""
|
||||
@@ -121,7 +121,7 @@ class TestProgramListing(ProgramsApiConfigMixin, SharedModuleStoreTestCase):
|
||||
self.create_programs_config(enabled=False)
|
||||
|
||||
response = self.client.get(self.url)
|
||||
self.assertEqual(response.status_code, 404)
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_empty_state(self, mock_get_programs):
|
||||
"""
|
||||
@@ -191,7 +191,7 @@ class TestProgramListing(ProgramsApiConfigMixin, SharedModuleStoreTestCase):
|
||||
expected_program = self.data[index]
|
||||
|
||||
expected_url = reverse('program_details_view', kwargs={'program_uuid': expected_program['uuid']})
|
||||
self.assertEqual(actual_program['detail_url'], expected_url)
|
||||
assert actual_program['detail_url'] == expected_url
|
||||
|
||||
|
||||
@skip_unless_lms
|
||||
@@ -236,9 +236,7 @@ class TestProgramDetails(ProgramsApiConfigMixin, CatalogIntegrationMixin, Shared
|
||||
def assert_programs_tab_present(self, response):
|
||||
"""Verify that the programs tab is present in the nav."""
|
||||
soup = BeautifulSoup(response.content, 'html.parser')
|
||||
self.assertTrue(
|
||||
any(soup.find_all('a', class_='tab-nav-link', href=reverse('program_listing_view')))
|
||||
)
|
||||
assert any(soup.find_all('a', class_='tab-nav-link', href=reverse('program_listing_view')))
|
||||
|
||||
def assert_pathway_data_present(self, response):
|
||||
""" Verify that the correct pathway data is present. """
|
||||
@@ -249,12 +247,12 @@ class TestProgramDetails(ProgramsApiConfigMixin, CatalogIntegrationMixin, Shared
|
||||
credit_pathways = load_serialized_data(response, 'creditPathways')
|
||||
if self.pathway_data['pathway_type'] == PathwayType.CREDIT.value:
|
||||
credit_pathway, = credit_pathways # Verify that there is only one credit pathway
|
||||
self.assertEqual(self.pathway_data, credit_pathway)
|
||||
self.assertEqual([], industry_pathways)
|
||||
assert self.pathway_data == credit_pathway
|
||||
assert [] == industry_pathways
|
||||
elif self.pathway_data['pathway_type'] == PathwayType.INDUSTRY.value:
|
||||
industry_pathway, = industry_pathways # Verify that there is only one industry pathway
|
||||
self.assertEqual(self.pathway_data, industry_pathway)
|
||||
self.assertEqual([], credit_pathways)
|
||||
assert self.pathway_data == industry_pathway
|
||||
assert [] == credit_pathways
|
||||
|
||||
def test_login_required(self, mock_get_programs, mock_get_pathways):
|
||||
"""
|
||||
@@ -292,7 +290,7 @@ class TestProgramDetails(ProgramsApiConfigMixin, CatalogIntegrationMixin, Shared
|
||||
self.create_programs_config(enabled=False)
|
||||
|
||||
response = self.client.get(self.url)
|
||||
self.assertEqual(response.status_code, 404)
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_404_if_no_data(self, mock_get_programs, _mock_get_pathways):
|
||||
"""Verify that the page 404s if no program data is found."""
|
||||
@@ -301,4 +299,4 @@ class TestProgramDetails(ProgramsApiConfigMixin, CatalogIntegrationMixin, Shared
|
||||
mock_get_programs.return_value = None
|
||||
|
||||
response = self.client.get(self.url)
|
||||
self.assertEqual(response.status_code, 404)
|
||||
assert response.status_code == 404
|
||||
|
||||
@@ -23,4 +23,4 @@ class TestUtils(TestCase):
|
||||
handles various url input
|
||||
"""
|
||||
actual = utils.strip_course_id(path + six.text_type(utils.FAKE_COURSE_KEY))
|
||||
self.assertEqual(actual, path)
|
||||
assert actual == path
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Tests of the LMS XBlock Runtime and associated utilities
|
||||
"""
|
||||
|
||||
|
||||
import pytest
|
||||
from ddt import data, ddt
|
||||
from django.conf import settings
|
||||
from django.test import TestCase
|
||||
@@ -68,51 +68,51 @@ class TestHandlerUrl(TestCase):
|
||||
)
|
||||
|
||||
def test_trailing_characters(self):
|
||||
self.assertFalse(self.runtime.handler_url(self.block, 'handler').endswith('?'))
|
||||
self.assertFalse(self.runtime.handler_url(self.block, 'handler').endswith('/'))
|
||||
assert not self.runtime.handler_url(self.block, 'handler').endswith('?')
|
||||
assert not self.runtime.handler_url(self.block, 'handler').endswith('/')
|
||||
|
||||
self.assertFalse(self.runtime.handler_url(self.block, 'handler', 'suffix').endswith('?'))
|
||||
self.assertFalse(self.runtime.handler_url(self.block, 'handler', 'suffix').endswith('/'))
|
||||
assert not self.runtime.handler_url(self.block, 'handler', 'suffix').endswith('?')
|
||||
assert not self.runtime.handler_url(self.block, 'handler', 'suffix').endswith('/')
|
||||
|
||||
self.assertFalse(self.runtime.handler_url(self.block, 'handler', 'suffix', 'query').endswith('?'))
|
||||
self.assertFalse(self.runtime.handler_url(self.block, 'handler', 'suffix', 'query').endswith('/'))
|
||||
assert not self.runtime.handler_url(self.block, 'handler', 'suffix', 'query').endswith('?')
|
||||
assert not self.runtime.handler_url(self.block, 'handler', 'suffix', 'query').endswith('/')
|
||||
|
||||
self.assertFalse(self.runtime.handler_url(self.block, 'handler', query='query').endswith('?'))
|
||||
self.assertFalse(self.runtime.handler_url(self.block, 'handler', query='query').endswith('/'))
|
||||
assert not self.runtime.handler_url(self.block, 'handler', query='query').endswith('?')
|
||||
assert not self.runtime.handler_url(self.block, 'handler', query='query').endswith('/')
|
||||
|
||||
def _parsed_query(self, query_string):
|
||||
"""Return the parsed query string from a handler_url generated with the supplied query_string"""
|
||||
return urlparse(self.runtime.handler_url(self.block, 'handler', query=query_string)).query
|
||||
|
||||
def test_query_string(self):
|
||||
self.assertIn('foo=bar', self._parsed_query('foo=bar'))
|
||||
self.assertIn('foo=bar&baz=true', self._parsed_query('foo=bar&baz=true'))
|
||||
self.assertIn('foo&bar&baz', self._parsed_query('foo&bar&baz'))
|
||||
assert 'foo=bar' in self._parsed_query('foo=bar')
|
||||
assert 'foo=bar&baz=true' in self._parsed_query('foo=bar&baz=true')
|
||||
assert 'foo&bar&baz' in self._parsed_query('foo&bar&baz')
|
||||
|
||||
def _parsed_path(self, handler_name='handler', suffix=''):
|
||||
"""Return the parsed path from a handler_url with the supplied handler_name and suffix"""
|
||||
return urlparse(self.runtime.handler_url(self.block, handler_name, suffix=suffix)).path
|
||||
|
||||
def test_suffix(self):
|
||||
self.assertTrue(self._parsed_path(suffix="foo").endswith('foo'))
|
||||
self.assertTrue(self._parsed_path(suffix="foo/bar").endswith('foo/bar'))
|
||||
self.assertTrue(self._parsed_path(suffix="/foo/bar").endswith('/foo/bar'))
|
||||
assert self._parsed_path(suffix='foo').endswith('foo')
|
||||
assert self._parsed_path(suffix='foo/bar').endswith('foo/bar')
|
||||
assert self._parsed_path(suffix='/foo/bar').endswith('/foo/bar')
|
||||
|
||||
def test_handler_name(self):
|
||||
self.assertIn('handler1', self._parsed_path('handler1'))
|
||||
self.assertIn('handler_a', self._parsed_path('handler_a'))
|
||||
assert 'handler1' in self._parsed_path('handler1')
|
||||
assert 'handler_a' in self._parsed_path('handler_a')
|
||||
|
||||
def test_thirdparty_fq(self):
|
||||
"""Testing the Fully-Qualified URL returned by thirdparty=True"""
|
||||
parsed_fq_url = urlparse(self.runtime.handler_url(self.block, 'handler', thirdparty=True))
|
||||
self.assertEqual(parsed_fq_url.scheme, 'https')
|
||||
self.assertEqual(parsed_fq_url.hostname, settings.SITE_NAME)
|
||||
assert parsed_fq_url.scheme == 'https'
|
||||
assert parsed_fq_url.hostname == settings.SITE_NAME
|
||||
|
||||
def test_not_thirdparty_rel(self):
|
||||
"""Testing the Fully-Qualified URL returned by thirdparty=False"""
|
||||
parsed_fq_url = urlparse(self.runtime.handler_url(self.block, 'handler', thirdparty=False))
|
||||
self.assertEqual(parsed_fq_url.scheme, '')
|
||||
self.assertIsNone(parsed_fq_url.hostname)
|
||||
assert parsed_fq_url.scheme == ''
|
||||
assert parsed_fq_url.hostname is None
|
||||
|
||||
|
||||
class TestUserServiceAPI(TestCase):
|
||||
@@ -146,21 +146,21 @@ class TestUserServiceAPI(TestCase):
|
||||
def test_get_set_tag(self):
|
||||
# test for when we haven't set the tag yet
|
||||
tag = self.runtime.service(self.mock_block, 'user_tags').get_tag(self.scope, self.key)
|
||||
self.assertIsNone(tag)
|
||||
assert tag is None
|
||||
|
||||
# set the tag
|
||||
set_value = 'value'
|
||||
self.runtime.service(self.mock_block, 'user_tags').set_tag(self.scope, self.key, set_value)
|
||||
tag = self.runtime.service(self.mock_block, 'user_tags').get_tag(self.scope, self.key)
|
||||
|
||||
self.assertEqual(tag, set_value)
|
||||
assert tag == set_value
|
||||
|
||||
# Try to set tag in wrong scope
|
||||
with self.assertRaises(ValueError):
|
||||
with pytest.raises(ValueError):
|
||||
self.runtime.service(self.mock_block, 'user_tags').set_tag('fake_scope', self.key, set_value)
|
||||
|
||||
# Try to get tag in wrong scope
|
||||
with self.assertRaises(ValueError):
|
||||
with pytest.raises(ValueError):
|
||||
self.runtime.service(self.mock_block, 'user_tags').get_tag('fake_scope', self.key)
|
||||
|
||||
|
||||
@@ -197,19 +197,19 @@ class TestBadgingService(ModuleStoreTestCase):
|
||||
@patch.dict(settings.FEATURES, {'ENABLE_OPENBADGES': True})
|
||||
def test_service_rendered(self):
|
||||
runtime = self.create_runtime()
|
||||
self.assertTrue(runtime.service(self.mock_block, 'badging'))
|
||||
assert runtime.service(self.mock_block, 'badging')
|
||||
|
||||
@patch.dict(settings.FEATURES, {'ENABLE_OPENBADGES': False})
|
||||
def test_no_service_rendered(self):
|
||||
runtime = self.create_runtime()
|
||||
self.assertFalse(runtime.service(self.mock_block, 'badging'))
|
||||
assert not runtime.service(self.mock_block, 'badging')
|
||||
|
||||
@data(True, False)
|
||||
@patch.dict(settings.FEATURES, {'ENABLE_OPENBADGES': True})
|
||||
def test_course_badges_toggle(self, toggle):
|
||||
self.course_id = CourseFactory.create(metadata={'issue_badges': toggle}).location.course_key
|
||||
runtime = self.create_runtime()
|
||||
self.assertIs(runtime.service(self.mock_block, 'badging').course_badges_enabled, toggle)
|
||||
assert runtime.service(self.mock_block, 'badging').course_badges_enabled is toggle
|
||||
|
||||
@patch.dict(settings.FEATURES, {'ENABLE_OPENBADGES': True})
|
||||
def test_get_badge_class(self):
|
||||
@@ -223,11 +223,11 @@ class TestBadgingService(ModuleStoreTestCase):
|
||||
criteria='test', display_name='Testola', image_file_handle=get_image('good')
|
||||
)
|
||||
# These defaults are set on the factory.
|
||||
self.assertEqual(badge_class.criteria, 'https://example.com/syllabus')
|
||||
self.assertEqual(badge_class.display_name, 'Test Badge')
|
||||
self.assertEqual(badge_class.description, "Yay! It's a test badge.")
|
||||
assert badge_class.criteria == 'https://example.com/syllabus'
|
||||
assert badge_class.display_name == 'Test Badge'
|
||||
assert badge_class.description == "Yay! It's a test badge."
|
||||
# File name won't always be the same.
|
||||
self.assertEqual(badge_class.image.path, premade_badge_class.image.path)
|
||||
assert badge_class.image.path == premade_badge_class.image.path
|
||||
|
||||
|
||||
class TestI18nService(ModuleStoreTestCase):
|
||||
@@ -256,15 +256,15 @@ class TestI18nService(ModuleStoreTestCase):
|
||||
Test: module i18n service in LMS
|
||||
"""
|
||||
i18n_service = self.runtime.service(self.mock_block, 'i18n')
|
||||
self.assertIsNotNone(i18n_service)
|
||||
self.assertIsInstance(i18n_service, ModuleI18nService)
|
||||
assert i18n_service is not None
|
||||
assert isinstance(i18n_service, ModuleI18nService)
|
||||
|
||||
def test_no_service_exception_with_none_declaration_(self):
|
||||
"""
|
||||
Test: NoSuchServiceError should be raised block declaration returns none
|
||||
"""
|
||||
self.mock_block.service_declaration.return_value = None
|
||||
with self.assertRaises(NoSuchServiceError):
|
||||
with pytest.raises(NoSuchServiceError):
|
||||
self.runtime.service(self.mock_block, 'i18n')
|
||||
|
||||
def test_no_service_exception_(self):
|
||||
@@ -272,17 +272,17 @@ class TestI18nService(ModuleStoreTestCase):
|
||||
Test: NoSuchServiceError should be raised if i18n service is none.
|
||||
"""
|
||||
self.runtime._services['i18n'] = None # pylint: disable=protected-access
|
||||
with self.assertRaises(NoSuchServiceError):
|
||||
with pytest.raises(NoSuchServiceError):
|
||||
self.runtime.service(self.mock_block, 'i18n')
|
||||
|
||||
def test_i18n_service_callable(self):
|
||||
"""
|
||||
Test: _services dict should contain the callable i18n service in LMS.
|
||||
"""
|
||||
self.assertTrue(callable(self.runtime._services.get('i18n'))) # pylint: disable=protected-access
|
||||
assert callable(self.runtime._services.get('i18n')) # pylint: disable=protected-access
|
||||
|
||||
def test_i18n_service_not_callable(self):
|
||||
"""
|
||||
Test: i18n service should not be callable in LMS after initialization.
|
||||
"""
|
||||
self.assertFalse(callable(self.runtime.service(self.mock_block, 'i18n')))
|
||||
assert not callable(self.runtime.service(self.mock_block, 'i18n'))
|
||||
|
||||
@@ -31,15 +31,15 @@ class CommandArgsTestCase(TestCase):
|
||||
def test_course_keys(self):
|
||||
parser = self._get_arg_parser()
|
||||
args = parser.parse_args(['course-v1:edX+test_course+2525_fall', 'UBC/Law281/2015_T1'])
|
||||
self.assertEqual(len(args.course_keys), 2)
|
||||
assert len(args.course_keys) == 2
|
||||
key = args.course_keys[0]
|
||||
self.assertIsInstance(key, CourseKey)
|
||||
self.assertEqual(six.text_type(key), 'course-v1:edX+test_course+2525_fall')
|
||||
assert isinstance(key, CourseKey)
|
||||
assert six.text_type(key) == 'course-v1:edX+test_course+2525_fall'
|
||||
|
||||
def test_no_course_keys(self):
|
||||
parser = self._get_arg_parser()
|
||||
args = parser.parse_args([])
|
||||
self.assertEqual(args.course_keys, [])
|
||||
assert args.course_keys == []
|
||||
|
||||
|
||||
class CommandExecutionTestCase(SharedModuleStoreTestCase):
|
||||
@@ -105,11 +105,11 @@ class CommandExecutionTestCase(SharedModuleStoreTestCase):
|
||||
return mock_update.called
|
||||
|
||||
def test_command_with_no_course_keys(self):
|
||||
self.assertTrue(self._scores_sent_with_args(course_keys=[]))
|
||||
assert self._scores_sent_with_args(course_keys=[])
|
||||
|
||||
def test_command_with_course_key(self):
|
||||
self.assertTrue(self._scores_sent_with_args(course_keys=[self.course_key]))
|
||||
assert self._scores_sent_with_args(course_keys=[self.course_key])
|
||||
|
||||
def test_command_with_wrong_course_key(self):
|
||||
fake_course_key = self.store.make_course_key(u'not', u'the', u'course')
|
||||
self.assertFalse(self._scores_sent_with_args(course_keys=[fake_course_key]))
|
||||
assert not self._scores_sent_with_args(course_keys=[fake_course_key])
|
||||
|
||||
@@ -61,9 +61,9 @@ class StoreOutcomeParametersTest(TestCase):
|
||||
assignment = GradedAssignment.objects.get(
|
||||
lis_result_sourcedid=params['lis_result_sourcedid']
|
||||
)
|
||||
self.assertEqual(assignment.course_key, self.course_key)
|
||||
self.assertEqual(assignment.usage_key, self.usage_key)
|
||||
self.assertEqual(assignment.user, self.user)
|
||||
assert assignment.course_key == self.course_key
|
||||
assert assignment.usage_key == self.usage_key
|
||||
assert assignment.user == self.user
|
||||
|
||||
def test_outcome_service_created(self):
|
||||
params = self.get_valid_request_params()
|
||||
@@ -72,7 +72,7 @@ class StoreOutcomeParametersTest(TestCase):
|
||||
outcome = OutcomeService.objects.get(
|
||||
lti_consumer=self.consumer
|
||||
)
|
||||
self.assertEqual(outcome.lti_consumer, self.consumer)
|
||||
assert outcome.lti_consumer == self.consumer
|
||||
|
||||
def test_graded_assignment_references_outcome_service(self):
|
||||
params = self.get_valid_request_params()
|
||||
@@ -84,7 +84,7 @@ class StoreOutcomeParametersTest(TestCase):
|
||||
assignment = GradedAssignment.objects.get(
|
||||
lis_result_sourcedid=params['lis_result_sourcedid']
|
||||
)
|
||||
self.assertEqual(assignment.outcome_service, outcome)
|
||||
assert assignment.outcome_service == outcome
|
||||
|
||||
def test_no_duplicate_graded_assignments(self):
|
||||
params = self.get_valid_request_params()
|
||||
@@ -95,7 +95,7 @@ class StoreOutcomeParametersTest(TestCase):
|
||||
assignments = GradedAssignment.objects.filter(
|
||||
lis_result_sourcedid=params['lis_result_sourcedid']
|
||||
)
|
||||
self.assertEqual(len(assignments), 1)
|
||||
assert len(assignments) == 1
|
||||
|
||||
def test_no_duplicate_outcome_services(self):
|
||||
params = self.get_valid_request_params()
|
||||
@@ -106,7 +106,7 @@ class StoreOutcomeParametersTest(TestCase):
|
||||
outcome_services = OutcomeService.objects.filter(
|
||||
lti_consumer=self.consumer
|
||||
)
|
||||
self.assertEqual(len(outcome_services), 1)
|
||||
assert len(outcome_services) == 1
|
||||
|
||||
def test_no_db_update_for_ungraded_assignment(self):
|
||||
params = self.get_valid_request_params()
|
||||
@@ -125,8 +125,8 @@ class StoreOutcomeParametersTest(TestCase):
|
||||
del params['tool_consumer_instance_guid']
|
||||
with self.assertNumQueries(8):
|
||||
outcomes.store_outcome_parameters(params, self.user, self.consumer)
|
||||
self.assertEqual(GradedAssignment.objects.count(), 1)
|
||||
self.assertEqual(OutcomeService.objects.count(), 1)
|
||||
assert GradedAssignment.objects.count() == 1
|
||||
assert OutcomeService.objects.count() == 1
|
||||
|
||||
|
||||
class SignAndSendReplaceResultTest(TestCase):
|
||||
@@ -176,7 +176,7 @@ class SignAndSendReplaceResultTest(TestCase):
|
||||
auth=ANY,
|
||||
headers={'content-type': 'application/xml'}
|
||||
)
|
||||
self.assertEqual(response, 'response')
|
||||
assert response == 'response'
|
||||
|
||||
|
||||
class XmlHandlingTest(TestCase):
|
||||
@@ -218,8 +218,8 @@ class XmlHandlingTest(TestCase):
|
||||
'//ns:imsx_messageIdentifier',
|
||||
namespaces={'ns': 'http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0'}
|
||||
)
|
||||
self.assertEqual(len(message_id), 1)
|
||||
self.assertEqual(message_id[0].text, 'random_uuid')
|
||||
assert len(message_id) == 1
|
||||
assert message_id[0].text == 'random_uuid'
|
||||
|
||||
def test_replace_result_sourced_id(self):
|
||||
xml = outcomes.generate_replace_result_xml(self.result_id, self.score)
|
||||
@@ -229,8 +229,8 @@ class XmlHandlingTest(TestCase):
|
||||
'ns:resultRecord/ns:sourcedGUID/ns:sourcedId',
|
||||
namespaces={'ns': 'http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0'}
|
||||
)
|
||||
self.assertEqual(len(sourced_id), 1)
|
||||
self.assertEqual(sourced_id[0].text, 'result_id')
|
||||
assert len(sourced_id) == 1
|
||||
assert sourced_id[0].text == 'result_id'
|
||||
|
||||
def test_replace_result_score(self):
|
||||
xml = outcomes.generate_replace_result_xml(self.result_id, self.score)
|
||||
@@ -240,8 +240,8 @@ class XmlHandlingTest(TestCase):
|
||||
'ns:resultRecord/ns:result/ns:resultScore/ns:textString',
|
||||
namespaces={'ns': 'http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0'}
|
||||
)
|
||||
self.assertEqual(len(xml_score), 1)
|
||||
self.assertEqual(xml_score[0].text, '0.25')
|
||||
assert len(xml_score) == 1
|
||||
assert xml_score[0].text == '0.25'
|
||||
|
||||
def create_response_object(
|
||||
self, status, xml,
|
||||
@@ -258,16 +258,16 @@ class XmlHandlingTest(TestCase):
|
||||
def test_response_with_correct_xml(self):
|
||||
xml = self.response_xml
|
||||
response = self.create_response_object(200, xml)
|
||||
self.assertTrue(outcomes.check_replace_result_response(response))
|
||||
assert outcomes.check_replace_result_response(response)
|
||||
|
||||
def test_response_with_bad_status_code(self):
|
||||
response = self.create_response_object(500, '')
|
||||
self.assertFalse(outcomes.check_replace_result_response(response))
|
||||
assert not outcomes.check_replace_result_response(response)
|
||||
|
||||
def test_response_with_invalid_xml(self):
|
||||
xml = '<badly>formatted</xml>'
|
||||
response = self.create_response_object(200, xml)
|
||||
self.assertFalse(outcomes.check_replace_result_response(response))
|
||||
assert not outcomes.check_replace_result_response(response)
|
||||
|
||||
def test_response_with_multiple_status_fields(self):
|
||||
response = self.create_response_object(
|
||||
@@ -275,21 +275,21 @@ class XmlHandlingTest(TestCase):
|
||||
major_code='<imsx_codeMajor>success</imsx_codeMajor>'
|
||||
'<imsx_codeMajor>failure</imsx_codeMajor>'
|
||||
)
|
||||
self.assertFalse(outcomes.check_replace_result_response(response))
|
||||
assert not outcomes.check_replace_result_response(response)
|
||||
|
||||
def test_response_with_no_status_field(self):
|
||||
response = self.create_response_object(
|
||||
200, self.response_xml,
|
||||
major_code=''
|
||||
)
|
||||
self.assertFalse(outcomes.check_replace_result_response(response))
|
||||
assert not outcomes.check_replace_result_response(response)
|
||||
|
||||
def test_response_with_failing_status_field(self):
|
||||
response = self.create_response_object(
|
||||
200, self.response_xml,
|
||||
major_code='<imsx_codeMajor>failure</imsx_codeMajor>'
|
||||
)
|
||||
self.assertFalse(outcomes.check_replace_result_response(response))
|
||||
assert not outcomes.check_replace_result_response(response)
|
||||
|
||||
|
||||
class TestAssignmentsForProblem(ModuleStoreTestCase):
|
||||
@@ -366,14 +366,14 @@ class TestAssignmentsForProblem(ModuleStoreTestCase):
|
||||
)
|
||||
lti_consumer_second.save()
|
||||
count = LtiConsumer.objects.count()
|
||||
self.assertEqual(count, 3)
|
||||
assert count == 3
|
||||
|
||||
def test_with_no_graded_assignments(self):
|
||||
with check_mongo_calls(3):
|
||||
assignments = outcomes.get_assignments_for_problem(
|
||||
self.unit, self.user_id, self.course.id
|
||||
)
|
||||
self.assertEqual(len(assignments), 0)
|
||||
assert len(assignments) == 0
|
||||
|
||||
def test_with_graded_unit(self):
|
||||
self.create_graded_assignment(self.unit, 'graded_unit', self.outcome_service)
|
||||
@@ -381,8 +381,8 @@ class TestAssignmentsForProblem(ModuleStoreTestCase):
|
||||
assignments = outcomes.get_assignments_for_problem(
|
||||
self.unit, self.user_id, self.course.id
|
||||
)
|
||||
self.assertEqual(len(assignments), 1)
|
||||
self.assertEqual(assignments[0].lis_result_sourcedid, 'graded_unit')
|
||||
assert len(assignments) == 1
|
||||
assert assignments[0].lis_result_sourcedid == 'graded_unit'
|
||||
|
||||
def test_with_graded_vertical(self):
|
||||
self.create_graded_assignment(self.vertical, 'graded_vertical', self.outcome_service)
|
||||
@@ -390,8 +390,8 @@ class TestAssignmentsForProblem(ModuleStoreTestCase):
|
||||
assignments = outcomes.get_assignments_for_problem(
|
||||
self.unit, self.user_id, self.course.id
|
||||
)
|
||||
self.assertEqual(len(assignments), 1)
|
||||
self.assertEqual(assignments[0].lis_result_sourcedid, 'graded_vertical')
|
||||
assert len(assignments) == 1
|
||||
assert assignments[0].lis_result_sourcedid == 'graded_vertical'
|
||||
|
||||
def test_with_graded_unit_and_vertical(self):
|
||||
self.create_graded_assignment(self.unit, 'graded_unit', self.outcome_service)
|
||||
@@ -400,9 +400,9 @@ class TestAssignmentsForProblem(ModuleStoreTestCase):
|
||||
assignments = outcomes.get_assignments_for_problem(
|
||||
self.unit, self.user_id, self.course.id
|
||||
)
|
||||
self.assertEqual(len(assignments), 2)
|
||||
self.assertEqual(assignments[0].lis_result_sourcedid, 'graded_unit')
|
||||
self.assertEqual(assignments[1].lis_result_sourcedid, 'graded_vertical')
|
||||
assert len(assignments) == 2
|
||||
assert assignments[0].lis_result_sourcedid == 'graded_unit'
|
||||
assert assignments[1].lis_result_sourcedid == 'graded_vertical'
|
||||
|
||||
def test_with_unit_used_twice(self):
|
||||
self.create_graded_assignment(self.unit, 'graded_unit', self.outcome_service)
|
||||
@@ -411,9 +411,9 @@ class TestAssignmentsForProblem(ModuleStoreTestCase):
|
||||
assignments = outcomes.get_assignments_for_problem(
|
||||
self.unit, self.user_id, self.course.id
|
||||
)
|
||||
self.assertEqual(len(assignments), 2)
|
||||
self.assertEqual(assignments[0].lis_result_sourcedid, 'graded_unit')
|
||||
self.assertEqual(assignments[1].lis_result_sourcedid, 'graded_unit2')
|
||||
assert len(assignments) == 2
|
||||
assert assignments[0].lis_result_sourcedid == 'graded_unit'
|
||||
assert assignments[1].lis_result_sourcedid == 'graded_unit2'
|
||||
|
||||
def test_with_unit_graded_for_different_user(self):
|
||||
self.create_graded_assignment(self.unit, 'graded_unit', self.outcome_service)
|
||||
@@ -422,7 +422,7 @@ class TestAssignmentsForProblem(ModuleStoreTestCase):
|
||||
assignments = outcomes.get_assignments_for_problem(
|
||||
self.unit, other_user.id, self.course.id
|
||||
)
|
||||
self.assertEqual(len(assignments), 0)
|
||||
assert len(assignments) == 0
|
||||
|
||||
def test_with_unit_graded_for_multiple_consumers(self):
|
||||
other_outcome_service = self.create_outcome_service('second_consumer')
|
||||
@@ -432,8 +432,8 @@ class TestAssignmentsForProblem(ModuleStoreTestCase):
|
||||
assignments = outcomes.get_assignments_for_problem(
|
||||
self.unit, self.user_id, self.course.id
|
||||
)
|
||||
self.assertEqual(len(assignments), 2)
|
||||
self.assertEqual(assignments[0].lis_result_sourcedid, 'graded_unit')
|
||||
self.assertEqual(assignments[1].lis_result_sourcedid, 'graded_unit2')
|
||||
self.assertEqual(assignments[0].outcome_service, self.outcome_service)
|
||||
self.assertEqual(assignments[1].outcome_service, other_outcome_service)
|
||||
assert len(assignments) == 2
|
||||
assert assignments[0].lis_result_sourcedid == 'graded_unit'
|
||||
assert assignments[1].lis_result_sourcedid == 'graded_unit2'
|
||||
assert assignments[0].outcome_service == self.outcome_service
|
||||
assert assignments[1].outcome_service == other_outcome_service
|
||||
|
||||
@@ -38,7 +38,7 @@ class ClientKeyValidatorTest(TestCase):
|
||||
Verify that check_client_key succeeds with a valid key
|
||||
"""
|
||||
key = self.lti_consumer.consumer_key
|
||||
self.assertTrue(SignatureValidator(self.lti_consumer).check_client_key(key))
|
||||
assert SignatureValidator(self.lti_consumer).check_client_key(key)
|
||||
|
||||
@ddt.data(
|
||||
('0123456789012345678901234567890123456789',),
|
||||
@@ -50,7 +50,7 @@ class ClientKeyValidatorTest(TestCase):
|
||||
"""
|
||||
Verify that check_client_key fails with a disallowed key
|
||||
"""
|
||||
self.assertFalse(SignatureValidator(self.lti_consumer).check_client_key(key))
|
||||
assert not SignatureValidator(self.lti_consumer).check_client_key(key)
|
||||
|
||||
|
||||
@ddt.ddt
|
||||
@@ -68,7 +68,7 @@ class NonceValidatorTest(TestCase):
|
||||
Verify that check_nonce succeeds with a key of maximum length
|
||||
"""
|
||||
nonce = '0123456789012345678901234567890123456789012345678901234567890123'
|
||||
self.assertTrue(SignatureValidator(self.lti_consumer).check_nonce(nonce))
|
||||
assert SignatureValidator(self.lti_consumer).check_nonce(nonce)
|
||||
|
||||
@ddt.data(
|
||||
('01234567890123456789012345678901234567890123456789012345678901234',),
|
||||
@@ -80,7 +80,7 @@ class NonceValidatorTest(TestCase):
|
||||
"""
|
||||
Verify that check_nonce fails with badly formatted nonce
|
||||
"""
|
||||
self.assertFalse(SignatureValidator(self.lti_consumer).check_nonce(nonce))
|
||||
assert not SignatureValidator(self.lti_consumer).check_nonce(nonce)
|
||||
|
||||
|
||||
class SignatureValidatorTest(TestCase):
|
||||
@@ -101,7 +101,7 @@ class SignatureValidatorTest(TestCase):
|
||||
"""
|
||||
key = self.lti_consumer.consumer_key
|
||||
secret = SignatureValidator(self.lti_consumer).get_client_secret(key, None)
|
||||
self.assertEqual(secret, self.lti_consumer.consumer_secret)
|
||||
assert secret == self.lti_consumer.consumer_secret
|
||||
|
||||
@patch('oauthlib.oauth1.SignatureOnlyEndpoint.validate_request',
|
||||
return_value=(True, None))
|
||||
|
||||
@@ -133,4 +133,4 @@ class SendCompositeOutcomeTest(BaseOutcomeTest):
|
||||
tasks.send_composite_outcome(
|
||||
self.user.id, six.text_type(self.course_key), self.assignment.id, 1
|
||||
)
|
||||
self.assertEqual(self.course_grade_mock.call_count, 0)
|
||||
assert self.course_grade_mock.call_count == 0
|
||||
|
||||
@@ -4,7 +4,7 @@ Tests for the LTI user management functionality
|
||||
|
||||
|
||||
import string
|
||||
|
||||
import pytest
|
||||
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.test import TestCase
|
||||
@@ -42,7 +42,7 @@ class UserManagementHelperTest(TestCase):
|
||||
|
||||
@patch('django.contrib.auth.authenticate', return_value=None)
|
||||
def test_permission_denied_for_unknown_user(self, _authenticate_mock):
|
||||
with self.assertRaises(PermissionDenied):
|
||||
with pytest.raises(PermissionDenied):
|
||||
users.switch_user(self.request, self.lti_user, self.lti_consumer)
|
||||
|
||||
@patch('lms.djangoapps.lti_provider.users.login')
|
||||
@@ -64,13 +64,11 @@ class UserManagementHelperTest(TestCase):
|
||||
def test_random_username_generator(self):
|
||||
for _idx in range(1000):
|
||||
username = users.generate_random_edx_username()
|
||||
self.assertLessEqual(len(username), 30, 'Username too long')
|
||||
assert len(username) <= 30, 'Username too long'
|
||||
# Check that the username contains only allowable characters
|
||||
for char in range(len(username)): # lint-amnesty, pylint: disable=consider-using-enumerate
|
||||
self.assertIn(
|
||||
username[char], string.ascii_letters + string.digits,
|
||||
assert username[char] in (string.ascii_letters + string.digits), \
|
||||
u"Username has forbidden character '{}'".format(username[char])
|
||||
)
|
||||
|
||||
|
||||
@patch('lms.djangoapps.lti_provider.users.switch_user', autospec=True)
|
||||
@@ -121,8 +119,8 @@ class AuthenticateLtiUserTest(TestCase):
|
||||
self.request.user = lti_user.edx_user
|
||||
assert self.request.user.is_authenticated
|
||||
users.authenticate_lti_user(self.request, self.lti_user_id, self.lti_consumer)
|
||||
self.assertFalse(create_user.called)
|
||||
self.assertFalse(switch_user.called)
|
||||
assert not create_user.called
|
||||
assert not switch_user.called
|
||||
|
||||
def test_authentication_with_unauthenticated_user(self, create_user, switch_user):
|
||||
lti_user = self.create_lti_user_model()
|
||||
@@ -130,7 +128,7 @@ class AuthenticateLtiUserTest(TestCase):
|
||||
with patch('django.contrib.auth.models.User.is_authenticated', new_callable=PropertyMock) as mock_is_auth:
|
||||
mock_is_auth.return_value = False
|
||||
users.authenticate_lti_user(self.request, self.lti_user_id, self.lti_consumer)
|
||||
self.assertFalse(create_user.called)
|
||||
assert not create_user.called
|
||||
switch_user.assert_called_with(self.request, lti_user, self.lti_consumer)
|
||||
|
||||
def test_authentication_with_wrong_user(self, create_user, switch_user):
|
||||
@@ -138,7 +136,7 @@ class AuthenticateLtiUserTest(TestCase):
|
||||
self.request.user = self.old_user
|
||||
assert self.request.user.is_authenticated
|
||||
users.authenticate_lti_user(self.request, self.lti_user_id, self.lti_consumer)
|
||||
self.assertFalse(create_user.called)
|
||||
assert not create_user.called
|
||||
switch_user.assert_called_with(self.request, lti_user, self.lti_consumer)
|
||||
|
||||
|
||||
@@ -158,25 +156,25 @@ class CreateLtiUserTest(TestCase):
|
||||
|
||||
def test_create_lti_user_creates_auth_user_model(self):
|
||||
users.create_lti_user('lti_user_id', self.lti_consumer)
|
||||
self.assertEqual(User.objects.count(), 1)
|
||||
assert User.objects.count() == 1
|
||||
|
||||
@patch('uuid.uuid4', return_value='random_uuid')
|
||||
@patch('lms.djangoapps.lti_provider.users.generate_random_edx_username', return_value='edx_id')
|
||||
def test_create_lti_user_creates_correct_user(self, uuid_mock, _username_mock):
|
||||
users.create_lti_user('lti_user_id', self.lti_consumer)
|
||||
self.assertEqual(User.objects.count(), 1)
|
||||
assert User.objects.count() == 1
|
||||
user = User.objects.get(username='edx_id')
|
||||
self.assertEqual(user.email, 'edx_id@lti.example.com')
|
||||
assert user.email == 'edx_id@lti.example.com'
|
||||
uuid_mock.assert_called_with()
|
||||
|
||||
@patch('lms.djangoapps.lti_provider.users.generate_random_edx_username', side_effect=['edx_id', 'new_edx_id'])
|
||||
def test_unique_username_created(self, username_mock):
|
||||
User(username='edx_id').save()
|
||||
users.create_lti_user('lti_user_id', self.lti_consumer)
|
||||
self.assertEqual(username_mock.call_count, 2)
|
||||
self.assertEqual(User.objects.count(), 2)
|
||||
assert username_mock.call_count == 2
|
||||
assert User.objects.count() == 2
|
||||
user = User.objects.get(username='new_edx_id')
|
||||
self.assertEqual(user.email, 'new_edx_id@lti.example.com')
|
||||
assert user.email == 'new_edx_id@lti.example.com'
|
||||
|
||||
|
||||
class LtiBackendTest(TestCase):
|
||||
@@ -210,7 +208,7 @@ class LtiBackendTest(TestCase):
|
||||
lti_user_id=self.lti_user_id,
|
||||
lti_consumer=self.lti_consumer
|
||||
)
|
||||
self.assertEqual(user, self.edx_user)
|
||||
assert user == self.edx_user
|
||||
|
||||
def test_missing_user_returns_none(self):
|
||||
user = users.LtiBackend().authenticate(
|
||||
@@ -219,7 +217,7 @@ class LtiBackendTest(TestCase):
|
||||
lti_user_id='Invalid Username',
|
||||
lti_consumer=self.lti_consumer
|
||||
)
|
||||
self.assertIsNone(user)
|
||||
assert user is None
|
||||
|
||||
def test_non_lti_user_returns_none(self):
|
||||
non_edx_user = UserFactory.create()
|
||||
@@ -228,7 +226,7 @@ class LtiBackendTest(TestCase):
|
||||
self.request,
|
||||
username=non_edx_user.username,
|
||||
)
|
||||
self.assertIsNone(user)
|
||||
assert user is None
|
||||
|
||||
def test_missing_lti_id_returns_null(self):
|
||||
user = users.LtiBackend().authenticate(
|
||||
@@ -236,7 +234,7 @@ class LtiBackendTest(TestCase):
|
||||
username=self.edx_user.username,
|
||||
lti_consumer=self.lti_consumer
|
||||
)
|
||||
self.assertIsNone(user)
|
||||
assert user is None
|
||||
|
||||
def test_missing_lti_consumer_returns_null(self):
|
||||
user = users.LtiBackend().authenticate(
|
||||
@@ -244,12 +242,12 @@ class LtiBackendTest(TestCase):
|
||||
username=self.edx_user.username,
|
||||
lti_user_id=self.lti_user_id,
|
||||
)
|
||||
self.assertIsNone(user)
|
||||
assert user is None
|
||||
|
||||
def test_existing_user_returned_by_get_user(self):
|
||||
user = users.LtiBackend().get_user(self.edx_user.id)
|
||||
self.assertEqual(user, self.edx_user)
|
||||
assert user == self.edx_user
|
||||
|
||||
def test_get_user_returns_none_for_invalid_user(self):
|
||||
user = users.LtiBackend().get_user(-1)
|
||||
self.assertIsNone(user)
|
||||
assert user is None
|
||||
|
||||
@@ -141,10 +141,7 @@ class LtiLaunchTest(LtiTestMixin, TestCase):
|
||||
"""
|
||||
for missing_param in views.REQUIRED_PARAMETERS:
|
||||
response = self.launch_with_missing_parameter(missing_param)
|
||||
self.assertEqual(
|
||||
response.status_code, 400,
|
||||
'Launch should fail when parameter ' + missing_param + ' is missing'
|
||||
)
|
||||
assert response.status_code == 400, (('Launch should fail when parameter ' + missing_param) + ' is missing')
|
||||
|
||||
def test_launch_with_disabled_feature_flag(self):
|
||||
"""
|
||||
@@ -154,7 +151,7 @@ class LtiLaunchTest(LtiTestMixin, TestCase):
|
||||
with patch.dict('django.conf.settings.FEATURES', {'ENABLE_LTI_PROVIDER': False}):
|
||||
request = build_launch_request()
|
||||
response = views.lti_launch(request, None, None)
|
||||
self.assertEqual(response.status_code, 403)
|
||||
assert response.status_code == 403
|
||||
|
||||
def test_forbidden_if_signature_fails(self):
|
||||
"""
|
||||
@@ -165,8 +162,8 @@ class LtiLaunchTest(LtiTestMixin, TestCase):
|
||||
|
||||
request = build_launch_request()
|
||||
response = views.lti_launch(request, None, None)
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.status_code, 403)
|
||||
assert response.status_code == 403
|
||||
assert response.status_code == 403
|
||||
|
||||
@patch('lms.djangoapps.lti_provider.views.render_courseware')
|
||||
def test_lti_consumer_record_supplemented_with_guid(self, _render):
|
||||
@@ -178,7 +175,7 @@ class LtiLaunchTest(LtiTestMixin, TestCase):
|
||||
consumer = models.LtiConsumer.objects.get(
|
||||
consumer_key=LTI_DEFAULT_PARAMS['oauth_consumer_key']
|
||||
)
|
||||
self.assertEqual(consumer.instance_guid, u'consumer instance guid')
|
||||
assert consumer.instance_guid == u'consumer instance guid'
|
||||
|
||||
|
||||
class LtiLaunchTestRender(LtiTestMixin, RenderXBlockTestMixin, ModuleStoreTestCase):
|
||||
|
||||
@@ -25,7 +25,7 @@ class TestUpdates(MobileAPITestCase, MobileAuthTestMixin, MobileCourseAccessTest
|
||||
|
||||
def verify_success(self, response):
|
||||
super(TestUpdates, self).verify_success(response) # lint-amnesty, pylint: disable=super-with-arguments
|
||||
self.assertEqual(response.data, [])
|
||||
assert response.data == []
|
||||
|
||||
@ddt.data(
|
||||
(True, API_V05),
|
||||
@@ -79,14 +79,14 @@ class TestUpdates(MobileAPITestCase, MobileAuthTestMixin, MobileCourseAccessTest
|
||||
# verify static URLs remain in the underlying content
|
||||
underlying_updates = modulestore().get_item(updates_usage_key)
|
||||
underlying_content = underlying_updates.items[0]['content'] if new_format else underlying_updates.data
|
||||
self.assertIn("\"/static/", underlying_content)
|
||||
assert '"/static/' in underlying_content
|
||||
|
||||
# verify content and sort order of updates (most recent first)
|
||||
for num in range(1, num_updates + 1):
|
||||
update_data = response.data[num_updates - num]
|
||||
self.assertEqual(num, update_data['id'])
|
||||
self.assertEqual("Date" + str(num), update_data['date'])
|
||||
self.assertIn("Update" + str(num), update_data['content'])
|
||||
assert num == update_data['id']
|
||||
assert 'Date' + str(num) == update_data['date']
|
||||
assert 'Update' + str(num) in update_data['content']
|
||||
|
||||
|
||||
@ddt.ddt
|
||||
@@ -107,7 +107,7 @@ class TestHandouts(MobileAPITestCase, MobileAuthTestMixin, MobileCourseAccessTes
|
||||
with self.store.default_store(default_ms):
|
||||
self.add_mobile_available_toy_course()
|
||||
response = self.api_response(expected_response_code=200, api_version=api_version)
|
||||
self.assertIn("Sample", response.data['handouts_html'])
|
||||
assert 'Sample' in response.data['handouts_html']
|
||||
|
||||
@ddt.data(
|
||||
(ModuleStoreEnum.Type.mongo, API_V05),
|
||||
@@ -126,7 +126,7 @@ class TestHandouts(MobileAPITestCase, MobileAuthTestMixin, MobileCourseAccessTes
|
||||
self.store.delete_item(handouts_usage_key, self.user.id)
|
||||
|
||||
response = self.api_response(expected_response_code=200, api_version=api_version)
|
||||
self.assertIsNone(response.data['handouts_html'])
|
||||
assert response.data['handouts_html'] is None
|
||||
|
||||
@ddt.data(
|
||||
(ModuleStoreEnum.Type.mongo, API_V05),
|
||||
@@ -145,7 +145,7 @@ class TestHandouts(MobileAPITestCase, MobileAuthTestMixin, MobileCourseAccessTes
|
||||
underlying_handouts.data = "<ol></ol>"
|
||||
self.store.update_item(underlying_handouts, self.user.id)
|
||||
response = self.api_response(expected_response_code=200, api_version=api_version)
|
||||
self.assertIsNone(response.data['handouts_html'])
|
||||
assert response.data['handouts_html'] is None
|
||||
|
||||
@ddt.data(
|
||||
(ModuleStoreEnum.Type.mongo, API_V05),
|
||||
@@ -161,11 +161,11 @@ class TestHandouts(MobileAPITestCase, MobileAuthTestMixin, MobileCourseAccessTes
|
||||
# check that we start with relative static assets
|
||||
handouts_usage_key = self.course.id.make_usage_key('course_info', 'handouts')
|
||||
underlying_handouts = self.store.get_item(handouts_usage_key)
|
||||
self.assertIn('\'/static/', underlying_handouts.data)
|
||||
assert "'/static/" in underlying_handouts.data
|
||||
|
||||
# but shouldn't finish with any
|
||||
response = self.api_response(api_version=api_version)
|
||||
self.assertNotIn('\'/static/', response.data['handouts_html'])
|
||||
assert "'/static/" not in response.data['handouts_html']
|
||||
|
||||
@ddt.data(
|
||||
(ModuleStoreEnum.Type.mongo, API_V05),
|
||||
@@ -186,7 +186,7 @@ class TestHandouts(MobileAPITestCase, MobileAuthTestMixin, MobileCourseAccessTes
|
||||
|
||||
# but shouldn't finish with any
|
||||
response = self.api_response(api_version=api_version)
|
||||
self.assertIn("/courses/{}/jump_to_id/".format(self.course.id), response.data['handouts_html'])
|
||||
assert '/courses/{}/jump_to_id/'.format(self.course.id) in response.data['handouts_html']
|
||||
|
||||
@ddt.data(
|
||||
(ModuleStoreEnum.Type.mongo, API_V05),
|
||||
@@ -207,7 +207,7 @@ class TestHandouts(MobileAPITestCase, MobileAuthTestMixin, MobileCourseAccessTes
|
||||
|
||||
# but shouldn't finish with any
|
||||
response = self.api_response(api_version=api_version)
|
||||
self.assertIn("/courses/{}/".format(self.course.id), response.data['handouts_html'])
|
||||
assert '/courses/{}/'.format(self.course.id) in response.data['handouts_html']
|
||||
|
||||
def add_mobile_available_toy_course(self):
|
||||
""" use toy course with handouts, and make it mobile_available """
|
||||
|
||||
@@ -22,7 +22,7 @@ class MobileContextProcessorTests(TestCase):
|
||||
request = RequestFactory().get('/')
|
||||
request.META['HTTP_USER_AGENT'] = settings.MOBILE_APP_USER_AGENT_REGEXES[0]
|
||||
context = is_from_mobile_app(request)
|
||||
self.assertEqual(context['is_from_mobile_app'], True)
|
||||
assert context['is_from_mobile_app'] is True
|
||||
|
||||
def test_not_is_from_mobile_app(self):
|
||||
"""
|
||||
@@ -31,4 +31,4 @@ class MobileContextProcessorTests(TestCase):
|
||||
request = RequestFactory().get('/')
|
||||
request.META['HTTP_USER_AGENT'] = "Not from the mobile app"
|
||||
context = is_from_mobile_app(request)
|
||||
self.assertEqual(context['is_from_mobile_app'], False)
|
||||
assert context['is_from_mobile_app'] is False
|
||||
|
||||
@@ -25,6 +25,6 @@ class TestMobileAPIDecorators(TestCase):
|
||||
"""
|
||||
pass # lint-amnesty, pylint: disable=unnecessary-pass
|
||||
|
||||
self.assertIn("Test docstring of decorated function.", decorated_func.__doc__)
|
||||
self.assertEqual(decorated_func.__name__, "decorated_func")
|
||||
self.assertTrue(decorated_func.__module__.endswith("test_decorator"))
|
||||
assert 'Test docstring of decorated function.' in decorated_func.__doc__
|
||||
assert decorated_func.__name__ == 'decorated_func'
|
||||
assert decorated_func.__module__.endswith('test_decorator')
|
||||
|
||||
@@ -67,10 +67,10 @@ class TestAppVersionUpgradeMiddleware(CacheIsolationTestCase):
|
||||
fake_request.META['HTTP_USER_AGENT'] = user_agent
|
||||
with mock.patch.object(caches['default'], 'get_many', wraps=caches['default'].get_many) as mocked_code:
|
||||
request_response = self.middleware.process_request(fake_request)
|
||||
self.assertEqual(cache_get_many_calls_for_request, mocked_code.call_count)
|
||||
assert cache_get_many_calls_for_request == mocked_code.call_count
|
||||
with mock.patch.object(caches['default'], 'get_many', wraps=caches['default'].get_many) as mocked_code:
|
||||
processed_response = self.middleware.process_response(fake_request, request_response or HttpResponse())
|
||||
self.assertEqual(0, mocked_code.call_count)
|
||||
assert 0 == mocked_code.call_count
|
||||
return request_response, processed_response
|
||||
|
||||
@ddt.data(
|
||||
@@ -84,10 +84,10 @@ class TestAppVersionUpgradeMiddleware(CacheIsolationTestCase):
|
||||
def test_non_mobile_app_requests(self, user_agent):
|
||||
with self.assertNumQueries(0):
|
||||
request_response, processed_response = self.process_middleware(user_agent, 0)
|
||||
self.assertIsNone(request_response)
|
||||
self.assertEqual(200, processed_response.status_code)
|
||||
self.assertNotIn(AppVersionUpgrade.LATEST_VERSION_HEADER, processed_response)
|
||||
self.assertNotIn(AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER, processed_response)
|
||||
assert request_response is None
|
||||
assert 200 == processed_response.status_code
|
||||
assert AppVersionUpgrade.LATEST_VERSION_HEADER not in processed_response
|
||||
assert AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER not in processed_response
|
||||
|
||||
@ddt.data(
|
||||
"edX/org.edx.mobile (6.6.6; OS Version 9.2 (Build 13C75))",
|
||||
@@ -98,10 +98,10 @@ class TestAppVersionUpgradeMiddleware(CacheIsolationTestCase):
|
||||
def test_no_update(self, user_agent):
|
||||
with self.assertNumQueries(2):
|
||||
request_response, processed_response = self.process_middleware(user_agent)
|
||||
self.assertIsNone(request_response)
|
||||
self.assertEqual(200, processed_response.status_code)
|
||||
self.assertNotIn(AppVersionUpgrade.LATEST_VERSION_HEADER, processed_response)
|
||||
self.assertNotIn(AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER, processed_response)
|
||||
assert request_response is None
|
||||
assert 200 == processed_response.status_code
|
||||
assert AppVersionUpgrade.LATEST_VERSION_HEADER not in processed_response
|
||||
assert AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER not in processed_response
|
||||
with self.assertNumQueries(0):
|
||||
self.process_middleware(user_agent)
|
||||
|
||||
@@ -115,10 +115,10 @@ class TestAppVersionUpgradeMiddleware(CacheIsolationTestCase):
|
||||
def test_new_version_available(self, user_agent, latest_version):
|
||||
with self.assertNumQueries(2):
|
||||
request_response, processed_response = self.process_middleware(user_agent)
|
||||
self.assertIsNone(request_response)
|
||||
self.assertEqual(200, processed_response.status_code)
|
||||
self.assertEqual(latest_version, processed_response[AppVersionUpgrade.LATEST_VERSION_HEADER])
|
||||
self.assertNotIn(AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER, processed_response)
|
||||
assert request_response is None
|
||||
assert 200 == processed_response.status_code
|
||||
assert latest_version == processed_response[AppVersionUpgrade.LATEST_VERSION_HEADER]
|
||||
assert AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER not in processed_response
|
||||
with self.assertNumQueries(0):
|
||||
self.process_middleware(user_agent)
|
||||
|
||||
@@ -136,9 +136,9 @@ class TestAppVersionUpgradeMiddleware(CacheIsolationTestCase):
|
||||
def test_version_update_required(self, user_agent, latest_version):
|
||||
with self.assertNumQueries(2):
|
||||
request_response, processed_response = self.process_middleware(user_agent)
|
||||
self.assertIsNotNone(request_response)
|
||||
self.assertEqual(426, processed_response.status_code)
|
||||
self.assertEqual(latest_version, processed_response[AppVersionUpgrade.LATEST_VERSION_HEADER])
|
||||
assert request_response is not None
|
||||
assert 426 == processed_response.status_code
|
||||
assert latest_version == processed_response[AppVersionUpgrade.LATEST_VERSION_HEADER]
|
||||
with self.assertNumQueries(0):
|
||||
self.process_middleware(user_agent)
|
||||
|
||||
@@ -154,9 +154,9 @@ class TestAppVersionUpgradeMiddleware(CacheIsolationTestCase):
|
||||
def test_version_update_available_with_deadline(self, user_agent, latest_version, upgrade_date):
|
||||
with self.assertNumQueries(2):
|
||||
request_response, processed_response = self.process_middleware(user_agent)
|
||||
self.assertIsNone(request_response)
|
||||
self.assertEqual(200, processed_response.status_code)
|
||||
self.assertEqual(latest_version, processed_response[AppVersionUpgrade.LATEST_VERSION_HEADER])
|
||||
self.assertEqual(upgrade_date, processed_response[AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER])
|
||||
assert request_response is None
|
||||
assert 200 == processed_response.status_code
|
||||
assert latest_version == processed_response[AppVersionUpgrade.LATEST_VERSION_HEADER]
|
||||
assert upgrade_date == processed_response[AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER]
|
||||
with self.assertNumQueries(0):
|
||||
self.process_middleware(user_agent)
|
||||
|
||||
@@ -141,4 +141,4 @@ class MobileAPIMilestonesMixin(object):
|
||||
self.api_response()
|
||||
else:
|
||||
response = self.api_response(expected_response_code=404)
|
||||
self.assertEqual(response.data, MilestoneAccessError().to_json())
|
||||
assert response.data == MilestoneAccessError().to_json()
|
||||
|
||||
@@ -31,8 +31,8 @@ class TestMobilePlatform(TestCase):
|
||||
@ddt.unpack
|
||||
def test_platform_instance(self, user_agent, platform_name, version):
|
||||
platform = MobilePlatform.get_instance(user_agent)
|
||||
self.assertEqual(platform_name, platform.NAME)
|
||||
self.assertEqual(version, platform.version)
|
||||
assert platform_name == platform.NAME
|
||||
assert version == platform.version
|
||||
|
||||
@ddt.data(
|
||||
("Mozilla/5.0 (Linux; Android 5.1; Nexus 5 Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
@@ -45,4 +45,4 @@ class TestMobilePlatform(TestCase):
|
||||
"edX/org.edx.mobile (0.1.5.2.5.1; OS Version 9.2 (Build 13C75))",
|
||||
)
|
||||
def test_non_mobile_app_requests(self, user_agent):
|
||||
self.assertIsNone(MobilePlatform.get_instance(user_agent))
|
||||
assert MobilePlatform.get_instance(user_agent) is None
|
||||
|
||||
@@ -65,14 +65,14 @@ class TestAppVersionConfigModel(TestCase):
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_no_configs_available(self, platform, version):
|
||||
self.assertIsNone(AppVersionConfig.latest_version(platform))
|
||||
self.assertIsNone(AppVersionConfig.last_supported_date(platform, version))
|
||||
assert AppVersionConfig.latest_version(platform) is None
|
||||
assert AppVersionConfig.last_supported_date(platform, version) is None
|
||||
|
||||
@ddt.data(('ios', '6.6.6'), ('android', '8.8.8'))
|
||||
@ddt.unpack
|
||||
def test_latest_version(self, platform, latest_version):
|
||||
self.set_app_version_config()
|
||||
self.assertEqual(latest_version, AppVersionConfig.latest_version(platform))
|
||||
assert latest_version == AppVersionConfig.latest_version(platform)
|
||||
|
||||
@ddt.data(
|
||||
('ios', '3.3.3', datetime(9000, 1, 1, tzinfo=UTC)),
|
||||
@@ -84,7 +84,7 @@ class TestAppVersionConfigModel(TestCase):
|
||||
@ddt.unpack
|
||||
def test_last_supported_date(self, platform, version, last_supported_date):
|
||||
self.set_app_version_config()
|
||||
self.assertEqual(last_supported_date, AppVersionConfig.last_supported_date(platform, version))
|
||||
assert last_supported_date == AppVersionConfig.last_supported_date(platform, version)
|
||||
|
||||
|
||||
class TestMobileApiConfig(TestCase):
|
||||
@@ -96,22 +96,16 @@ class TestMobileApiConfig(TestCase):
|
||||
"""Check that video_profiles config is returned in order as a list"""
|
||||
MobileApiConfig(video_profiles="mobile_low,mobile_high,youtube").save()
|
||||
video_profile_list = MobileApiConfig.get_video_profiles()
|
||||
self.assertEqual(
|
||||
video_profile_list,
|
||||
[u'mobile_low', u'mobile_high', u'youtube']
|
||||
)
|
||||
assert video_profile_list == [u'mobile_low', u'mobile_high', u'youtube']
|
||||
|
||||
def test_video_profile_list_with_whitespace(self):
|
||||
"""Check video_profiles config with leading and trailing whitespace"""
|
||||
MobileApiConfig(video_profiles=" mobile_low , mobile_high,youtube ").save()
|
||||
video_profile_list = MobileApiConfig.get_video_profiles()
|
||||
self.assertEqual(
|
||||
video_profile_list,
|
||||
[u'mobile_low', u'mobile_high', u'youtube']
|
||||
)
|
||||
assert video_profile_list == [u'mobile_low', u'mobile_high', u'youtube']
|
||||
|
||||
def test_empty_video_profile(self):
|
||||
"""Test an empty video_profile"""
|
||||
MobileApiConfig(video_profiles="").save()
|
||||
video_profile_list = MobileApiConfig.get_video_profiles()
|
||||
self.assertEqual(video_profile_list, [])
|
||||
assert video_profile_list == []
|
||||
|
||||
@@ -89,7 +89,7 @@ class MobileAPITestCase(ModuleStoreTestCase, APITestCase):
|
||||
url = self.reverse_url(reverse_args, **kwargs)
|
||||
response = self.url_method(url, data=data, **kwargs)
|
||||
if expected_response_code is not None:
|
||||
self.assertEqual(response.status_code, expected_response_code)
|
||||
assert response.status_code == expected_response_code
|
||||
return response
|
||||
|
||||
def reverse_url(self, reverse_args=None, **kwargs):
|
||||
@@ -153,13 +153,13 @@ class MobileCourseAccessTestMixin(MobileAPIMilestonesMixin):
|
||||
|
||||
def verify_success(self, response):
|
||||
"""Base implementation of verifying a successful response."""
|
||||
self.assertEqual(response.status_code, 200)
|
||||
assert response.status_code == 200
|
||||
|
||||
def verify_failure(self, response, error_type=None):
|
||||
"""Base implementation of verifying a failed response."""
|
||||
self.assertEqual(response.status_code, 404)
|
||||
assert response.status_code == 404
|
||||
if error_type:
|
||||
self.assertEqual(response.data, error_type.to_json())
|
||||
assert response.data == error_type.to_json()
|
||||
|
||||
def init_course_access(self, course_id=None):
|
||||
"""Base implementation of initializing the user for each test."""
|
||||
|
||||
@@ -59,8 +59,8 @@ class TestUserDetailApi(MobileAPITestCase, MobileAuthUserTestMixin):
|
||||
self.login()
|
||||
|
||||
response = self.api_response(api_version=api_version)
|
||||
self.assertEqual(response.data['username'], self.user.username)
|
||||
self.assertEqual(response.data['email'], self.user.email)
|
||||
assert response.data['username'] == self.user.username
|
||||
assert response.data['email'] == self.user.email
|
||||
|
||||
|
||||
@ddt.ddt
|
||||
@@ -76,7 +76,7 @@ class TestUserInfoApi(MobileAPITestCase, MobileAuthTestMixin):
|
||||
self.login()
|
||||
|
||||
response = self.api_response(expected_response_code=302, api_version=api_version)
|
||||
self.assertIn(self.username, response['location'])
|
||||
assert self.username in response['location']
|
||||
|
||||
@ddt.data(API_V05, API_V1)
|
||||
def test_last_loggedin_updated(self, api_version):
|
||||
@@ -126,25 +126,25 @@ class TestUserEnrollmentApi(UrlResetMixin, MobileAPITestCase, MobileAuthUserTest
|
||||
"""
|
||||
super(TestUserEnrollmentApi, self).verify_success(response) # lint-amnesty, pylint: disable=super-with-arguments
|
||||
courses = response.data
|
||||
self.assertEqual(len(courses), 1)
|
||||
assert len(courses) == 1
|
||||
|
||||
found_course = courses[0]['course']
|
||||
self.assertIn('courses/{}/about'.format(self.course.id), found_course['course_about'])
|
||||
self.assertIn('course_info/{}/updates'.format(self.course.id), found_course['course_updates'])
|
||||
self.assertIn('course_info/{}/handouts'.format(self.course.id), found_course['course_handouts'])
|
||||
self.assertEqual(found_course['id'], six.text_type(self.course.id))
|
||||
self.assertEqual(courses[0]['mode'], CourseMode.DEFAULT_MODE_SLUG)
|
||||
self.assertEqual(courses[0]['course']['subscription_id'], self.course.clean_id(padding_char='_'))
|
||||
assert 'courses/{}/about'.format(self.course.id) in found_course['course_about']
|
||||
assert 'course_info/{}/updates'.format(self.course.id) in found_course['course_updates']
|
||||
assert 'course_info/{}/handouts'.format(self.course.id) in found_course['course_handouts']
|
||||
assert found_course['id'] == six.text_type(self.course.id)
|
||||
assert courses[0]['mode'] == CourseMode.DEFAULT_MODE_SLUG
|
||||
assert courses[0]['course']['subscription_id'] == self.course.clean_id(padding_char='_')
|
||||
|
||||
expected_course_image_url = course_image_url(self.course)
|
||||
self.assertIsNotNone(expected_course_image_url)
|
||||
self.assertIn(expected_course_image_url, found_course['course_image'])
|
||||
self.assertIn(expected_course_image_url, found_course['media']['course_image']['uri'])
|
||||
assert expected_course_image_url is not None
|
||||
assert expected_course_image_url in found_course['course_image']
|
||||
assert expected_course_image_url in found_course['media']['course_image']['uri']
|
||||
|
||||
def verify_failure(self, response, error_type=None):
|
||||
self.assertEqual(response.status_code, 200)
|
||||
assert response.status_code == 200
|
||||
courses = response.data
|
||||
self.assertEqual(len(courses), 0)
|
||||
assert len(courses) == 0
|
||||
|
||||
@patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True})
|
||||
@ddt.data(API_V05, API_V1)
|
||||
@@ -160,10 +160,8 @@ class TestUserEnrollmentApi(UrlResetMixin, MobileAPITestCase, MobileAuthUserTest
|
||||
# verify courses are returned in the order of enrollment, with most recently enrolled first.
|
||||
response = self.api_response(api_version=api_version)
|
||||
for course_index in range(num_courses):
|
||||
self.assertEqual(
|
||||
response.data[course_index]['course']['id'],
|
||||
six.text_type(courses[num_courses - course_index - 1].id)
|
||||
)
|
||||
assert response.data[course_index]['course']['id'] ==\
|
||||
six.text_type(courses[((num_courses - course_index) - 1)].id)
|
||||
|
||||
@ddt.data(API_V05, API_V1)
|
||||
@patch.dict(settings.FEATURES, {
|
||||
@@ -201,10 +199,10 @@ class TestUserEnrollmentApi(UrlResetMixin, MobileAPITestCase, MobileAuthUserTest
|
||||
response = self.api_response(api_version=api_version)
|
||||
for course_index in range(len(courses)):
|
||||
result = response.data[course_index]['course']['courseware_access']
|
||||
self.assertEqual(result['error_code'], expected_error_codes[::-1][course_index])
|
||||
assert result['error_code'] == expected_error_codes[::(- 1)][course_index]
|
||||
|
||||
if result['error_code'] is not None:
|
||||
self.assertFalse(result['has_access'])
|
||||
assert not result['has_access']
|
||||
|
||||
@ddt.data(
|
||||
('next_week', ADVERTISED_START, ADVERTISED_START, "string", API_V05),
|
||||
@@ -232,8 +230,8 @@ class TestUserEnrollmentApi(UrlResetMixin, MobileAPITestCase, MobileAuthUserTest
|
||||
self.enroll(course.id)
|
||||
|
||||
response = self.api_response(api_version=api_version)
|
||||
self.assertEqual(response.data[0]['course']['start_type'], expected_type)
|
||||
self.assertEqual(response.data[0]['course']['start_display'], expected_display)
|
||||
assert response.data[0]['course']['start_type'] == expected_type
|
||||
assert response.data[0]['course']['start_display'] == expected_display
|
||||
|
||||
@ddt.data(API_V05, API_V1)
|
||||
@patch.dict(settings.FEATURES, {"ENABLE_DISCUSSION_SERVICE": True, 'ENABLE_MKTG_SITE': True})
|
||||
@@ -242,7 +240,7 @@ class TestUserEnrollmentApi(UrlResetMixin, MobileAPITestCase, MobileAuthUserTest
|
||||
|
||||
response = self.api_response(api_version=api_version)
|
||||
response_discussion_url = response.data[0]['course']['discussion_url']
|
||||
self.assertIn('/api/discussion/v1/courses/{}'.format(self.course.id), response_discussion_url)
|
||||
assert '/api/discussion/v1/courses/{}'.format(self.course.id) in response_discussion_url
|
||||
|
||||
@ddt.data(API_V05, API_V1)
|
||||
def test_org_query(self, api_version):
|
||||
@@ -265,11 +263,11 @@ class TestUserEnrollmentApi(UrlResetMixin, MobileAPITestCase, MobileAuthUserTest
|
||||
response = self.api_response(data={'org': 'edX'}, api_version=api_version)
|
||||
|
||||
# Test for 3 expected courses
|
||||
self.assertEqual(len(response.data), 3)
|
||||
assert len(response.data) == 3
|
||||
|
||||
# Verify only edX courses are returned
|
||||
for entry in response.data:
|
||||
self.assertEqual(entry['course']['org'], 'edX')
|
||||
assert entry['course']['org'] == 'edX'
|
||||
|
||||
def create_enrollment(self, expired):
|
||||
"""
|
||||
@@ -300,15 +298,15 @@ class TestUserEnrollmentApi(UrlResetMixin, MobileAPITestCase, MobileAuthUserTest
|
||||
return self.api_response(api_version=api_version).data
|
||||
|
||||
def _assert_enrollment_results(self, api_version, courses, num_courses_returned, gating_enabled=True): # lint-amnesty, pylint: disable=missing-function-docstring
|
||||
self.assertEqual(len(courses), num_courses_returned)
|
||||
assert len(courses) == num_courses_returned
|
||||
|
||||
if api_version == API_V05:
|
||||
if num_courses_returned:
|
||||
self.assertNotIn('audit_access_expires', courses[0])
|
||||
assert 'audit_access_expires' not in courses[0]
|
||||
else:
|
||||
self.assertIn('audit_access_expires', courses[0])
|
||||
assert 'audit_access_expires' in courses[0]
|
||||
if gating_enabled:
|
||||
self.assertIsNotNone(courses[0].get('audit_access_expires'))
|
||||
assert courses[0].get('audit_access_expires') is not None
|
||||
|
||||
@ddt.data(
|
||||
(API_V05, True, 0),
|
||||
@@ -369,7 +367,7 @@ class TestUserEnrollmentCertificates(UrlResetMixin, MobileAPITestCase, Milestone
|
||||
|
||||
response = self.api_response()
|
||||
certificate_data = response.data[0]['certificate']
|
||||
self.assertEqual(certificate_data['url'], certificate_url)
|
||||
assert certificate_data['url'] == certificate_url
|
||||
|
||||
@patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True})
|
||||
def test_no_certificate(self):
|
||||
@@ -458,24 +456,16 @@ class TestCourseStatusGET(CourseStatusAPITestCase, MobileAuthUserTestMixin,
|
||||
self.login_and_enroll()
|
||||
|
||||
response = self.api_response(api_version=API_V05)
|
||||
self.assertEqual(
|
||||
response.data["last_visited_module_id"],
|
||||
six.text_type(self.sub_section.location)
|
||||
)
|
||||
self.assertEqual(
|
||||
response.data["last_visited_module_path"],
|
||||
[six.text_type(module.location) for module in [self.sub_section, self.section, self.course]]
|
||||
)
|
||||
assert response.data['last_visited_module_id'] == six.text_type(self.sub_section.location)
|
||||
assert response.data['last_visited_module_path'] == [six.text_type(module.location) for module in
|
||||
[self.sub_section, self.section, self.course]]
|
||||
|
||||
def test_success_v1(self):
|
||||
self.override_waffle_switch(True)
|
||||
self.login_and_enroll()
|
||||
submit_completions_for_testing(self.user, [self.unit.location])
|
||||
response = self.api_response(api_version=API_V1)
|
||||
self.assertEqual(
|
||||
response.data["last_visited_block_id"],
|
||||
six.text_type(self.unit.location)
|
||||
)
|
||||
assert response.data['last_visited_block_id'] == six.text_type(self.unit.location)
|
||||
|
||||
|
||||
class TestCourseStatusPATCH(CourseStatusAPITestCase, MobileAuthUserTestMixin,
|
||||
@@ -490,27 +480,18 @@ class TestCourseStatusPATCH(CourseStatusAPITestCase, MobileAuthUserTestMixin,
|
||||
def test_success(self):
|
||||
self.login_and_enroll()
|
||||
response = self.api_response(data={"last_visited_module_id": six.text_type(self.other_unit.location)})
|
||||
self.assertEqual(
|
||||
response.data["last_visited_module_id"],
|
||||
six.text_type(self.other_sub_section.location)
|
||||
)
|
||||
assert response.data['last_visited_module_id'] == six.text_type(self.other_sub_section.location)
|
||||
|
||||
def test_invalid_module(self):
|
||||
self.login_and_enroll()
|
||||
response = self.api_response(data={"last_visited_module_id": "abc"}, expected_response_code=400)
|
||||
self.assertEqual(
|
||||
response.data,
|
||||
errors.ERROR_INVALID_MODULE_ID
|
||||
)
|
||||
assert response.data == errors.ERROR_INVALID_MODULE_ID
|
||||
|
||||
def test_nonexistent_module(self):
|
||||
self.login_and_enroll()
|
||||
non_existent_key = self.course.id.make_usage_key('video', 'non-existent')
|
||||
response = self.api_response(data={"last_visited_module_id": non_existent_key}, expected_response_code=400)
|
||||
self.assertEqual(
|
||||
response.data,
|
||||
errors.ERROR_INVALID_MODULE_ID
|
||||
)
|
||||
assert response.data == errors.ERROR_INVALID_MODULE_ID
|
||||
|
||||
def test_no_timezone(self):
|
||||
self.login_and_enroll()
|
||||
@@ -522,10 +503,7 @@ class TestCourseStatusPATCH(CourseStatusAPITestCase, MobileAuthUserTestMixin,
|
||||
},
|
||||
expected_response_code=400
|
||||
)
|
||||
self.assertEqual(
|
||||
response.data,
|
||||
errors.ERROR_INVALID_MODIFICATION_DATE
|
||||
)
|
||||
assert response.data == errors.ERROR_INVALID_MODIFICATION_DATE
|
||||
|
||||
def _date_sync(self, date, initial_unit, update_unit, expected_subsection):
|
||||
"""
|
||||
@@ -544,10 +522,7 @@ class TestCourseStatusPATCH(CourseStatusAPITestCase, MobileAuthUserTestMixin,
|
||||
"modification_date": date.isoformat()
|
||||
}
|
||||
)
|
||||
self.assertEqual(
|
||||
response.data["last_visited_module_id"],
|
||||
six.text_type(expected_subsection.location)
|
||||
)
|
||||
assert response.data['last_visited_module_id'] == six.text_type(expected_subsection.location)
|
||||
|
||||
def test_old_date(self):
|
||||
self.login_and_enroll()
|
||||
@@ -567,18 +542,12 @@ class TestCourseStatusPATCH(CourseStatusAPITestCase, MobileAuthUserTestMixin,
|
||||
"modification_date": timezone.now().isoformat()
|
||||
}
|
||||
)
|
||||
self.assertEqual(
|
||||
response.data["last_visited_module_id"],
|
||||
six.text_type(self.other_sub_section.location)
|
||||
)
|
||||
assert response.data['last_visited_module_id'] == six.text_type(self.other_sub_section.location)
|
||||
|
||||
def test_invalid_date(self):
|
||||
self.login_and_enroll()
|
||||
response = self.api_response(data={"modification_date": "abc"}, expected_response_code=400)
|
||||
self.assertEqual(
|
||||
response.data,
|
||||
errors.ERROR_INVALID_MODIFICATION_DATE
|
||||
)
|
||||
assert response.data == errors.ERROR_INVALID_MODIFICATION_DATE
|
||||
|
||||
|
||||
@ddt.ddt
|
||||
@@ -616,16 +585,16 @@ class TestCourseEnrollmentSerializer(MobileAPITestCase, MilestonesTestCaseMixin)
|
||||
based on version of api being used
|
||||
'''
|
||||
if api_version != API_V05:
|
||||
self.assertIn('audit_access_expires', response)
|
||||
assert 'audit_access_expires' in response
|
||||
else:
|
||||
self.assertNotIn('audit_access_expires', response)
|
||||
assert 'audit_access_expires' not in response
|
||||
|
||||
@ddt.data(API_V05, API_V1)
|
||||
def test_success(self, api_version):
|
||||
serialized = self.get_serialized_data(api_version)
|
||||
self.assertEqual(serialized['course']['name'], self.course.display_name)
|
||||
self.assertEqual(serialized['course']['number'], self.course.id.course)
|
||||
self.assertEqual(serialized['course']['org'], self.course.id.org)
|
||||
assert serialized['course']['name'] == self.course.display_name
|
||||
assert serialized['course']['number'] == self.course.id.course
|
||||
assert serialized['course']['org'] == self.course.id.org
|
||||
self._expiration_in_response(serialized, api_version)
|
||||
|
||||
# Assert utm parameters
|
||||
@@ -642,6 +611,6 @@ class TestCourseEnrollmentSerializer(MobileAPITestCase, MilestonesTestCaseMixin)
|
||||
self.store.update_item(self.course, self.user.id)
|
||||
|
||||
serialized = self.get_serialized_data(api_version)
|
||||
self.assertEqual(serialized['course']['number'], self.course.display_coursenumber)
|
||||
self.assertEqual(serialized['course']['org'], self.course.display_organization)
|
||||
assert serialized['course']['number'] == self.course.display_coursenumber
|
||||
assert serialized['course']['org'] == self.course.display_organization
|
||||
self._expiration_in_response(serialized, api_version)
|
||||
|
||||
Reference in New Issue
Block a user