replaced unittest assertions pytest assertions (#26574)

This commit is contained in:
Aarif
2021-02-22 20:04:51 +05:00
committed by GitHub
parent c21ac0c3df
commit 813064ad49
23 changed files with 384 additions and 410 deletions

View File

@@ -40,7 +40,7 @@ class ApiTestCase(TestCase):
"""Make a request with the given args and return the parsed JSON response"""
resp = self.request_with_auth("get", *args, **kwargs)
self.assertHttpOK(resp)
self.assertTrue(resp["Content-Type"].startswith("application/json"))
assert resp['Content-Type'].startswith('application/json')
return json.loads(resp.content.decode('utf-8'))
def assertAllowedMethods(self, uri, expected_methods):
@@ -48,34 +48,34 @@ class ApiTestCase(TestCase):
resp = self.request_with_auth("options", uri)
self.assertHttpOK(resp)
allow_header = resp.get("Allow")
self.assertIsNotNone(allow_header)
assert allow_header is not None
allowed_methods = re.split('[^A-Z]+', allow_header)
six.assertCountEqual(self, allowed_methods, expected_methods)
def assertSelfReferential(self, obj):
"""Assert that accessing the "url" entry in the given object returns the same object"""
copy = self.get_json(obj["url"])
self.assertEqual(obj, copy)
assert obj == copy
def assertHttpOK(self, response):
"""Assert that the given response has the status code 200"""
self.assertEqual(response.status_code, 200)
assert response.status_code == 200
def assertHttpCreated(self, response):
"""Assert that the given response has the status code 201"""
self.assertEqual(response.status_code, 201)
assert response.status_code == 201
def assertHttpForbidden(self, response):
"""Assert that the given response has the status code 403"""
self.assertEqual(response.status_code, 403)
assert response.status_code == 403
def assertHttpBadRequest(self, response):
"""Assert that the given response has the status code 400"""
self.assertEqual(response.status_code, 400)
assert response.status_code == 400
def assertHttpMethodNotAllowed(self, response):
"""Assert that the given response has the status code 405"""
self.assertEqual(response.status_code, 405)
assert response.status_code == 405
def assertAuthDisabled(self, method, uri):
"""
@@ -88,4 +88,4 @@ class ApiTestCase(TestCase):
# We don't want this for views available to anonymous users.
basic_auth_header = "Basic " + base64.b64encode('username:password'.encode('utf-8')).decode('utf-8')
response = getattr(self.client, method)(uri, HTTP_AUTHORIZATION=basic_auth_header)
self.assertNotEqual(response.status_code, 403)
assert response.status_code != 403

View File

@@ -121,8 +121,8 @@ class OAuth2AllowInActiveUsersTests(TestCase): # lint-amnesty, pylint: disable=
the expected error_code in the JSON response body.
"""
response_dict = json.loads(response.content.decode('utf-8'))
self.assertEqual(response.status_code, status_code)
self.assertEqual(response_dict['error_code'], error_code)
assert response.status_code == status_code
assert response_dict['error_code'] == error_code
@ddt.data(None, {})
def test_get_form_with_wrong_authorization_header_token_type_failing(self, params):
@@ -132,31 +132,31 @@ class OAuth2AllowInActiveUsersTests(TestCase): # lint-amnesty, pylint: disable=
params,
HTTP_AUTHORIZATION='Wrong token-type-obviously'
)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
# If no Authorization header is provided that contains a bearer token,
# authorization passes to the next registered authorization class, or
# (in this case) to standard DRF fallback code, so no error_code is
# provided (yet).
self.assertNotIn('error_code', json.loads(response.content.decode('utf-8')))
assert 'error_code' not in json.loads(response.content.decode('utf-8'))
def test_get_form_passing_auth_with_dot(self):
response = self.get_with_bearer_token(self.OAUTH2_BASE_TESTING_URL, token=self.dot_access_token.token)
self.assertEqual(response.status_code, status.HTTP_200_OK)
assert response.status_code == status.HTTP_200_OK
def test_get_form_failing_auth_url_transport(self):
"""Ensure GETing form over OAuth with correct client credentials in query fails when DEBUG is False"""
query = urlencode({'access_token': self.dot_access_token.token})
response = self.csrf_client.get(self.OAUTH2_BASE_TESTING_URL + '?%s' % query)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
# This case is handled directly by DRF so no error_code is provided (yet).
self.assertNotIn('error_code', json.loads(response.content.decode('utf-8')))
assert 'error_code' not in json.loads(response.content.decode('utf-8'))
def test_post_form_passing_auth(self):
"""Ensure POSTing form over OAuth with correct credentials passes and does not require CSRF"""
response = self.post_with_bearer_token(self.OAUTH2_BASE_TESTING_URL)
self.assertEqual(response.status_code, status.HTTP_200_OK)
assert response.status_code == status.HTTP_200_OK
def test_post_form_token_removed_failing_auth(self):
"""Ensure POSTing when there is no OAuth access token in db fails"""
@@ -248,14 +248,14 @@ class OAuthDenyDisabledUsers(OAuth2AllowInActiveUsersTests): # pylint: disable=
Asserts response with disabled user with DOT App
"""
response = self.get_with_bearer_token(self.OAUTH2_BASE_TESTING_URL, token=self.dot_access_token.token)
self.assertEqual(response.status_code, status.HTTP_200_OK)
assert response.status_code == status.HTTP_200_OK
def test_post_form_passing_auth(self):
"""
Asserts response with disabled user with DOT App
"""
response = self.post_with_bearer_token(self.OAUTH2_BASE_TESTING_URL)
self.assertEqual(response.status_code, status.HTTP_200_OK)
assert response.status_code == status.HTTP_200_OK
def test_get_form_without_oauth_app(self):
"""
@@ -263,7 +263,7 @@ class OAuthDenyDisabledUsers(OAuth2AllowInActiveUsersTests): # pylint: disable=
"""
dot_models.Application.objects.filter(user_id=self.user.id).delete()
response = self.get_with_bearer_token(self.OAUTH2_BASE_TESTING_URL, token=self.dot_access_token.token)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_post_form_without_oauth_app(self):
"""
@@ -271,4 +271,4 @@ class OAuthDenyDisabledUsers(OAuth2AllowInActiveUsersTests): # pylint: disable=
"""
dot_models.Application.objects.filter(user_id=self.user.id).delete()
response = self.post_with_bearer_token(self.OAUTH2_BASE_TESTING_URL)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
assert response.status_code == status.HTTP_401_UNAUTHORIZED

View File

@@ -17,7 +17,7 @@ class TestDictExceptionsAllowDictDetails(TestCase):
def test_drf_errors_are_not_coerced_to_strings(self):
# Demonstrate that dictionaries in exceptions are not coerced to strings.
exc = drf_exceptions.AuthenticationFailed({u'error_code': -1})
self.assertNotIsInstance(exc.detail, six.string_types)
assert not isinstance(exc.detail, six.string_types)
@ddt.data(
drf_exceptions.AuthenticationFailed,
@@ -28,13 +28,13 @@ class TestDictExceptionsAllowDictDetails(TestCase):
)
def test_exceptions_allows_dict_detail(self, exception_class):
exc = exception_class({u'error_code': -1})
self.assertEqual(exc.detail, {u'error_code': u'-1'})
assert exc.detail == {u'error_code': u'-1'}
def test_method_not_allowed_allows_dict_detail(self):
exc = drf_exceptions.MethodNotAllowed(u'POST', {u'error_code': -1})
self.assertEqual(exc.detail, {u'error_code': u'-1'})
assert exc.detail == {u'error_code': u'-1'}
def test_not_acceptable_allows_dict_detail(self):
exc = drf_exceptions.NotAcceptable({u'error_code': -1}, available_renderers=['application/json'])
self.assertEqual(exc.detail, {u'error_code': u'-1'})
self.assertEqual(exc.available_renderers, ['application/json'])
assert exc.detail == {u'error_code': u'-1'}
assert exc.available_renderers == ['application/json']

View File

@@ -35,8 +35,8 @@ class AbsoluteURLFieldTests(TestCase):
)
def test_to_representation_with_absolute_url(self, value):
""" Verify the method returns the passed value, if the value is an absolute URL. """
self.assertEqual(self.field.to_representation(value), value)
assert self.field.to_representation(value) == value
def test_to_representation(self):
""" Verify the method returns an absolute URL. """
self.assertEqual(self.field.to_representation('/image.jpg'), MockRequest.ROOT + '/image.jpg')
assert self.field.to_representation('/image.jpg') == (MockRequest.ROOT + '/image.jpg')

View File

@@ -2,12 +2,12 @@
TestCases verifying proper behavior of custom DRF request parsers.
"""
from collections import namedtuple
from io import BytesIO
import pytest
from rest_framework import exceptions
from rest_framework.test import APITestCase, APIRequestFactory
from rest_framework.test import APIRequestFactory, APITestCase
from openedx.core.lib.api import parsers
@@ -36,9 +36,9 @@ class TestTypedFileUploadParser(APITestCase):
)
context = {'view': self.view, 'request': request}
result = self.parser.parse(stream=BytesIO(b'abcdefgh'), media_type='image/png', parser_context=context)
self.assertEqual(result.data, {})
self.assertIn('file', result.files)
self.assertEqual(result.files['file'].read(), b'abcdefgh')
assert result.data == {}
assert 'file' in result.files
assert result.files['file'].read() == b'abcdefgh'
def test_parse_unsupported_type(self):
"""
@@ -51,7 +51,7 @@ class TestTypedFileUploadParser(APITestCase):
HTTP_CONTENT_DISPOSITION='attachment; filename="file.tiff"',
)
context = {'view': self.view, 'request': request}
with self.assertRaises(exceptions.UnsupportedMediaType):
with pytest.raises(exceptions.UnsupportedMediaType):
self.parser.parse(stream=BytesIO(b'abcdefgh'), media_type='image/tiff', parser_context=context)
def test_parse_unconstrained_type(self):
@@ -68,9 +68,9 @@ class TestTypedFileUploadParser(APITestCase):
result = self.parser.parse(
stream=BytesIO(b'abcdefgh'), media_type='application/octet-stream', parser_context=context
)
self.assertEqual(result.data, {})
self.assertIn('file', result.files)
self.assertEqual(result.files['file'].read(), b'abcdefgh')
assert result.data == {}
assert 'file' in result.files
assert result.files['file'].read() == b'abcdefgh'
def test_parse_mismatched_filename_and_mimetype(self):
"""
@@ -84,10 +84,12 @@ class TestTypedFileUploadParser(APITestCase):
HTTP_CONTENT_DISPOSITION='attachment; filename="file.jpg"',
)
context = {'view': self.view, 'request': request}
with self.assertRaises(exceptions.ParseError) as err:
with pytest.raises(exceptions.ParseError) as err:
self.parser.parse(stream=BytesIO(b'abcdefgh'), media_type='image/png', parser_context=context)
self.assertIn('developer_message', err.detail) # lint-amnesty, pylint: disable=no-member
self.assertNotIn('user_message', err.detail) # lint-amnesty, pylint: disable=no-member
assert 'developer_message' in err.detail
# lint-amnesty, pylint: disable=no-member
assert 'user_message' not in err.detail
# lint-amnesty, pylint: disable=no-member
def test_no_acceptable_types(self):
"""
@@ -95,7 +97,7 @@ class TestTypedFileUploadParser(APITestCase):
everything.
"""
view = object()
self.assertFalse(hasattr(view, 'upload_media_types'))
assert not hasattr(view, 'upload_media_types')
request = self.request_factory.post(
'/',
@@ -103,7 +105,9 @@ class TestTypedFileUploadParser(APITestCase):
HTTP_CONTENT_DISPOSITION='attachment; filename="file.png"',
)
context = {'view': view, 'request': request}
with self.assertRaises(exceptions.UnsupportedMediaType) as err:
with pytest.raises(exceptions.UnsupportedMediaType) as err:
self.parser.parse(stream=BytesIO(b'abcdefgh'), media_type='image/png', parser_context=context)
self.assertIn('developer_message', err.detail) # lint-amnesty, pylint: disable=no-member
self.assertIn('user_message', err.detail) # lint-amnesty, pylint: disable=no-member
assert 'developer_message' in err.detail
# lint-amnesty, pylint: disable=no-member
assert 'user_message' in err.detail
# lint-amnesty, pylint: disable=no-member

View File

@@ -1,16 +1,15 @@
""" Tests for API permissions classes. """
import ddt
import pytest
from django.contrib.auth.models import AnonymousUser
from django.http import Http404
from django.test import RequestFactory, TestCase
from opaque_keys.edx.keys import CourseKey
from rest_framework.generics import GenericAPIView
from openedx.core.lib.api.permissions import IsCourseStaffInstructor, IsMasterCourseStaffInstructor, IsStaffOrOwner
from common.djangoapps.student.roles import CourseInstructorRole, CourseStaffRole
from common.djangoapps.student.tests.factories import UserFactory
from openedx.core.lib.api.permissions import IsCourseStaffInstructor, IsMasterCourseStaffInstructor, IsStaffOrOwner
class TestObject(object):
@@ -42,22 +41,22 @@ class IsCourseStaffInstructorTests(TestCase):
def test_course_staff_has_access(self):
CourseStaffRole(course_key=self.course_key).add_users(self.user)
self.assertTrue(self.permission.has_object_permission(self.request, None, self.obj))
assert self.permission.has_object_permission(self.request, None, self.obj)
def test_course_instructor_has_access(self):
CourseInstructorRole(course_key=self.course_key).add_users(self.user)
self.assertTrue(self.permission.has_object_permission(self.request, None, self.obj))
assert self.permission.has_object_permission(self.request, None, self.obj)
def test_course_coach_has_access(self):
self.request.user = self.coach
self.assertTrue(self.permission.has_object_permission(self.request, None, self.obj))
assert self.permission.has_object_permission(self.request, None, self.obj)
def test_any_user_has_no_access(self):
self.assertFalse(self.permission.has_object_permission(self.request, None, self.obj))
assert not self.permission.has_object_permission(self.request, None, self.obj)
def test_anonymous_has_no_access(self):
self.request.user = AnonymousUser()
self.assertFalse(self.permission.has_object_permission(self.request, None, self.obj))
assert not self.permission.has_object_permission(self.request, None, self.obj)
class IsMasterCourseStaffInstructorTests(TestCase):
@@ -76,31 +75,31 @@ class IsMasterCourseStaffInstructorTests(TestCase):
def test_course_staff_has_access(self):
CourseStaffRole(course_key=self.course_key).add_users(self.user)
self.assertTrue(self.permission.has_permission(self.get_request, None))
self.assertTrue(self.permission.has_permission(self.post_request, None))
assert self.permission.has_permission(self.get_request, None)
assert self.permission.has_permission(self.post_request, None)
def test_course_instructor_has_access(self):
CourseInstructorRole(course_key=self.course_key).add_users(self.user)
self.assertTrue(self.permission.has_permission(self.get_request, None))
self.assertTrue(self.permission.has_permission(self.post_request, None))
assert self.permission.has_permission(self.get_request, None)
assert self.permission.has_permission(self.post_request, None)
def test_any_user_has_partial_access(self):
self.assertFalse(self.permission.has_permission(self.get_request, None))
self.assertFalse(self.permission.has_permission(self.post_request, None))
assert not self.permission.has_permission(self.get_request, None)
assert not self.permission.has_permission(self.post_request, None)
def test_anonymous_has_no_access(self):
user = AnonymousUser()
self.get_request.user = user
self.post_request.user = user
self.assertFalse(self.permission.has_permission(self.get_request, None))
self.assertFalse(self.permission.has_permission(self.post_request, None))
assert not self.permission.has_permission(self.get_request, None)
assert not self.permission.has_permission(self.post_request, None)
def test_wrong_course_id_raises(self):
get_request = RequestFactory().get('/?master_course_id=this_is_invalid')
with self.assertRaises(Http404):
with pytest.raises(Http404):
self.permission.has_permission(get_request, None)
post_request = RequestFactory().post('/', data={'master_course_id': 'this_is_invalid'})
with self.assertRaises(Http404):
with pytest.raises(Http404):
self.permission.has_permission(post_request, None)
@@ -123,7 +122,7 @@ class IsStaffOrOwnerTests(TestCase):
permitted (boolean)
"""
self.request.user = user
self.assertEqual(self.permission.has_object_permission(self.request, None, self.obj), permitted)
assert self.permission.has_object_permission(self.request, None, self.obj) == permitted
def test_staff_user(self):
""" Staff users should be permitted. """
@@ -144,14 +143,14 @@ class IsStaffOrOwnerTests(TestCase):
def test_has_permission_as_staff(self):
""" Staff users always have permission. """
self.request.user = UserFactory(is_staff=True)
self.assertTrue(self.permission.has_permission(self.request, None))
assert self.permission.has_permission(self.request, None)
def test_has_permission_as_owner_with_get(self):
""" Owners always have permission to make GET actions. """
user = UserFactory()
request = RequestFactory().get('/?username={}'.format(user.username))
request.user = user
self.assertTrue(self.permission.has_permission(request, None))
assert self.permission.has_permission(request, None)
def test_has_permission_with_view_kwargs_as_owner_with_get(self):
""" Owners always have permission to make GET actions. """
@@ -159,7 +158,7 @@ class IsStaffOrOwnerTests(TestCase):
self.request.user = user
view = GenericAPIView()
view.kwargs = {'username': user.username}
self.assertTrue(self.permission.has_permission(self.request, view))
assert self.permission.has_permission(self.request, view)
@ddt.data('patch', 'post', 'put')
def test_has_permission_as_owner_with_edit(self, action):
@@ -170,14 +169,14 @@ class IsStaffOrOwnerTests(TestCase):
request = getattr(RequestFactory(), action)('/', data, format='json')
request.user = user
request.data = data # Note (CCB): This is a hack that should be fixed. (ECOM-3171)
self.assertTrue(self.permission.has_permission(request, None))
assert self.permission.has_permission(request, None)
def test_has_permission_as_non_owner(self):
""" Non-owners should not have permission. """
user = UserFactory()
request = RequestFactory().get('/?username={}'.format(user.username))
request.user = UserFactory()
self.assertFalse(self.permission.has_permission(request, None))
assert not self.permission.has_permission(request, None)
def test_has_permission_with_view_kwargs_as_non_owner(self):
""" Non-owners should not have permission. """
@@ -185,4 +184,4 @@ class IsStaffOrOwnerTests(TestCase):
self.request.user = user
view = GenericAPIView()
view.kwargs = {'username': UserFactory().username}
self.assertFalse(self.permission.has_permission(self.request, view))
assert not self.permission.has_permission(self.request, view)

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Tests for xblock_utils.py
"""
@@ -6,7 +5,9 @@ Tests for xblock_utils.py
import unittest
from uuid import UUID
import pytest
from django.conf import settings
from openedx.core.lib import blockstore_api as api
# A fake UUID that won't represent any real bundle/draft/collection:
@@ -27,7 +28,7 @@ class BlockstoreApiClientTest(unittest.TestCase):
def test_nonexistent_collection(self):
""" Request a collection that doesn't exist -> CollectionNotFound """
with self.assertRaises(api.CollectionNotFound):
with pytest.raises(api.CollectionNotFound):
api.get_collection(BAD_UUID)
def test_collection_crud(self):
@@ -35,27 +36,27 @@ class BlockstoreApiClientTest(unittest.TestCase):
title = "Fire 🔥 Collection"
# Create:
coll = api.create_collection(title)
self.assertEqual(coll.title, title)
self.assertIsInstance(coll.uuid, UUID)
assert coll.title == title
assert isinstance(coll.uuid, UUID)
# Fetch:
coll2 = api.get_collection(coll.uuid)
self.assertEqual(coll, coll2)
assert coll == coll2
# Update:
new_title = "Air 🌀 Collection"
coll3 = api.update_collection(coll.uuid, title=new_title)
self.assertEqual(coll3.title, new_title)
assert coll3.title == new_title
coll4 = api.get_collection(coll.uuid)
self.assertEqual(coll4.title, new_title)
assert coll4.title == new_title
# Delete:
api.delete_collection(coll.uuid)
with self.assertRaises(api.CollectionNotFound):
with pytest.raises(api.CollectionNotFound):
api.get_collection(coll.uuid)
# Bundles
def test_nonexistent_bundle(self):
""" Request a bundle that doesn't exist -> BundleNotFound """
with self.assertRaises(api.BundleNotFound):
with pytest.raises(api.BundleNotFound):
api.get_bundle(BAD_UUID)
def test_bundle_crud(self):
@@ -69,27 +70,27 @@ class BlockstoreApiClientTest(unittest.TestCase):
# Create:
bundle = api.create_bundle(coll.uuid, **args)
for attr, value in args.items():
self.assertEqual(getattr(bundle, attr), value)
self.assertIsInstance(bundle.uuid, UUID)
assert getattr(bundle, attr) == value
assert isinstance(bundle.uuid, UUID)
# Fetch:
bundle2 = api.get_bundle(bundle.uuid)
self.assertEqual(bundle, bundle2)
assert bundle == bundle2
# Update:
new_description = "Water Nation Bending Lessons"
bundle3 = api.update_bundle(bundle.uuid, description=new_description)
self.assertEqual(bundle3.description, new_description)
assert bundle3.description == new_description
bundle4 = api.get_bundle(bundle.uuid)
self.assertEqual(bundle4.description, new_description)
assert bundle4.description == new_description
# Delete:
api.delete_bundle(bundle.uuid)
with self.assertRaises(api.BundleNotFound):
with pytest.raises(api.BundleNotFound):
api.get_bundle(bundle.uuid)
# Drafts, files, and reading/writing file contents:
def test_nonexistent_draft(self):
""" Request a draft that doesn't exist -> DraftNotFound """
with self.assertRaises(api.DraftNotFound):
with pytest.raises(api.DraftNotFound):
api.get_draft(BAD_UUID)
def test_drafts_and_files(self):
@@ -101,45 +102,43 @@ class BlockstoreApiClientTest(unittest.TestCase):
bundle = api.create_bundle(coll.uuid, title="Earth 🗿 Bundle", slug="earth", description="another test bundle")
# Create a draft
draft = api.get_or_create_bundle_draft(bundle.uuid, draft_name="test-draft")
self.assertEqual(draft.bundle_uuid, bundle.uuid)
self.assertEqual(draft.name, "test-draft")
self.assertGreaterEqual(draft.updated_at.year, 2019)
assert draft.bundle_uuid == bundle.uuid
assert draft.name == 'test-draft'
assert draft.updated_at.year >= 2019
# And retrieve it again:
draft2 = api.get_or_create_bundle_draft(bundle.uuid, draft_name="test-draft")
self.assertEqual(draft, draft2)
assert draft == draft2
# Also test retrieving using get_draft
draft3 = api.get_draft(draft.uuid)
self.assertEqual(draft, draft3)
assert draft == draft3
# Write a file into the bundle:
api.write_draft_file(draft.uuid, "test.txt", b"initial version")
# Now the file should be visible in the draft:
draft_contents = api.get_bundle_file_data(bundle.uuid, "test.txt", use_draft=draft.name)
self.assertEqual(draft_contents, b"initial version")
assert draft_contents == b'initial version'
api.commit_draft(draft.uuid)
# Write a new version into the draft:
api.write_draft_file(draft.uuid, "test.txt", b"modified version")
published_contents = api.get_bundle_file_data(bundle.uuid, "test.txt")
self.assertEqual(published_contents, b"initial version")
assert published_contents == b'initial version'
draft_contents2 = api.get_bundle_file_data(bundle.uuid, "test.txt", use_draft=draft.name)
self.assertEqual(draft_contents2, b"modified version")
assert draft_contents2 == b'modified version'
# Now delete the draft:
api.delete_draft(draft.uuid)
draft_contents3 = api.get_bundle_file_data(bundle.uuid, "test.txt", use_draft=draft.name)
# Confirm the file is now reset:
self.assertEqual(draft_contents3, b"initial version")
assert draft_contents3 == b'initial version'
# Finaly, test the get_bundle_file* methods:
file_info1 = api.get_bundle_file_metadata(bundle.uuid, "test.txt")
self.assertEqual(file_info1.path, "test.txt")
self.assertEqual(file_info1.size, len(b"initial version"))
self.assertEqual(file_info1.hash_digest, "a45a5c6716276a66c4005534a51453ab16ea63c4")
assert file_info1.path == 'test.txt'
assert file_info1.size == len(b'initial version')
assert file_info1.hash_digest == 'a45a5c6716276a66c4005534a51453ab16ea63c4'
self.assertEqual(list(api.get_bundle_files(bundle.uuid)), [file_info1])
self.assertEqual(api.get_bundle_files_dict(bundle.uuid), {
"test.txt": file_info1,
})
assert list(api.get_bundle_files(bundle.uuid)) == [file_info1]
assert api.get_bundle_files_dict(bundle.uuid) == {'test.txt': file_info1}
# Links
@@ -163,16 +162,16 @@ class BlockstoreApiClientTest(unittest.TestCase):
api.commit_draft(lib2_draft.uuid) # Creates version 1
# Lib2 has no links:
self.assertFalse(api.get_bundle_links(lib2_bundle.uuid))
assert not api.get_bundle_links(lib2_bundle.uuid)
# Create a link from lib2 to lib1
link1_name = "lib2_to_lib1"
api.set_draft_link(lib2_draft.uuid, link1_name, lib1_bundle.uuid, version=1)
# Now confirm the link exists in the draft:
lib2_draft_links = api.get_bundle_links(lib2_bundle.uuid, use_draft=lib2_draft.name)
self.assertIn(link1_name, lib2_draft_links)
self.assertEqual(lib2_draft_links[link1_name].direct.bundle_uuid, lib1_bundle.uuid)
self.assertEqual(lib2_draft_links[link1_name].direct.version, 1)
assert link1_name in lib2_draft_links
assert lib2_draft_links[link1_name].direct.bundle_uuid == lib1_bundle.uuid
assert lib2_draft_links[link1_name].direct.version == 1
# Now commit the change to lib2:
api.commit_draft(lib2_draft.uuid) # Creates version 2
@@ -183,13 +182,13 @@ class BlockstoreApiClientTest(unittest.TestCase):
# And confirm the link exists in the resulting bundle version:
course_links = api.get_bundle_links(course_bundle.uuid)
self.assertIn(link2_name, course_links)
self.assertEqual(course_links[link2_name].direct.bundle_uuid, lib2_bundle.uuid)
self.assertEqual(course_links[link2_name].direct.version, 2)
assert link2_name in course_links
assert course_links[link2_name].direct.bundle_uuid == lib2_bundle.uuid
assert course_links[link2_name].direct.version == 2
# And since the links go course->lib2->lib1, course has an indirect link to lib1:
self.assertEqual(course_links[link2_name].indirect[0].bundle_uuid, lib1_bundle.uuid)
self.assertEqual(course_links[link2_name].indirect[0].version, 1)
assert course_links[link2_name].indirect[0].bundle_uuid == lib1_bundle.uuid
assert course_links[link2_name].indirect[0].version == 1
# Finally, test deleting a link from course's draft:
api.set_draft_link(course_draft.uuid, link2_name, None, None)
self.assertFalse(api.get_bundle_links(course_bundle.uuid, use_draft=course_draft.name))
assert not api.get_bundle_links(course_bundle.uuid, use_draft=course_draft.name)

View File

@@ -2,9 +2,9 @@
Tests for the gating API
"""
import unittest
import pytest
import six
from completion.models import BlockCompletion
from ddt import data, ddt, unpack
@@ -13,6 +13,7 @@ from milestones import api as milestones_api
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import Mock, patch
from common.djangoapps.student.tests.factories import UserFactory
from lms.djangoapps.gating import api as lms_gating_api
from lms.djangoapps.grades.constants import GradeOverrideFeatureEnum
from lms.djangoapps.grades.models import PersistentSubsectionGrade, PersistentSubsectionGradeOverride
@@ -20,7 +21,6 @@ from lms.djangoapps.grades.tests.base import GradeTestBase
from lms.djangoapps.grades.tests.utils import mock_get_score
from openedx.core.lib.gating import api as gating_api
from openedx.core.lib.gating.exceptions import GatingValidationError
from common.djangoapps.student.tests.factories import UserFactory
from xmodule.modulestore.tests.django_utils import TEST_DATA_SPLIT_MODULESTORE, ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
@@ -85,27 +85,27 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
""" Test test_get_prerequisite_milestone_returns_none """
prereq = gating_api._get_prerequisite_milestone(self.seq1.location) # pylint: disable=protected-access
self.assertIsNone(prereq)
self.assertTrue(mock_log.called)
assert prereq is None
assert mock_log.called
def test_get_prerequisite_milestone_returns_milestone(self):
""" Test test_get_prerequisite_milestone_returns_milestone """
gating_api.add_prerequisite(self.course.id, self.seq1.location)
prereq = gating_api._get_prerequisite_milestone(self.seq1.location) # pylint: disable=protected-access
self.assertIsNotNone(prereq)
assert prereq is not None
@data('', '0', '50', '100')
def test_validate_min_score_is_valid(self, min_score):
""" Test test_validate_min_score_is_valid """
self.assertIsNone(gating_api._validate_min_score(min_score)) # pylint: disable=protected-access
assert gating_api._validate_min_score(min_score) is None # pylint: disable=protected-access
@data('abc', '-10', '110')
def test_validate_min_score_raises(self, min_score):
""" Test test_validate_min_score_non_integer """
with self.assertRaises(GatingValidationError):
with pytest.raises(GatingValidationError):
gating_api._validate_min_score(min_score) # pylint: disable=protected-access
def test_find_gating_milestones(self):
@@ -116,10 +116,10 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
milestone = milestones_api.add_milestone(self.generic_milestone)
milestones_api.add_course_content_milestone(self.course.id, self.seq1.location, 'fulfills', milestone)
self.assertEqual(len(gating_api.find_gating_milestones(self.course.id, self.seq1.location, 'fulfills')), 1)
self.assertEqual(len(gating_api.find_gating_milestones(self.course.id, self.seq1.location, 'requires')), 0)
self.assertEqual(len(gating_api.find_gating_milestones(self.course.id, self.seq2.location, 'fulfills')), 0)
self.assertEqual(len(gating_api.find_gating_milestones(self.course.id, self.seq2.location, 'requires')), 1)
assert len(gating_api.find_gating_milestones(self.course.id, self.seq1.location, 'fulfills')) == 1
assert len(gating_api.find_gating_milestones(self.course.id, self.seq1.location, 'requires')) == 0
assert len(gating_api.find_gating_milestones(self.course.id, self.seq2.location, 'fulfills')) == 0
assert len(gating_api.find_gating_milestones(self.course.id, self.seq2.location, 'requires')) == 1
def test_get_gating_milestone_not_none(self):
""" Test test_get_gating_milestone_not_none """
@@ -127,8 +127,8 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
gating_api.add_prerequisite(self.course.id, self.seq1.location)
gating_api.set_required_content(self.course.id, self.seq2.location, self.seq1.location, 100)
self.assertIsNotNone(gating_api.get_gating_milestone(self.course.id, self.seq1.location, 'fulfills'))
self.assertIsNotNone(gating_api.get_gating_milestone(self.course.id, self.seq2.location, 'requires'))
assert gating_api.get_gating_milestone(self.course.id, self.seq1.location, 'fulfills') is not None
assert gating_api.get_gating_milestone(self.course.id, self.seq2.location, 'requires') is not None
def test_get_gating_milestone_is_none(self):
""" Test test_get_gating_milestone_is_none """
@@ -136,8 +136,8 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
gating_api.add_prerequisite(self.course.id, self.seq1.location)
gating_api.set_required_content(self.course.id, self.seq2.location, self.seq1.location, 100)
self.assertIsNone(gating_api.get_gating_milestone(self.course.id, self.seq1.location, 'requires'))
self.assertIsNone(gating_api.get_gating_milestone(self.course.id, self.seq2.location, 'fulfills'))
assert gating_api.get_gating_milestone(self.course.id, self.seq1.location, 'requires') is None
assert gating_api.get_gating_milestone(self.course.id, self.seq2.location, 'fulfills') is None
def test_prerequisites(self):
""" Test test_prerequisites """
@@ -145,15 +145,15 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
gating_api.add_prerequisite(self.course.id, self.seq1.location)
prereqs = gating_api.get_prerequisites(self.course.id)
self.assertEqual(len(prereqs), 1)
self.assertEqual(prereqs[0]['block_display_name'], self.seq1.display_name)
self.assertEqual(prereqs[0]['block_usage_key'], six.text_type(self.seq1.location))
self.assertTrue(gating_api.is_prerequisite(self.course.id, self.seq1.location))
assert len(prereqs) == 1
assert prereqs[0]['block_display_name'] == self.seq1.display_name
assert prereqs[0]['block_usage_key'] == six.text_type(self.seq1.location)
assert gating_api.is_prerequisite(self.course.id, self.seq1.location)
gating_api.remove_prerequisite(self.seq1.location)
self.assertEqual(len(gating_api.get_prerequisites(self.course.id)), 0)
self.assertFalse(gating_api.is_prerequisite(self.course.id, self.seq1.location))
assert len(gating_api.get_prerequisites(self.course.id)) == 0
assert not gating_api.is_prerequisite(self.course.id, self.seq1.location)
def test_required_content(self):
""" Test test_required_content """
@@ -164,18 +164,18 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
prereq_content_key, min_score, min_completion = gating_api.get_required_content(
self.course.id, self.seq2.location
)
self.assertEqual(prereq_content_key, six.text_type(self.seq1.location))
self.assertEqual(min_score, 100)
self.assertEqual(min_completion, 100)
assert prereq_content_key == six.text_type(self.seq1.location)
assert min_score == 100
assert min_completion == 100
gating_api.set_required_content(self.course.id, self.seq2.location, None, None, None)
prereq_content_key, min_score, min_completion = gating_api.get_required_content(
self.course.id, self.seq2.location
)
self.assertIsNone(prereq_content_key)
self.assertIsNone(min_score)
self.assertIsNone(min_completion)
assert prereq_content_key is None
assert min_score is None
assert min_completion is None
def test_get_gated_content(self):
"""
@@ -185,19 +185,19 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
staff = UserFactory(is_staff=True)
student = UserFactory(is_staff=False)
self.assertEqual(gating_api.get_gated_content(self.course, staff), [])
self.assertEqual(gating_api.get_gated_content(self.course, student), [])
assert gating_api.get_gated_content(self.course, staff) == []
assert gating_api.get_gated_content(self.course, student) == []
gating_api.add_prerequisite(self.course.id, self.seq1.location)
gating_api.set_required_content(self.course.id, self.seq2.location, self.seq1.location, 100)
milestone = milestones_api.get_course_content_milestones(self.course.id, self.seq2.location, 'requires')[0]
self.assertEqual(gating_api.get_gated_content(self.course, staff), [])
self.assertEqual(gating_api.get_gated_content(self.course, student), [six.text_type(self.seq2.location)])
assert gating_api.get_gated_content(self.course, staff) == []
assert gating_api.get_gated_content(self.course, student) == [six.text_type(self.seq2.location)]
milestones_api.add_user_milestone({'id': student.id}, milestone)
self.assertEqual(gating_api.get_gated_content(self.course, student), [])
assert gating_api.get_gated_content(self.course, student) == []
@data(
(100, 0, 50, 0, False),
@@ -221,7 +221,7 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
milestone = milestones_api.add_milestone(self.generic_milestone)
milestones_api.add_course_content_milestone(self.course.id, self.seq1.location, 'fulfills', milestone)
self.assertFalse(gating_api.is_gate_fulfilled(self.course.id, self.seq1.location, student.id))
assert not gating_api.is_gate_fulfilled(self.course.id, self.seq1.location, student.id)
# complete the prerequisite to unlock the gated content
# this call triggers reevaluation of prerequisites fulfilled by the gating block.
@@ -232,9 +232,7 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
Mock(location=self.seq1.location, percent_graded=learner_score / 100.0),
student,
)
self.assertEqual(
gating_api.is_gate_fulfilled(self.course.id, self.seq1.location, student.id), is_gate_fulfilled
)
assert gating_api.is_gate_fulfilled(self.course.id, self.seq1.location, student.id) == is_gate_fulfilled
@data(
(1, 1, 100),
@@ -270,7 +268,7 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
html_block.location: user_html_completion,
}
completion_percentage = gating_api.get_subsection_completion_percentage(self.seq1.location, student)
self.assertEqual(completion_percentage, expected_completion_percentage)
assert completion_percentage == expected_completion_percentage
@data(
('discussion', None, 100),
@@ -310,7 +308,7 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
component.location: completed,
}
completion_percentage = gating_api.get_subsection_completion_percentage(self.seq1.location, student)
self.assertEqual(completion_percentage, expected_completion_percentage)
assert completion_percentage == expected_completion_percentage
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
def test_compute_is_prereq_met(self):
@@ -327,30 +325,30 @@ class TestGatingApi(ModuleStoreTestCase, MilestonesTestCaseMixin):
mock_grade.return_value = 75
# don't force recompute
prereq_met, prereq_meta_info = gating_api.compute_is_prereq_met(self.seq2.location, student.id, False)
self.assertFalse(prereq_met)
self.assertIsNone(prereq_meta_info['url'])
self.assertIsNone(prereq_meta_info['display_name'])
assert not prereq_met
assert prereq_meta_info['url'] is None
assert prereq_meta_info['display_name'] is None
# force recompute
prereq_met, prereq_meta_info = gating_api.compute_is_prereq_met(self.seq2.location, student.id, True)
self.assertFalse(prereq_met)
self.assertIsNotNone(prereq_meta_info['url'])
self.assertIsNotNone(prereq_meta_info['display_name'])
assert not prereq_met
assert prereq_meta_info['url'] is not None
assert prereq_meta_info['display_name'] is not None
# change to passing grade
mock_grade.return_value = 100
# don't force recompute
prereq_met, prereq_meta_info = gating_api.compute_is_prereq_met(self.seq2.location, student.id, False)
self.assertFalse(prereq_met)
self.assertIsNone(prereq_meta_info['url'])
self.assertIsNone(prereq_meta_info['display_name'])
assert not prereq_met
assert prereq_meta_info['url'] is None
assert prereq_meta_info['display_name'] is None
# force recompute
prereq_met, prereq_meta_info = gating_api.compute_is_prereq_met(self.seq2.location, student.id, True)
self.assertTrue(prereq_met)
self.assertIsNotNone(prereq_meta_info['url'])
self.assertIsNotNone(prereq_meta_info['display_name'])
assert prereq_met
assert prereq_meta_info['url'] is not None
assert prereq_meta_info['display_name'] is not None
class TestGatingGradesIntegration(GradeTestBase):

View File

@@ -27,7 +27,7 @@ class TestRequestCachedDecorator(TestCase):
"""
to_be_wrapped = Mock()
to_be_wrapped.return_value = 42
self.assertEqual(to_be_wrapped.call_count, 0)
assert to_be_wrapped.call_count == 0
def mock_wrapper(*args, **kwargs):
"""Simple wrapper to let us decorate our mock."""
@@ -35,12 +35,12 @@ class TestRequestCachedDecorator(TestCase):
wrapped = request_cached()(mock_wrapper) # lint-amnesty, pylint: disable=no-value-for-parameter
result = wrapped()
self.assertEqual(result, 42)
self.assertEqual(to_be_wrapped.call_count, 1)
assert result == 42
assert to_be_wrapped.call_count == 1
result = wrapped()
self.assertEqual(result, 42)
self.assertEqual(to_be_wrapped.call_count, 1)
assert result == 42
assert to_be_wrapped.call_count == 1
def test_request_cached_with_caches_despite_changing_wrapped_result(self):
"""
@@ -48,7 +48,7 @@ class TestRequestCachedDecorator(TestCase):
"""
to_be_wrapped = Mock()
to_be_wrapped.side_effect = [1, 2, 3]
self.assertEqual(to_be_wrapped.call_count, 0)
assert to_be_wrapped.call_count == 0
def mock_wrapper(*args, **kwargs):
"""Simple wrapper to let us decorate our mock."""
@@ -56,24 +56,24 @@ class TestRequestCachedDecorator(TestCase):
wrapped = request_cached()(mock_wrapper) # lint-amnesty, pylint: disable=no-value-for-parameter
result = wrapped()
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 1)
assert result == 1
assert to_be_wrapped.call_count == 1
result = wrapped()
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 1)
assert result == 1
assert to_be_wrapped.call_count == 1
direct_result = mock_wrapper()
self.assertEqual(direct_result, 2)
self.assertEqual(to_be_wrapped.call_count, 2)
assert direct_result == 2
assert to_be_wrapped.call_count == 2
result = wrapped()
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 2)
assert result == 1
assert to_be_wrapped.call_count == 2
direct_result = mock_wrapper()
self.assertEqual(direct_result, 3)
self.assertEqual(to_be_wrapped.call_count, 3)
assert direct_result == 3
assert to_be_wrapped.call_count == 3
def test_request_cached_with_changing_args(self):
"""
@@ -82,7 +82,7 @@ class TestRequestCachedDecorator(TestCase):
"""
to_be_wrapped = Mock()
to_be_wrapped.side_effect = [1, 2, 3, 4, 5, 6]
self.assertEqual(to_be_wrapped.call_count, 0)
assert to_be_wrapped.call_count == 0
def mock_wrapper(*args, **kwargs):
"""Simple wrapper to let us decorate our mock."""
@@ -92,27 +92,27 @@ class TestRequestCachedDecorator(TestCase):
# This will be a miss, and make an underlying call.
result = wrapped(1)
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 1)
assert result == 1
assert to_be_wrapped.call_count == 1
# This will be a miss, and make an underlying call.
result = wrapped(2)
self.assertEqual(result, 2)
self.assertEqual(to_be_wrapped.call_count, 2)
assert result == 2
assert to_be_wrapped.call_count == 2
# This is bypass of the decorator.
direct_result = mock_wrapper(3)
self.assertEqual(direct_result, 3)
self.assertEqual(to_be_wrapped.call_count, 3)
assert direct_result == 3
assert to_be_wrapped.call_count == 3
# These will be hits, and not make an underlying call.
result = wrapped(1)
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 3)
assert result == 1
assert to_be_wrapped.call_count == 3
result = wrapped(2)
self.assertEqual(result, 2)
self.assertEqual(to_be_wrapped.call_count, 3)
assert result == 2
assert to_be_wrapped.call_count == 3
def test_request_cached_with_changing_kwargs(self):
"""
@@ -121,7 +121,7 @@ class TestRequestCachedDecorator(TestCase):
"""
to_be_wrapped = Mock()
to_be_wrapped.side_effect = [1, 2, 3, 4, 5, 6]
self.assertEqual(to_be_wrapped.call_count, 0)
assert to_be_wrapped.call_count == 0
def mock_wrapper(*args, **kwargs):
"""Simple wrapper to let us decorate our mock."""
@@ -131,42 +131,42 @@ class TestRequestCachedDecorator(TestCase):
# This will be a miss, and make an underlying call.
result = wrapped(1, foo=1)
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 1)
assert result == 1
assert to_be_wrapped.call_count == 1
# This will be a miss, and make an underlying call.
result = wrapped(2, foo=2)
self.assertEqual(result, 2)
self.assertEqual(to_be_wrapped.call_count, 2)
assert result == 2
assert to_be_wrapped.call_count == 2
# This is bypass of the decorator.
direct_result = mock_wrapper(3, foo=3)
self.assertEqual(direct_result, 3)
self.assertEqual(to_be_wrapped.call_count, 3)
assert direct_result == 3
assert to_be_wrapped.call_count == 3
# These will be hits, and not make an underlying call.
result = wrapped(1, foo=1)
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 3)
assert result == 1
assert to_be_wrapped.call_count == 3
result = wrapped(2, foo=2)
self.assertEqual(result, 2)
self.assertEqual(to_be_wrapped.call_count, 3)
assert result == 2
assert to_be_wrapped.call_count == 3
# Since we're changing foo, this will be a miss.
result = wrapped(2, foo=5)
self.assertEqual(result, 4)
self.assertEqual(to_be_wrapped.call_count, 4)
assert result == 4
assert to_be_wrapped.call_count == 4
# Since we're adding bar, this will be a miss.
result = wrapped(2, foo=1, bar=2)
self.assertEqual(result, 5)
self.assertEqual(to_be_wrapped.call_count, 5)
assert result == 5
assert to_be_wrapped.call_count == 5
# Should be a hit, even when kwargs are in a different order
result = wrapped(2, bar=2, foo=1)
self.assertEqual(result, 5)
self.assertEqual(to_be_wrapped.call_count, 5)
assert result == 5
assert to_be_wrapped.call_count == 5
def test_request_cached_mixed_unicode_str_args(self):
"""
@@ -180,13 +180,13 @@ class TestRequestCachedDecorator(TestCase):
assert isinstance(arg2, six.text_type), 'Second parameter has to be of type `unicode`'
return True
self.assertTrue(dummy_function('Hello', u'World'), 'Should be callable with ASCII chars')
self.assertTrue(dummy_function('H∂llå', u'Wørld'), 'Should be callable with non-ASCII chars')
assert dummy_function('Hello', u'World'), 'Should be callable with ASCII chars'
assert dummy_function('H∂llå', u'Wørld'), 'Should be callable with non-ASCII chars'
wrapped = request_cached()(dummy_function) # lint-amnesty, pylint: disable=no-value-for-parameter
self.assertTrue(wrapped('Hello', u'World'), 'Wrapper should handle ASCII only chars')
self.assertTrue(wrapped('H∂llå', u'Wørld'), 'Wrapper should handle non-ASCII chars')
assert wrapped('Hello', u'World'), 'Wrapper should handle ASCII only chars'
assert wrapped('H∂llå', u'Wørld'), 'Wrapper should handle non-ASCII chars'
def test_request_cached_with_none_result(self):
"""
@@ -196,7 +196,7 @@ class TestRequestCachedDecorator(TestCase):
"""
to_be_wrapped = Mock()
to_be_wrapped.side_effect = [None, None, None, 1, 1]
self.assertEqual(to_be_wrapped.call_count, 0)
assert to_be_wrapped.call_count == 0
def mock_wrapper(*args, **kwargs):
"""Simple wrapper to let us decorate our mock."""
@@ -206,27 +206,27 @@ class TestRequestCachedDecorator(TestCase):
# This will be a miss, and make an underlying call.
result = wrapped(1)
self.assertEqual(result, None)
self.assertEqual(to_be_wrapped.call_count, 1)
assert result is None
assert to_be_wrapped.call_count == 1
# This will be a miss, and make an underlying call.
result = wrapped(2)
self.assertEqual(result, None)
self.assertEqual(to_be_wrapped.call_count, 2)
assert result is None
assert to_be_wrapped.call_count == 2
# This is bypass of the decorator.
direct_result = mock_wrapper(3)
self.assertEqual(direct_result, None)
self.assertEqual(to_be_wrapped.call_count, 3)
assert direct_result is None
assert to_be_wrapped.call_count == 3
# These will be hits, and not make an underlying call.
result = wrapped(1)
self.assertEqual(result, None)
self.assertEqual(to_be_wrapped.call_count, 3)
assert result is None
assert to_be_wrapped.call_count == 3
result = wrapped(2)
self.assertEqual(result, None)
self.assertEqual(to_be_wrapped.call_count, 3)
assert result is None
assert to_be_wrapped.call_count == 3
def test_request_cached_with_request_cache_getter(self):
"""
@@ -235,7 +235,7 @@ class TestRequestCachedDecorator(TestCase):
"""
to_be_wrapped = Mock()
to_be_wrapped.side_effect = [1, 2, 3]
self.assertEqual(to_be_wrapped.call_count, 0)
assert to_be_wrapped.call_count == 0
def mock_wrapper(*args, **kwargs):
"""Simple wrapper to let us decorate our mock."""
@@ -246,22 +246,22 @@ class TestRequestCachedDecorator(TestCase):
# This will be a miss, and make an underlying call.
result = wrapped(1)
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 1)
assert result == 1
assert to_be_wrapped.call_count == 1
# This will be a miss, and make an underlying call.
result = wrapped(2)
self.assertEqual(result, 2)
self.assertEqual(to_be_wrapped.call_count, 2)
assert result == 2
assert to_be_wrapped.call_count == 2
# These will be a hits, and not make an underlying call.
result = wrapped(1)
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 2)
assert result == 1
assert to_be_wrapped.call_count == 2
# Ensure the appropriate request cache was used
self.assertFalse(RequestCache().data)
self.assertTrue(RequestCache('test').data)
assert not RequestCache().data
assert RequestCache('test').data
def test_request_cached_with_arg_map_function(self):
"""
@@ -270,7 +270,7 @@ class TestRequestCachedDecorator(TestCase):
"""
to_be_wrapped = Mock()
to_be_wrapped.side_effect = [1, 2, 3]
self.assertEqual(to_be_wrapped.call_count, 0)
assert to_be_wrapped.call_count == 0
def mock_wrapper(*args, **kwargs):
"""Simple wrapper to let us decorate our mock."""
@@ -281,19 +281,19 @@ class TestRequestCachedDecorator(TestCase):
# This will be a miss, and make an underlying call.
result = wrapped(1)
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 1)
assert result == 1
assert to_be_wrapped.call_count == 1
# This will be a miss, and make an underlying call.
result = wrapped(2)
self.assertEqual(result, 2)
self.assertEqual(to_be_wrapped.call_count, 2)
assert result == 2
assert to_be_wrapped.call_count == 2
# These will be a hits, and not make an underlying call.
result = wrapped(1)
self.assertEqual(result, 1)
self.assertEqual(to_be_wrapped.call_count, 2)
assert result == 1
assert to_be_wrapped.call_count == 2
result = wrapped(3)
self.assertEqual(result, 2)
self.assertEqual(to_be_wrapped.call_count, 2)
assert result == 2
assert to_be_wrapped.call_count == 2

View File

@@ -1,11 +1,10 @@
"""
Tests of management command utility code
"""
from unittest import TestCase
import ddt
import pytest
from django.core.management import CommandError
from .. import command_utils
@@ -30,7 +29,7 @@ class MutuallyExclusiveRequiredOptionsTestCase(TestCase):
@ddt.unpack
def test_successful_exclusive_options(self, exclusions, opts, expected):
result = command_utils.get_mutually_exclusive_required_option(opts, *exclusions)
self.assertEqual(result, expected)
assert result == expected
@ddt.data(
(['opta'], {'opta': 0}),
@@ -45,5 +44,5 @@ class MutuallyExclusiveRequiredOptionsTestCase(TestCase):
)
@ddt.unpack
def test_invalid_exclusive_options(self, exclusions, opts):
with self.assertRaises(CommandError):
with pytest.raises(CommandError):
command_utils.get_mutually_exclusive_required_option(opts, *exclusions)

View File

@@ -1,8 +1,7 @@
"""
Tests for the plugin API
"""
import pytest
from django.test import TestCase
from edx_django_utils.plugins import PluginError
@@ -19,7 +18,7 @@ class TestCourseTabApi(TestCase):
Verify that get_plugin works as expected.
"""
tab_type = CourseTabPluginManager.get_plugin("instructor")
self.assertEqual(tab_type.title, "Instructor")
assert tab_type.title == 'Instructor'
with self.assertRaises(PluginError):
with pytest.raises(PluginError):
CourseTabPluginManager.get_plugin("no_such_type")

View File

@@ -1,8 +1,7 @@
""" Tests of specific tabs. """
from unittest import TestCase
import pytest
from mock import Mock, patch
import xmodule.tabs as xmodule_tabs
@@ -32,10 +31,9 @@ class CourseTabPluginManagerTestCase(TestCase):
"Third": create_mock_plugin(tab_type="Third", priority=3),
}
get_available_plugins.return_value = mock_plugins
self.assertEqual(
[plugin.type for plugin in CourseTabPluginManager.get_tab_types()],
["First", "Second", "Third", "Duplicate", "Duplicate", "Last"]
)
assert [plugin.type for plugin in CourseTabPluginManager.get_tab_types()] == [
'First', 'Second', 'Third', 'Duplicate', 'Duplicate', 'Last'
]
class KeyCheckerTestCase(TestCase):
@@ -50,9 +48,9 @@ class KeyCheckerTestCase(TestCase):
def test_key_checker(self):
self.assertTrue(xmodule_tabs.key_checker(self.valid_keys)(self.dict_value, raise_error=False))
self.assertFalse(xmodule_tabs.key_checker(self.invalid_keys)(self.dict_value, raise_error=False))
with self.assertRaises(xmodule_tabs.InvalidTabsException):
assert xmodule_tabs.key_checker(self.valid_keys)(self.dict_value, raise_error=False)
assert not xmodule_tabs.key_checker(self.invalid_keys)(self.dict_value, raise_error=False)
with pytest.raises(xmodule_tabs.InvalidTabsException):
xmodule_tabs.key_checker(self.invalid_keys)(self.dict_value)
@@ -68,8 +66,8 @@ class NeedNameTestCase(TestCase):
self.invalid_dict = {'a': 1, 'b': 2}
def test_need_name(self):
self.assertTrue(xmodule_tabs.need_name(self.valid_dict1))
self.assertTrue(xmodule_tabs.need_name(self.valid_dict2))
self.assertTrue(xmodule_tabs.need_name(self.valid_dict3))
with self.assertRaises(xmodule_tabs.InvalidTabsException):
assert xmodule_tabs.need_name(self.valid_dict1)
assert xmodule_tabs.need_name(self.valid_dict2)
assert xmodule_tabs.need_name(self.valid_dict3)
with pytest.raises(xmodule_tabs.InvalidTabsException):
xmodule_tabs.need_name(self.invalid_dict)

View File

@@ -24,7 +24,7 @@ class CourseImageTestCase(ModuleStoreTestCase):
"""
if not expected_url.startswith("/"):
expected_url = "/" + expected_url
self.assertEqual(expected_url, actual_url)
assert expected_url == actual_url
def test_get_image_url(self):
"""Test image URL formatting."""
@@ -61,10 +61,7 @@ class CourseImageTestCase(ModuleStoreTestCase):
`DEFAULT_COURSE_ABOUT_IMAGE_URL` defined in the settings.
"""
course = CourseFactory.create(course_image='', default_store=default_store)
self.assertEqual(
'static/test.png',
course_image_url(course),
)
assert 'static/test.png' == course_image_url(course)
def test_get_banner_image_url(self):
"""Test banner image URL formatting."""

View File

@@ -29,23 +29,23 @@ class TestDerivedSettings(TestCase):
def test_derived_settings_are_derived(self):
derive_settings(__name__)
self.assertEqual(self.module.DERIVED_VALUE, 'mutter paneer')
self.assertEqual(self.module.ANOTHER_DERIVED_VALUE, 'mutter paneer with naan')
assert self.module.DERIVED_VALUE == 'mutter paneer'
assert self.module.ANOTHER_DERIVED_VALUE == 'mutter paneer with naan'
def test_unregistered_derived_settings(self):
derive_settings(__name__)
self.assertTrue(callable(self.module.UNREGISTERED_DERIVED_VALUE))
assert callable(self.module.UNREGISTERED_DERIVED_VALUE)
def test_derived_settings_overridden(self):
self.module.DERIVED_VALUE = 'aloo gobi'
derive_settings(__name__)
self.assertEqual(self.module.DERIVED_VALUE, 'aloo gobi')
self.assertEqual(self.module.ANOTHER_DERIVED_VALUE, 'aloo gobi with naan')
assert self.module.DERIVED_VALUE == 'aloo gobi'
assert self.module.ANOTHER_DERIVED_VALUE == 'aloo gobi with naan'
def test_derived_dict_settings(self):
derive_settings(__name__)
self.assertEqual(self.module.DICT_VALUE['test_key'], 'mutter paneermutter paneermutter paneer')
assert self.module.DICT_VALUE['test_key'] == 'mutter paneermutter paneermutter paneer'
def test_derived_nested_settings(self):
derive_settings(__name__)
self.assertEqual(self.module.DICT_VALUE['list_key'][1], 'mutter paneer')
assert self.module.DICT_VALUE['list_key'][1] == 'mutter paneer'

View File

@@ -34,7 +34,7 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
cache.clear()
def _mock_catalog_api(self, responses, url=None):
self.assertTrue(httpretty.is_enabled(), msg='httpretty must be enabled to mock Catalog API calls.')
assert httpretty.is_enabled(), 'httpretty must be enabled to mock Catalog API calls.'
url = url if url else CatalogIntegration.current().get_internal_api_url().strip('/') + '/programs/'
@@ -42,7 +42,7 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
def _assert_num_requests(self, count):
"""DRY helper for verifying request counts."""
self.assertEqual(len(httpretty.httpretty.latest_requests), count)
assert len(httpretty.httpretty.latest_requests) == count
def test_get_unpaginated_data(self):
"""Verify that unpaginated data can be retrieved."""
@@ -63,8 +63,8 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
actual_collection = get_edx_api_data(catalog_integration, 'programs', api=api)
# Verify that the helper function didn't initialize its own client.
self.assertFalse(mock_init.called)
self.assertEqual(actual_collection, expected_collection)
assert not mock_init.called
assert actual_collection == expected_collection
# Verify the API was actually hit (not the cache)
self._assert_num_requests(1)
@@ -92,7 +92,7 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
self._mock_catalog_api(responses)
actual_collection = get_edx_api_data(catalog_integration, 'programs', api=api)
self.assertEqual(actual_collection, expected_collection)
assert actual_collection == expected_collection
self._assert_num_requests(len(expected_collection))
@@ -121,7 +121,7 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
)
actual_collection = get_edx_api_data(catalog_integration, 'programs', api=api, traverse_pagination=False)
self.assertEqual(actual_collection, expected_response)
assert actual_collection == expected_response
self._assert_num_requests(1)
def test_get_specific_resource(self):
@@ -143,7 +143,7 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
)
actual_resource = get_edx_api_data(catalog_integration, 'programs', api=api, resource_id=resource_id)
self.assertEqual(actual_resource, expected_resource)
assert actual_resource == expected_resource
self._assert_num_requests(1)
@@ -172,7 +172,7 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
)
actual_resource = get_edx_api_data(catalog_integration, 'programs', api=api, resource_id=resource_id)
self.assertEqual(actual_resource, expected_resource)
assert actual_resource == expected_resource
self._assert_num_requests(1)
@@ -203,7 +203,7 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
actual_resource_for_lang = get_edx_api_data(
catalog_integration, 'course_runs', resource_id=resource_id, api=api, cache_key=cache_key, fields=['lang']
)
self.assertEqual(actual_resource_for_lang, expected_resource_for_lang)
assert actual_resource_for_lang == expected_resource_for_lang
# Hit the cache
actual_resource = get_edx_api_data(
@@ -211,7 +211,7 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
fields=['weeks_to_complete']
)
self.assertEqual(actual_resource, expected_resource_for_weeks_to_complete)
assert actual_resource == expected_resource_for_weeks_to_complete
# Verify that only one requests were made, not three.
self._assert_num_requests(1)
@@ -252,12 +252,12 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
# Hit the cache.
actual_collection = get_edx_api_data(catalog_integration, 'programs', api=api, cache_key=cache_key)
self.assertEqual(actual_collection, expected_collection)
assert actual_collection == expected_collection
actual_resource = get_edx_api_data(
catalog_integration, 'programs', api=api, resource_id=resource_id, cache_key=cache_key
)
self.assertEqual(actual_resource, expected_resource)
assert actual_resource == expected_resource
# Verify that only two requests were made, not four.
self._assert_num_requests(2)
@@ -269,8 +269,8 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
actual = get_edx_api_data(catalog_integration, 'programs', api=None)
self.assertTrue(mock_warning.called)
self.assertEqual(actual, [])
assert mock_warning.called
assert actual == []
@mock.patch(UTILITY_MODULE + '.log.exception')
def test_data_retrieval_failure(self, mock_exception):
@@ -284,8 +284,8 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
actual = get_edx_api_data(catalog_integration, 'programs', api=api)
self.assertTrue(mock_exception.called)
self.assertEqual(actual, [])
assert mock_exception.called
assert actual == []
@mock.patch(UTILITY_MODULE + '.log.warning')
def test_api_config_disabled_with_id_and_not_collection(self, mock_warning):
@@ -300,8 +300,8 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
many=False
)
self.assertTrue(mock_warning.called)
self.assertEqual(actual, {})
assert mock_warning.called
assert actual == {}
@mock.patch(UTILITY_MODULE + '.log.exception')
def test_data_retrieval_failure_with_id(self, mock_exception):
@@ -320,5 +320,5 @@ class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, Cach
resource_id=100,
many=False
)
self.assertTrue(mock_exception.called)
self.assertEqual(actual, {})
assert mock_exception.called
assert actual == {}

View File

@@ -2,10 +2,10 @@
Tests for graph traversal generator functions.
"""
from unittest import TestCase
import ddt
import pytest
from ..grade_utils import compare_scores, round_away_from_zero
@@ -32,10 +32,10 @@ class TestGradeUtils(TestCase):
assert expected_percentage_2 == percentage_2
def test_compare_scores_raise_zero_division(self):
with self.assertRaises(ZeroDivisionError):
with pytest.raises(ZeroDivisionError):
compare_scores(1, 0, 1, 2)
with self.assertRaises(ZeroDivisionError):
with pytest.raises(ZeroDivisionError):
compare_scores(1, 2, 0, 0)
def test_compare_scores_treat_undefined_as_zero(self):

View File

@@ -71,71 +71,58 @@ class TestGraphTraversals(TestCase):
return result
def test_pre_order(self):
self.assertEqual(
list(traverse_pre_order(
start_node='b1',
get_children=(lambda node: self.parent_to_children_map[node]),
filter_func=(lambda node: node != 'd3'),
)),
['b1', 'c1', 'd1', 'e1', 'd2', 'e2', 'f1', 'c2']
)
assert list(
traverse_pre_order(start_node='b1',
get_children=(lambda node: self.parent_to_children_map[node]),
filter_func=(lambda node: (node != 'd3')))
) == ['b1', 'c1', 'd1', 'e1', 'd2', 'e2', 'f1', 'c2']
def test_post_order(self):
self.assertEqual(
list(traverse_post_order(
assert list(
traverse_post_order(
start_node='b1',
get_children=(lambda node: self.parent_to_children_map[node]),
filter_func=(lambda node: node != 'd3'),
)),
['e1', 'd1', 'f1', 'e2', 'd2', 'c1', 'c2', 'b1']
)
filter_func=(lambda node: (node != 'd3')))
) == ['e1', 'd1', 'f1', 'e2', 'd2', 'c1', 'c2', 'b1']
def test_topological(self):
self.assertEqual(
list(traverse_topologically(
assert list(
traverse_topologically(
start_node='b1',
get_children=(lambda node: self.parent_to_children_map[node]),
get_parents=(lambda node: self.child_to_parents_map[node]),
filter_func=(lambda node: node != 'd3'),
)),
['b1', 'c1', 'd1', 'd2', 'e1', 'e2', 'f1', 'c2']
)
filter_func=(lambda node: (node != 'd3')))
) == ['b1', 'c1', 'd1', 'd2', 'e1', 'e2', 'f1', 'c2']
def test_topological_yield_descendants(self):
self.assertEqual(
list(traverse_topologically(
assert list(
traverse_topologically(
start_node='b1',
get_children=(lambda node: self.parent_to_children_map[node]),
get_parents=(lambda node: self.child_to_parents_map[node]),
filter_func=(lambda node: node != 'd2'),
yield_descendants_of_unyielded=True,
)),
['b1', 'c1', 'd1', 'e1', 'e2', 'f1', 'c2', 'd3']
)
filter_func=(lambda node: (node != 'd2')),
yield_descendants_of_unyielded=True)
) == ['b1', 'c1', 'd1', 'e1', 'e2', 'f1', 'c2', 'd3']
def test_topological_not_yield_descendants(self):
self.assertEqual(
list(traverse_topologically(
assert list(
traverse_topologically(
start_node='b1',
get_children=(lambda node: self.parent_to_children_map[node]),
get_parents=(lambda node: self.child_to_parents_map[node]),
filter_func=(lambda node: node != 'd2'),
yield_descendants_of_unyielded=False,
)),
['b1', 'c1', 'd1', 'e1', 'c2', 'd3']
)
filter_func=(lambda node: (node != 'd2')),
yield_descendants_of_unyielded=False)
) == ['b1', 'c1', 'd1', 'e1', 'c2', 'd3']
def test_topological_yield_single_node(self):
self.assertEqual(
list(traverse_topologically(
assert list(
traverse_topologically(
start_node='b1',
get_children=(lambda node: self.parent_to_children_map[node]),
get_parents=(lambda node: self.child_to_parents_map[node]),
filter_func=(lambda node: node == 'c2'),
yield_descendants_of_unyielded=True,
)),
['c2']
)
filter_func=(lambda node: (node == 'c2')),
yield_descendants_of_unyielded=True)
) == ['c2']
def test_topological_complex(self):
"""
@@ -176,11 +163,9 @@ class TestGraphTraversals(TestCase):
}
child_to_parents = self.get_child_to_parents_map(parent_to_children)
for _ in range(2): # should get the same result twice
self.assertEqual(
list(traverse_topologically(
assert list(
traverse_topologically(
start_node='root',
get_children=(lambda node: parent_to_children[node]),
get_parents=(lambda node: child_to_parents[node]),
)),
['root', 'A', 'D', 'B', 'E', 'F', 'J', 'K', 'M', 'N', 'G', 'C', 'H', 'L', 'O', 'P', 'I'],
)
get_parents=(lambda node: child_to_parents[node]))
) == ['root', 'A', 'D', 'B', 'E', 'F', 'J', 'K', 'M', 'N', 'G', 'C', 'H', 'L', 'O', 'P', 'I']

View File

@@ -18,7 +18,7 @@ class TestHashUtils(TestCase):
make sure short token returns 32 size token
"""
token = short_token()
self.assertEqual(len(token), 32)
assert len(token) == 32
@ddt.data(0, 10, 30, 64)
def test_create_hash256_of_size(self, size):
@@ -26,8 +26,8 @@ class TestHashUtils(TestCase):
Test create hash256
"""
token = create_hash256(size)
self.assertEqual(len(token), size)
assert len(token) == size
def test_create_hash256_default(self):
token = create_hash256()
self.assertIsNotNone(token)
assert token is not None

View File

@@ -1,18 +1,17 @@
"""Tests for request_utils module."""
import unittest
from unittest.mock import Mock, patch, call
from unittest.mock import Mock, call, patch
import pytest
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.test.client import RequestFactory
from openedx.core.lib.request_utils import (
get_request_or_stub,
course_id_from_url,
safe_get_host,
CookieMonitoringMiddleware,
course_id_from_url,
get_request_or_stub,
safe_get_host
)
@@ -37,7 +36,7 @@ class RequestUtilTestCase(unittest.TestCase):
"""
stub = get_request_or_stub()
expected_url = "http://{site_name}/foobar".format(site_name=settings.SITE_NAME)
self.assertEqual(stub.build_absolute_uri("foobar"), expected_url)
assert stub.build_absolute_uri('foobar') == expected_url
def test_safe_get_host(self):
""" Tests that the safe_get_host function returns the desired host """
@@ -47,30 +46,30 @@ class RequestUtilTestCase(unittest.TestCase):
request.META['HTTP_HOST'] = 'www.userProvidedHost.com'
# If ALLOWED_HOSTS is not set properly, safe_get_host should return SITE_NAME
settings.ALLOWED_HOSTS = None
self.assertEqual(safe_get_host(request), "siteName.com")
assert safe_get_host(request) == 'siteName.com'
settings.ALLOWED_HOSTS = ["*"]
self.assertEqual(safe_get_host(request), "siteName.com")
assert safe_get_host(request) == 'siteName.com'
settings.ALLOWED_HOSTS = ["foo.com", "*"]
self.assertEqual(safe_get_host(request), "siteName.com")
assert safe_get_host(request) == 'siteName.com'
# If ALLOWED_HOSTS is set properly, and the host is valid, we just return the user-provided host
settings.ALLOWED_HOSTS = [request.META['HTTP_HOST']]
self.assertEqual(safe_get_host(request), request.META['HTTP_HOST'])
assert safe_get_host(request) == request.META['HTTP_HOST']
# If ALLOWED_HOSTS is set properly but the host is invalid, we should get a SuspiciousOperation
settings.ALLOWED_HOSTS = ["the_valid_website.com"]
with self.assertRaises(SuspiciousOperation):
with pytest.raises(SuspiciousOperation):
safe_get_host(request)
def test_course_id_from_url(self):
""" Test course_id_from_url(). """
self.assertIsNone(course_id_from_url('/login'))
self.assertIsNone(course_id_from_url('/course/edX/maths/2020'))
self.assertIsNone(course_id_from_url('/courses/edX/maths/'))
self.assertIsNone(course_id_from_url('/api/courses/v1/blocks/edX/maths/2020'))
self.assertIsNone(course_id_from_url('/api/courses/v1/blocks/course-v1:incidental+courseid+formatting'))
self.assertIsNone(course_id_from_url('/api/courses/v41/notcourses/course-v1:incidental+courseid+formatting'))
assert course_id_from_url('/login') is None
assert course_id_from_url('/course/edX/maths/2020') is None
assert course_id_from_url('/courses/edX/maths/') is None
assert course_id_from_url('/api/courses/v1/blocks/edX/maths/2020') is None
assert course_id_from_url('/api/courses/v1/blocks/course-v1:incidental+courseid+formatting') is None
assert course_id_from_url('/api/courses/v41/notcourses/course-v1:incidental+courseid+formatting') is None
course_id = course_id_from_url('/courses/course-v1:edX+maths+2020')
self.assertCourseIdFieldsMatch(course_id=course_id, org="edX", course='maths', run='2020')
@@ -86,9 +85,9 @@ class RequestUtilTestCase(unittest.TestCase):
def assertCourseIdFieldsMatch(self, course_id, org, course, run):
""" Asserts that the passed-in course id matches the specified fields"""
self.assertEqual(course_id.org, org)
self.assertEqual(course_id.course, course)
self.assertEqual(course_id.run, run)
assert course_id.org == org
assert course_id.course == course
assert course_id.run == run
@patch("openedx.core.lib.request_utils.CAPTURE_COOKIE_SIZES")
@patch("openedx.core.lib.request_utils.set_custom_attribute")

View File

@@ -37,11 +37,11 @@ class TestTimeZoneUtils(TestCase):
"""
Asserts that all display_tz_info is equal to the expected inputs
"""
self.assertEqual(display_tz_info['str'], u'{name} ({abbr}, UTC{offset})'.format(name=expected_name,
abbr=expected_abbr,
offset=expected_offset))
self.assertEqual(display_tz_info['abbr'], expected_abbr)
self.assertEqual(display_tz_info['offset'], expected_offset)
assert display_tz_info['str'] == '{name} ({abbr}, UTC{offset})'.format(
name=expected_name, abbr=expected_abbr, offset=expected_offset
)
assert display_tz_info['abbr'] == expected_abbr
assert display_tz_info['offset'] == expected_offset
def test_display_time_zone_without_dst(self):
"""

View File

@@ -27,8 +27,8 @@ class TestQuoteSlashes(TestCase):
@data(*TEST_STRINGS)
def test_inverse(self, test_string):
self.assertEqual(test_string, unquote_slashes(quote_slashes(test_string)))
assert test_string == unquote_slashes(quote_slashes(test_string))
@data(*TEST_STRINGS)
def test_escaped(self, test_string):
self.assertNotIn('/', quote_slashes(test_string))
assert '/' not in quote_slashes(test_string)

View File

@@ -71,9 +71,9 @@ class TestXblockUtils(SharedModuleStoreTestCase):
new_content = '<p>New Content<p>'
fragment = self.create_fragment()
wrapped_fragment = wrap_fragment(fragment, new_content)
self.assertEqual('<p>New Content<p>', wrapped_fragment.content)
self.assertEqual('body {background-color:red;}', wrapped_fragment.resources[0].data)
self.assertEqual('alert("Hi!");', wrapped_fragment.resources[1].data)
assert '<p>New Content<p>' == wrapped_fragment.content
assert 'body {background-color:red;}' == wrapped_fragment.resources[0].data
assert 'alert("Hi!");' == wrapped_fragment.resources[1].data
def test_request_token(self):
"""
@@ -82,13 +82,13 @@ class TestXblockUtils(SharedModuleStoreTestCase):
request_with_token = RequestFactory().get('/')
request_with_token._xblock_token = '123' # pylint: disable=protected-access
token = request_token(request_with_token)
self.assertEqual(token, '123')
assert token == '123'
request_without_token = RequestFactory().get('/')
token = request_token(request_without_token)
# Test to see if the token is an uuid1 hex value
test_uuid = uuid.UUID(token, version=1)
self.assertEqual(token, test_uuid.hex)
assert token == test_uuid.hex
@ddt.data(
('course_mongo', 'data-usage-id="i4x:;_;_TestX;_TS01;_course;_2015"'),
@@ -110,14 +110,14 @@ class TestXblockUtils(SharedModuleStoreTestCase):
usage_id_serializer=lambda usage_id: quote_slashes(six.text_type(usage_id)),
request_token=uuid.uuid1().hex
)
self.assertIsInstance(test_wrap_output, Fragment)
self.assertIn('xblock-baseview', test_wrap_output.content)
self.assertIn('data-runtime-class="TestRuntime"', test_wrap_output.content)
self.assertIn(data_usage_id, test_wrap_output.content)
self.assertIn('<h1>Test!</h1>', test_wrap_output.content)
self.assertIn('data-custom-attribute="custom-value"', test_wrap_output.content)
self.assertEqual(test_wrap_output.resources[0].data, u'body {background-color:red;}')
self.assertEqual(test_wrap_output.resources[1].data, 'alert("Hi!");')
assert isinstance(test_wrap_output, Fragment)
assert 'xblock-baseview' in test_wrap_output.content
assert 'data-runtime-class="TestRuntime"' in test_wrap_output.content
assert data_usage_id in test_wrap_output.content
assert '<h1>Test!</h1>' in test_wrap_output.content
assert 'data-custom-attribute="custom-value"' in test_wrap_output.content
assert test_wrap_output.resources[0].data == u'body {background-color:red;}'
assert test_wrap_output.resources[1].data == 'alert("Hi!");'
@ddt.data('course_mongo', 'course_split')
def test_replace_jump_to_id_urls(self, course_id):
@@ -133,8 +133,8 @@ class TestXblockUtils(SharedModuleStoreTestCase):
frag=Fragment('<a href="/jump_to_id/id">'),
context=None
)
self.assertIsInstance(test_replace, Fragment)
self.assertEqual(test_replace.content, '<a href="/base_url/id">')
assert isinstance(test_replace, Fragment)
assert test_replace.content == '<a href="/base_url/id">'
@ddt.data(
('course_mongo', '<a href="/courses/TestX/TS01/2015/id">'),
@@ -153,8 +153,8 @@ class TestXblockUtils(SharedModuleStoreTestCase):
frag=Fragment('<a href="/course/id">'),
context=None
)
self.assertIsInstance(test_replace, Fragment)
self.assertEqual(test_replace.content, anchor_tag)
assert isinstance(test_replace, Fragment)
assert test_replace.content == anchor_tag
@ddt.data(
('course_mongo', '<a href="/c4x/TestX/TS01/asset/id">'),
@@ -174,8 +174,8 @@ class TestXblockUtils(SharedModuleStoreTestCase):
frag=Fragment('<a href="/static/id">'),
context=None
)
self.assertIsInstance(test_replace, Fragment)
self.assertEqual(test_replace.content, anchor_tag)
assert isinstance(test_replace, Fragment)
assert test_replace.content == anchor_tag
def test_sanitize_html_id(self):
"""
@@ -184,7 +184,7 @@ class TestXblockUtils(SharedModuleStoreTestCase):
dirty_string = 'I:have-un:allowed_characters'
clean_string = sanitize_html_id(dirty_string)
self.assertEqual(clean_string, 'I_have_un_allowed_characters')
assert clean_string == 'I_have_un_allowed_characters'
@ddt.data(
(True, ["combined.css"]),
@@ -205,7 +205,7 @@ class TestXblockUtils(SharedModuleStoreTestCase):
}
with self.settings(PIPELINE=pipeline):
css_dependencies = get_css_dependencies("style-group")
self.assertEqual(css_dependencies, expected_css_dependencies)
assert css_dependencies == expected_css_dependencies
@ddt.data(
(True, ["combined.js"]),
@@ -226,7 +226,7 @@ class TestXblockUtils(SharedModuleStoreTestCase):
}
with self.settings(PIPELINE=pipeline):
js_dependencies = get_js_dependencies("js-group")
self.assertEqual(js_dependencies, expected_js_dependencies)
assert js_dependencies == expected_js_dependencies
class TestXBlockAside(SharedModuleStoreTestCase):

View File

@@ -106,9 +106,9 @@ class DiscussionXBlockImportExportTests(TestCase):
block = DiscussionXBlock.parse_xml(node, self.runtime_mock, self.keys, self.id_gen_mock)
try:
self.assertEqual(block.discussion_id, id_pair.value)
self.assertEqual(block.discussion_category, category_pair.value)
self.assertEqual(block.discussion_target, target_pair.value)
assert block.discussion_id == id_pair.value
assert block.discussion_category == category_pair.value
assert block.discussion_target == target_pair.value
except AssertionError:
print(xblock_xml)
raise
@@ -138,9 +138,9 @@ class DiscussionXBlockImportExportTests(TestCase):
block = DiscussionXBlock.parse_xml(node, self.runtime_mock, self.keys, self.id_gen_mock)
try:
self.assertEqual(block.discussion_id, id_pair.value)
self.assertEqual(block.discussion_category, category_pair.value)
self.assertEqual(block.discussion_target, target_pair.value)
assert block.discussion_id == id_pair.value
assert block.discussion_category == category_pair.value
assert block.discussion_target == target_pair.value
except AssertionError:
print(xblock_xml, xblock_definition_xml)
raise
@@ -163,15 +163,12 @@ class DiscussionXBlockImportExportTests(TestCase):
discussion_id_field = block.fields['discussion_id'] # pylint: disable=unsubscriptable-object
# precondition checks - discussion_id does not have a value and uses UNIQUE_ID
self.assertEqual(
discussion_id_field._get_cached_value(block), # pylint: disable=protected-access
NO_CACHE_VALUE
)
self.assertEqual(discussion_id_field.default, UNIQUE_ID)
assert discussion_id_field._get_cached_value(block) == NO_CACHE_VALUE # pylint: disable=W0212
assert discussion_id_field.default == UNIQUE_ID
block.add_xml_to_node(target_node)
self.assertEqual(target_node.tag, "discussion")
self.assertNotIn("discussion_id", target_node.attrib)
assert target_node.tag == 'discussion' # pylint: disable=W0212
assert 'discussion_id' not in target_node.attrib
@ddt.data("jediwannabe", "iddqd", "itisagooddaytodie")
def test_export_custom_discussion_id(self, discussion_id):
@@ -184,8 +181,8 @@ class DiscussionXBlockImportExportTests(TestCase):
block.discussion_id = discussion_id
# precondition check
self.assertEqual(block.discussion_id, discussion_id)
assert block.discussion_id == discussion_id
block.add_xml_to_node(target_node)
self.assertEqual(target_node.tag, "discussion")
self.assertTrue(target_node.attrib["discussion_id"], discussion_id)
assert target_node.tag == 'discussion'
assert target_node.attrib['discussion_id'], discussion_id