diff --git a/cms/djangoapps/contentstore/tests/test_clone_course.py b/cms/djangoapps/contentstore/tests/test_clone_course.py
index 120944d63a..34b3ae7053 100644
--- a/cms/djangoapps/contentstore/tests/test_clone_course.py
+++ b/cms/djangoapps/contentstore/tests/test_clone_course.py
@@ -4,10 +4,9 @@ Unit tests for cloning a course between the same and different module stores.
import json
+from unittest.mock import Mock, patch
-import six
from django.conf import settings
-from mock import Mock, patch
from opaque_keys.edx.locator import CourseLocator
from cms.djangoapps.contentstore.tasks import rerun_course
@@ -58,7 +57,7 @@ class CloneCourseTest(CourseTestCase):
course_run = '2015_Q1'
display_name = 'rerun'
fields = {'display_name': display_name}
- course_assets = set([u'subs_Introduction%20To%20New.srt.sjson'], )
+ course_assets = {'subs_Introduction%20To%20New.srt.sjson'}
# Create a course using split modulestore
course = CourseFactory.create(
@@ -79,14 +78,14 @@ class CloneCourseTest(CourseTestCase):
# Get & verify all assets of the course
assets, count = contentstore().get_all_content_for_course(course.id)
self.assertEqual(count, 1)
- self.assertEqual(set([asset['asset_key'].block_id for asset in assets]), course_assets) # lint-amnesty, pylint: disable=consider-using-set-comprehension
+ self.assertEqual({asset['asset_key'].block_id for asset in assets}, course_assets) # lint-amnesty, pylint: disable=consider-using-set-comprehension
# rerun from split into split
split_rerun_id = CourseLocator(org=org, course=course_number, run="2012_Q2")
CourseRerunState.objects.initiated(course.id, split_rerun_id, self.user, fields['display_name'])
result = rerun_course.delay(
- six.text_type(course.id),
- six.text_type(split_rerun_id),
+ str(course.id),
+ str(split_rerun_id),
self.user.id,
json.dumps(fields, cls=EdxJSONEncoder)
)
@@ -109,7 +108,7 @@ class CloneCourseTest(CourseTestCase):
# Mark the action as initiated
fields = {'display_name': 'rerun'}
CourseRerunState.objects.initiated(mongo_course1_id, split_course3_id, self.user, fields['display_name'])
- result = rerun_course.delay(six.text_type(mongo_course1_id), six.text_type(split_course3_id), self.user.id,
+ result = rerun_course.delay(str(mongo_course1_id), str(split_course3_id), self.user.id,
json.dumps(fields, cls=EdxJSONEncoder))
self.assertEqual(result.get(), "succeeded")
self.assertTrue(has_course_author_access(self.user, split_course3_id), "Didn't grant access")
@@ -117,7 +116,7 @@ class CloneCourseTest(CourseTestCase):
self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.SUCCEEDED)
# try creating rerunning again to same name and ensure it generates error
- result = rerun_course.delay(six.text_type(mongo_course1_id), six.text_type(split_course3_id), self.user.id)
+ result = rerun_course.delay(str(mongo_course1_id), str(split_course3_id), self.user.id)
self.assertEqual(result.get(), "duplicate course")
# the below will raise an exception if the record doesn't exist
CourseRerunState.objects.find_first(
@@ -130,7 +129,7 @@ class CloneCourseTest(CourseTestCase):
split_course4_id = CourseLocator(org="edx3", course="split3", run="rerun_fail")
fields = {'display_name': 'total failure'}
CourseRerunState.objects.initiated(split_course3_id, split_course4_id, self.user, fields['display_name'])
- result = rerun_course.delay(six.text_type(split_course3_id), six.text_type(split_course4_id), self.user.id,
+ result = rerun_course.delay(str(split_course3_id), str(split_course4_id), self.user.id,
json.dumps(fields, cls=EdxJSONEncoder))
self.assertIn("exception: ", result.get())
self.assertIsNone(self.store.get_course(split_course4_id), "Didn't delete course after error")
diff --git a/cms/djangoapps/contentstore/tests/test_contentstore.py b/cms/djangoapps/contentstore/tests/test_contentstore.py
index 6be1cd8d64..dbdb978a8b 100644
--- a/cms/djangoapps/contentstore/tests/test_contentstore.py
+++ b/cms/djangoapps/contentstore/tests/test_contentstore.py
@@ -7,13 +7,11 @@ from datetime import timedelta
from functools import wraps
from json import loads
from textwrap import dedent
-from unittest import SkipTest
+from unittest import SkipTest, mock
from uuid import uuid4
import ddt
import lxml.html
-import mock
-import six
from django.conf import settings
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.middleware.csrf import _compare_salted_tokens # lint-amnesty, pylint: disable=unused-import
@@ -26,8 +24,6 @@ from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import AssetKey, CourseKey, UsageKey
from opaque_keys.edx.locations import CourseLocator
from path import Path as path
-from six import text_type
-from six.moves import range
from waffle.testutils import override_switch
from cms.djangoapps.contentstore.config import waffle
@@ -36,11 +32,11 @@ from cms.djangoapps.contentstore.utils import delete_course, reverse_course_url,
from cms.djangoapps.contentstore.views.component import ADVANCED_COMPONENT_TYPES
from common.djangoapps.course_action_state.managers import CourseActionStateItemNotFoundError
from common.djangoapps.course_action_state.models import CourseRerunState, CourseRerunUIStateManager
-from openedx.core.djangoapps.django_comment_common.utils import are_permissions_roles_seeded
-from openedx.core.lib.tempdir import mkdtemp_clean
from common.djangoapps.student import auth
from common.djangoapps.student.models import CourseEnrollment
from common.djangoapps.student.roles import CourseCreatorRole, CourseInstructorRole
+from openedx.core.djangoapps.django_comment_common.utils import are_permissions_roles_seeded
+from openedx.core.lib.tempdir import mkdtemp_clean
from xmodule.capa_module import ProblemBlock
from xmodule.contentstore.content import StaticContent
from xmodule.contentstore.django import contentstore
@@ -124,7 +120,7 @@ class ImportRequiredTestCases(ContentStoreTestCase):
Asset name in XML: "/invalid\\displayname/subs-esLhHcdKGWvKs.srt"
"""
content_store = contentstore()
- expected_displayname = u'_invalid_displayname_subs-esLhHcdKGWvKs.srt'
+ expected_displayname = '_invalid_displayname_subs-esLhHcdKGWvKs.srt'
import_course_from_xml(
self.store,
@@ -162,11 +158,11 @@ class ImportRequiredTestCases(ContentStoreTestCase):
# Test course export does not fail
root_dir = path(mkdtemp_clean())
- print(u'Exporting to tempdir = {0}'.format(root_dir))
- export_course_to_xml(self.store, content_store, course.id, root_dir, u'test_export')
+ print(f'Exporting to tempdir = {root_dir}')
+ export_course_to_xml(self.store, content_store, course.id, root_dir, 'test_export')
- filesystem = OSFS(text_type(root_dir / 'test_export/static'))
- exported_static_files = filesystem.listdir(u'/')
+ filesystem = OSFS(str(root_dir / 'test_export/static'))
+ exported_static_files = filesystem.listdir('/')
# Verify that asset have been overwritten during export.
self.assertEqual(len(exported_static_files), 1)
@@ -243,38 +239,38 @@ class ImportRequiredTestCases(ContentStoreTestCase):
self.assertIsNotNone(course_updates)
# check that course which is imported has files 'updates.html' and 'updates.items.json'
- filesystem = OSFS(text_type(data_dir + '/course_info_updates/info'))
- self.assertTrue(filesystem.exists(u'updates.html'))
- self.assertTrue(filesystem.exists(u'updates.items.json'))
+ filesystem = OSFS(str(data_dir + '/course_info_updates/info'))
+ self.assertTrue(filesystem.exists('updates.html'))
+ self.assertTrue(filesystem.exists('updates.items.json'))
# verify that course info update module has same data content as in data file from which it is imported
# check 'data' field content
- with filesystem.open(u'updates.html', 'r') as course_policy:
+ with filesystem.open('updates.html', 'r') as course_policy:
on_disk = course_policy.read()
self.assertEqual(course_updates.data, on_disk)
# check 'items' field content
- with filesystem.open(u'updates.items.json', 'r') as course_policy:
+ with filesystem.open('updates.items.json', 'r') as course_policy:
on_disk = loads(course_policy.read())
self.assertEqual(course_updates.items, on_disk)
# now export the course to a tempdir and test that it contains files 'updates.html' and 'updates.items.json'
# with same content as in course 'info' directory
root_dir = path(mkdtemp_clean())
- print(u'Exporting to tempdir = {0}'.format(root_dir))
- export_course_to_xml(self.store, content_store, course.id, root_dir, u'test_export')
+ print(f'Exporting to tempdir = {root_dir}')
+ export_course_to_xml(self.store, content_store, course.id, root_dir, 'test_export')
# check that exported course has files 'updates.html' and 'updates.items.json'
- filesystem = OSFS(text_type(root_dir / 'test_export/info'))
- self.assertTrue(filesystem.exists(u'updates.html'))
- self.assertTrue(filesystem.exists(u'updates.items.json'))
+ filesystem = OSFS(str(root_dir / 'test_export/info'))
+ self.assertTrue(filesystem.exists('updates.html'))
+ self.assertTrue(filesystem.exists('updates.items.json'))
# verify that exported course has same data content as in course_info_update module
- with filesystem.open(u'updates.html', 'r') as grading_policy:
+ with filesystem.open('updates.html', 'r') as grading_policy:
on_disk = grading_policy.read()
self.assertEqual(on_disk, course_updates.data)
- with filesystem.open(u'updates.items.json', 'r') as grading_policy:
+ with filesystem.open('updates.items.json', 'r') as grading_policy:
on_disk = loads(grading_policy.read())
self.assertEqual(on_disk, course_updates.items)
@@ -319,42 +315,42 @@ class ImportRequiredTestCases(ContentStoreTestCase):
course_id = self.import_and_populate_course()
root_dir = path(mkdtemp_clean())
- print(u'Exporting to tempdir = {0}'.format(root_dir))
+ print(f'Exporting to tempdir = {root_dir}')
# export out to a tempdir
- export_course_to_xml(self.store, content_store, course_id, root_dir, u'test_export')
+ export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_export')
# check for static tabs
- self.verify_content_existence(self.store, root_dir, course_id, u'tabs', 'static_tab', '.html')
+ self.verify_content_existence(self.store, root_dir, course_id, 'tabs', 'static_tab', '.html')
# check for about content
- self.verify_content_existence(self.store, root_dir, course_id, u'about', 'about', '.html')
+ self.verify_content_existence(self.store, root_dir, course_id, 'about', 'about', '.html')
# assert that there is an html and video directory in drafts:
draft_dir = OSFS(root_dir / 'test_export/drafts')
- self.assertTrue(draft_dir.exists(u'html'))
- self.assertTrue(draft_dir.exists(u'video'))
+ self.assertTrue(draft_dir.exists('html'))
+ self.assertTrue(draft_dir.exists('video'))
# and assert that they contain the created modules
- self.assertIn(self.DRAFT_HTML + ".xml", draft_dir.listdir(u'html'))
- self.assertIn(self.DRAFT_VIDEO + ".xml", draft_dir.listdir(u'video'))
+ self.assertIn(self.DRAFT_HTML + ".xml", draft_dir.listdir('html'))
+ self.assertIn(self.DRAFT_VIDEO + ".xml", draft_dir.listdir('video'))
# and assert the child of the orphaned draft wasn't exported
- self.assertNotIn(self.ORPHAN_DRAFT_HTML + ".xml", draft_dir.listdir(u'html'))
+ self.assertNotIn(self.ORPHAN_DRAFT_HTML + ".xml", draft_dir.listdir('html'))
# check for grading_policy.json
filesystem = OSFS(root_dir / 'test_export/policies/2012_Fall')
- self.assertTrue(filesystem.exists(u'grading_policy.json'))
+ self.assertTrue(filesystem.exists('grading_policy.json'))
course = self.store.get_course(course_id)
# compare what's on disk compared to what we have in our course
- with filesystem.open(u'grading_policy.json', 'r') as grading_policy:
+ with filesystem.open('grading_policy.json', 'r') as grading_policy:
on_disk = loads(grading_policy.read())
self.assertEqual(on_disk, course.grading_policy)
# check for policy.json
- self.assertTrue(filesystem.exists(u'policy.json'))
+ self.assertTrue(filesystem.exists('policy.json'))
# compare what's on disk to what we have in the course module
- with filesystem.open(u'policy.json', 'r') as course_policy:
+ with filesystem.open('policy.json', 'r') as course_policy:
on_disk = loads(course_policy.read())
self.assertIn('course/2012_Fall', on_disk)
self.assertEqual(on_disk['course/2012_Fall'], own_metadata(course))
@@ -421,10 +417,10 @@ class ImportRequiredTestCases(ContentStoreTestCase):
root_dir = path(mkdtemp_clean())
- print(u'Exporting to tempdir = {0}'.format(root_dir))
+ print(f'Exporting to tempdir = {root_dir}')
# export out to a tempdir
- export_course_to_xml(self.store, content_store, course_id, root_dir, u'test_export')
+ export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_export')
shutil.rmtree(root_dir)
@@ -447,10 +443,10 @@ class ImportRequiredTestCases(ContentStoreTestCase):
root_dir = path(mkdtemp_clean())
- print(u'Exporting to tempdir = {0}'.format(root_dir))
+ print(f'Exporting to tempdir = {root_dir}')
# export out to a tempdir
- export_course_to_xml(self.store, content_store, course_id, root_dir, u'test_export')
+ export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_export')
shutil.rmtree(root_dir)
@@ -503,7 +499,7 @@ class ImportRequiredTestCases(ContentStoreTestCase):
# Export the course
root_dir = path(mkdtemp_clean())
- export_course_to_xml(self.store, content_store, course_id, root_dir, u'test_roundtrip')
+ export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_roundtrip')
# Reimport and get the video back
import_course_from_xml(self.store, self.user.id, root_dir)
@@ -524,7 +520,7 @@ class ImportRequiredTestCases(ContentStoreTestCase):
# Export the course
root_dir = path(mkdtemp_clean())
- export_course_to_xml(self.store, content_store, course_id, root_dir, u'test_roundtrip')
+ export_course_to_xml(self.store, content_store, course_id, root_dir, 'test_roundtrip')
# Reimport and get the video back
import_course_from_xml(self.store, self.user.id, root_dir, create_if_not_present=True)
@@ -547,8 +543,8 @@ class ImportRequiredTestCases(ContentStoreTestCase):
root_dir = path(mkdtemp_clean())
- print(u'Exporting to tempdir = {0}'.format(root_dir))
- export_course_to_xml(self.store, None, course_id, root_dir, u'test_export_no_content_store')
+ print(f'Exporting to tempdir = {root_dir}')
+ export_course_to_xml(self.store, None, course_id, root_dir, 'test_export_no_content_store')
# Delete the course from module store and reimport it
@@ -603,7 +599,7 @@ class ImportRequiredTestCases(ContentStoreTestCase):
content_store,
course_id,
root_dir,
- u'test_no_xml_attributes'
+ 'test_no_xml_attributes'
)
@@ -614,7 +610,7 @@ class MiscCourseTests(ContentStoreTestCase):
"""
def setUp(self):
- super(MiscCourseTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
# save locs not items b/c the items won't have the subsequently created children in them until refetched
self.chapter_loc = self.store.create_child(
self.user.id, self.course.location, 'chapter', 'test_chapter'
@@ -699,7 +695,7 @@ class MiscCourseTests(ContentStoreTestCase):
def test_export_on_invalid_displayname(self, invalid_displayname):
""" Tests that assets with invalid 'displayname' does not cause export to fail """
content_store = contentstore()
- exported_asset_name = u'_Fake_asset_displayname'
+ exported_asset_name = '_Fake_asset_displayname'
# Create an asset with slash `invalid_displayname` '
asset_key = self.course.id.make_asset_key('asset', "fake_asset.txt")
@@ -716,11 +712,11 @@ class MiscCourseTests(ContentStoreTestCase):
# Now export the course to a tempdir and test that it contains assets. The export should pass
root_dir = path(mkdtemp_clean())
- print(u'Exporting to tempdir = {0}'.format(root_dir))
- export_course_to_xml(self.store, content_store, self.course.id, root_dir, u'test_export')
+ print(f'Exporting to tempdir = {root_dir}')
+ export_course_to_xml(self.store, content_store, self.course.id, root_dir, 'test_export')
filesystem = OSFS(root_dir / 'test_export/static')
- exported_static_files = filesystem.listdir(u'/')
+ exported_static_files = filesystem.listdir('/')
# Verify that only single asset has been exported with the expected asset name.
self.assertTrue(filesystem.exists(exported_asset_name))
@@ -741,13 +737,13 @@ class MiscCourseTests(ContentStoreTestCase):
# Make an existing unit a draft
self.store.convert_to_draft(self.problem.location, self.user.id)
root_dir = path(mkdtemp_clean())
- export_course_to_xml(self.store, None, self.course.id, root_dir, u'test_export')
+ export_course_to_xml(self.store, None, self.course.id, root_dir, 'test_export')
# Verify that problem is exported in the drafts. This is expected because we are
# mocking get_item to for drafts. Expect no draft is exported.
# Specifically get_item is used in `xmodule.modulestore.xml_exporter._export_drafts`
export_draft_dir = OSFS(root_dir / 'test_export/drafts')
- self.assertEqual(len(export_draft_dir.listdir(u'/')), 0)
+ self.assertEqual(len(export_draft_dir.listdir('/')), 0)
# Remove tempdir
shutil.rmtree(root_dir)
@@ -755,11 +751,11 @@ class MiscCourseTests(ContentStoreTestCase):
def test_assets_overwrite(self):
""" Tests that assets will similar 'displayname' will be overwritten during export """
content_store = contentstore()
- asset_displayname = u'Fake_asset.txt'
+ asset_displayname = 'Fake_asset.txt'
# Create two assets with similar 'displayname'
for i in range(2):
- asset_path = 'sample_asset_{}.txt'.format(i)
+ asset_path = f'sample_asset_{i}.txt'
asset_key = self.course.id.make_asset_key('asset', asset_path)
content = StaticContent(
asset_key, asset_displayname, 'application/text', b'test',
@@ -776,12 +772,12 @@ class MiscCourseTests(ContentStoreTestCase):
# Now export the course to a tempdir and test that it contains assets.
root_dir = path(mkdtemp_clean())
- print(u'Exporting to tempdir = {0}'.format(root_dir))
- export_course_to_xml(self.store, content_store, self.course.id, root_dir, u'test_export')
+ print(f'Exporting to tempdir = {root_dir}')
+ export_course_to_xml(self.store, content_store, self.course.id, root_dir, 'test_export')
# Verify that asset have been overwritten during export.
filesystem = OSFS(root_dir / 'test_export/static')
- exported_static_files = filesystem.listdir(u'/')
+ exported_static_files = filesystem.listdir('/')
self.assertTrue(filesystem.exists(asset_displayname))
self.assertEqual(len(exported_static_files), 1)
@@ -938,7 +934,7 @@ class MiscCourseTests(ContentStoreTestCase):
"""
Tests the ajax callback to render an XModule
"""
- with override_settings(COURSES_WITH_UNSAFE_CODE=[text_type(self.course.id)]):
+ with override_settings(COURSES_WITH_UNSAFE_CODE=[str(self.course.id)]):
# also try a custom response which will trigger the 'is this course in whitelist' logic
resp = self.client.get_json(
get_url('xblock_view_handler', self.vert_loc, kwargs={'view_name': 'container_preview'})
@@ -947,7 +943,7 @@ class MiscCourseTests(ContentStoreTestCase):
vertical = self.store.get_item(self.vert_loc)
for child in vertical.children:
- self.assertContains(resp, text_type(child))
+ self.assertContains(resp, str(child))
def test_delete(self):
# make sure the parent points to the child object which is to be deleted
@@ -980,7 +976,7 @@ class MiscCourseTests(ContentStoreTestCase):
self.assertIsNotNone(content)
# let's restore the asset
- restore_asset_from_trashcan(text_type(asset_key))
+ restore_asset_from_trashcan(str(asset_key))
# now try to find it in courseware store, and they should be back after restore
content = contentstore('trashcan').find(asset_key, throw_on_not_found=False)
@@ -1004,7 +1000,7 @@ class MiscCourseTests(ContentStoreTestCase):
url = reverse_course_url(
'assets_handler',
self.course.id,
- kwargs={'asset_key_string': text_type(asset_key)}
+ kwargs={'asset_key_string': str(asset_key)}
)
resp = self.client.delete(url)
self.assertEqual(resp.status_code, 204)
@@ -1061,7 +1057,7 @@ class MiscCourseTests(ContentStoreTestCase):
self.assertEqual(resp.status_code, 404)
@override_switch(
- '{}.{}'.format(waffle.WAFFLE_NAMESPACE, waffle.ENABLE_ACCESSIBILITY_POLICY_PAGE),
+ f'{waffle.WAFFLE_NAMESPACE}.{waffle.ENABLE_ACCESSIBILITY_POLICY_PAGE}',
active=False)
def test_disabled_accessibility_page(self):
"""
@@ -1118,7 +1114,7 @@ class MiscCourseTests(ContentStoreTestCase):
# check that /static/ has been converted to the full path
# note, we know the link it should be because that's what in the 'toy' course in the test data
asset_key = self.course.id.make_asset_key('asset', 'handouts_sample_handout.txt')
- self.assertContains(resp, text_type(asset_key))
+ self.assertContains(resp, str(asset_key))
def test_prefetch_children(self):
# make sure we haven't done too many round trips to DB:
@@ -1161,7 +1157,7 @@ class ContentStoreTest(ContentStoreTestCase):
"Please change either organization or course number to be unique.")
def setUp(self):
- super(ContentStoreTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course_data = {
'org': 'MITx',
@@ -1177,7 +1173,7 @@ class ContentStoreTest(ContentStoreTestCase):
test_course_data = {}
test_course_data.update(self.course_data)
if number_suffix:
- test_course_data['number'] = '{0}_{1}'.format(test_course_data['number'], number_suffix)
+ test_course_data['number'] = '{}_{}'.format(test_course_data['number'], number_suffix)
course_key = _get_course_id(self.store, test_course_data)
_create_course(self, course_key, test_course_data)
# Verify that the creator is now registered in the course.
@@ -1451,13 +1447,13 @@ class ContentStoreTest(ContentStoreTestCase):
"""
with mock.patch.dict('django.conf.settings.FEATURES', {'ALLOW_UNICODE_COURSE_ID': False}):
error_message = "Special characters not allowed in organization, course number, and course run."
- self.course_data['org'] = u'��������������'
+ self.course_data['org'] = '��������������'
self.assert_create_course_failed(error_message)
- self.course_data['number'] = u'��chantillon'
+ self.course_data['number'] = '��chantillon'
self.assert_create_course_failed(error_message)
- self.course_data['run'] = u'����������'
+ self.course_data['run'] = '����������'
self.assert_create_course_failed(error_message)
def assert_course_permission_denied(self):
@@ -1472,7 +1468,7 @@ class ContentStoreTest(ContentStoreTestCase):
resp = self.client.get_html('/home/')
self.assertContains(
resp,
- u'
'.format(settings.STUDIO_SHORT_NAME),
+ f'',
status_code=200,
html=True
)
@@ -1495,8 +1491,8 @@ class ContentStoreTest(ContentStoreTestCase):
self.assertContains(
resp,
''.format( # lint-amnesty, pylint: disable=line-too-long
- locator=text_type(course.location),
- course_key=text_type(course.id),
+ locator=str(course.location),
+ course_key=str(course.id),
),
status_code=200,
html=True
@@ -1507,7 +1503,7 @@ class ContentStoreTest(ContentStoreTestCase):
course = CourseFactory.create()
section_data = {
- 'parent_locator': text_type(course.location),
+ 'parent_locator': str(course.location),
'category': 'chapter',
'display_name': 'Section One',
}
@@ -1516,7 +1512,7 @@ class ContentStoreTest(ContentStoreTestCase):
self.assertEqual(resp.status_code, 200)
data = parse_json(resp)
- retarget = text_type(course.id.make_usage_key('chapter', 'REPLACE')).replace('REPLACE', r'([0-9]|[a-f]){3,}')
+ retarget = str(course.id.make_usage_key('chapter', 'REPLACE')).replace('REPLACE', r'([0-9]|[a-f]){3,}')
self.assertRegex(data['locator'], retarget)
def test_capa_module(self):
@@ -1524,7 +1520,7 @@ class ContentStoreTest(ContentStoreTestCase):
course = CourseFactory.create()
problem_data = {
- 'parent_locator': text_type(course.location),
+ 'parent_locator': str(course.location),
'category': 'problem'
}
@@ -1806,7 +1802,7 @@ class MetadataSaveTestCase(ContentStoreTestCase):
"""Test that metadata is correctly cached and decached."""
def setUp(self):
- super(MetadataSaveTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
course = CourseFactory.create()
@@ -1866,7 +1862,7 @@ class RerunCourseTest(ContentStoreTestCase):
"""
def setUp(self):
- super(RerunCourseTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.destination_course_data = {
'org': 'MITx',
'number': '111',
@@ -1880,7 +1876,7 @@ class RerunCourseTest(ContentStoreTestCase):
"""Create and send an ajax post for the rerun request"""
# create data to post
- rerun_course_data = {'source_course_key': text_type(source_course_key)}
+ rerun_course_data = {'source_course_key': str(source_course_key)}
if not destination_course_data:
destination_course_data = self.destination_course_data
rerun_course_data.update(destination_course_data)
@@ -1900,7 +1896,7 @@ class RerunCourseTest(ContentStoreTestCase):
def get_unsucceeded_course_action_elements(self, html, course_key):
"""Returns the elements in the unsucceeded course action section that have the given course_key"""
- return html.cssselect(u'.courses-processing li[data-course-key="{}"]'.format(text_type(course_key)))
+ return html.cssselect('.courses-processing li[data-course-key="{}"]'.format(str(course_key)))
def assertInCourseListing(self, course_key):
"""
@@ -1928,7 +1924,7 @@ class RerunCourseTest(ContentStoreTestCase):
'course_key': destination_course_key,
'should_display': True,
}
- for field_name, expected_value in six.iteritems(expected_states):
+ for field_name, expected_value in expected_states.items():
self.assertEqual(getattr(rerun_state, field_name), expected_value)
# Verify that the creator is now enrolled in the course.
@@ -1945,7 +1941,7 @@ class RerunCourseTest(ContentStoreTestCase):
source_course = CourseFactory.create()
destination_course_key = self.post_rerun_request(source_course.id)
self.verify_rerun_course(source_course.id, destination_course_key, self.destination_course_data['display_name'])
- videos, __ = get_videos_for_course(text_type(destination_course_key))
+ videos, __ = get_videos_for_course(str(destination_course_key))
videos = list(videos)
self.assertEqual(0, len(videos))
self.assertInCourseListing(destination_course_key)
@@ -1972,7 +1968,7 @@ class RerunCourseTest(ContentStoreTestCase):
create_video(
dict(
edx_video_id="tree-hugger",
- courses=[text_type(source_course.id)],
+ courses=[str(source_course.id)],
status='test',
duration=2,
encoded_videos=[]
@@ -1982,9 +1978,9 @@ class RerunCourseTest(ContentStoreTestCase):
self.verify_rerun_course(source_course.id, destination_course_key, self.destination_course_data['display_name'])
# Verify that the VAL copies videos to the rerun
- videos, __ = get_videos_for_course(text_type(source_course.id))
+ videos, __ = get_videos_for_course(str(source_course.id))
source_videos = list(videos)
- videos, __ = get_videos_for_course(text_type(destination_course_key))
+ videos, __ = get_videos_for_course(str(destination_course_key))
target_videos = list(videos)
self.assertEqual(1, len(source_videos))
self.assertEqual(source_videos, target_videos)
@@ -2101,7 +2097,7 @@ class RerunCourseTest(ContentStoreTestCase):
'run': '2013'
}
- source_wiki_slug = '{0}.{1}.{2}'.format(course_data['org'], course_data['number'], course_data['run'])
+ source_wiki_slug = '{}.{}.{}'.format(course_data['org'], course_data['number'], course_data['run'])
source_course_key = _get_course_id(self.store, course_data)
_create_course(self, source_course_key, course_data)
@@ -2119,7 +2115,7 @@ class RerunCourseTest(ContentStoreTestCase):
self.verify_rerun_course(source_course.id, destination_course_key, destination_course_data['display_name'])
destination_course = self.store.get_course(destination_course_key)
- destination_wiki_slug = '{0}.{1}.{2}'.format(
+ destination_wiki_slug = '{}.{}.{}'.format(
destination_course.id.org, destination_course.id.course, destination_course.id.run
)
@@ -2137,8 +2133,8 @@ class ContentLicenseTest(ContentStoreTestCase):
root_dir = path(mkdtemp_clean())
self.course.license = "creative-commons: BY SA"
self.store.update_item(self.course, None)
- export_course_to_xml(self.store, content_store, self.course.id, root_dir, u'test_license')
- fname = "{block}.xml".format(block=self.course.scope_ids.usage_id.block_id)
+ export_course_to_xml(self.store, content_store, self.course.id, root_dir, 'test_license')
+ fname = f"{self.course.scope_ids.usage_id.block_id}.xml"
run_file_path = root_dir / "test_license" / "course" / fname
with run_file_path.open() as f:
run_xml = etree.parse(f)
@@ -2151,8 +2147,8 @@ class ContentLicenseTest(ContentStoreTestCase):
parent_location=self.course.location, category='video',
license="all-rights-reserved"
)
- export_course_to_xml(self.store, content_store, self.course.id, root_dir, u'test_license')
- fname = "{block}.xml".format(block=video_descriptor.scope_ids.usage_id.block_id)
+ export_course_to_xml(self.store, content_store, self.course.id, root_dir, 'test_license')
+ fname = f"{video_descriptor.scope_ids.usage_id.block_id}.xml"
video_file_path = root_dir / "test_license" / "video" / fname
with video_file_path.open() as f:
video_xml = etree.parse(f)
@@ -2174,7 +2170,7 @@ class EntryPageTestCase(TestCase):
"""
def setUp(self):
- super(EntryPageTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.client = AjaxEnabledTestClient()
def _test_page(self, page, status_code=200):
@@ -2197,7 +2193,7 @@ class EntryPageTestCase(TestCase):
self._test_page("/logout", 200)
@override_switch(
- '{}.{}'.format(waffle.WAFFLE_NAMESPACE, waffle.ENABLE_ACCESSIBILITY_POLICY_PAGE),
+ f'{waffle.WAFFLE_NAMESPACE}.{waffle.ENABLE_ACCESSIBILITY_POLICY_PAGE}',
active=True)
def test_accessibility(self):
self._test_page('/accessibility')
diff --git a/cms/djangoapps/contentstore/tests/test_core_caching.py b/cms/djangoapps/contentstore/tests/test_core_caching.py
index a66782006c..e6b23c2dee 100644
--- a/cms/djangoapps/contentstore/tests/test_core_caching.py
+++ b/cms/djangoapps/contentstore/tests/test_core_caching.py
@@ -9,7 +9,7 @@ from opaque_keys.edx.locator import AssetLocator, CourseLocator
from openedx.core.djangoapps.contentserver.caching import del_cached_content, get_cached_content, set_cached_content
-class Content(object):
+class Content:
"""
Mock cached content
"""
@@ -25,9 +25,9 @@ class CachingTestCase(TestCase):
"""
Tests for https://edx.lighthouseapp.com/projects/102637/tickets/112-updating-asset-does-not-refresh-the-cached-copy
"""
- unicodeLocation = AssetLocator(CourseLocator(u'c4x', u'mitX', u'800'), u'thumbnail', u'monsters.jpg')
+ unicodeLocation = AssetLocator(CourseLocator('c4x', 'mitX', '800'), 'thumbnail', 'monsters.jpg')
# Note that some of the parts are strings instead of unicode strings
- nonUnicodeLocation = AssetLocator(CourseLocator('c4x', u'mitX', u'800'), 'thumbnail', 'monsters.jpg')
+ nonUnicodeLocation = AssetLocator(CourseLocator('c4x', 'mitX', '800'), 'thumbnail', 'monsters.jpg')
mockAsset = Content(unicodeLocation, 'my content')
def test_put_and_get(self):
diff --git a/cms/djangoapps/contentstore/tests/test_course_create_rerun.py b/cms/djangoapps/contentstore/tests/test_course_create_rerun.py
index 4961e010ce..70232c47e9 100644
--- a/cms/djangoapps/contentstore/tests/test_course_create_rerun.py
+++ b/cms/djangoapps/contentstore/tests/test_course_create_rerun.py
@@ -6,16 +6,11 @@ Test view handler for rerun (and eventually create)
import datetime
import ddt
-import six
from django.test import override_settings
from django.test.client import RequestFactory
from django.urls import reverse
from opaque_keys.edx.keys import CourseKey
-from organizations.api import (
- add_organization,
- get_organization_by_short_name,
- get_course_organizations
-)
+from organizations.api import add_organization, get_course_organizations, get_organization_by_short_name
from organizations.exceptions import InvalidOrganizationException
from cms.djangoapps.contentstore.tests.utils import AjaxEnabledTestClient, parse_json
@@ -37,7 +32,7 @@ class TestCourseListing(ModuleStoreTestCase):
"""
Add a user and a course
"""
- super(TestCourseListing, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
# create and log in a staff user.
# create and log in a non-staff user
self.user = UserFactory()
@@ -81,7 +76,7 @@ class TestCourseListing(ModuleStoreTestCase):
'description': 'Testing Organization Description',
})
response = self.client.ajax_post(self.course_create_rerun_url, {
- 'source_course_key': six.text_type(self.source_course_key),
+ 'source_course_key': str(self.source_course_key),
'org': self.source_course_key.org, 'course': self.source_course_key.course, 'run': 'copy',
'display_name': 'not the same old name',
})
@@ -160,7 +155,7 @@ class TestCourseListing(ModuleStoreTestCase):
with self.assertRaises(InvalidOrganizationException):
get_organization_by_short_name("orgX")
data = parse_json(response)
- self.assertIn(u'Organization you selected does not exist in the system', data['error'])
+ self.assertIn('Organization you selected does not exist in the system', data['error'])
@ddt.data(True, False)
def test_course_creation_for_known_organization(self, organizations_autocreate):
diff --git a/cms/djangoapps/contentstore/tests/test_course_listing.py b/cms/djangoapps/contentstore/tests/test_course_listing.py
index 0502bf9201..acd2fbfd82 100644
--- a/cms/djangoapps/contentstore/tests/test_course_listing.py
+++ b/cms/djangoapps/contentstore/tests/test_course_listing.py
@@ -5,14 +5,13 @@ by reversing group name formats.
import random
+from unittest.mock import Mock, patch
import ddt
from ccx_keys.locator import CCXLocator
from django.conf import settings
from django.test import RequestFactory
-from mock import Mock, patch
from opaque_keys.edx.locations import CourseLocator
-from six.moves import range
from cms.djangoapps.contentstore.tests.utils import AjaxEnabledTestClient
from cms.djangoapps.contentstore.utils import delete_course
@@ -51,7 +50,7 @@ class TestCourseListing(ModuleStoreTestCase):
"""
Add a user and a course
"""
- super(TestCourseListing, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
# create and log in a staff user.
# create and log in a non-staff user
self.user = UserFactory()
@@ -91,7 +90,7 @@ class TestCourseListing(ModuleStoreTestCase):
"""
Test on empty course listing, studio name is properly displayed
"""
- message = u"Are you staff on an existing {studio_name} course?".format(studio_name=settings.STUDIO_SHORT_NAME)
+ message = f"Are you staff on an existing {settings.STUDIO_SHORT_NAME} course?"
response = self.client.get('/home')
self.assertContains(response, message)
@@ -256,9 +255,9 @@ class TestCourseListing(ModuleStoreTestCase):
# create courses and assign those to the user which have their number in user_course_ids
with self.store.default_store(store):
for number in range(TOTAL_COURSES_COUNT):
- org = 'Org{0}'.format(number)
- course = 'Course{0}'.format(number)
- run = 'Run{0}'.format(number)
+ org = f'Org{number}'
+ course = f'Course{number}'
+ run = f'Run{number}'
course_location = self.store.make_course_key(org, course, run)
if number in user_course_ids:
self._create_course_with_access_groups(course_location, self.user, store=store)
@@ -369,7 +368,7 @@ class TestCourseListing(ModuleStoreTestCase):
# verify return values
def _set_of_course_keys(course_list, key_attribute_name='id'):
"""Returns a python set of course keys by accessing the key with the given attribute name."""
- return set(getattr(c, key_attribute_name) for c in course_list)
+ return {getattr(c, key_attribute_name) for c in course_list}
found_courses, unsucceeded_course_actions = _accessible_courses_iter_for_tests(self.request)
self.assertSetEqual(_set_of_course_keys(courses + courses_in_progress), _set_of_course_keys(found_courses))
diff --git a/cms/djangoapps/contentstore/tests/test_course_settings.py b/cms/djangoapps/contentstore/tests/test_course_settings.py
index 0d52d95d1a..6eb4f2aa76 100644
--- a/cms/djangoapps/contentstore/tests/test_course_settings.py
+++ b/cms/djangoapps/contentstore/tests/test_course_settings.py
@@ -7,10 +7,10 @@ import copy
import datetime
import json
import unittest
+from unittest import mock
+from unittest.mock import Mock, patch
import ddt
-import mock
-import six
from crum import set_current_request
from django.conf import settings
from django.test import RequestFactory
@@ -18,7 +18,6 @@ from django.test.utils import override_settings
from edx_toggles.toggles.testutils import override_waffle_flag
from milestones.models import MilestoneRelationshipType
from milestones.tests.utils import MilestonesTestCaseMixin
-from mock import Mock, patch
from pytz import UTC
from cms.djangoapps.contentstore.utils import reverse_course_url, reverse_usage_url
@@ -31,11 +30,11 @@ from cms.djangoapps.models.settings.course_metadata import CourseMetadata
from cms.djangoapps.models.settings.encoder import CourseSettingsEncoder
from cms.djangoapps.models.settings.waffle import MATERIAL_RECOMPUTE_ONLY_FLAG
from common.djangoapps.course_modes.models import CourseMode
-from openedx.core.djangoapps.models.course_details import CourseDetails
from common.djangoapps.student.roles import CourseInstructorRole, CourseStaffRole
from common.djangoapps.student.tests.factories import UserFactory
from common.djangoapps.util import milestones_helpers
from common.djangoapps.xblock_django.models import XBlockStudioConfigurationFlag
+from openedx.core.djangoapps.models.course_details import CourseDetails
from xmodule.fields import Date
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
@@ -100,7 +99,7 @@ class CourseAdvanceSettingViewTest(CourseTestCase, MilestonesTestCaseMixin):
"""
def setUp(self):
- super(CourseAdvanceSettingViewTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.fullcourse = CourseFactory.create()
self.course_setting_url = get_url(self.course.id, 'advanced_settings_handler')
@@ -204,7 +203,7 @@ class CourseDetailsViewTest(CourseTestCase, MilestonesTestCaseMixin):
dt1 = date.from_json(encoded[field])
dt2 = details[field]
- self.assertEqual(dt1, dt2, msg=u"{} != {} at {}".format(dt1, dt2, context))
+ self.assertEqual(dt1, dt2, msg=f"{dt1} != {dt2} at {context}")
else:
self.fail(field + " missing from encoded but in details at " + context)
elif field in encoded and encoded[field] is not None:
@@ -253,7 +252,7 @@ class CourseDetailsViewTest(CourseTestCase, MilestonesTestCaseMixin):
# update pre requisite courses with a new course keys
pre_requisite_course = CourseFactory.create(org='edX', course='900', run='test_run')
pre_requisite_course2 = CourseFactory.create(org='edX', course='902', run='test_run')
- pre_requisite_course_keys = [six.text_type(pre_requisite_course.id), six.text_type(pre_requisite_course2.id)]
+ pre_requisite_course_keys = [str(pre_requisite_course.id), str(pre_requisite_course2.id)]
course_detail_json['pre_requisite_courses'] = pre_requisite_course_keys
self.client.ajax_post(url, course_detail_json)
@@ -283,7 +282,7 @@ class CourseDetailsViewTest(CourseTestCase, MilestonesTestCaseMixin):
# update pre requisite courses one valid and one invalid key
pre_requisite_course = CourseFactory.create(org='edX', course='900', run='test_run')
- pre_requisite_course_keys = [six.text_type(pre_requisite_course.id), 'invalid_key']
+ pre_requisite_course_keys = [str(pre_requisite_course.id), 'invalid_key']
course_detail_json['pre_requisite_courses'] = pre_requisite_course_keys
response = self.client.ajax_post(url, course_detail_json)
self.assertEqual(400, response.status_code)
@@ -564,10 +563,10 @@ class CourseGradingTest(CourseTestCase):
mock.call(
GRADING_POLICY_CHANGED_EVENT_TYPE,
{
- 'course_id': six.text_type(self.course.id),
+ 'course_id': str(self.course.id),
'event_transaction_type': 'edx.grades.grading_policy_changed',
'grading_policy_hash': policy_hash,
- 'user_id': six.text_type(self.user.id),
+ 'user_id': str(self.user.id),
'event_transaction_id': 'mockUUID',
}
) for policy_hash in (
@@ -687,8 +686,8 @@ class CourseGradingTest(CourseTestCase):
mock.call(
GRADING_POLICY_CHANGED_EVENT_TYPE,
{
- 'course_id': six.text_type(self.course.id),
- 'user_id': six.text_type(self.user.id),
+ 'course_id': str(self.course.id),
+ 'user_id': str(self.user.id),
'grading_policy_hash': policy_hash,
'event_transaction_id': 'mockUUID',
'event_transaction_type': 'edx.grades.grading_policy_changed',
@@ -725,10 +724,10 @@ class CourseGradingTest(CourseTestCase):
mock.call(
GRADING_POLICY_CHANGED_EVENT_TYPE,
{
- 'course_id': six.text_type(self.course.id),
+ 'course_id': str(self.course.id),
'event_transaction_type': 'edx.grades.grading_policy_changed',
'grading_policy_hash': policy_hash,
- 'user_id': six.text_type(self.user.id),
+ 'user_id': str(self.user.id),
'event_transaction_id': 'mockUUID',
}
) for policy_hash in (grading_policy_1, grading_policy_2, grading_policy_3)
@@ -802,10 +801,10 @@ class CourseGradingTest(CourseTestCase):
mock.call(
GRADING_POLICY_CHANGED_EVENT_TYPE,
{
- 'course_id': six.text_type(self.course.id),
+ 'course_id': str(self.course.id),
'event_transaction_type': 'edx.grades.grading_policy_changed',
'grading_policy_hash': policy_hash,
- 'user_id': six.text_type(self.user.id),
+ 'user_id': str(self.user.id),
'event_transaction_id': 'mockUUID',
}
) for policy_hash in (grading_policy_1, grading_policy_2)
@@ -895,15 +894,15 @@ class CourseGradingTest(CourseTestCase):
Test setting and getting section grades via the grade as url
"""
grade_type_url = self.setup_test_set_get_section_grader_ajax()
- response = self.client.ajax_post(grade_type_url, {'graderType': u'Homework'})
+ response = self.client.ajax_post(grade_type_url, {'graderType': 'Homework'})
self.assertEqual(200, response.status_code)
response = self.client.get_json(grade_type_url + '?fields=graderType')
- self.assertEqual(json.loads(response.content.decode('utf-8')).get('graderType'), u'Homework')
+ self.assertEqual(json.loads(response.content.decode('utf-8')).get('graderType'), 'Homework')
# and unset
- response = self.client.ajax_post(grade_type_url, {'graderType': u'notgraded'})
+ response = self.client.ajax_post(grade_type_url, {'graderType': 'notgraded'})
self.assertEqual(200, response.status_code)
response = self.client.get_json(grade_type_url + '?fields=graderType')
- self.assertEqual(json.loads(response.content.decode('utf-8')).get('graderType'), u'notgraded')
+ self.assertEqual(json.loads(response.content.decode('utf-8')).get('graderType'), 'notgraded')
def _grading_policy_hash_for_course(self):
return hash_grading_policy(modulestore().get_course(self.course.id).grading_policy)
@@ -916,7 +915,7 @@ class CourseMetadataEditingTest(CourseTestCase):
"""
def setUp(self):
- super(CourseMetadataEditingTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.fullcourse = CourseFactory.create()
self.course_setting_url = get_url(self.course.id, 'advanced_settings_handler')
self.fullcourse_setting_url = get_url(self.fullcourse.id, 'advanced_settings_handler')
@@ -1175,8 +1174,8 @@ class CourseMetadataEditingTest(CourseTestCase):
self.assertEqual(len(errors), 3)
self.assertFalse(test_model)
- error_keys = set([error_obj['model']['display_name'] for error_obj in errors]) # lint-amnesty, pylint: disable=consider-using-set-comprehension
- test_keys = set(['Advanced Module List', 'Course Advertised Start Date', 'Days Early for Beta Users'])
+ error_keys = {error_obj['model']['display_name'] for error_obj in errors}
+ test_keys = {'Advanced Module List', 'Course Advertised Start Date', 'Days Early for Beta Users'}
self.assertEqual(error_keys, test_keys)
# try fresh fetch to ensure no update happened
@@ -1527,7 +1526,7 @@ class CourseGraderUpdatesTest(CourseTestCase):
def setUp(self):
"""Compute the url to use in tests"""
- super(CourseGraderUpdatesTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.url = get_url(self.course.id, 'grading_handler')
self.starting_graders = CourseGradingModel(self.course).graders
@@ -1625,9 +1624,9 @@ id=\"course-enrollment-end-time\" value=\"\" placeholder=\"HH:MM\" autocomplete=
"""
Initialize course used to test enrollment fields.
"""
- super(CourseEnrollmentEndFieldTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course = CourseFactory.create(org='edX', number='dummy', display_name='Marketing Site Course')
- self.course_details_url = reverse_course_url('settings_handler', six.text_type(self.course.id))
+ self.course_details_url = reverse_course_url('settings_handler', str(self.course.id))
def _get_course_details_response(self, global_staff):
"""
diff --git a/cms/djangoapps/contentstore/tests/test_courseware_index.py b/cms/djangoapps/contentstore/tests/test_courseware_index.py
index 5c175d1ab8..ca49b5013a 100644
--- a/cms/djangoapps/contentstore/tests/test_courseware_index.py
+++ b/cms/djangoapps/contentstore/tests/test_courseware_index.py
@@ -7,17 +7,15 @@ import json
import time
from datetime import datetime
from unittest import skip
+from unittest.mock import patch
from uuid import uuid4
import ddt
import pytest
-import six
from django.conf import settings
from lazy.lazy import lazy
-from mock import patch
from pytz import UTC
from search.search_engine_base import SearchEngine
-from six.moves import range
from xblock.core import XBlock # lint-amnesty, pylint: disable=unused-import
from cms.djangoapps.contentstore.courseware_index import (
@@ -71,7 +69,7 @@ def create_children(store, parent, category, load_factor):
child_object = ItemFactory.create(
parent_location=parent.location,
category=category,
- display_name=u"{} {} {}".format(category, child_index, time.clock()), # lint-amnesty, pylint: disable=no-member
+ display_name=f"{category} {child_index} {time.clock()}", # lint-amnesty, pylint: disable=no-member
modulestore=store,
publish_item=True,
start=datetime(2015, 3, 1, tzinfo=UTC),
@@ -195,7 +193,7 @@ class TestCoursewareSearchIndexer(MixedWithOptionsTestCase):
WORKS_WITH_STORES = (ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def setUp(self):
- super(TestCoursewareSearchIndexer, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course = None
self.chapter = None
@@ -263,7 +261,7 @@ class TestCoursewareSearchIndexer(MixedWithOptionsTestCase):
)
def _get_default_search(self):
- return {"course": six.text_type(self.course.id)}
+ return {"course": str(self.course.id)}
def _test_indexing_course(self, store):
""" indexing course tests """
@@ -361,10 +359,10 @@ class TestCoursewareSearchIndexer(MixedWithOptionsTestCase):
results = response["results"]
date_map = {
- six.text_type(self.chapter.location): early_date,
- six.text_type(self.sequential.location): early_date,
- six.text_type(self.vertical.location): later_date,
- six.text_type(self.html_unit.location): later_date,
+ str(self.chapter.location): early_date,
+ str(self.sequential.location): early_date,
+ str(self.vertical.location): later_date,
+ str(self.html_unit.location): later_date,
}
for result in results:
self.assertEqual(result["data"]["start_date"], date_map[result["data"]["id"]])
@@ -429,7 +427,7 @@ class TestCoursewareSearchIndexer(MixedWithOptionsTestCase):
self.update_item(store, self.course)
self.reindex_course(store)
response = self.searcher.search(
- field_dictionary={"course": six.text_type(self.course.id)}
+ field_dictionary={"course": str(self.course.id)}
)
self.assertEqual(response["total"], 1)
self.assertEqual(response["results"][0]["data"]["content"]["display_name"], display_name)
@@ -446,7 +444,7 @@ class TestCoursewareSearchIndexer(MixedWithOptionsTestCase):
)
self.reindex_course(store)
response = self.searcher.search(
- field_dictionary={"course": six.text_type(self.course.id)}
+ field_dictionary={"course": str(self.course.id)}
)
self.assertEqual(response["total"], 1)
self.assertEqual(response["results"][0]["data"]["content"]["short_description"], short_description)
@@ -473,7 +471,7 @@ class TestCoursewareSearchIndexer(MixedWithOptionsTestCase):
self.reindex_course(store)
response = self.searcher.search(
- field_dictionary={"course": six.text_type(self.course.id)}
+ field_dictionary={"course": str(self.course.id)}
)
self.assertEqual(response["total"], 1)
self.assertIn(CourseMode.HONOR, response["results"][0]["data"]["modes"])
@@ -605,11 +603,11 @@ class TestLargeCourseDeletions(MixedWithOptionsTestCase):
self.course_id = None
def setUp(self):
- super(TestLargeCourseDeletions, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course_id = None
def tearDown(self):
- super(TestLargeCourseDeletions, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments
+ super().tearDown()
self._clean_course_id()
def assert_search_count(self, expected_count):
@@ -622,13 +620,13 @@ class TestLargeCourseDeletions(MixedWithOptionsTestCase):
""" Test that deleting items from a course works even when present within a very large course """
def id_list(top_parent_object):
""" private function to get ids from object down the tree """
- list_of_ids = [six.text_type(top_parent_object.location)]
+ list_of_ids = [str(top_parent_object.location)]
for child in top_parent_object.get_children():
list_of_ids.extend(id_list(child))
return list_of_ids
course, course_size = create_large_course(store, load_factor)
- self.course_id = six.text_type(course.id)
+ self.course_id = str(course.id)
# index full course
CoursewareSearchIndexer.do_course_reindex(store, course.id)
@@ -657,10 +655,10 @@ class TestLargeCourseDeletions(MixedWithOptionsTestCase):
self._do_test_large_course_deletion(store, load_factor)
except: # pylint: disable=bare-except
# Catch any exception here to see when we fail
- print(u"Failed with load_factor of {}".format(load_factor))
+ print(f"Failed with load_factor of {load_factor}")
- @skip(("This test is to see how we handle very large courses, to ensure that the delete"
- "procedure works smoothly - too long to run during the normal course of things"))
+ @skip("This test is to see how we handle very large courses, to ensure that the delete"
+ "procedure works smoothly - too long to run during the normal course of things")
@ddt.data(*WORKS_WITH_STORES)
def test_large_course_deletion(self, store_type):
self._perform_test_using_store(store_type, self._test_large_course_deletion)
@@ -676,7 +674,7 @@ class TestTaskExecution(SharedModuleStoreTestCase):
@classmethod
def setUpClass(cls):
- super(TestTaskExecution, cls).setUpClass()
+ super().setUpClass()
SignalHandler.course_published.disconnect(listen_for_course_publish)
SignalHandler.library_updated.disconnect(listen_for_library_update)
cls.course = CourseFactory.create(start=datetime(2015, 3, 1, tzinfo=UTC))
@@ -730,7 +728,7 @@ class TestTaskExecution(SharedModuleStoreTestCase):
def tearDownClass(cls):
SignalHandler.course_published.connect(listen_for_course_publish)
SignalHandler.library_updated.connect(listen_for_library_update)
- super(TestTaskExecution, cls).tearDownClass()
+ super().tearDownClass()
def test_task_indexing_course(self):
"""
@@ -739,7 +737,7 @@ class TestTaskExecution(SharedModuleStoreTestCase):
"""
searcher = SearchEngine.get_search_engine(CoursewareSearchIndexer.INDEX_NAME)
response = searcher.search(
- field_dictionary={"course": six.text_type(self.course.id)}
+ field_dictionary={"course": str(self.course.id)}
)
self.assertEqual(response["total"], 0)
@@ -747,14 +745,14 @@ class TestTaskExecution(SharedModuleStoreTestCase):
# Note that this test will only succeed if celery is working in inline mode
response = searcher.search(
- field_dictionary={"course": six.text_type(self.course.id)}
+ field_dictionary={"course": str(self.course.id)}
)
self.assertEqual(response["total"], 3)
def test_task_library_update(self):
""" Making sure that the receiver correctly fires off the task when invoked by signal """
searcher = SearchEngine.get_search_engine(LibrarySearchIndexer.INDEX_NAME)
- library_search_key = six.text_type(normalize_key_for_search(self.library.location.library_key))
+ library_search_key = str(normalize_key_for_search(self.library.location.library_key))
response = searcher.search(field_dictionary={"library": library_search_key})
self.assertEqual(response["total"], 0)
@@ -787,7 +785,7 @@ class TestLibrarySearchIndexer(MixedWithOptionsTestCase):
WORKS_WITH_STORES = (ModuleStoreEnum.Type.split, )
def setUp(self):
- super(TestLibrarySearchIndexer, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.library = None
self.html_unit1 = None
@@ -819,7 +817,7 @@ class TestLibrarySearchIndexer(MixedWithOptionsTestCase):
def _get_default_search(self):
""" Returns field_dictionary for default search """
- return {"library": six.text_type(self.library.location.library_key.replace(version_guid=None, branch=None))}
+ return {"library": str(self.library.location.library_key.replace(version_guid=None, branch=None))}
def reindex_library(self, store):
""" kick off complete reindex of the course """
@@ -937,7 +935,7 @@ class GroupConfigurationSearchMongo(CourseTestCase, MixedWithOptionsTestCase):
INDEX_NAME = CoursewareSearchIndexer.INDEX_NAME
def setUp(self):
- super(GroupConfigurationSearchMongo, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self._setup_course_with_content()
self._setup_split_test_module()
@@ -1099,26 +1097,26 @@ class GroupConfigurationSearchMongo(CourseTestCase, MixedWithOptionsTestCase):
Set up cohort and experiment content groups.
"""
cohort_groups_list = {
- u'id': 666,
- u'name': u'Test name',
- u'scheme': u'cohort',
- u'description': u'Test description',
- u'version': UserPartition.VERSION,
- u'groups': [
- {u'id': 0, u'name': u'Group A', u'version': 1, u'usage': []},
- {u'id': 1, u'name': u'Group B', u'version': 1, u'usage': []},
+ 'id': 666,
+ 'name': 'Test name',
+ 'scheme': 'cohort',
+ 'description': 'Test description',
+ 'version': UserPartition.VERSION,
+ 'groups': [
+ {'id': 0, 'name': 'Group A', 'version': 1, 'usage': []},
+ {'id': 1, 'name': 'Group B', 'version': 1, 'usage': []},
],
}
experiment_groups_list = {
- u'id': 0,
- u'name': u'Experiment aware partition',
- u'scheme': u'random',
- u'description': u'Experiment aware description',
- u'version': UserPartition.VERSION,
- u'groups': [
- {u'id': 2, u'name': u'Group A', u'version': 1, u'usage': []},
- {u'id': 3, u'name': u'Group B', u'version': 1, u'usage': []},
- {u'id': 4, u'name': u'Group C', u'version': 1, u'usage': []}
+ 'id': 0,
+ 'name': 'Experiment aware partition',
+ 'scheme': 'random',
+ 'description': 'Experiment aware description',
+ 'version': UserPartition.VERSION,
+ 'groups': [
+ {'id': 2, 'name': 'Group A', 'version': 1, 'usage': []},
+ {'id': 3, 'name': 'Group B', 'version': 1, 'usage': []},
+ {'id': 4, 'name': 'Group C', 'version': 1, 'usage': []}
],
}
@@ -1153,9 +1151,9 @@ class GroupConfigurationSearchMongo(CourseTestCase, MixedWithOptionsTestCase):
"""
return {
'course_name': self.course.display_name,
- 'id': six.text_type(html_unit.location),
+ 'id': str(html_unit.location),
'content': {'html_content': '', 'display_name': html_unit.display_name},
- 'course': six.text_type(self.course.id),
+ 'course': str(self.course.id),
'location': [
self.chapter.display_name,
self.sequential.display_name,
@@ -1173,9 +1171,9 @@ class GroupConfigurationSearchMongo(CourseTestCase, MixedWithOptionsTestCase):
"""
return {
'course_name': self.course.display_name,
- 'id': six.text_type(html_unit.location),
+ 'id': str(html_unit.location),
'content': {'html_content': '', 'display_name': html_unit.display_name},
- 'course': six.text_type(self.course.id),
+ 'course': str(self.course.id),
'location': [
self.chapter.display_name,
self.sequential2.display_name,
@@ -1194,7 +1192,7 @@ class GroupConfigurationSearchMongo(CourseTestCase, MixedWithOptionsTestCase):
return {
'start_date': datetime(2015, 4, 1, 0, 0, tzinfo=UTC),
'content': {'display_name': vertical.display_name},
- 'course': six.text_type(self.course.id),
+ 'course': str(self.course.id),
'location': [
self.chapter.display_name,
self.sequential2.display_name,
@@ -1202,7 +1200,7 @@ class GroupConfigurationSearchMongo(CourseTestCase, MixedWithOptionsTestCase):
],
'content_type': 'Sequence',
'content_groups': content_groups,
- 'id': six.text_type(vertical.location),
+ 'id': str(vertical.location),
'course_name': self.course.display_name,
'org': self.course.org
}
@@ -1213,9 +1211,9 @@ class GroupConfigurationSearchMongo(CourseTestCase, MixedWithOptionsTestCase):
"""
return {
'course_name': self.course.display_name,
- 'id': six.text_type(html_unit.location),
+ 'id': str(html_unit.location),
'content': {'html_content': '', 'display_name': html_unit.display_name},
- 'course': six.text_type(self.course.id),
+ 'course': str(self.course.id),
'location': [
self.chapter.display_name,
self.sequential.display_name,
@@ -1247,7 +1245,7 @@ class GroupConfigurationSearchMongo(CourseTestCase, MixedWithOptionsTestCase):
# Only published modules should be in the index
added_to_index = self.reindex_course(self.store)
self.assertEqual(added_to_index, 16)
- response = self.searcher.search(field_dictionary={"course": six.text_type(self.course.id)})
+ response = self.searcher.search(field_dictionary={"course": str(self.course.id)})
self.assertEqual(response["total"], 16)
group_access_content = {'group_access': {666: [1]}}
@@ -1265,44 +1263,44 @@ class GroupConfigurationSearchMongo(CourseTestCase, MixedWithOptionsTestCase):
self.assertTrue(mock_index.called)
indexed_content = self._get_index_values_from_call_args(mock_index)
self.assertIn(self._html_group_result(self.html_unit1, [1]), indexed_content)
- self.assertIn(self._html_experiment_group_result(self.html_unit4, [six.text_type(2)]), indexed_content)
- self.assertIn(self._html_experiment_group_result(self.html_unit5, [six.text_type(3)]), indexed_content)
- self.assertIn(self._html_experiment_group_result(self.html_unit6, [six.text_type(4)]), indexed_content)
- self.assertNotIn(self._html_experiment_group_result(self.html_unit6, [six.text_type(5)]), indexed_content)
+ self.assertIn(self._html_experiment_group_result(self.html_unit4, [str(2)]), indexed_content)
+ self.assertIn(self._html_experiment_group_result(self.html_unit5, [str(3)]), indexed_content)
+ self.assertIn(self._html_experiment_group_result(self.html_unit6, [str(4)]), indexed_content)
+ self.assertNotIn(self._html_experiment_group_result(self.html_unit6, [str(5)]), indexed_content)
self.assertIn(
- self._vertical_experiment_group_result(self.condition_0_vertical, [six.text_type(2)]),
+ self._vertical_experiment_group_result(self.condition_0_vertical, [str(2)]),
indexed_content
)
self.assertNotIn(
- self._vertical_experiment_group_result(self.condition_1_vertical, [six.text_type(2)]),
+ self._vertical_experiment_group_result(self.condition_1_vertical, [str(2)]),
indexed_content
)
self.assertNotIn(
- self._vertical_experiment_group_result(self.condition_2_vertical, [six.text_type(2)]),
+ self._vertical_experiment_group_result(self.condition_2_vertical, [str(2)]),
indexed_content
)
self.assertNotIn(
- self._vertical_experiment_group_result(self.condition_0_vertical, [six.text_type(3)]),
+ self._vertical_experiment_group_result(self.condition_0_vertical, [str(3)]),
indexed_content
)
self.assertIn(
- self._vertical_experiment_group_result(self.condition_1_vertical, [six.text_type(3)]),
+ self._vertical_experiment_group_result(self.condition_1_vertical, [str(3)]),
indexed_content
)
self.assertNotIn(
- self._vertical_experiment_group_result(self.condition_2_vertical, [six.text_type(3)]),
+ self._vertical_experiment_group_result(self.condition_2_vertical, [str(3)]),
indexed_content
)
self.assertNotIn(
- self._vertical_experiment_group_result(self.condition_0_vertical, [six.text_type(4)]),
+ self._vertical_experiment_group_result(self.condition_0_vertical, [str(4)]),
indexed_content
)
self.assertNotIn(
- self._vertical_experiment_group_result(self.condition_1_vertical, [six.text_type(4)]),
+ self._vertical_experiment_group_result(self.condition_1_vertical, [str(4)]),
indexed_content
)
self.assertIn(
- self._vertical_experiment_group_result(self.condition_2_vertical, [six.text_type(4)]),
+ self._vertical_experiment_group_result(self.condition_2_vertical, [str(4)]),
indexed_content
)
mock_index.reset_mock()
diff --git a/cms/djangoapps/contentstore/tests/test_export_git.py b/cms/djangoapps/contentstore/tests/test_export_git.py
index bfbd98d3f2..21d0c89788 100644
--- a/cms/djangoapps/contentstore/tests/test_export_git.py
+++ b/cms/djangoapps/contentstore/tests/test_export_git.py
@@ -32,7 +32,7 @@ class TestExportGit(CourseTestCase):
"""
Setup test course, user, and url.
"""
- super(TestExportGit, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course_module = modulestore().get_course(self.course.id)
self.test_url = reverse_course_url('export_git', self.course.id)
@@ -46,7 +46,7 @@ class TestExportGit(CourseTestCase):
os.mkdir(repo_dir)
self.addCleanup(shutil.rmtree, repo_dir)
- bare_repo_dir = '{0}/{1}.git'.format(
+ bare_repo_dir = '{}/{}.git'.format(
os.path.abspath(git_export_utils.GIT_REPO_EXPORT_DIR),
repo_name
)
@@ -55,7 +55,7 @@ class TestExportGit(CourseTestCase):
subprocess.check_output(['git', '--bare', 'init', ], cwd=bare_repo_dir)
self.populate_course()
- self.course_module.giturl = 'file://{}'.format(bare_repo_dir)
+ self.course_module.giturl = f'file://{bare_repo_dir}'
modulestore().update_item(self.course_module, self.user.id)
def test_giturl_missing(self):
@@ -70,7 +70,7 @@ class TestExportGit(CourseTestCase):
'course settings before you can export to git.'),
)
- response = self.client.get('{}?action=push'.format(self.test_url))
+ response = self.client.get(f'{self.test_url}?action=push')
self.assertContains(
response,
('giturl must be defined in your '
@@ -84,7 +84,7 @@ class TestExportGit(CourseTestCase):
self.course_module.giturl = 'foobar'
modulestore().update_item(self.course_module, self.user.id)
- response = self.client.get('{}?action=push'.format(self.test_url))
+ response = self.client.get(f'{self.test_url}?action=push')
self.assertContains(response, 'Export Failed:')
def test_exception_translation(self):
@@ -94,7 +94,7 @@ class TestExportGit(CourseTestCase):
self.course_module.giturl = 'foobar'
modulestore().update_item(self.course_module, self.user.id)
- response = self.client.get('{}?action=push'.format(self.test_url))
+ response = self.client.get(f'{self.test_url}?action=push')
self.assertNotContains(response, 'django.utils.functional.__proxy__')
def test_course_export_success(self):
@@ -103,7 +103,7 @@ class TestExportGit(CourseTestCase):
"""
self.make_bare_repo_with_course('test_repo')
- response = self.client.get('{}?action=push'.format(self.test_url))
+ response = self.client.get(f'{self.test_url}?action=push')
self.assertContains(response, 'Export Succeeded')
def test_repo_with_dots(self):
@@ -111,7 +111,7 @@ class TestExportGit(CourseTestCase):
Regression test for a bad directory pathing of repo's that have dots.
"""
self.make_bare_repo_with_course('test.repo')
- response = self.client.get('{}?action=push'.format(self.test_url))
+ response = self.client.get(f'{self.test_url}?action=push')
self.assertContains(response, 'Export Succeeded')
def test_dirty_repo(self):
diff --git a/cms/djangoapps/contentstore/tests/test_gating.py b/cms/djangoapps/contentstore/tests/test_gating.py
index 7ed635f732..5f7bf639c7 100644
--- a/cms/djangoapps/contentstore/tests/test_gating.py
+++ b/cms/djangoapps/contentstore/tests/test_gating.py
@@ -3,8 +3,9 @@ Unit tests for the gating feature in Studio
"""
+from unittest.mock import patch
+
from milestones.tests.utils import MilestonesTestCaseMixin
-from mock import patch
from cms.djangoapps.contentstore.signals.handlers import handle_item_deleted
from openedx.core.lib.gating import api as gating_api
@@ -22,7 +23,7 @@ class TestHandleItemDeleted(ModuleStoreTestCase, MilestonesTestCaseMixin):
"""
Initial data setup
"""
- super(TestHandleItemDeleted, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course = CourseFactory.create()
self.course.enable_subsection_gating = True
diff --git a/cms/djangoapps/contentstore/tests/test_i18n.py b/cms/djangoapps/contentstore/tests/test_i18n.py
index 8d0344143f..7ddc9965c2 100644
--- a/cms/djangoapps/contentstore/tests/test_i18n.py
+++ b/cms/djangoapps/contentstore/tests/test_i18n.py
@@ -1,13 +1,11 @@
-# -*- coding: utf-8 -*-
"""
Tests for validate Internationalization and Module i18n service.
"""
import gettext
-from unittest import skip
+from unittest import mock, skip
-import mock
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.utils import translation
from django.utils.translation import get_language
@@ -62,7 +60,7 @@ class TestModuleI18nService(ModuleStoreTestCase):
def setUp(self):
""" Setting up tests """
- super(TestModuleI18nService, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.test_language = 'dummy language'
self.request = mock.Mock()
self.course = CourseFactory.create()
@@ -89,7 +87,7 @@ class TestModuleI18nService(ModuleStoreTestCase):
Test django translation service works fine.
"""
- class wrap_ugettext_with_xyz(object): # pylint: disable=invalid-name
+ class wrap_ugettext_with_xyz: # pylint: disable=invalid-name
"""
A context manager function that just adds 'XYZ ' to the front
of all strings of the module ugettext function.
@@ -187,7 +185,7 @@ class InternationalizationTest(ModuleStoreTestCase):
will be cleared out before each test case execution and deleted
afterwards.
"""
- super(InternationalizationTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.uname = 'testuser'
self.email = 'test+courses@edx.org'
@@ -216,7 +214,7 @@ class InternationalizationTest(ModuleStoreTestCase):
resp = self.client.get_html('/home/')
self.assertContains(resp,
- u'',
+ '',
status_code=200,
html=True)
@@ -232,7 +230,7 @@ class InternationalizationTest(ModuleStoreTestCase):
)
self.assertContains(resp,
- u'',
+ '',
status_code=200,
html=True)
@@ -257,9 +255,9 @@ class InternationalizationTest(ModuleStoreTestCase):
)
TEST_STRING = (
- u''
- u'My \xc7\xf6\xfcrs\xe9s L#'
- u'
'
+ ''
+ 'My \xc7\xf6\xfcrs\xe9s L#'
+ '
'
)
self.assertContains(resp,
diff --git a/cms/djangoapps/contentstore/tests/test_import.py b/cms/djangoapps/contentstore/tests/test_import.py
index 61b8854f23..41b06729ac 100644
--- a/cms/djangoapps/contentstore/tests/test_import.py
+++ b/cms/djangoapps/contentstore/tests/test_import.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""
Tests for import_course_from_xml using the mongo modulestore.
@@ -6,14 +5,13 @@ Tests for import_course_from_xml using the mongo modulestore.
import copy
+from unittest.mock import patch
from uuid import uuid4
import ddt
-import six
from django.conf import settings
from django.test.client import Client
from django.test.utils import override_settings
-from mock import patch
from xmodule.contentstore.django import contentstore
from xmodule.exceptions import NotFoundError
@@ -37,7 +35,7 @@ class ContentStoreImportTest(ModuleStoreTestCase):
NOTE: refactor using CourseFactory so they do not.
"""
def setUp(self):
- super(ContentStoreImportTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.client = Client()
self.client.login(username=self.user.username, password=self.user_password)
@@ -48,7 +46,7 @@ class ContentStoreImportTest(ModuleStoreTestCase):
def tearDown(self):
self.task_patcher.stop()
- super(ContentStoreImportTest, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments
+ super().tearDown()
def load_test_import_course(self, target_id=None, create_if_not_present=True, module_store=None):
'''
@@ -97,7 +95,7 @@ class ContentStoreImportTest(ModuleStoreTestCase):
# Test with the split modulestore because store.has_course fails in old mongo with unicode characters.
with modulestore().default_store(ModuleStoreEnum.Type.split):
module_store = modulestore()
- course_id = module_store.make_course_key(u'Юникода', u'unicode_course', u'échantillon')
+ course_id = module_store.make_course_key('Юникода', 'unicode_course', 'échantillon')
import_course_from_xml(
module_store,
self.user.id,
@@ -111,7 +109,7 @@ class ContentStoreImportTest(ModuleStoreTestCase):
self.assertIsNotNone(course)
# test that course 'display_name' same as imported course 'display_name'
- self.assertEqual(course.display_name, u"Φυσικά το όνομα Unicode")
+ self.assertEqual(course.display_name, "Φυσικά το όνομα Unicode")
def test_static_import(self):
'''
@@ -135,7 +133,7 @@ class ContentStoreImportTest(ModuleStoreTestCase):
self.assertIsNotNone(content)
# make sure course.static_asset_path is correct
- print(u"static_asset_path = {0}".format(course.static_asset_path))
+ print(f"static_asset_path = {course.static_asset_path}")
self.assertEqual(course.static_asset_path, 'test_import_course')
def test_asset_import_nostatic(self):
@@ -174,7 +172,7 @@ class ContentStoreImportTest(ModuleStoreTestCase):
def test_tab_name_imports_correctly(self):
_module_store, _content_store, course = self.load_test_import_course()
- print(u"course tabs = {0}".format(course.tabs))
+ print(f"course tabs = {course.tabs}")
self.assertEqual(course.tabs[2]['name'], 'Syllabus')
def test_import_performance_mongo(self):
@@ -269,7 +267,7 @@ class ContentStoreImportTest(ModuleStoreTestCase):
self.assertIsNotNone(split_test_module)
remapped_verticals = {
- key: target_id.make_usage_key('vertical', value) for key, value in six.iteritems(groups_to_verticals)
+ key: target_id.make_usage_key('vertical', value) for key, value in groups_to_verticals.items()
}
self.assertEqual(remapped_verticals, split_test_module.group_id_to_child)
diff --git a/cms/djangoapps/contentstore/tests/test_libraries.py b/cms/djangoapps/contentstore/tests/test_libraries.py
index 27edd08d24..0c5002b4b6 100644
--- a/cms/djangoapps/contentstore/tests/test_libraries.py
+++ b/cms/djangoapps/contentstore/tests/test_libraries.py
@@ -3,12 +3,11 @@ Content library unit tests that require the CMS runtime.
"""
+from unittest.mock import Mock, patch
+
import ddt
-import six
from django.test.utils import override_settings
-from mock import Mock, patch
from opaque_keys.edx.locator import CourseKey, LibraryLocator
-from six.moves import range
from cms.djangoapps.contentstore.tests.utils import AjaxEnabledTestClient, parse_json
from cms.djangoapps.contentstore.utils import reverse_library_url, reverse_url, reverse_usage_url
@@ -41,7 +40,7 @@ class LibraryTestCase(ModuleStoreTestCase):
"""
def setUp(self):
- super(LibraryTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.user = UserFactory(password=self.user_password, is_staff=True)
self.client = AjaxEnabledTestClient()
@@ -85,7 +84,7 @@ class LibraryTestCase(ModuleStoreTestCase):
parent_location=course.location,
user_id=self.user.id,
publish_item=publish_item,
- source_library_id=six.text_type(library_key),
+ source_library_id=str(library_key),
**(other_settings or {})
)
@@ -189,7 +188,7 @@ class TestLibraries(LibraryTestCase):
# Create many blocks in the library and add them to a course:
for num in range(8):
ItemFactory.create(
- data=u"This is #{}".format(num + 1),
+ data="This is #{}".format(num + 1),
category="html", parent_location=self.library.location, user_id=self.user.id, publish_item=False
)
@@ -488,11 +487,11 @@ class TestLibraries(LibraryTestCase):
self._create_library(library="l4", display_name="Library-Title-4", org='org-test2')
self.assertEqual(len(self.client.get_json(LIBRARY_REST_URL).json()), 5) # 1 more from self.setUp()
- self.assertEqual(len(self.client.get_json('{}?org=org-test1'.format(LIBRARY_REST_URL)).json()), 2)
- self.assertEqual(len(self.client.get_json('{}?text_search=test-lib'.format(LIBRARY_REST_URL)).json()), 2)
- self.assertEqual(len(self.client.get_json('{}?text_search=library-title'.format(LIBRARY_REST_URL)).json()), 3)
- self.assertEqual(len(self.client.get_json('{}?text_search=library-'.format(LIBRARY_REST_URL)).json()), 3)
- self.assertEqual(len(self.client.get_json('{}?text_search=org-test'.format(LIBRARY_REST_URL)).json()), 3)
+ self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?org=org-test1').json()), 2)
+ self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=test-lib').json()), 2)
+ self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=library-title').json()), 3)
+ self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=library-').json()), 3)
+ self.assertEqual(len(self.client.get_json(f'{LIBRARY_REST_URL}?text_search=org-test').json()), 3)
@ddt.ddt
@@ -504,7 +503,7 @@ class TestLibraryAccess(LibraryTestCase):
def setUp(self):
""" Create a library, staff user, and non-staff user """
- super(TestLibraryAccess, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.non_staff_user_password = 'foo'
self.non_staff_user = UserFactory(password=self.non_staff_user_password, is_staff=False)
@@ -531,11 +530,11 @@ class TestLibraryAccess(LibraryTestCase):
`library` can be a LibraryLocator or the library's root XBlock
"""
- if isinstance(library, (six.string_types, LibraryLocator)):
+ if isinstance(library, (str, LibraryLocator)):
lib_key = library
else:
lib_key = library.location.library_key
- response = self.client.get(reverse_library_url('library_handler', six.text_type(lib_key)))
+ response = self.client.get(reverse_library_url('library_handler', str(lib_key)))
self.assertIn(response.status_code, (200, 302, 403))
return response.status_code == 200
@@ -544,7 +543,7 @@ class TestLibraryAccess(LibraryTestCase):
Log out when done each test
"""
self.client.logout()
- super(TestLibraryAccess, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments
+ super().tearDown()
def test_creation(self):
"""
@@ -599,7 +598,7 @@ class TestLibraryAccess(LibraryTestCase):
# Now non_staff_user should be able to access library2_key only:
lib_list = self._list_libraries()
self.assertEqual(len(lib_list), 1)
- self.assertEqual(lib_list[0]["library_key"], six.text_type(library2_key))
+ self.assertEqual(lib_list[0]["library_key"], str(library2_key))
self.assertTrue(self._can_access_library(library2_key))
self.assertFalse(self._can_access_library(self.library))
@@ -626,7 +625,7 @@ class TestLibraryAccess(LibraryTestCase):
# Now non_staff_user should be able to access lib_key_pacific only:
lib_list = self._list_libraries()
self.assertEqual(len(lib_list), 1)
- self.assertEqual(lib_list[0]["library_key"], six.text_type(lib_key_pacific))
+ self.assertEqual(lib_list[0]["library_key"], str(lib_key_pacific))
self.assertTrue(self._can_access_library(lib_key_pacific))
self.assertFalse(self._can_access_library(lib_key_atlantic))
self.assertFalse(self._can_access_library(self.lib_key))
@@ -666,8 +665,8 @@ class TestLibraryAccess(LibraryTestCase):
def can_copy_block():
""" Check if studio lets us duplicate the XBlock in the library """
response = self.client.ajax_post(reverse_url('xblock_handler'), {
- 'parent_locator': six.text_type(self.library.location),
- 'duplicate_source_locator': six.text_type(block.location),
+ 'parent_locator': str(self.library.location),
+ 'duplicate_source_locator': str(block.location),
})
self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous
return response.status_code == 200
@@ -675,7 +674,7 @@ class TestLibraryAccess(LibraryTestCase):
def can_create_block():
""" Check if studio lets us make a new XBlock in the library """
response = self.client.ajax_post(reverse_url('xblock_handler'), {
- 'parent_locator': six.text_type(self.library.location), 'category': 'html',
+ 'parent_locator': str(self.library.location), 'category': 'html',
})
self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous
return response.status_code == 200
@@ -728,8 +727,8 @@ class TestLibraryAccess(LibraryTestCase):
# Copy block to the course:
response = self.client.ajax_post(reverse_url('xblock_handler'), {
- 'parent_locator': six.text_type(course.location),
- 'duplicate_source_locator': six.text_type(block.location),
+ 'parent_locator': str(course.location),
+ 'duplicate_source_locator': str(block.location),
})
self.assertIn(response.status_code, (200, 403)) # 400 would be ambiguous
duplicate_action_allowed = (response.status_code == 200)
@@ -837,7 +836,7 @@ class TestOverrides(LibraryTestCase):
"""
def setUp(self):
- super(TestOverrides, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.original_display_name = "A Problem Block"
self.original_weight = 1
@@ -1022,7 +1021,7 @@ class TestIncompatibleModuleStore(LibraryTestCase):
"""
def setUp(self):
- super(TestIncompatibleModuleStore, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
# Create a course in an incompatible modulestore.
with modulestore().default_store(ModuleStoreEnum.Type.mongo):
self.course = CourseFactory.create()
diff --git a/cms/djangoapps/contentstore/tests/test_orphan.py b/cms/djangoapps/contentstore/tests/test_orphan.py
index c6deba4d68..48745753f4 100644
--- a/cms/djangoapps/contentstore/tests/test_orphan.py
+++ b/cms/djangoapps/contentstore/tests/test_orphan.py
@@ -6,7 +6,6 @@ Test finding orphans via the view and django config
import json
import ddt
-import six
from opaque_keys.edx.locator import BlockUsageLocator
from cms.djangoapps.contentstore.tests.utils import CourseTestCase
@@ -95,13 +94,13 @@ class TestOrphan(TestOrphanBase):
HTTP_ACCEPT='application/json'
).content.decode('utf-8')
)
- self.assertEqual(len(orphans), 3, u"Wrong # {}".format(orphans))
+ self.assertEqual(len(orphans), 3, f"Wrong # {orphans}")
location = course.location.replace(category='chapter', name='OrphanChapter')
- self.assertIn(six.text_type(location), orphans)
+ self.assertIn(str(location), orphans)
location = course.location.replace(category='vertical', name='OrphanVert')
- self.assertIn(six.text_type(location), orphans)
+ self.assertIn(str(location), orphans)
location = course.location.replace(category='html', name='OrphanHtml')
- self.assertIn(six.text_type(location), orphans)
+ self.assertIn(str(location), orphans)
@ddt.data(
(ModuleStoreEnum.Type.split, 9, 5),
@@ -121,7 +120,7 @@ class TestOrphan(TestOrphanBase):
orphans = json.loads(
self.client.get(orphan_url, HTTP_ACCEPT='application/json').content.decode('utf-8')
)
- self.assertEqual(len(orphans), 0, u"Orphans not deleted {}".format(orphans))
+ self.assertEqual(len(orphans), 0, f"Orphans not deleted {orphans}")
# make sure that any children with one orphan parent and one non-orphan
# parent are not deleted
@@ -174,8 +173,8 @@ class TestOrphan(TestOrphanBase):
# HTML component has `vertical1` as its parent.
html_parent = self.store.get_parent_location(multi_parent_html.location)
- self.assertNotEqual(six.text_type(html_parent), six.text_type(orphan_vertical.location))
- self.assertEqual(six.text_type(html_parent), six.text_type(vertical1.location))
+ self.assertNotEqual(str(html_parent), str(orphan_vertical.location))
+ self.assertEqual(str(html_parent), str(vertical1.location))
# Get path of the `multi_parent_html` & verify path_to_location returns a expected path
path = path_to_location(self.store, multi_parent_html.location)
@@ -227,7 +226,7 @@ class TestOrphan(TestOrphanBase):
# Verify chapter1 is parent of vertical1.
vertical1_parent = self.store.get_parent_location(vertical1.location)
- self.assertEqual(six.text_type(vertical1_parent), six.text_type(chapter1.location))
+ self.assertEqual(str(vertical1_parent), str(chapter1.location))
# Make `Vertical1` the parent of `HTML0`. So `HTML0` will have to parents (`Vertical0` & `Vertical1`)
vertical1.children.append(html.location)
@@ -236,7 +235,7 @@ class TestOrphan(TestOrphanBase):
# Get parent location & verify its either of the two verticals. As both parents are non-orphan,
# alphabetically least is returned
html_parent = self.store.get_parent_location(html.location)
- self.assertEqual(six.text_type(html_parent), six.text_type(vertical1.location))
+ self.assertEqual(str(html_parent), str(vertical1.location))
# verify path_to_location returns a expected path
path = path_to_location(self.store, html.location)
diff --git a/cms/djangoapps/contentstore/tests/test_outlines.py b/cms/djangoapps/contentstore/tests/test_outlines.py
index 4ad80c5347..12f495cc1e 100644
--- a/cms/djangoapps/contentstore/tests/test_outlines.py
+++ b/cms/djangoapps/contentstore/tests/test_outlines.py
@@ -6,12 +6,8 @@ from datetime import datetime, timezone
from opaque_keys.edx.keys import CourseKey
-from openedx.core.djangoapps.content.learning_sequences.data import (
- CourseOutlineData,
- ExamData,
- VisibilityData,
-)
from openedx.core.djangoapps.content.learning_sequences.api import get_course_outline
+from openedx.core.djangoapps.content.learning_sequences.data import CourseOutlineData, ExamData, VisibilityData
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
diff --git a/cms/djangoapps/contentstore/tests/test_permissions.py b/cms/djangoapps/contentstore/tests/test_permissions.py
index 4a5e005c9a..98d8fa074a 100644
--- a/cms/djangoapps/contentstore/tests/test_permissions.py
+++ b/cms/djangoapps/contentstore/tests/test_permissions.py
@@ -6,7 +6,6 @@ Test CRUD for authorization.
import copy
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
-from six.moves import range
from cms.djangoapps.contentstore.tests.utils import AjaxEnabledTestClient
from cms.djangoapps.contentstore.utils import reverse_course_url, reverse_url
@@ -25,7 +24,7 @@ class TestCourseAccess(ModuleStoreTestCase):
Create a pool of users w/o granting them any permissions
"""
- super(TestCourseAccess, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.client = AjaxEnabledTestClient()
self.client.login(username=self.user.username, password=self.user_password)
@@ -51,8 +50,8 @@ class TestCourseAccess(ModuleStoreTestCase):
"""
users = []
for i in range(8):
- username = "user{}".format(i)
- email = "test+user{}@edx.org".format(i)
+ username = f"user{i}"
+ email = f"test+user{i}@edx.org"
user = User.objects.create_user(username, email, 'foo')
user.is_active = True
user.save()
@@ -94,7 +93,7 @@ class TestCourseAccess(ModuleStoreTestCase):
user = users.pop()
group.add_users(user)
user_by_role[role].append(user)
- self.assertTrue(auth.has_course_author_access(user, self.course_key), "{} does not have access".format(user)) # lint-amnesty, pylint: disable=line-too-long
+ self.assertTrue(auth.has_course_author_access(user, self.course_key), f"{user} does not have access") # lint-amnesty, pylint: disable=line-too-long
course_team_url = reverse_course_url('course_team_handler', self.course_key)
response = self.client.get_html(course_team_url)
@@ -127,9 +126,9 @@ class TestCourseAccess(ModuleStoreTestCase):
if hasattr(user, '_roles'):
del user._roles
- self.assertTrue(auth.has_course_author_access(user, copy_course_key), u"{} no copy access".format(user))
+ self.assertTrue(auth.has_course_author_access(user, copy_course_key), f"{user} no copy access")
if (role is OrgStaffRole) or (role is OrgInstructorRole):
auth.remove_users(self.user, role(self.course_key.org), user)
else:
auth.remove_users(self.user, role(self.course_key), user)
- self.assertFalse(auth.has_course_author_access(user, self.course_key), u"{} remove didn't work".format(user)) # lint-amnesty, pylint: disable=line-too-long
+ self.assertFalse(auth.has_course_author_access(user, self.course_key), f"{user} remove didn't work") # lint-amnesty, pylint: disable=line-too-long
diff --git a/cms/djangoapps/contentstore/tests/test_proctoring.py b/cms/djangoapps/contentstore/tests/test_proctoring.py
index aedb929b08..76437f7b5c 100644
--- a/cms/djangoapps/contentstore/tests/test_proctoring.py
+++ b/cms/djangoapps/contentstore/tests/test_proctoring.py
@@ -4,12 +4,11 @@ Tests for the edx_proctoring integration into Studio
from datetime import datetime, timedelta
+from unittest.mock import patch
import ddt
-import six
from django.conf import settings
from edx_proctoring.api import get_all_exams_for_course, get_review_policy_by_exam_id
-from mock import patch
from pytz import UTC
from cms.djangoapps.contentstore.signals.handlers import listen_for_course_publish
@@ -28,7 +27,7 @@ class TestProctoredExams(ModuleStoreTestCase):
"""
Initial data setup
"""
- super(TestProctoredExams, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course = CourseFactory.create(
org='edX',
@@ -43,7 +42,7 @@ class TestProctoredExams(ModuleStoreTestCase):
Helper method to compare the sequence with the stored exam,
which should just be a single one
"""
- exams = get_all_exams_for_course(six.text_type(self.course.id))
+ exams = get_all_exams_for_course(str(self.course.id))
self.assertEqual(len(exams), 1)
@@ -58,8 +57,8 @@ class TestProctoredExams(ModuleStoreTestCase):
# the hide after due value only applies to timed exams
self.assertEqual(exam['hide_after_due'], sequence.hide_after_due)
- self.assertEqual(exam['course_id'], six.text_type(self.course.id))
- self.assertEqual(exam['content_id'], six.text_type(sequence.location))
+ self.assertEqual(exam['course_id'], str(self.course.id))
+ self.assertEqual(exam['content_id'], str(sequence.location))
self.assertEqual(exam['exam_name'], sequence.display_name)
self.assertEqual(exam['time_limit_mins'], sequence.default_time_limit_minutes)
self.assertEqual(exam['is_proctored'], sequence.is_proctored_exam)
@@ -166,7 +165,7 @@ class TestProctoredExams(ModuleStoreTestCase):
listen_for_course_publish(self, self.course.id)
- exams = get_all_exams_for_course(six.text_type(self.course.id))
+ exams = get_all_exams_for_course(str(self.course.id))
self.assertEqual(len(exams), 1)
sequence.is_time_limited = False
@@ -197,7 +196,7 @@ class TestProctoredExams(ModuleStoreTestCase):
listen_for_course_publish(self, self.course.id)
- exams = get_all_exams_for_course(six.text_type(self.course.id))
+ exams = get_all_exams_for_course(str(self.course.id))
self.assertEqual(len(exams), 1)
self.store.delete_item(chapter.location, self.user.id)
@@ -207,7 +206,7 @@ class TestProctoredExams(ModuleStoreTestCase):
# look through exam table, the dangling exam
# should be disabled
- exams = get_all_exams_for_course(six.text_type(self.course.id))
+ exams = get_all_exams_for_course(str(self.course.id))
self.assertEqual(len(exams), 1)
exam = exams[0]
@@ -232,7 +231,7 @@ class TestProctoredExams(ModuleStoreTestCase):
listen_for_course_publish(self, self.course.id)
- exams = get_all_exams_for_course(six.text_type(self.course.id))
+ exams = get_all_exams_for_course(str(self.course.id))
self.assertEqual(len(exams), 0)
@ddt.data(
@@ -271,7 +270,7 @@ class TestProctoredExams(ModuleStoreTestCase):
# there shouldn't be any exams because we haven't enabled that
# advanced setting flag
- exams = get_all_exams_for_course(six.text_type(self.course.id))
+ exams = get_all_exams_for_course(str(self.course.id))
self.assertEqual(len(exams), expected_count)
def test_self_paced_no_due_dates(self):
@@ -299,7 +298,7 @@ class TestProctoredExams(ModuleStoreTestCase):
is_onboarding_exam=False,
)
listen_for_course_publish(self, self.course.id)
- exams = get_all_exams_for_course(six.text_type(self.course.id))
+ exams = get_all_exams_for_course(str(self.course.id))
# self-paced courses should ignore due dates
assert exams[0]['due_date'] is None
@@ -308,5 +307,5 @@ class TestProctoredExams(ModuleStoreTestCase):
self.course.self_paced = False
self.course = self.update_course(self.course, 1)
listen_for_course_publish(self, self.course.id)
- exams = get_all_exams_for_course(six.text_type(self.course.id))
+ exams = get_all_exams_for_course(str(self.course.id))
assert exams[0]['due_date'] is not None
diff --git a/cms/djangoapps/contentstore/tests/test_request_event.py b/cms/djangoapps/contentstore/tests/test_request_event.py
index aa51ef3d50..c4d21f7249 100644
--- a/cms/djangoapps/contentstore/tests/test_request_event.py
+++ b/cms/djangoapps/contentstore/tests/test_request_event.py
@@ -3,7 +3,6 @@
from django.test import TestCase
from django.urls import reverse
-from six import unichr
from cms.djangoapps.contentstore.views.helpers import event as cms_user_track
@@ -20,7 +19,7 @@ class CMSLogTest(TestCase):
"""
requests = [
{"event": "my_event", "event_type": "my_event_type", "page": "my_page"},
- {"event": "{'json': 'object'}", "event_type": unichr(512), "page": "my_page"}
+ {"event": "{'json': 'object'}", "event_type": chr(512), "page": "my_page"}
]
for request_params in requests:
response = self.client.post(reverse(cms_user_track), request_params)
@@ -33,7 +32,7 @@ class CMSLogTest(TestCase):
"""
requests = [
{"event": "my_event", "event_type": "my_event_type", "page": "my_page"},
- {"event": "{'json': 'object'}", "event_type": unichr(512), "page": "my_page"}
+ {"event": "{'json': 'object'}", "event_type": chr(512), "page": "my_page"}
]
for request_params in requests:
response = self.client.get(reverse(cms_user_track), request_params)
diff --git a/cms/djangoapps/contentstore/tests/test_signals.py b/cms/djangoapps/contentstore/tests/test_signals.py
index ae81839a3f..c2ceda240e 100644
--- a/cms/djangoapps/contentstore/tests/test_signals.py
+++ b/cms/djangoapps/contentstore/tests/test_signals.py
@@ -1,9 +1,9 @@
"""Tests for verifying availability of resources for locking"""
+from unittest.mock import Mock, patch
+
import ddt
-import six
-from mock import Mock, patch
from cms.djangoapps.contentstore.signals.handlers import GRADING_POLICY_COUNTDOWN_SECONDS, handle_grading_policy_changed
from common.djangoapps.student.models import CourseEnrollment
@@ -17,7 +17,7 @@ class LockedTest(ModuleStoreTestCase):
"""Test class to verify locking of mocked resources"""
def setUp(self):
- super(LockedTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course = CourseFactory.create(
org='edx',
name='course',
@@ -33,9 +33,9 @@ class LockedTest(ModuleStoreTestCase):
add_mock.return_value = lock_available
sender = Mock()
- handle_grading_policy_changed(sender, course_key=six.text_type(self.course.id))
+ handle_grading_policy_changed(sender, course_key=str(self.course.id))
- cache_key = 'handle_grading_policy_changed-{}'.format(six.text_type(self.course.id))
+ cache_key = 'handle_grading_policy_changed-{}'.format(str(self.course.id))
self.assertEqual(lock_available, compute_grades_async_mock.called)
if lock_available:
add_mock.assert_called_once_with(cache_key, "true", GRADING_POLICY_COUNTDOWN_SECONDS)
diff --git a/cms/djangoapps/contentstore/tests/test_tasks.py b/cms/djangoapps/contentstore/tests/test_tasks.py
index 8d927a0bad..cb4d604e69 100644
--- a/cms/djangoapps/contentstore/tests/test_tasks.py
+++ b/cms/djangoapps/contentstore/tests/test_tasks.py
@@ -5,9 +5,9 @@ Unit tests for course import and export Celery tasks
import copy
import json
+from unittest import mock
from uuid import uuid4
-import mock
from django.conf import settings
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.test.utils import override_settings
@@ -45,7 +45,7 @@ class ExportCourseTestCase(CourseTestCase):
Verify that a routine course export task succeeds
"""
key = str(self.course.location.course_key)
- result = export_olx.delay(self.user.id, key, u'en')
+ result = export_olx.delay(self.user.id, key, 'en')
status = UserTaskStatus.objects.get(task_id=result.id)
self.assertEqual(status.state, UserTaskStatus.SUCCEEDED)
artifacts = UserTaskArtifact.objects.filter(status=status)
@@ -59,17 +59,17 @@ class ExportCourseTestCase(CourseTestCase):
The export task should fail gracefully if an exception is thrown
"""
key = str(self.course.location.course_key)
- result = export_olx.delay(self.user.id, key, u'en')
- self._assert_failed(result, json.dumps({u'raw_error_msg': u'Boom!'}))
+ result = export_olx.delay(self.user.id, key, 'en')
+ self._assert_failed(result, json.dumps({'raw_error_msg': 'Boom!'}))
def test_invalid_user_id(self):
"""
Verify that attempts to export a course as an invalid user fail
"""
- user_id = User.objects.order_by(u'-id').first().pk + 100
+ user_id = User.objects.order_by('-id').first().pk + 100
key = str(self.course.location.course_key)
- result = export_olx.delay(user_id, key, u'en')
- self._assert_failed(result, u'Unknown User ID: {}'.format(user_id))
+ result = export_olx.delay(user_id, key, 'en')
+ self._assert_failed(result, f'Unknown User ID: {user_id}')
def test_non_course_author(self):
"""
@@ -77,8 +77,8 @@ class ExportCourseTestCase(CourseTestCase):
"""
_, nonstaff_user = self.create_non_staff_authed_user_client()
key = str(self.course.location.course_key)
- result = export_olx.delay(nonstaff_user.id, key, u'en')
- self._assert_failed(result, u'Permission denied')
+ result = export_olx.delay(nonstaff_user.id, key, 'en')
+ self._assert_failed(result, 'Permission denied')
def _assert_failed(self, task_result, error_message):
"""
@@ -89,7 +89,7 @@ class ExportCourseTestCase(CourseTestCase):
artifacts = UserTaskArtifact.objects.filter(status=status)
self.assertEqual(len(artifacts), 1)
error = artifacts[0]
- self.assertEqual(error.name, u'Error')
+ self.assertEqual(error.name, 'Error')
self.assertEqual(error.text, error_message)
@@ -104,7 +104,7 @@ class ExportLibraryTestCase(LibraryTestCase):
Verify that a routine library export task succeeds
"""
key = str(self.lib_key)
- result = export_olx.delay(self.user.id, key, u'en')
+ result = export_olx.delay(self.user.id, key, 'en')
status = UserTaskStatus.objects.get(task_id=result.id)
self.assertEqual(status.state, UserTaskStatus.SUCCEEDED)
artifacts = UserTaskArtifact.objects.filter(status=status)
diff --git a/cms/djangoapps/contentstore/tests/test_transcripts_utils.py b/cms/djangoapps/contentstore/tests/test_transcripts_utils.py
index b21cc74e24..799cdd5b55 100644
--- a/cms/djangoapps/contentstore/tests/test_transcripts_utils.py
+++ b/cms/djangoapps/contentstore/tests/test_transcripts_utils.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
""" Tests for transcripts_utils. """
@@ -7,6 +6,7 @@ import json
import tempfile
import textwrap
import unittest
+from unittest.mock import Mock, patch
from uuid import uuid4
import ddt
@@ -14,8 +14,6 @@ import pytest
from django.conf import settings
from django.test.utils import override_settings
from django.utils import translation
-from mock import Mock, patch
-from six import text_type
from cms.djangoapps.contentstore.tests.utils import mock_requests_get
from common.djangoapps.student.tests.factories import UserFactory
@@ -33,7 +31,7 @@ TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().
class TestGenerateSubs(unittest.TestCase):
"""Tests for `generate_subs` function."""
def setUp(self):
- super(TestGenerateSubs, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.source_subs = {
'start': [100, 200, 240, 390, 1000],
@@ -104,11 +102,11 @@ class TestSaveSubsToStore(SharedModuleStoreTestCase):
"""
A helper to compute a static file location from a subtitle id.
"""
- return StaticContent.compute_location(cls.course.id, u'subs_{0}.srt.sjson'.format(sub_id))
+ return StaticContent.compute_location(cls.course.id, f'subs_{sub_id}.srt.sjson')
@classmethod
def setUpClass(cls):
- super(TestSaveSubsToStore, cls).setUpClass()
+ super().setUpClass()
cls.course = CourseFactory.create(
org=cls.org, number=cls.number, display_name=cls.display_name)
@@ -125,8 +123,8 @@ class TestSaveSubsToStore(SharedModuleStoreTestCase):
}
# Prefix it to ensure that unicode filenames are allowed
- cls.subs_id = u'uniçøde_{}'.format(uuid4())
- cls.subs_copied_id = u'cøpy_{}'.format(uuid4())
+ cls.subs_id = f'uniçøde_{uuid4()}'
+ cls.subs_copied_id = f'cøpy_{uuid4()}'
cls.content_location = cls.sub_id_to_location(cls.subs_id)
cls.content_copied_location = cls.sub_id_to_location(cls.subs_copied_id)
@@ -138,7 +136,7 @@ class TestSaveSubsToStore(SharedModuleStoreTestCase):
cls.content_location_unjsonable = cls.sub_id_to_location(cls.unjsonable_subs_id)
def setUp(self):
- super(TestSaveSubsToStore, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.addCleanup(self.clear_subs_content)
self.clear_subs_content()
@@ -186,7 +184,7 @@ class TestYoutubeSubsBase(SharedModuleStoreTestCase):
"""
@classmethod
def setUpClass(cls):
- super(TestYoutubeSubsBase, cls).setUpClass()
+ super().setUpClass()
cls.course = CourseFactory.create(
org=cls.org, number=cls.number, display_name=cls.display_name) # lint-amnesty, pylint: disable=no-member
@@ -205,7 +203,7 @@ class TestDownloadYoutubeSubs(TestYoutubeSubsBase):
"""
Remove, if subtitle content exists.
"""
- filename = 'subs_{0}.srt.sjson'.format(subs_id)
+ filename = f'subs_{subs_id}.srt.sjson'
content_location = StaticContent.compute_location(self.course.id, filename)
try:
content = contentstore().find(content_location)
@@ -281,7 +279,7 @@ class TestDownloadYoutubeSubs(TestYoutubeSubsBase):
# Check assets status after importing subtitles.
for subs_id in good_youtube_subs.values(): # lint-amnesty, pylint: disable=undefined-variable
- filename = 'subs_{0}.srt.sjson'.format(subs_id)
+ filename = f'subs_{subs_id}.srt.sjson'
content_location = StaticContent.compute_location(
self.course.id, filename
)
@@ -381,7 +379,7 @@ class TestGenerateSubsFromSource(TestDownloadYoutubeSubs): # lint-amnesty, pyli
# Check assets status after importing subtitles.
for subs_id in youtube_subs.values():
- filename = 'subs_{0}.srt.sjson'.format(subs_id)
+ filename = f'subs_{subs_id}.srt.sjson'
content_location = StaticContent.compute_location(
self.course.id, filename
)
@@ -408,7 +406,7 @@ class TestGenerateSubsFromSource(TestDownloadYoutubeSubs): # lint-amnesty, pyli
with self.assertRaises(transcripts_utils.TranscriptsGenerationException) as cm:
transcripts_utils.generate_subs_from_source(youtube_subs, 'BAD_FORMAT', srt_filedata, self.course)
- exception_message = text_type(cm.exception)
+ exception_message = str(cm.exception)
self.assertEqual(exception_message, "We support only SubRip (*.srt) transcripts format.")
def test_fail_bad_subs_filedata(self):
@@ -422,7 +420,7 @@ class TestGenerateSubsFromSource(TestDownloadYoutubeSubs): # lint-amnesty, pyli
with self.assertRaises(transcripts_utils.TranscriptsGenerationException) as cm:
transcripts_utils.generate_subs_from_source(youtube_subs, 'srt', srt_filedata, self.course)
- exception_message = text_type(cm.exception)
+ exception_message = str(cm.exception)
self.assertEqual(exception_message, "Something wrong with SubRip transcripts file during parsing.")
@@ -561,7 +559,7 @@ class TestTranscript(unittest.TestCase):
Tests for Transcript class e.g. different transcript conversions.
"""
def setUp(self):
- super(TestTranscript, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.srt_transcript = textwrap.dedent("""\
0
@@ -591,7 +589,7 @@ class TestTranscript(unittest.TestCase):
}
""")
- self.txt_transcript = u"Elephant's Dream\nAt the left we can see..."
+ self.txt_transcript = "Elephant's Dream\nAt the left we can see..."
def test_convert_srt_to_txt(self):
"""
@@ -659,10 +657,10 @@ class TestSubsFilename(unittest.TestCase):
"""
def test_unicode(self):
- name = transcripts_utils.subs_filename(u"˙∆©ƒƒƒ")
- self.assertEqual(name, u'subs_˙∆©ƒƒƒ.srt.sjson')
- name = transcripts_utils.subs_filename(u"˙∆©ƒƒƒ", 'uk')
- self.assertEqual(name, u'uk_subs_˙∆©ƒƒƒ.srt.sjson')
+ name = transcripts_utils.subs_filename("˙∆©ƒƒƒ")
+ self.assertEqual(name, 'subs_˙∆©ƒƒƒ.srt.sjson')
+ name = transcripts_utils.subs_filename("˙∆©ƒƒƒ", 'uk')
+ self.assertEqual(name, 'uk_subs_˙∆©ƒƒƒ.srt.sjson')
@ddt.ddt
@@ -710,7 +708,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
"""Tests for `get_transcript` function."""
def setUp(self):
- super(TestGetTranscript, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course = CourseFactory.create()
@@ -731,8 +729,8 @@ class TestGetTranscript(SharedModuleStoreTestCase):
self.subs_srt = transcripts_utils.Transcript.convert(json.dumps(self.subs_sjson), 'sjson', 'srt')
self.subs = {
- u'en': self.subs_srt,
- u'ur': transcripts_utils.Transcript.convert(json.dumps(self.subs_sjson), 'sjson', 'srt'),
+ 'en': self.subs_srt,
+ 'ur': transcripts_utils.Transcript.convert(json.dumps(self.subs_sjson), 'sjson', 'srt'),
}
self.srt_mime_type = transcripts_utils.Transcript.mime_types[transcripts_utils.Transcript.SRT]
@@ -743,15 +741,15 @@ class TestGetTranscript(SharedModuleStoreTestCase):
self.video = ItemFactory.create(
category='video',
parent_location=self.vertical.location,
- edx_video_id=u'1234-5678-90'
+ edx_video_id='1234-5678-90'
)
- def create_transcript(self, subs_id, language=u'en', filename='video.srt', youtube_id_1_0='', html5_sources=None):
+ def create_transcript(self, subs_id, language='en', filename='video.srt', youtube_id_1_0='', html5_sources=None):
"""
create transcript.
"""
transcripts = {}
- if language != u'en':
+ if language != 'en':
transcripts = {language: filename}
html5_sources = html5_sources or []
@@ -761,7 +759,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
sub=subs_id,
youtube_id_1_0=youtube_id_1_0,
transcripts=transcripts,
- edx_video_id=u'1234-5678-90',
+ edx_video_id='1234-5678-90',
html5_sources=html5_sources
)
@@ -803,9 +801,9 @@ class TestGetTranscript(SharedModuleStoreTestCase):
@ddt.data(
# en lang does not exist so NotFoundError will be raised
- (u'en',),
+ ('en',),
# ur lang does not exist so KeyError and then NotFoundError will be raised
- (u'ur',),
+ ('ur',),
)
@ddt.unpack
def test_get_transcript_not_found(self, lang):
@@ -821,7 +819,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
@ddt.data(
# video.sub transcript
{
- 'language': u'en',
+ 'language': 'en',
'subs_id': 'video_101',
'youtube_id_1_0': '',
'html5_sources': [],
@@ -829,7 +827,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
},
# if video.sub is present, rest will be skipped.
{
- 'language': u'en',
+ 'language': 'en',
'subs_id': 'video_101',
'youtube_id_1_0': 'test_yt_id',
'html5_sources': ['www.abc.com/foo.mp4'],
@@ -837,7 +835,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
},
# video.youtube_id_1_0 transcript
{
- 'language': u'en',
+ 'language': 'en',
'subs_id': '',
'youtube_id_1_0': 'test_yt_id',
'html5_sources': [],
@@ -845,7 +843,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
},
# video.html5_sources transcript
{
- 'language': u'en',
+ 'language': 'en',
'subs_id': '',
'youtube_id_1_0': '',
'html5_sources': ['www.abc.com/foo.mp4'],
@@ -853,7 +851,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
},
# non-english transcript
{
- 'language': u'ur',
+ 'language': 'ur',
'subs_id': '',
'youtube_id_1_0': '',
'html5_sources': [],
@@ -888,7 +886,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
"""
Verify that `get_transcript` function returns correct data for non-english when transcript is in content store.
"""
- language = u'ur'
+ language = 'ur'
self.create_transcript(self.subs_id, language)
content, filename, mimetype = transcripts_utils.get_transcript(
self.video,
@@ -928,7 +926,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
output_format='mpeg'
)
- exception_message = text_type(invalid_format_exception.exception)
+ exception_message = str(invalid_format_exception.exception)
self.assertEqual(exception_message, 'Invalid transcript format `mpeg`')
def test_get_transcript_no_content(self):
@@ -944,7 +942,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
'ur'
)
- exception_message = text_type(no_content_exception.exception)
+ exception_message = str(no_content_exception.exception)
self.assertEqual(exception_message, 'No transcript content')
def test_get_transcript_no_en_transcript(self):
@@ -959,7 +957,7 @@ class TestGetTranscript(SharedModuleStoreTestCase):
'en'
)
- exception_message = text_type(no_en_transcript_exception.exception)
+ exception_message = str(no_en_transcript_exception.exception)
self.assertEqual(exception_message, 'No transcript for `en` language')
@ddt.data(
diff --git a/cms/djangoapps/contentstore/tests/test_users_default_role.py b/cms/djangoapps/contentstore/tests/test_users_default_role.py
index eb92b9c308..2bd93d94a4 100644
--- a/cms/djangoapps/contentstore/tests/test_users_default_role.py
+++ b/cms/djangoapps/contentstore/tests/test_users_default_role.py
@@ -6,8 +6,8 @@ after deleting it creates same course again
from cms.djangoapps.contentstore.tests.utils import AjaxEnabledTestClient
from cms.djangoapps.contentstore.utils import delete_course, reverse_url
-from lms.djangoapps.courseware.tests.factories import UserFactory
from common.djangoapps.student.models import CourseEnrollment
+from lms.djangoapps.courseware.tests.factories import UserFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
@@ -19,7 +19,7 @@ class TestUsersDefaultRole(ModuleStoreTestCase):
"""
Add a user and a course
"""
- super(TestUsersDefaultRole, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
# create and log in a staff user.
self.user = UserFactory(is_staff=True)
self.client = AjaxEnabledTestClient()
@@ -49,7 +49,7 @@ class TestUsersDefaultRole(ModuleStoreTestCase):
Reverse the setup
"""
self.client.logout()
- super(TestUsersDefaultRole, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments
+ super().tearDown()
def test_user_forum_default_role_on_course_deletion(self):
"""
diff --git a/cms/djangoapps/contentstore/tests/test_utils.py b/cms/djangoapps/contentstore/tests/test_utils.py
index 642a379b06..97e6fd492d 100644
--- a/cms/djangoapps/contentstore/tests/test_utils.py
+++ b/cms/djangoapps/contentstore/tests/test_utils.py
@@ -4,7 +4,6 @@
import collections
from datetime import datetime, timedelta
-import six
from django.test import TestCase
from opaque_keys.edx.locator import CourseLocator
from pytz import UTC
@@ -83,7 +82,7 @@ class ExtraPanelTabTestCase(TestCase):
if tabs is None:
tabs = []
course = collections.namedtuple('MockCourse', ['tabs'])
- if isinstance(tabs, six.string_types):
+ if isinstance(tabs, str):
course.tabs = self.get_tab_type_dicts(tabs)
else:
course.tabs = tabs
@@ -95,7 +94,7 @@ class XBlockVisibilityTestCase(SharedModuleStoreTestCase):
@classmethod
def setUpClass(cls):
- super(XBlockVisibilityTestCase, cls).setUpClass()
+ super().setUpClass()
cls.dummy_user = ModuleStoreEnum.UserID.test
cls.past = datetime(1970, 1, 1, tzinfo=UTC)
@@ -168,7 +167,7 @@ class ReleaseDateSourceTest(CourseTestCase):
"""Tests for finding the source of an xblock's release date."""
def setUp(self):
- super(ReleaseDateSourceTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.chapter = ItemFactory.create(category='chapter', parent_location=self.course.location)
self.sequential = ItemFactory.create(category='sequential', parent_location=self.chapter.location)
@@ -222,7 +221,7 @@ class StaffLockTest(CourseTestCase):
"""Base class for testing staff lock functions."""
def setUp(self):
- super(StaffLockTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.chapter = ItemFactory.create(category='chapter', parent_location=self.course.location)
self.sequential = ItemFactory.create(category='sequential', parent_location=self.chapter.location)
@@ -332,7 +331,7 @@ class GroupVisibilityTest(CourseTestCase):
"""
def setUp(self):
- super(GroupVisibilityTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
chapter = ItemFactory.create(category='chapter', parent_location=self.course.location)
sequential = ItemFactory.create(category='sequential', parent_location=chapter.location)
@@ -432,7 +431,7 @@ class GetUserPartitionInfoTest(ModuleStoreTestCase):
def setUp(self):
"""Create a dummy course. """
- super(GetUserPartitionInfoTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course = CourseFactory()
self.block = ItemFactory.create(category="problem", parent_location=self.course.location)
@@ -465,18 +464,18 @@ class GetUserPartitionInfoTest(ModuleStoreTestCase):
expected = [
{
"id": 0,
- "name": u"Cohort user partition",
- "scheme": u"cohort",
+ "name": "Cohort user partition",
+ "scheme": "cohort",
"groups": [
{
"id": 0,
- "name": u"Group A",
+ "name": "Group A",
"selected": False,
"deleted": False,
},
{
"id": 1,
- "name": u"Group B",
+ "name": "Group B",
"selected": False,
"deleted": False,
},
@@ -484,12 +483,12 @@ class GetUserPartitionInfoTest(ModuleStoreTestCase):
},
{
"id": 1,
- "name": u"Random user partition",
- "scheme": u"random",
+ "name": "Random user partition",
+ "scheme": "random",
"groups": [
{
"id": 0,
- "name": u"Group C",
+ "name": "Group C",
"selected": False,
"deleted": False,
},
diff --git a/cms/djangoapps/contentstore/tests/test_video_utils.py b/cms/djangoapps/contentstore/tests/test_video_utils.py
index 71e9643fad..f8f54c0702 100644
--- a/cms/djangoapps/contentstore/tests/test_video_utils.py
+++ b/cms/djangoapps/contentstore/tests/test_video_utils.py
@@ -1,4 +1,3 @@
-#-*- coding: utf-8 -*-
"""
Unit tests for video utils.
"""
@@ -6,16 +5,15 @@ Unit tests for video utils.
from datetime import datetime
from unittest import TestCase
+from unittest.mock import patch
import ddt
import pytz
import requests
-import six
from django.conf import settings
from django.core.files.uploadedfile import UploadedFile
from django.test.utils import override_settings
from edxval.api import create_profile, create_video, get_course_video_image_url, update_video_image
-from mock import patch
from cms.djangoapps.contentstore.tests.utils import CourseTestCase
from cms.djangoapps.contentstore.video_utils import (
@@ -59,8 +57,8 @@ class ScrapeVideoThumbnailsTestCase(CourseTestCase):
"""
def setUp(self):
- super(ScrapeVideoThumbnailsTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
- course_ids = [six.text_type(self.course.id)]
+ super().setUp()
+ course_ids = [str(self.course.id)]
profiles = ['youtube']
created = datetime.now(pytz.utc)
previous_uploads = [
@@ -116,7 +114,7 @@ class ScrapeVideoThumbnailsTestCase(CourseTestCase):
# Create video images.
with make_image_file() as image_file:
update_video_image(
- 'test-youtube-video-2', six.text_type(self.course.id), image_file, 'image.jpg'
+ 'test-youtube-video-2', str(self.course.id), image_file, 'image.jpg'
)
def mocked_youtube_thumbnail_response(
@@ -232,7 +230,7 @@ class ScrapeVideoThumbnailsTestCase(CourseTestCase):
"""
Test that youtube thumbnails are correctly scrapped.
"""
- course_id = six.text_type(self.course.id)
+ course_id = str(self.course.id)
video1_edx_video_id = 'test-youtube-video-1'
video2_edx_video_id = 'test-youtube-video-2'
@@ -286,7 +284,7 @@ class ScrapeVideoThumbnailsTestCase(CourseTestCase):
"""
Test that we get correct logs in case of failure as well as success.
"""
- course_id = six.text_type(self.course.id)
+ course_id = str(self.course.id)
video1_edx_video_id = 'test-youtube-video-1'
mocked_request.side_effect = [
self.mocked_youtube_thumbnail_response(
@@ -297,13 +295,13 @@ class ScrapeVideoThumbnailsTestCase(CourseTestCase):
scrape_youtube_thumbnail(course_id, video1_edx_video_id, 'test-yt-id')
if is_success:
mock_logger.info.assert_called_with(
- u'VIDEOS: Scraping youtube video thumbnail for edx_video_id [%s] in course [%s]',
+ 'VIDEOS: Scraping youtube video thumbnail for edx_video_id [%s] in course [%s]',
video1_edx_video_id,
course_id
)
else:
mock_logger.info.assert_called_with(
- u'VIDEOS: Scraping youtube video thumbnail failed for edx_video_id [%s] in course [%s] with error: %s',
+ 'VIDEOS: Scraping youtube video thumbnail failed for edx_video_id [%s] in course [%s] with error: %s',
video1_edx_video_id,
course_id,
'This image file must be larger than 2 KB.'
@@ -313,21 +311,21 @@ class ScrapeVideoThumbnailsTestCase(CourseTestCase):
(
None,
'image/jpeg',
- u'This image file must be larger than {image_min_size}.'.format(
+ 'This image file must be larger than {image_min_size}.'.format(
image_min_size=settings.VIDEO_IMAGE_MIN_FILE_SIZE_KB
)
),
(
b'dummy-content',
None,
- u'This image file type is not supported. Supported file types are {supported_file_formats}.'.format(
+ 'This image file type is not supported. Supported file types are {supported_file_formats}.'.format(
supported_file_formats=list(settings.VIDEO_IMAGE_SUPPORTED_FILE_FORMATS.keys())
)
),
(
None,
None,
- u'This image file type is not supported. Supported file types are {supported_file_formats}.'.format(
+ 'This image file type is not supported. Supported file types are {supported_file_formats}.'.format(
supported_file_formats=list(settings.VIDEO_IMAGE_SUPPORTED_FILE_FORMATS.keys())
)
),
@@ -347,7 +345,7 @@ class ScrapeVideoThumbnailsTestCase(CourseTestCase):
Test that when no thumbnail is downloaded, video image is not updated.
"""
mock_download_youtube_thumbnail.return_value = image_content, image_content_type
- course_id = six.text_type(self.course.id)
+ course_id = str(self.course.id)
video1_edx_video_id = 'test-youtube-video-1'
# Verify that video1 has no image attached.
@@ -358,7 +356,7 @@ class ScrapeVideoThumbnailsTestCase(CourseTestCase):
scrape_youtube_thumbnail(course_id, video1_edx_video_id, 'test-yt-id')
mock_logger.info.assert_called_with(
- u'VIDEOS: Scraping youtube video thumbnail failed for edx_video_id [%s] in course [%s] with error: %s',
+ 'VIDEOS: Scraping youtube video thumbnail failed for edx_video_id [%s] in course [%s] with error: %s',
video1_edx_video_id,
course_id,
error_message
diff --git a/cms/djangoapps/contentstore/tests/tests.py b/cms/djangoapps/contentstore/tests/tests.py
index 19837e7136..8424e144b4 100644
--- a/cms/djangoapps/contentstore/tests/tests.py
+++ b/cms/djangoapps/contentstore/tests/tests.py
@@ -5,8 +5,8 @@ This test file will test registration, login, activation, and session activity t
import datetime
import time
+from unittest import mock
-import mock
from ddt import data, ddt, unpack
from django.conf import settings
from django.core.cache import cache
@@ -91,7 +91,7 @@ class AuthTestCase(ContentStoreTestCase):
ENABLED_CACHES = ['default', 'mongo_metadata_inheritance', 'loc_cache']
def setUp(self):
- super(AuthTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.email = 'a@b.com'
self.pw = 'xyz'
@@ -127,7 +127,7 @@ class AuthTestCase(ContentStoreTestCase):
# Not logged in. Should redirect to login.
print('Not logged in')
for page in auth_pages:
- print(u"Checking '{0}'".format(page))
+ print(f"Checking '{page}'")
self.check_page_get(page, expected=302)
# Logged in should work.
@@ -135,7 +135,7 @@ class AuthTestCase(ContentStoreTestCase):
print('Logged in')
for page in simple_auth_pages:
- print(u"Checking '{0}'".format(page))
+ print(f"Checking '{page}'")
self.check_page_get(page, expected=200)
@override_settings(SESSION_INACTIVITY_TIMEOUT_IN_SECONDS=1)
@@ -176,7 +176,7 @@ class AuthTestCase(ContentStoreTestCase):
assertion_method = getattr(self, assertion_method_name)
assertion_method(
response,
- u'Sign Up'.format
+ 'Sign Up'.format
(settings.LMS_ROOT_URL)
)
self.assertContains(
@@ -191,7 +191,7 @@ class ForumTestCase(CourseTestCase):
def setUp(self):
""" Creates the test course. """
- super(ForumTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course = CourseFactory.create(org='testX', number='727', display_name='Forum Course')
def set_blackout_dates(self, blackout_dates):
@@ -242,7 +242,7 @@ class CourseKeyVerificationTestCase(CourseTestCase):
"""
Create test course.
"""
- super(CourseKeyVerificationTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.course = CourseFactory.create(org='edX', number='test_course_key', display_name='Test Course')
@data(('edX/test_course_key/Test_Course', 200), ('garbage:edX+test_course_key+Test_Course', 404))
@@ -251,7 +251,7 @@ class CourseKeyVerificationTestCase(CourseTestCase):
"""
Tests for the ensure_valid_course_key decorator.
"""
- url = '/import/{course_key}'.format(course_key=course_key)
+ url = f'/import/{course_key}'
resp = self.client.get_html(url)
self.assertEqual(resp.status_code, status_code)
diff --git a/cms/djangoapps/contentstore/tests/utils.py b/cms/djangoapps/contentstore/tests/utils.py
index f739e6bf86..7389a5a7e1 100644
--- a/cms/djangoapps/contentstore/tests/utils.py
+++ b/cms/djangoapps/contentstore/tests/utils.py
@@ -5,12 +5,11 @@ Utilities for contentstore tests
import json
import textwrap
+from unittest.mock import Mock
-import six
from django.conf import settings
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.test.client import Client
-from mock import Mock
from opaque_keys.edx.keys import AssetKey, CourseKey
from cms.djangoapps.contentstore.utils import reverse_url
@@ -51,7 +50,7 @@ class AjaxEnabledTestClient(Client):
Convenience method for client post which serializes the data into json and sets the accept type
to json
"""
- if not isinstance(data, six.string_types):
+ if not isinstance(data, str):
data = json.dumps(data or {})
kwargs.setdefault("HTTP_X_REQUESTED_WITH", "XMLHttpRequest")
kwargs.setdefault("HTTP_ACCEPT", "application/json")
@@ -84,7 +83,7 @@ class CourseTestCase(ProceduralCourseTestMixin, ModuleStoreTestCase):
afterwards.
"""
- super(CourseTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
+ super().setUp()
self.client = AjaxEnabledTestClient()
self.client.login(username=self.user.username, password=self.user_password)
@@ -195,7 +194,7 @@ class CourseTestCase(ProceduralCourseTestMixin, ModuleStoreTestCase):
html_module = self.store.get_item(course_id.make_usage_key('html', 'nonportable'))
new_data = html_module.data = html_module.data.replace(
'/static/',
- '/c4x/{0}/{1}/asset/'.format(course_id.org, course_id.course)
+ f'/c4x/{course_id.org}/{course_id.course}/asset/'
)
self.store.update_item(html_module, self.user.id)
@@ -285,10 +284,10 @@ class CourseTestCase(ProceduralCourseTestMixin, ModuleStoreTestCase):
course2_items = self.store.get_items(course2_id)
self.assertGreater(len(course1_items), 0) # ensure it found content instead of [] == []
if len(course1_items) != len(course2_items):
- course1_block_ids = set([item.location.block_id for item in course1_items]) # lint-amnesty, pylint: disable=consider-using-set-comprehension
- course2_block_ids = set([item.location.block_id for item in course2_items]) # lint-amnesty, pylint: disable=consider-using-set-comprehension
+ course1_block_ids = {item.location.block_id for item in course1_items}
+ course2_block_ids = {item.location.block_id for item in course2_items}
raise AssertionError(
- u"Course1 extra blocks: {}; course2 extra blocks: {}".format(
+ "Course1 extra blocks: {}; course2 extra blocks: {}".format(
course1_block_ids - course2_block_ids, course2_block_ids - course1_block_ids
)
)
@@ -357,7 +356,7 @@ class CourseTestCase(ProceduralCourseTestMixin, ModuleStoreTestCase):
course1_asset_attrs = content_store.get_attrs(course1_id.make_asset_key(category, filename))
course2_asset_attrs = content_store.get_attrs(course2_id.make_asset_key(category, filename))
self.assertEqual(len(course1_asset_attrs), len(course2_asset_attrs))
- for key, value in six.iteritems(course1_asset_attrs):
+ for key, value in course1_asset_attrs.items():
if key in ['_id', 'filename', 'uploadDate', 'content_son', 'thumbnail_location']:
pass
else: