From 82406e970a3caf2932b16ff88829dc3f134616c8 Mon Sep 17 00:00:00 2001 From: Usama Sadiq Date: Fri, 12 Mar 2021 14:43:44 +0500 Subject: [PATCH] reafctor: ran pyupgrade on lms/djangoapps/courseware (#26739) --- lms/djangoapps/courseware/tests/factories.py | 12 +- lms/djangoapps/courseware/tests/helpers.py | 23 +- lms/djangoapps/courseware/tests/test_about.py | 82 +++-- .../courseware/tests/test_access.py | 26 +- .../tests/test_comprehensive_theming.py | 2 +- .../tests/test_context_processor.py | 4 +- .../courseware/tests/test_course_info.py | 53 ++- .../courseware/tests/test_course_survey.py | 38 +- .../courseware/tests/test_course_tools.py | 10 +- .../courseware/tests/test_courses.py | 52 ++- .../tests/test_credit_requirements.py | 19 +- .../courseware/tests/test_date_summary.py | 72 ++-- .../tests/test_discussion_xblock.py | 30 +- .../courseware/tests/test_entrance_exam.py | 103 +++--- .../courseware/tests/test_field_overrides.py | 6 +- .../courseware/tests/test_footer.py | 3 +- .../courseware/tests/test_group_access.py | 6 +- lms/djangoapps/courseware/tests/test_i18n.py | 9 +- .../courseware/tests/test_lti_integration.py | 83 +++-- .../courseware/tests/test_masquerade.py | 42 ++- .../courseware/tests/test_middleware.py | 2 +- .../courseware/tests/test_model_data.py | 14 +- .../courseware/tests/test_module_render.py | 204 ++++++----- .../courseware/tests/test_navigation.py | 32 +- lms/djangoapps/courseware/tests/test_rules.py | 2 +- .../tests/test_self_paced_overrides.py | 10 +- .../courseware/tests/test_services.py | 2 +- .../courseware/tests/test_split_module.py | 34 +- .../tests/test_submitting_problems.py | 46 ++- lms/djangoapps/courseware/tests/test_tabs.py | 67 ++-- .../tests/test_user_state_client.py | 2 +- .../courseware/tests/test_video_handlers.py | 122 ++++--- .../courseware/tests/test_video_mongo.py | 263 +++++++------- .../courseware/tests/test_video_xml.py | 1 - .../tests/test_view_authentication.py | 60 ++-- lms/djangoapps/courseware/tests/test_views.py | 324 +++++++++--------- .../courseware/tests/test_word_cloud.py | 43 ++- lms/djangoapps/courseware/tests/tests.py | 19 +- 38 files changed, 934 insertions(+), 988 deletions(-) diff --git a/lms/djangoapps/courseware/tests/factories.py b/lms/djangoapps/courseware/tests/factories.py index 9e116b7655..bb81bc1d9a 100644 --- a/lms/djangoapps/courseware/tests/factories.py +++ b/lms/djangoapps/courseware/tests/factories.py @@ -31,7 +31,7 @@ from common.djangoapps.student.tests.factories import UserProfileFactory as Stud # TODO fix this (course_id and location are invalid names as constants, and course_id should really be COURSE_KEY) # pylint: disable=invalid-name course_id = CourseKey.from_string('edX/test_course/test') -location = partial(course_id.make_usage_key, u'problem') +location = partial(course_id.make_usage_key, 'problem') class UserProfileFactory(StudentUserProfileFactory): @@ -126,7 +126,7 @@ class GlobalStaffFactory(UserFactory): class StudentModuleFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring - class Meta(object): + class Meta: model = StudentModule module_type = "problem" @@ -139,7 +139,7 @@ class StudentModuleFactory(DjangoModelFactory): # lint-amnesty, pylint: disable class UserStateSummaryFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring - class Meta(object): + class Meta: model = XModuleUserStateSummaryField field_name = 'existing_field' @@ -148,7 +148,7 @@ class UserStateSummaryFactory(DjangoModelFactory): # lint-amnesty, pylint: disa class StudentPrefsFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring - class Meta(object): + class Meta: model = XModuleStudentPrefsField field_name = 'existing_field' @@ -158,7 +158,7 @@ class StudentPrefsFactory(DjangoModelFactory): # lint-amnesty, pylint: disable= class StudentInfoFactory(DjangoModelFactory): # lint-amnesty, pylint: disable=missing-class-docstring - class Meta(object): + class Meta: model = XModuleStudentInfoField field_name = 'existing_field' @@ -171,6 +171,6 @@ class RequestFactoryNoCsrf(RequestFactory): RequestFactory, which disables csrf checks. """ def request(self, **kwargs): - request = super(RequestFactoryNoCsrf, self).request(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments + request = super().request(**kwargs) setattr(request, '_dont_enforce_csrf_checks', True) # pylint: disable=literal-used-as-attribute return request diff --git a/lms/djangoapps/courseware/tests/helpers.py b/lms/djangoapps/courseware/tests/helpers.py index b634a59c0f..7bb65476f7 100644 --- a/lms/djangoapps/courseware/tests/helpers.py +++ b/lms/djangoapps/courseware/tests/helpers.py @@ -8,15 +8,12 @@ import json from collections import OrderedDict from datetime import timedelta -import six from django.contrib import messages from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.test import TestCase from django.test.client import Client, RequestFactory from django.urls import reverse from django.utils.timezone import now -from six import text_type -from six.moves import range from xblock.field_data import DictFieldData from common.djangoapps.edxmako.shortcuts import render_to_string @@ -94,7 +91,7 @@ class BaseTestXmodule(ModuleStoreTestCase): self.item_descriptor.xmodule_runtime = self.new_module_runtime() - self.item_url = six.text_type(self.item_descriptor.location) + self.item_url = str(self.item_descriptor.location) def setup_course(self): # lint-amnesty, pylint: disable=missing-function-docstring self.course = CourseFactory.create(data=self.COURSE_DATA) @@ -132,7 +129,7 @@ class BaseTestXmodule(ModuleStoreTestCase): assert all(self.login_statuses) def setUp(self): - super(BaseTestXmodule, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.setup_course() self.initialize_module(metadata=self.METADATA, data=self.DATA) @@ -140,7 +137,7 @@ class BaseTestXmodule(ModuleStoreTestCase): """Return item url with dispatch.""" return reverse( 'xblock_handler', - args=(six.text_type(self.course.id), quote_slashes(self.item_url), 'xmodule_handler', dispatch) + args=(str(self.course.id), quote_slashes(self.item_url), 'xmodule_handler', dispatch) ) @@ -150,7 +147,7 @@ class XModuleRenderingTestBase(BaseTestXmodule): # lint-amnesty, pylint: disabl """ Create a runtime that actually does html rendering """ - runtime = super(XModuleRenderingTestBase, self).new_module_runtime() # lint-amnesty, pylint: disable=super-with-arguments + runtime = super().new_module_runtime() runtime.render_template = render_to_string return runtime @@ -185,7 +182,7 @@ class LoginEnrollmentTestCase(TestCase): """ make_request = getattr(self.client, method.lower()) response = make_request(url, **kwargs) - assert response.status_code == status_code, u'{method} request to {url} returned status code {actual}, expected status code {expected}'.format(method=method, url=url, actual=response.status_code, expected=status_code) # pylint: disable=line-too-long + assert response.status_code == status_code, f'{method} request to {url} returned status code {response.status_code}, expected status code {status_code}' # pylint: disable=line-too-long return response def assert_account_activated(self, url, method="GET", **kwargs): # lint-amnesty, pylint: disable=missing-function-docstring @@ -257,7 +254,7 @@ class LoginEnrollmentTestCase(TestCase): """ resp = self.client.post(reverse('change_enrollment'), { 'enrollment_action': 'enroll', - 'course_id': text_type(course.id), + 'course_id': str(course.id), 'check_access': True, }) result = resp.status_code == 200 @@ -273,7 +270,7 @@ class LoginEnrollmentTestCase(TestCase): url = reverse('change_enrollment') request_data = { 'enrollment_action': 'unenroll', - 'course_id': text_type(course.id), + 'course_id': str(course.id), } self.assert_request_status_code(200, url, method="POST", data=request_data) @@ -387,7 +384,7 @@ def masquerade_as_group_member(user, course, partition_id, group_id): user, data={"role": "student", "user_partition_id": partition_id, "group_id": group_id} ) - response = MasqueradeView.as_view()(request, six.text_type(course.id)) + response = MasqueradeView.as_view()(request, str(course.id)) setup_masquerade(request, course.id, True) return response.status_code @@ -419,7 +416,7 @@ def get_expiration_banner_text(user, course, language='en'): # lint-amnesty, py if upgrade_deadline: formatted_upgrade_deadline = strftime_localized_html(upgrade_deadline, 'SHORT_DATE') - bannerText = u'Audit Access Expires {expiration_date}
\ + bannerText = 'Audit Access Expires {expiration_date}
\ You lose all access to this course, including your progress, on {expiration_date}.\
Upgrade by {upgrade_deadline} to get unlimited access to the course as long as it exists\ on the site. Upgrade now to retain access past\ @@ -429,7 +426,7 @@ def get_expiration_banner_text(user, course, language='en'): # lint-amnesty, py upgrade_deadline=formatted_upgrade_deadline ) else: - bannerText = u'Audit Access Expires {expiration_date}
\ + bannerText = 'Audit Access Expires {expiration_date}
\ You lose all access to this course, including your progress, on {expiration_date}.\ '.format( expiration_date=formatted_expiration_date diff --git a/lms/djangoapps/courseware/tests/test_about.py b/lms/djangoapps/courseware/tests/test_about.py index 36f539f9d1..6beca7ec82 100644 --- a/lms/djangoapps/courseware/tests/test_about.py +++ b/lms/djangoapps/courseware/tests/test_about.py @@ -5,17 +5,15 @@ Test the about xblock import datetime +from unittest import mock +from unittest.mock import patch import ddt -import mock import pytz -import six from ccx_keys.locator import CCXLocator from django.conf import settings from django.test.utils import override_settings from django.urls import reverse from milestones.tests.utils import MilestonesTestCaseMixin -from mock import patch -from six import text_type from waffle.testutils import override_switch from common.djangoapps.course_modes.models import CourseMode @@ -59,7 +57,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra @classmethod def setUpClass(cls): - super(AboutTestCase, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() cls.course_without_about = CourseFactory.create(catalog_visibility=CATALOG_VISIBILITY_NONE) cls.course_with_about = CourseFactory.create(catalog_visibility=CATALOG_VISIBILITY_ABOUT) @@ -78,7 +76,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra ) def setUp(self): - super(AboutTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course_mode = CourseMode( course_id=self.purchase_course.id, @@ -92,7 +90,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra """ This test asserts that a non-logged in user can visit the course about page """ - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) self.assertContains(resp, "OOGIE BLOOGIE") @@ -104,7 +102,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra This test asserts that a logged-in user can visit the course about page """ self.setup_user() - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) self.assertContains(resp, "OOGIE BLOOGIE") @@ -115,7 +113,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra """ self.setup_user() self.enroll(self.course, True) - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) self.assertContains(resp, "You are enrolled in this course") self.assertContains(resp, "View Course") @@ -125,25 +123,25 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra """ Verify that the About Page honors the permission settings in the course module """ - url = reverse('about_course', args=[text_type(self.course_with_about.id)]) + url = reverse('about_course', args=[str(self.course_with_about.id)]) resp = self.client.get(url) self.assertContains(resp, "WITH ABOUT") - url = reverse('about_course', args=[text_type(self.course_without_about.id)]) + url = reverse('about_course', args=[str(self.course_without_about.id)]) resp = self.client.get(url) assert resp.status_code == 404 @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) def test_logged_in_marketing(self): self.setup_user() - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) # should be redirected assert resp.status_code == 302 # follow this time, and check we're redirected to the course home page resp = self.client.get(url, follow=True) target_url = resp.redirect_chain[-1][0] - course_home_url = reverse('openedx.course_experience.course_home', args=[text_type(self.course.id)]) + course_home_url = reverse('openedx.course_experience.course_home', args=[str(self.course.id)]) assert target_url.endswith(course_home_url) @patch.dict(settings.FEATURES, {'ENABLE_COURSE_HOME_REDIRECT': False}) @@ -154,7 +152,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra ENABLE_COURSE_HOME_REDIRECT is set to False """ self.setup_user() - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) # should not be redirected self.assertContains(resp, "OOGIE BLOOGIE") @@ -167,7 +165,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra ENABLE_MKTG_SITE is set to False """ self.setup_user() - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) # should not be redirected self.assertContains(resp, "OOGIE BLOOGIE") @@ -175,14 +173,14 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra @patch.dict(settings.FEATURES, {'ENABLE_PREREQUISITE_COURSES': True}) def test_pre_requisite_course(self): pre_requisite_course = CourseFactory.create(org='edX', course='900', display_name='pre requisite course') - course = CourseFactory.create(pre_requisite_courses=[text_type(pre_requisite_course.id)]) + course = CourseFactory.create(pre_requisite_courses=[str(pre_requisite_course.id)]) self.setup_user() - url = reverse('about_course', args=[text_type(course.id)]) + url = reverse('about_course', args=[str(course.id)]) resp = self.client.get(url) assert resp.status_code == 200 pre_requisite_courses = get_prerequisite_courses_display(course) - pre_requisite_course_about_url = reverse('about_course', args=[text_type(pre_requisite_courses[0]['key'])]) - assert u'
{}'.format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']) in resp.content.decode(resp.charset).strip('\n') # pylint: disable=line-too-long + pre_requisite_course_about_url = reverse('about_course', args=[str(pre_requisite_courses[0]['key'])]) + assert '{}'.format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']) in resp.content.decode(resp.charset).strip('\n') # pylint: disable=line-too-long @patch.dict(settings.FEATURES, {'ENABLE_PREREQUISITE_COURSES': True}) def test_about_page_unfulfilled_prereqs(self): @@ -192,7 +190,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra display_name='pre requisite course', ) - pre_requisite_courses = [text_type(pre_requisite_course.id)] + pre_requisite_courses = [str(pre_requisite_course.id)] # for this failure to occur, the enrollment window needs to be in the past course = CourseFactory.create( @@ -211,14 +209,14 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra self.enroll(self.course, True) self.enroll(pre_requisite_course, True) - url = reverse('about_course', args=[text_type(course.id)]) + url = reverse('about_course', args=[str(course.id)]) resp = self.client.get(url) assert resp.status_code == 200 pre_requisite_courses = get_prerequisite_courses_display(course) - pre_requisite_course_about_url = reverse('about_course', args=[text_type(pre_requisite_courses[0]['key'])]) - assert u'{}'.format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']) in resp.content.decode(resp.charset).strip('\n') # pylint: disable=line-too-long + pre_requisite_course_about_url = reverse('about_course', args=[str(pre_requisite_courses[0]['key'])]) + assert '{}'.format(pre_requisite_course_about_url, pre_requisite_courses[0]['display']) in resp.content.decode(resp.charset).strip('\n') # pylint: disable=line-too-long - url = reverse('about_course', args=[six.text_type(pre_requisite_course.id)]) + url = reverse('about_course', args=[str(pre_requisite_course.id)]) resp = self.client.get(url) assert resp.status_code == 200 @@ -235,7 +233,7 @@ class AboutTestCase(LoginEnrollmentTestCase, SharedModuleStoreTestCase, EventTra """ with mock.patch('xmodule.course_module.CourseBlock.course_visibility', course_visibility): with override_waffle_flag(COURSE_ENABLE_UNENROLLED_ACCESS_FLAG, active=True): - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) if course_visibility == COURSE_VISIBILITY_PUBLIC or course_visibility == COURSE_VISIBILITY_PUBLIC_OUTLINE: # lint-amnesty, pylint: disable=consider-using-in self.assertContains(resp, "View Course") @@ -253,7 +251,7 @@ class AboutTestCaseXML(LoginEnrollmentTestCase, ModuleStoreTestCase): """ Set up the tests """ - super(AboutTestCaseXML, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # The following test course (which lives at common/test/data/2014) # is closed; we're testing that an about page still appears when @@ -277,13 +275,13 @@ class AboutTestCaseXML(LoginEnrollmentTestCase, ModuleStoreTestCase): @patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_logged_in_xml(self): self.setup_user() - url = reverse('about_course', args=[text_type(self.xml_course_id)]) + url = reverse('about_course', args=[str(self.xml_course_id)]) resp = self.client.get(url) self.assertContains(resp, self.xml_data) @patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_anonymous_user_xml(self): - url = reverse('about_course', args=[text_type(self.xml_course_id)]) + url = reverse('about_course', args=[str(self.xml_course_id)]) resp = self.client.get(url) self.assertContains(resp, self.xml_data) @@ -294,7 +292,7 @@ class AboutWithCappedEnrollmentsTestCase(LoginEnrollmentTestCase, SharedModuleSt """ @classmethod def setUpClass(cls): - super(AboutWithCappedEnrollmentsTestCase, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create(metadata={"max_student_enrollments_allowed": 1}) cls.about = ItemFactory.create( category="about", parent_location=cls.course.location, @@ -306,7 +304,7 @@ class AboutWithCappedEnrollmentsTestCase(LoginEnrollmentTestCase, SharedModuleSt This test will make sure that enrollment caps are enforced """ self.setup_user() - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) self.assertContains(resp, '') @@ -339,7 +337,7 @@ class AboutWithInvitationOnly(SharedModuleStoreTestCase): """ @classmethod def setUpClass(cls): - super(AboutWithInvitationOnly, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create(metadata={"invitation_only": True}) cls.about = ItemFactory.create( category="about", parent_location=cls.course.location, @@ -351,7 +349,7 @@ class AboutWithInvitationOnly(SharedModuleStoreTestCase): Test for user not logged in, invitation only course. """ - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) self.assertContains(resp, "Enrollment in this course is by invitation only") @@ -368,9 +366,9 @@ class AboutWithInvitationOnly(SharedModuleStoreTestCase): CourseEnrollmentAllowedFactory(email=user.email, course_id=self.course.id) self.client.login(username=user.username, password='test') - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) - self.assertContains(resp, u"Enroll Now") + self.assertContains(resp, "Enroll Now") # Check that registration button is present self.assertContains(resp, REG_STR) @@ -382,7 +380,7 @@ class AboutWithClosedEnrollment(ModuleStoreTestCase): set but it is currently outside of that period. """ def setUp(self): - super(AboutWithClosedEnrollment, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course = CourseFactory.create(metadata={"invitation_only": False}) @@ -401,7 +399,7 @@ class AboutWithClosedEnrollment(ModuleStoreTestCase): ) def test_closed_enrollmement(self): - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) self.assertContains(resp, "Enrollment is Closed") @@ -409,7 +407,7 @@ class AboutWithClosedEnrollment(ModuleStoreTestCase): self.assertNotContains(resp, REG_STR) def test_course_price_is_not_visble_in_sidebar(self): - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) # course price is not visible ihe course_about page when the course # mode is not set to honor @@ -422,7 +420,7 @@ class AboutSidebarHTMLTestCase(SharedModuleStoreTestCase): This test case will check the About page for the content in the HTML sidebar. """ def setUp(self): - super(AboutSidebarHTMLTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course = CourseFactory.create() @ddt.data( @@ -449,7 +447,7 @@ class AboutSidebarHTMLTestCase(SharedModuleStoreTestCase): display_name=itemfactory_display_name, data=itemfactory_data, ) - url = reverse('about_course', args=[text_type(self.course.id)]) + url = reverse('about_course', args=[str(self.course.id)]) resp = self.client.get(url) if waffle_switch_value and itemfactory_display_name and itemfactory_data: self.assertContains(resp, '
') @@ -467,11 +465,11 @@ class CourseAboutTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase) @classmethod def setUpClass(cls): - super(CourseAboutTestCaseCCX, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() def setUp(self): - super(CourseAboutTestCaseCCX, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # Create ccx coach account self.coach = coach = AdminFactory.create(password="test") @@ -485,7 +483,7 @@ class CourseAboutTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase) # create ccx ccx = CcxFactory(course_id=self.course.id, coach=self.coach) - ccx_locator = CCXLocator.from_course_locator(self.course.id, six.text_type(ccx.id)) + ccx_locator = CCXLocator.from_course_locator(self.course.id, str(ccx.id)) self.setup_user() url = reverse('openedx.course_experience.course_home', args=[ccx_locator]) diff --git a/lms/djangoapps/courseware/tests/test_access.py b/lms/djangoapps/courseware/tests/test_access.py index af7d23d23c..ac2773f6ef 100644 --- a/lms/djangoapps/courseware/tests/test_access.py +++ b/lms/djangoapps/courseware/tests/test_access.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Test the access control framework """ @@ -7,17 +6,16 @@ Test the access control framework import datetime import itertools +from unittest.mock import Mock, patch import pytest import ddt import pytz -import six from ccx_keys.locator import CCXLocator from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.test import TestCase from django.test.client import RequestFactory from django.urls import reverse from milestones.tests.utils import MilestonesTestCaseMixin -from mock import Mock, patch from opaque_keys.edx.locator import CourseLocator import lms.djangoapps.courseware.access as access @@ -75,14 +73,14 @@ class CoachAccessTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase) """ Set up course for tests """ - super(CoachAccessTestCaseCCX, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() def setUp(self): """ Set up tests """ - super(CoachAccessTestCaseCCX, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # Create ccx coach account self.coach = AdminFactory.create(password="test") @@ -104,7 +102,7 @@ class CoachAccessTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase) ) ccx.save() - ccx_locator = CCXLocator.from_course_locator(self.course.id, six.text_type(ccx.id)) + ccx_locator = CCXLocator.from_course_locator(self.course.id, str(ccx.id)) role = CourseCcxCoachRole(ccx_locator) role.add_users(self.coach) CourseEnrollment.enroll(self.coach, ccx_locator) @@ -151,12 +149,12 @@ class CoachAccessTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase) CourseEnrollment.enroll(student, ccx_locator) # Test for access of a coach - resp = self.client.get(reverse('student_progress', args=[six.text_type(ccx_locator), student.id])) + resp = self.client.get(reverse('student_progress', args=[str(ccx_locator), student.id])) assert resp.status_code == 200 # Assert access of a student self.client.login(username=student.username, password='test') - resp = self.client.get(reverse('student_progress', args=[six.text_type(ccx_locator), self.coach.id])) + resp = self.client.get(reverse('student_progress', args=[str(ccx_locator), self.coach.id])) assert resp.status_code == 404 @@ -175,7 +173,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes } def setUp(self): - super(AccessTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course = CourseFactory.create(org='edX', course='toy', run='test_run') self.anonymous_user = AnonymousUserFactory() self.beta_user = BetaTesterFactory(course_key=self.course.id) @@ -554,7 +552,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes org='test_org', number='788', run='test_run' ) - pre_requisite_courses = [six.text_type(pre_requisite_course.id)] + pre_requisite_courses = [str(pre_requisite_course.id)] course = CourseFactory.create( org='test_org', number='786', run='test_run', pre_requisite_courses=pre_requisite_courses ) @@ -600,7 +598,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes run='test_run', ) - pre_requisite_courses = [six.text_type(pre_requisite_course.id)] + pre_requisite_courses = [str(pre_requisite_course.id)] course = CourseFactory.create( org='edX', course='1000', @@ -616,7 +614,7 @@ class AccessTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, MilestonesTes self.login(user.email, test_password) CourseEnrollmentFactory(user=user, course_id=course.id) - url = reverse('courseware', args=[six.text_type(course.id)]) + url = reverse('courseware', args=[str(course.id)]) response = self.client.get(url) self.assertRedirects( response, @@ -637,7 +635,7 @@ class UserRoleTestCase(TestCase): """ def setUp(self): - super(UserRoleTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course_key = CourseLocator('edX', 'toy', '2012_Fall') self.anonymous_user = AnonymousUserFactory() self.student = UserFactory() @@ -680,7 +678,7 @@ class CourseOverviewAccessTestCase(ModuleStoreTestCase): """ def setUp(self): - super(CourseOverviewAccessTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() today = datetime.datetime.now(pytz.UTC) last_week = today - datetime.timedelta(days=7) diff --git a/lms/djangoapps/courseware/tests/test_comprehensive_theming.py b/lms/djangoapps/courseware/tests/test_comprehensive_theming.py index a5ced9d9d6..43eb9663a4 100644 --- a/lms/djangoapps/courseware/tests/test_comprehensive_theming.py +++ b/lms/djangoapps/courseware/tests/test_comprehensive_theming.py @@ -15,7 +15,7 @@ class TestComprehensiveTheming(TestCase): """Test comprehensive theming.""" def setUp(self): - super(TestComprehensiveTheming, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # Clear the internal staticfiles caches, to get test isolation. staticfiles.finders.get_finder.cache_clear() diff --git a/lms/djangoapps/courseware/tests/test_context_processor.py b/lms/djangoapps/courseware/tests/test_context_processor.py index 31373c2f0f..07c9001ab4 100644 --- a/lms/djangoapps/courseware/tests/test_context_processor.py +++ b/lms/djangoapps/courseware/tests/test_context_processor.py @@ -3,8 +3,8 @@ Unit tests for courseware context_processor """ +from unittest.mock import Mock from django.contrib.auth.models import AnonymousUser -from mock import Mock from lms.djangoapps.courseware.context_processor import user_timezone_locale_prefs from openedx.core.djangoapps.user_api.preferences.api import set_user_preference @@ -18,7 +18,7 @@ class UserPrefContextProcessorUnitTest(ModuleStoreTestCase): """ def setUp(self): - super(UserPrefContextProcessorUnitTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create() self.request = Mock() diff --git a/lms/djangoapps/courseware/tests/test_course_info.py b/lms/djangoapps/courseware/tests/test_course_info.py index 77c3f9deea..5ea0d6f63a 100644 --- a/lms/djangoapps/courseware/tests/test_course_info.py +++ b/lms/djangoapps/courseware/tests/test_course_info.py @@ -1,4 +1,3 @@ -# coding=utf-8 """ Test the course_info xblock """ @@ -6,16 +5,14 @@ Test the course_info xblock from datetime import datetime +from unittest import mock import ddt -import mock -import six from ccx_keys.locator import CCXLocator from django.conf import settings from django.http import QueryDict from django.test.utils import override_settings from django.urls import reverse from edx_toggles.toggles.testutils import override_waffle_flag -from six import text_type from lms.djangoapps.ccx.tests.factories import CcxFactory from openedx.core.djangoapps.self_paced.models import SelfPacedConfiguration @@ -51,7 +48,7 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, @classmethod def setUpClass(cls): - super(CourseInfoTestCase, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() cls.page = ItemFactory.create( category="course_info", parent_location=cls.course.location, @@ -60,14 +57,14 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, def test_logged_in_unenrolled(self): self.setup_user() - url = reverse('info', args=[text_type(self.course.id)]) + url = reverse('info', args=[str(self.course.id)]) resp = self.client.get(url) self.assertContains(resp, "OOGIE BLOOGIE") self.assertContains(resp, "You are not currently enrolled in this course") def test_logged_in_enrolled(self): self.enroll(self.course) - url = reverse('info', args=[text_type(self.course.id)]) + url = reverse('info', args=[str(self.course.id)]) resp = self.client.get(url) assert b'You are not currently enrolled in this course' not in resp.content @@ -85,19 +82,19 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, self.setup_user() self.enroll(self.course) - url = reverse('info', args=[text_type(self.course.id)]) + url = reverse('info', args=[str(self.course.id)]) self.verify_consent_required(self.client, url) # lint-amnesty, pylint: disable=no-value-for-parameter def test_anonymous_user(self): - url = reverse('info', args=[text_type(self.course.id)]) + url = reverse('info', args=[str(self.course.id)]) resp = self.client.get(url) assert resp.status_code == 200 assert b'OOGIE BLOOGIE' not in resp.content def test_logged_in_not_enrolled(self): self.setup_user() - url = reverse('info', args=[text_type(self.course.id)]) + url = reverse('info', args=[str(self.course.id)]) self.client.get(url) # Check whether the user has been enrolled in the course. @@ -116,7 +113,7 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, """ self.setup_user() self.enroll(self.course) - url = reverse('info', args=[text_type(self.course.id)]) + url = reverse('info', args=[str(self.course.id)]) response = self.client.get(url) start_date = strftime_localized(self.course.start, 'SHORT_DATE') expected_params = QueryDict(mutable=True) @@ -135,14 +132,14 @@ class CourseInfoTestCase(EnterpriseTestConsentRequired, LoginEnrollmentTestCase, """ self.setup_user() self.enroll(self.course) - fake_unicode_start_time = u"üñîçø∂é_ßtå®t_tîµé" + fake_unicode_start_time = "üñîçø∂é_ßtå®t_tîµé" mock_strftime_localized.return_value = fake_unicode_start_time - url = reverse('info', args=[text_type(self.course.id)]) + url = reverse('info', args=[str(self.course.id)]) response = self.client.get(url) expected_params = QueryDict(mutable=True) expected_params['notlive'] = fake_unicode_start_time - expected_url = u'{url}?{params}'.format( + expected_url = '{url}?{params}'.format( url=reverse('dashboard'), params=expected_params.urlencode() ) @@ -162,7 +159,7 @@ class CourseInfoLastAccessedTestCase(LoginEnrollmentTestCase, ModuleStoreTestCas """ def setUp(self): - super(CourseInfoLastAccessedTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course = CourseFactory.create() self.page = ItemFactory.create( category="course_info", parent_location=self.course.location, @@ -175,7 +172,7 @@ class CourseInfoLastAccessedTestCase(LoginEnrollmentTestCase, ModuleStoreTestCas is no course content. """ SelfPacedConfiguration(enable_course_home_improvements=True).save() - url = reverse('info', args=(six.text_type(self.course.id),)) + url = reverse('info', args=(str(self.course.id),)) response = self.client.get(url) content = pq(response.content) assert content('.page-header-secondary a').length == 0 @@ -206,7 +203,7 @@ class CourseInfoLastAccessedTestCase(LoginEnrollmentTestCase, ModuleStoreTestCas } ) self.client.get(section_url) - info_url = reverse('info', args=(six.text_type(self.course.id),)) + info_url = reverse('info', args=(str(self.course.id),)) # Assuring a non-authenticated user cannot see the resume course button. resume_course_url = self.get_resume_course_url(info_url) @@ -230,7 +227,7 @@ class CourseInfoTitleTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase): Tests of the CourseInfo page title site configuration options. """ def setUp(self): - super(CourseInfoTitleTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course = CourseFactory.create( org="HogwartZ", number="Potions_3", @@ -292,7 +289,7 @@ class CourseInfoTitleTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase): Test the info page on a course with all the multiple display options depeding on the current site configuration """ - url = reverse('info', args=(six.text_type(self.course.id),)) + url = reverse('info', args=(str(self.course.id),)) with with_site_configuration_context(configuration=site_config): response = self.client.get(url) @@ -317,11 +314,11 @@ class CourseInfoTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase): @classmethod def setUpClass(cls): - super(CourseInfoTestCaseCCX, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() def setUp(self): - super(CourseInfoTestCaseCCX, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # Create ccx coach account self.coach = coach = AdminFactory.create(password="test") @@ -334,7 +331,7 @@ class CourseInfoTestCaseCCX(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ # create ccx ccx = CcxFactory(course_id=self.course.id, coach=self.coach) - ccx_locator = CCXLocator.from_course_locator(self.course.id, six.text_type(ccx.id)) + ccx_locator = CCXLocator.from_course_locator(self.course.id, str(ccx.id)) self.setup_user() url = reverse('info', args=[ccx_locator]) @@ -354,7 +351,7 @@ class CourseInfoTestCaseXML(LoginEnrollmentTestCase, ModuleStoreTestCase): """ Set up the tests """ - super(CourseInfoTestCaseXML, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # The following test course (which lives at common/test/data/2014) # is closed; we're testing that a course info page still appears when @@ -378,13 +375,13 @@ class CourseInfoTestCaseXML(LoginEnrollmentTestCase, ModuleStoreTestCase): @mock.patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_logged_in_xml(self): self.setup_user() - url = reverse('info', args=[text_type(self.xml_course_key)]) + url = reverse('info', args=[str(self.xml_course_key)]) resp = self.client.get(url) self.assertContains(resp, self.xml_data) @mock.patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_anonymous_user_xml(self): - url = reverse('info', args=[text_type(self.xml_course_key)]) + url = reverse('info', args=[str(self.xml_course_key)]) resp = self.client.get(url) self.assertNotContains(resp, self.xml_data) @@ -399,12 +396,12 @@ class SelfPacedCourseInfoTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest @classmethod def setUpClass(cls): - super(SelfPacedCourseInfoTestCase, cls).setUpClass() + super().setUpClass() cls.instructor_paced_course = CourseFactory.create(self_paced=False) cls.self_paced_course = CourseFactory.create(self_paced=True) def setUp(self): - super(SelfPacedCourseInfoTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() ContentTypeGatingConfig.objects.create(enabled=True, enabled_as_of=datetime(2018, 1, 1)) self.setup_user() @@ -414,7 +411,7 @@ class SelfPacedCourseInfoTestCase(LoginEnrollmentTestCase, SharedModuleStoreTest Fetch the given course's info page, asserting the number of SQL and Mongo queries. """ - url = reverse('info', args=[text_type(course.id)]) + url = reverse('info', args=[str(course.id)]) with self.assertNumQueries(sql_queries, table_blacklist=QUERY_COUNT_TABLE_BLACKLIST): with check_mongo_calls(mongo_queries): with mock.patch("openedx.core.djangoapps.theming.helpers.get_current_site", return_value=None): diff --git a/lms/djangoapps/courseware/tests/test_course_survey.py b/lms/djangoapps/courseware/tests/test_course_survey.py index c057c1a0b2..5946643b32 100644 --- a/lms/djangoapps/courseware/tests/test_course_survey.py +++ b/lms/djangoapps/courseware/tests/test_course_survey.py @@ -6,10 +6,8 @@ Python tests for the Survey workflows from collections import OrderedDict from copy import deepcopy -import six from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.urls import reverse -from six.moves import range from common.test.utils import XssTestMixin from lms.djangoapps.courseware.tests.helpers import LoginEnrollmentTestCase @@ -26,7 +24,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe @classmethod def setUpClass(cls): - super(SurveyViewsTests, cls).setUpClass() + super().setUpClass() cls.test_survey_name = 'TestSurvey' cls.course = CourseFactory.create( display_name='', @@ -45,20 +43,20 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe """ Set up the test data used in the specific tests """ - super(SurveyViewsTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.test_form = '' self.survey = SurveyForm.create(self.test_survey_name, self.test_form) self.student_answers = OrderedDict({ - u'field1': u'value1', - u'field2': u'value2', + 'field1': 'value1', + 'field2': 'value2', }) # Create student accounts and activate them. for i in range(len(self.STUDENT_INFO)): email, password = self.STUDENT_INFO[i] - username = 'u{0}'.format(i) + username = f'u{i}' self.create_account(username, email, password) self.activate_user(email) @@ -81,12 +79,12 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe resp = self.client.get( reverse( view_name, - kwargs={'course_id': six.text_type(course.id)} + kwargs={'course_id': str(course.id)} ) ) self.assertRedirects( resp, - reverse('course_survey', kwargs={'course_id': six.text_type(course.id)}) + reverse('course_survey', kwargs={'course_id': str(course.id)}) ) def _assert_no_redirect(self, course): @@ -98,7 +96,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe resp = self.client.get( reverse( view_name, - kwargs={'course_id': six.text_type(course.id)} + kwargs={'course_id': str(course.id)} ) ) assert resp.status_code == 200 @@ -125,7 +123,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe resp = self.client.get( reverse( 'openedx.course_experience.course_home', - kwargs={'course_id': six.text_type(self.course.id)} + kwargs={'course_id': str(self.course.id)} ) ) assert resp.status_code == 200 @@ -150,13 +148,13 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe resp = self.client.get( reverse( 'course_survey', - kwargs={'course_id': six.text_type(self.course.id)} + kwargs={'course_id': str(self.course.id)} ) ) assert resp.status_code == 200 - expected = u''.format( - course_id=six.text_type(self.course.id) + expected = ''.format( + course_id=str(self.course.id) ) self.assertContains(resp, expected) @@ -168,7 +166,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe answers = deepcopy(self.student_answers) answers.update({ - 'course_id': six.text_type(self.course.id) + 'course_id': str(self.course.id) }) resp = self.client.post( @@ -202,13 +200,13 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe resp = self.client.get( reverse( 'course_survey', - kwargs={'course_id': six.text_type(self.course_with_bogus_survey.id)} + kwargs={'course_id': str(self.course_with_bogus_survey.id)} ) ) course_home_path = 'openedx.course_experience.course_home' self.assertRedirects( resp, - reverse(course_home_path, kwargs={'course_id': six.text_type(self.course_with_bogus_survey.id)}) + reverse(course_home_path, kwargs={'course_id': str(self.course_with_bogus_survey.id)}) ) def test_visiting_survey_with_no_course_survey(self): @@ -219,13 +217,13 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe resp = self.client.get( reverse( 'course_survey', - kwargs={'course_id': six.text_type(self.course_without_survey.id)} + kwargs={'course_id': str(self.course_without_survey.id)} ) ) course_home_path = 'openedx.course_experience.course_home' self.assertRedirects( resp, - reverse(course_home_path, kwargs={'course_id': six.text_type(self.course_without_survey.id)}) + reverse(course_home_path, kwargs={'course_id': str(self.course_without_survey.id)}) ) def test_survey_xss(self): @@ -233,7 +231,7 @@ class SurveyViewsTests(LoginEnrollmentTestCase, SharedModuleStoreTestCase, XssTe response = self.client.get( reverse( 'course_survey', - kwargs={'course_id': six.text_type(self.course.id)} + kwargs={'course_id': str(self.course.id)} ) ) self.assert_no_xss(response, '') diff --git a/lms/djangoapps/courseware/tests/test_course_tools.py b/lms/djangoapps/courseware/tests/test_course_tools.py index 4a012ee6f0..ff59493181 100644 --- a/lms/djangoapps/courseware/tests/test_course_tools.py +++ b/lms/djangoapps/courseware/tests/test_course_tools.py @@ -5,10 +5,10 @@ Unit tests for course tools. import datetime +from unittest.mock import patch import crum import pytz from django.test import RequestFactory -from mock import patch from common.djangoapps.course_modes.models import CourseMode from common.djangoapps.course_modes.tests.factories import CourseModeFactory @@ -24,7 +24,7 @@ class VerifiedUpgradeToolTest(SharedModuleStoreTestCase): # lint-amnesty, pylin @classmethod def setUpClass(cls): - super(VerifiedUpgradeToolTest, cls).setUpClass() + super().setUpClass() cls.now = datetime.datetime.now(pytz.UTC) cls.course = CourseFactory.create( @@ -37,7 +37,7 @@ class VerifiedUpgradeToolTest(SharedModuleStoreTestCase): # lint-amnesty, pylin cls.course_overview = CourseOverview.get_from_id(cls.course.id) def setUp(self): - super(VerifiedUpgradeToolTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course_verified_mode = CourseModeFactory( course_id=self.course.id, @@ -102,7 +102,7 @@ class FinancialAssistanceToolTest(SharedModuleStoreTestCase): """ @classmethod def setUpClass(cls): - super(FinancialAssistanceToolTest, cls).setUpClass() + super().setUpClass() cls.now = datetime.datetime.now(pytz.UTC) cls.course = CourseFactory.create( @@ -114,7 +114,7 @@ class FinancialAssistanceToolTest(SharedModuleStoreTestCase): cls.course_overview = CourseOverview.get_from_id(cls.course.id) def setUp(self): - super(FinancialAssistanceToolTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course_financial_mode = CourseModeFactory( course_id=self.course.id, diff --git a/lms/djangoapps/courseware/tests/test_courses.py b/lms/djangoapps/courseware/tests/test_courses.py index f177aeacae..ffb2a0dcc3 100644 --- a/lms/djangoapps/courseware/tests/test_courses.py +++ b/lms/djangoapps/courseware/tests/test_courses.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Tests for course access """ @@ -7,11 +6,10 @@ Tests for course access import datetime import itertools +from unittest import mock import pytest import ddt -import mock import pytz -import six from completion.models import BlockCompletion from completion.test_utils import CompletionWaffleTestMixin from crum import set_current_request @@ -20,8 +18,6 @@ from django.test.client import RequestFactory from django.test.utils import override_settings from django.urls import reverse from opaque_keys.edx.keys import CourseKey -from six import text_type -from six.moves import range from lms.djangoapps.courseware.courses import ( course_open_for_self_enrollment, @@ -75,9 +71,9 @@ class CoursesTest(ModuleStoreTestCase): org='org', number='num', display_name='name' ) - cms_url = u"//{}/course/{}".format(CMS_BASE_TEST, six.text_type(self.course.id)) + cms_url = "//{}/course/{}".format(CMS_BASE_TEST, str(self.course.id)) assert cms_url == get_cms_course_link(self.course) - cms_url = u"//{}/course/{}".format(CMS_BASE_TEST, six.text_type(self.course.location)) + cms_url = "//{}/course/{}".format(CMS_BASE_TEST, str(self.course.location)) assert cms_url == get_cms_block_link(self.course, 'course') @ddt.data(GET_COURSE_WITH_ACCESS, GET_COURSE_OVERVIEW_WITH_ACCESS) @@ -88,7 +84,7 @@ class CoursesTest(ModuleStoreTestCase): with pytest.raises(CoursewareAccessException) as error: course_access_func(user, 'load', course.id) - assert text_type(error.value) == 'Course not found.' + assert str(error.value) == 'Course not found.' assert error.value.access_response.error_code == 'not_visible_to_user' assert not error.value.access_response.has_access @@ -130,10 +126,10 @@ class CoursesTest(ModuleStoreTestCase): unfiltered_courses = get_courses(user) for org in [primary_course.org, alternate_course.org]: - assert any(((course.org == org) for course in unfiltered_courses)) + assert any((course.org == org) for course in unfiltered_courses) filtered_courses = get_courses(user, org=primary) - assert all(((course.org == primary_course.org) for course in filtered_courses)) + assert all((course.org == primary_course.org) for course in filtered_courses) with mock.patch( 'openedx.core.djangoapps.site_configuration.helpers.get_value', @@ -147,7 +143,7 @@ class CoursesTest(ModuleStoreTestCase): # Request filtering for an org matching the designated org. site_courses = get_courses(user, org=alternate) - assert all(((course.org == alternate_course.org) for course in site_courses)) + assert all((course.org == alternate_course.org) for course in site_courses) def test_get_courses_with_filter(self): """ @@ -165,7 +161,7 @@ class CoursesTest(ModuleStoreTestCase): ) for filter_, expected_courses in test_cases: assert {course.id for course in get_courses(user, filter_=filter_)} ==\ - expected_courses, u'testing get_courses with filter_={}'.format(filter_) + expected_courses, f'testing get_courses with filter_={filter_}' def test_get_current_child(self): mock_xmodule = mock.MagicMock() @@ -217,17 +213,17 @@ class MongoCourseImageTestCase(ModuleStoreTestCase): def test_get_image_url(self): """Test image URL formatting.""" course = CourseFactory.create(org='edX', course='999') - assert course_image_url(course) == '/c4x/edX/999/asset/{0}'.format(course.course_image) + assert course_image_url(course) == f'/c4x/edX/999/asset/{course.course_image}' def test_non_ascii_image_name(self): # Verify that non-ascii image names are cleaned - course = CourseFactory.create(course_image=u'before_\N{SNOWMAN}_after.jpg') - assert course_image_url(course) == '/c4x/{org}/{course}/asset/before___after.jpg'.format(org=course.location.org, course=course.location.course) # pylint: disable=line-too-long + course = CourseFactory.create(course_image='before_\N{SNOWMAN}_after.jpg') + assert course_image_url(course) == f'/c4x/{course.location.org}/{course.location.course}/asset/before___after.jpg' # pylint: disable=line-too-long def test_spaces_in_image_name(self): # Verify that image names with spaces in them are cleaned - course = CourseFactory.create(course_image=u'before after.jpg') - assert course_image_url(course) == '/c4x/{org}/{course}/asset/before_after.jpg'.format(org=course.location.org, course=course.location.course) # pylint: disable=line-too-long + course = CourseFactory.create(course_image='before after.jpg') + assert course_image_url(course) == f'/c4x/{course.location.org}/{course.location.course}/asset/before_after.jpg' # pylint: disable=line-too-long def test_static_asset_path_course_image_default(self): """ @@ -242,7 +238,7 @@ class MongoCourseImageTestCase(ModuleStoreTestCase): Test that with course_image and static_asset_path both being set, that we get the right course_image url. """ - course = CourseFactory.create(course_image=u'things_stuff.jpg', + course = CourseFactory.create(course_image='things_stuff.jpg', static_asset_path="foo") assert course_image_url(course) == '/static/foo/things_stuff.jpg' @@ -256,12 +252,12 @@ class XmlCourseImageTestCase(XModuleXmlImportTest): assert course_image_url(course) == '/static/xml_test_course/images/course_image.jpg' def test_non_ascii_image_name(self): - course = self.process_xml(xml.CourseFactory.build(course_image=u'before_\N{SNOWMAN}_after.jpg')) - assert course_image_url(course) == u'/static/xml_test_course/before_☃_after.jpg' + course = self.process_xml(xml.CourseFactory.build(course_image='before_\N{SNOWMAN}_after.jpg')) + assert course_image_url(course) == '/static/xml_test_course/before_☃_after.jpg' def test_spaces_in_image_name(self): - course = self.process_xml(xml.CourseFactory.build(course_image=u'before after.jpg')) - assert course_image_url(course) == u'/static/xml_test_course/before after.jpg' + course = self.process_xml(xml.CourseFactory.build(course_image='before after.jpg')) + assert course_image_url(course) == '/static/xml_test_course/before after.jpg' class CoursesRenderTest(ModuleStoreTestCase): @@ -273,7 +269,7 @@ class CoursesRenderTest(ModuleStoreTestCase): """ Set up the course and user context """ - super(CoursesRenderTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() store = modulestore() course_items = import_course_from_xml(store, self.user.id, TEST_DATA_DIR, ['toy']) @@ -285,7 +281,7 @@ class CoursesRenderTest(ModuleStoreTestCase): def test_get_course_info_section_render(self): # Test render works okay course_info = get_course_info_section(self.request, self.request.user, self.course, 'handouts') - assert course_info == u"Sample" + assert course_info == "Sample" # Test when render raises an exception with mock.patch('lms.djangoapps.courseware.courses.get_module') as mock_module_render: @@ -312,7 +308,7 @@ class CoursesRenderTest(ModuleStoreTestCase): class CourseEnrollmentOpenTests(ModuleStoreTestCase): # lint-amnesty, pylint: disable=missing-class-docstring def setUp(self): - super(CourseEnrollmentOpenTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.now = datetime.datetime.now().replace(tzinfo=pytz.UTC) def test_course_enrollment_open(self): @@ -362,7 +358,7 @@ class CourseInstantiationTests(ModuleStoreTestCase): Tests around instantiating a course multiple times in the same request. """ def setUp(self): - super(CourseInstantiationTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.factory = RequestFactory() @@ -377,7 +373,7 @@ class CourseInstantiationTests(ModuleStoreTestCase): __ = ItemFactory(parent=section, category='problem') fake_request = self.factory.get( - reverse('progress', kwargs={'course_id': six.text_type(course.id)}) + reverse('progress', kwargs={'course_id': str(course.id)}) ) course = modulestore().get_course(course.id, depth=course_depth) @@ -423,7 +419,7 @@ class TestGetCourseChapters(ModuleStoreTestCase): ItemFactory(parent=course, category='chapter') course_chapter_ids = get_course_chapter_ids(course.location.course_key) assert len(course_chapter_ids) == 2 - assert course_chapter_ids == [six.text_type(child) for child in course.children] + assert course_chapter_ids == [str(child) for child in course.children] class TestGetCourseAssignments(CompletionWaffleTestMixin, ModuleStoreTestCase): diff --git a/lms/djangoapps/courseware/tests/test_credit_requirements.py b/lms/djangoapps/courseware/tests/test_credit_requirements.py index b92b547c69..82af3f4f22 100644 --- a/lms/djangoapps/courseware/tests/test_credit_requirements.py +++ b/lms/djangoapps/courseware/tests/test_credit_requirements.py @@ -3,11 +3,10 @@ Tests for credit requirement display on the progress page. """ +from unittest.mock import patch import ddt -import six from django.conf import settings from django.urls import reverse -from mock import patch from common.djangoapps.course_modes.models import CourseMode from openedx.core.djangoapps.credit import api as credit_api @@ -33,11 +32,11 @@ class ProgressPageCreditRequirementsTest(SharedModuleStoreTestCase): @classmethod def setUpClass(cls): - super(ProgressPageCreditRequirementsTest, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() def setUp(self): - super(ProgressPageCreditRequirementsTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # Configure course as a credit course CreditCourse.objects.create(course_key=self.course.id, enabled=True) @@ -89,7 +88,7 @@ class ProgressPageCreditRequirementsTest(SharedModuleStoreTestCase): self.assertContains(response, "Upcoming") self.assertContains( response, - u"{}, you have not yet met the requirements for credit".format(self.USER_FULL_NAME) + f"{self.USER_FULL_NAME}, you have not yet met the requirements for credit" ) def test_credit_requirements_eligible(self): @@ -116,13 +115,13 @@ class ProgressPageCreditRequirementsTest(SharedModuleStoreTestCase): self.assertContains(response, self.VERIFICATION_REQ_DISPLAY) self.assertContains( response, - u"{}, you have met the requirements for credit in this course.".format(self.USER_FULL_NAME) + f"{self.USER_FULL_NAME}, you have met the requirements for credit in this course." ) - self.assertContains(response, u"Completed by {date}") + self.assertContains(response, "Completed by {date}") credit_requirements = credit_api.get_credit_requirement_status(self.course.id, self.user.username) for requirement in credit_requirements: - self.assertContains(response, requirement['status_date'].strftime(u'%Y-%m-%d %H:%M')) + self.assertContains(response, requirement['status_date'].strftime('%Y-%m-%d %H:%M')) self.assertNotContains(response, "95%") def test_credit_requirements_not_eligible(self): @@ -142,7 +141,7 @@ class ProgressPageCreditRequirementsTest(SharedModuleStoreTestCase): self.assertContains(response, self.VERIFICATION_REQ_DISPLAY) self.assertContains( response, - u"{}, you are no longer eligible for credit in this course.".format(self.USER_FULL_NAME) + f"{self.USER_FULL_NAME}, you are no longer eligible for credit in this course." ) self.assertContains(response, "Verification Failed") @@ -170,5 +169,5 @@ class ProgressPageCreditRequirementsTest(SharedModuleStoreTestCase): def _get_progress_page(self): """Load the progress page for the course the user is enrolled in. """ - url = reverse("progress", kwargs={"course_id": six.text_type(self.course.id)}) + url = reverse("progress", kwargs={"course_id": str(self.course.id)}) return self.client.get(url) diff --git a/lms/djangoapps/courseware/tests/test_date_summary.py b/lms/djangoapps/courseware/tests/test_date_summary.py index dd5c3aa2e5..c31ff41750 100644 --- a/lms/djangoapps/courseware/tests/test_date_summary.py +++ b/lms/djangoapps/courseware/tests/test_date_summary.py @@ -1,9 +1,10 @@ -# -*- coding: utf-8 -*- +# lint-amnesty, pylint: disable=django-not-configured """Tests for course home page date summary blocks.""" from datetime import datetime, timedelta +from unittest.mock import patch import crum import ddt import waffle @@ -11,7 +12,6 @@ from django.contrib.messages.middleware import MessageMiddleware from django.test import RequestFactory from django.urls import reverse from edx_toggles.toggles.testutils import override_waffle_flag -from mock import patch from pytz import utc from common.djangoapps.course_modes.models import CourseMode @@ -41,7 +41,7 @@ from lms.djangoapps.verify_student.services import IDVerificationService from lms.djangoapps.verify_student.tests.factories import SoftwareSecurePhotoVerificationFactory from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.djangoapps.self_paced.models import SelfPacedConfiguration -from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory +from openedx.core.djangoapps.site_configuration.tests.factories import SiteFactory # pylint: disable=unused-import from openedx.core.djangoapps.user_api.preferences.api import set_user_preference from openedx.features.course_duration_limits.models import CourseDurationLimitConfig from openedx.features.course_experience import ( @@ -62,7 +62,7 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): MODULESTORE = TEST_DATA_SPLIT_MODULESTORE def setUp(self): - super(CourseDateSummaryTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() SelfPacedConfiguration.objects.create(enable_course_home_improvements=True) def make_request(self, user): @@ -95,7 +95,7 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): """Assert that the enabled block types for this course are as expected.""" blocks = get_course_date_blocks(course, user) assert len(blocks) == len(expected_blocks) - assert set((type(b) for b in blocks)) == set(expected_blocks) + assert {type(b) for b in blocks} == set(expected_blocks) @ddt.data( # Verified enrollment with no photo-verification before course start @@ -241,8 +241,10 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): ) blocks = get_course_date_blocks(course, user, request, num_assignments=2) assert len(blocks) == len(expected_blocks) - assert set((type(b) for b in blocks)) == set(expected_blocks) - assignment_blocks = filter(lambda b: isinstance(b, CourseAssignmentDate), blocks) + assert {type(b) for b in blocks} == set(expected_blocks) + assignment_blocks = filter( # pylint: disable=filter-builtin-not-iterating + lambda b: isinstance(b, CourseAssignmentDate), blocks + ) for assignment in assignment_blocks: assignment_title = str(assignment.title_html) or str(assignment.title) assert assignment_title != 'Third nearest assignment' @@ -265,8 +267,10 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): ) blocks = get_course_date_blocks(course, user, request, include_past_dates=True) assert len(blocks) == len(expected_blocks) - assert set((type(b) for b in blocks)) == set(expected_blocks) - assignment_blocks = filter(lambda b: isinstance(b, CourseAssignmentDate), blocks) + assert {type(b) for b in blocks} == set(expected_blocks) + assignment_blocks = filter( # pylint: disable=filter-builtin-not-iterating + lambda b: isinstance(b, CourseAssignmentDate), blocks + ) for assignment in assignment_blocks: assignment_title = str(assignment.title_html) or str(assignment.title) assert assignment_title != 'Not returned since we do not get non-graded subsections' @@ -576,7 +580,7 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): CourseEnrollmentFactory(course_id=course.id, user=user, mode=CourseMode.VERIFIED) block = VerifiedUpgradeDeadlineDate(course, user) - assert block.link == '{}?sku={}'.format(configuration.basket_checkout_page, sku) + assert block.link == f'{configuration.basket_checkout_page}?sku={sku}' ## CertificateAvailableDate @waffle.testutils.override_switch('certificates.auto_certificate_generation', True) @@ -702,8 +706,8 @@ class CourseDateSummaryTest(SharedModuleStoreTestCase): assert block.link == '' @ddt.data( - (-1, u'1 day ago - {date}'), - (1, u'in 1 day - {date}') + (-1, '1 day ago - {date}'), + (1, 'in 1 day - {date}') ) @ddt.unpack def test_render_date_string_past(self, delta, expected_date_string): @@ -770,7 +774,7 @@ class TestDateAlerts(SharedModuleStoreTestCase): Unit tests for date alerts. """ def setUp(self): - super(TestDateAlerts, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() with freeze_time('2017-07-01 09:00:00'): self.course = create_course_run(days_till_start=0) self.course.certificate_available_date = self.course.start + timedelta(days=21) @@ -782,11 +786,11 @@ class TestDateAlerts(SharedModuleStoreTestCase): MessageMiddleware().process_request(self.request) @ddt.data( - ['2017-01-01 09:00:00', u'in 6 months on ]*\b{attname}=['"]([\w\d\- ]+)['"][^>]*>""") # noqa: W605,E501 + regex_string = r"""<{tag} [^>]*\b{attname}=['"]([\w\d\- ]+)['"][^>]*>""" # noqa: W605,E501 regex = regex_string.format(tag=tag, attname=attname) match = re.search(regex, content) - assert match, (u"Couldn't find desired tag '%s' with attr '%s' in %r" % (tag, attname, content)) + assert match, (f"Couldn't find desired tag '{tag}' with attr '{attname}' in {content!r}") attvalues = match.group(1).split() assert value in attvalues @@ -166,7 +165,7 @@ class I18nLangPrefTests(BaseI18nTestCase): and use the dark lang preview functionality. """ def setUp(self): - super(I18nLangPrefTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user_login() def set_lang_preference(self, language): diff --git a/lms/djangoapps/courseware/tests/test_lti_integration.py b/lms/djangoapps/courseware/tests/test_lti_integration.py index b2bf22201f..2f4886b278 100644 --- a/lms/djangoapps/courseware/tests/test_lti_integration.py +++ b/lms/djangoapps/courseware/tests/test_lti_integration.py @@ -4,12 +4,11 @@ import json from collections import OrderedDict -import mock +from unittest import mock +import urllib import oauthlib -import six from django.conf import settings from django.urls import reverse -from six import text_type from lms.djangoapps.courseware.tests.helpers import BaseTestXmodule from lms.djangoapps.courseware.views.views import get_course_lti_endpoints @@ -33,44 +32,42 @@ class TestLTI(BaseTestXmodule): """ Mock oauth1 signing of requests library for testing. """ - super(TestLTI, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments - mocked_nonce = u'135685044251684026041377608307' - mocked_timestamp = u'1234567890' - mocked_signature_after_sign = u'my_signature%3D' - mocked_decoded_signature = u'my_signature=' + super().setUp() + mocked_nonce = '135685044251684026041377608307' + mocked_timestamp = '1234567890' + mocked_signature_after_sign = 'my_signature%3D' + mocked_decoded_signature = 'my_signature=' # Note: this course_id is actually a course_key - context_id = text_type(self.item_descriptor.course_id) - user_id = text_type(self.item_descriptor.xmodule_runtime.anonymous_student_id) + context_id = str(self.item_descriptor.course_id) + user_id = str(self.item_descriptor.xmodule_runtime.anonymous_student_id) hostname = self.item_descriptor.xmodule_runtime.hostname - resource_link_id = text_type(six.moves.urllib.parse.quote('{}-{}'.format(hostname, - self.item_descriptor.location.html_id() - ))) + resource_link_id = str(urllib.parse.quote('{}-{}'.format(hostname, self.item_descriptor.location.html_id()))) sourcedId = "{context}:{resource_link}:{user_id}".format( - context=six.moves.urllib.parse.quote(context_id), + context=urllib.parse.quote(context_id), resource_link=resource_link_id, user_id=user_id ) self.correct_headers = { - u'user_id': user_id, - u'oauth_callback': u'about:blank', - u'launch_presentation_return_url': '', - u'lti_message_type': u'basic-lti-launch-request', - u'lti_version': 'LTI-1p0', - u'roles': u'Student', - u'context_id': context_id, + 'user_id': user_id, + 'oauth_callback': 'about:blank', + 'launch_presentation_return_url': '', + 'lti_message_type': 'basic-lti-launch-request', + 'lti_version': 'LTI-1p0', + 'roles': 'Student', + 'context_id': context_id, - u'resource_link_id': resource_link_id, - u'lis_result_sourcedid': sourcedId, + 'resource_link_id': resource_link_id, + 'lis_result_sourcedid': sourcedId, - u'oauth_nonce': mocked_nonce, - u'oauth_timestamp': mocked_timestamp, - u'oauth_consumer_key': u'', - u'oauth_signature_method': u'HMAC-SHA1', - u'oauth_version': u'1.0', - u'oauth_signature': mocked_decoded_signature + 'oauth_nonce': mocked_nonce, + 'oauth_timestamp': mocked_timestamp, + 'oauth_consumer_key': '', + 'oauth_signature_method': 'HMAC-SHA1', + 'oauth_version': '1.0', + 'oauth_signature': mocked_decoded_signature } saved_sign = oauthlib.oauth1.Client.sign @@ -80,14 +77,14 @@ class TestLTI(BaseTestXmodule): 'input_fields': self.correct_headers, 'element_class': self.item_descriptor.category, 'element_id': self.item_descriptor.location.html_id(), - 'launch_url': u'http://www.example.com', # default value + 'launch_url': 'http://www.example.com', # default value 'open_in_a_new_page': True, 'form_url': self.item_descriptor.xmodule_runtime.handler_url(self.item_descriptor, 'preview_handler').rstrip('/?'), 'hide_launch': False, 'has_score': False, 'module_score': None, - 'comment': u'', + 'comment': '', 'weight': 1.0, 'ask_to_send_username': self.item_descriptor.ask_to_send_username, 'ask_to_send_email': self.item_descriptor.ask_to_send_email, @@ -103,12 +100,12 @@ class TestLTI(BaseTestXmodule): # self is here: __, headers, __ = saved_sign(self, *args, **kwargs) # we should replace nonce, timestamp and signed_signature in headers: - old = headers[u'Authorization'] + old = headers['Authorization'] old_parsed = OrderedDict([param.strip().replace('"', '').split('=') for param in old.split(',')]) - old_parsed[u'OAuth oauth_nonce'] = mocked_nonce - old_parsed[u'oauth_timestamp'] = mocked_timestamp - old_parsed[u'oauth_signature'] = mocked_signature_after_sign - headers[u'Authorization'] = ', '.join([k + '="' + v + '"' for k, v in old_parsed.items()]) + old_parsed['OAuth oauth_nonce'] = mocked_nonce + old_parsed['oauth_timestamp'] = mocked_timestamp + old_parsed['oauth_signature'] = mocked_signature_after_sign + headers['Authorization'] = ', '.join([k + '="' + v + '"' for k, v in old_parsed.items()]) return None, headers, None patcher = mock.patch.object(oauthlib.oauth1.Client, "sign", mocked_sign) @@ -136,7 +133,7 @@ class TestLTIBlockListing(SharedModuleStoreTestCase): @classmethod def setUpClass(cls): - super(TestLTIBlockListing, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create(display_name=cls.COURSE_NAME, number=cls.COURSE_SLUG) cls.chapter1 = ItemFactory.create( parent_location=cls.course.location, @@ -175,17 +172,17 @@ class TestLTIBlockListing(SharedModuleStoreTestCase): return "https://{}{}".format(settings.SITE_NAME, reverse( 'xblock_handler_noauth', args=[ - text_type(self.course.id), - quote_slashes(text_type(self.lti_published.scope_ids.usage_id)), + str(self.course.id), + quote_slashes(str(self.lti_published.scope_ids.usage_id)), handler ] )) def test_lti_rest_bad_course(self): """Tests what happens when the lti listing rest endpoint gets a bad course_id""" - bad_ids = [u"sf", u"dne/dne/dne", u"fo/ey/\\u5305"] + bad_ids = ["sf", "dne/dne/dne", "fo/ey/\\u5305"] for bad_course_id in bad_ids: - lti_rest_endpoints_url = 'courses/{}/lti_rest_endpoints/'.format(bad_course_id) + lti_rest_endpoints_url = f'courses/{bad_course_id}/lti_rest_endpoints/' response = self.client.get(lti_rest_endpoints_url) assert 404 == response.status_code @@ -193,7 +190,7 @@ class TestLTIBlockListing(SharedModuleStoreTestCase): """tests that the draft lti module is part of the endpoint response""" request = mock.Mock() request.method = 'GET' - response = get_course_lti_endpoints(request, course_id=text_type(self.course.id)) + response = get_course_lti_endpoints(request, course_id=str(self.course.id)) assert 200 == response.status_code assert 'application/json' == response['Content-Type'] @@ -212,5 +209,5 @@ class TestLTIBlockListing(SharedModuleStoreTestCase): for method in DISALLOWED_METHODS: request = mock.Mock() request.method = method - response = get_course_lti_endpoints(request, text_type(self.course.id)) + response = get_course_lti_endpoints(request, str(self.course.id)) assert 405 == response.status_code diff --git a/lms/djangoapps/courseware/tests/test_masquerade.py b/lms/djangoapps/courseware/tests/test_masquerade.py index 549dc39ff6..3c75002919 100644 --- a/lms/djangoapps/courseware/tests/test_masquerade.py +++ b/lms/djangoapps/courseware/tests/test_masquerade.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Unit tests for masquerade. """ @@ -7,14 +6,13 @@ Unit tests for masquerade. import json import pickle from datetime import datetime +from unittest.mock import patch import pytest import ddt -import six from django.conf import settings from django.test import TestCase from django.urls import reverse from edx_toggles.toggles.testutils import override_waffle_flag -from mock import patch from pytz import UTC from xblock.runtime import DictKeyValueStore @@ -45,7 +43,7 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase, Mas """ @classmethod def setUpClass(cls): - super(MasqueradeTestCase, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create(number='masquerade-test', metadata={'start': datetime.now(UTC)}) cls.info_page = ItemFactory.create( category="course_info", parent_location=cls.course.location, @@ -83,7 +81,7 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase, Mas ) def setUp(self): - super(MasqueradeTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.test_user = self.create_user() self.login(self.test_user.email, 'test') @@ -96,7 +94,7 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase, Mas url = reverse( 'courseware_section', kwargs={ - 'course_id': six.text_type(self.course.id), + 'course_id': str(self.course.id), 'chapter': self.chapter.location.block_id, 'section': self.sequential.location.block_id, } @@ -110,7 +108,7 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase, Mas url = reverse( 'info', kwargs={ - 'course_id': six.text_type(self.course.id), + 'course_id': str(self.course.id), } ) return self.client.get(url) @@ -122,7 +120,7 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase, Mas url = reverse( 'progress', kwargs={ - 'course_id': six.text_type(self.course.id), + 'course_id': str(self.course.id), } ) return self.client.get(url) @@ -142,8 +140,8 @@ class MasqueradeTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase, Mas problem_url = reverse( 'xblock_handler', kwargs={ - 'course_id': six.text_type(self.course.id), - 'usage_id': six.text_type(self.problem.location), + 'course_id': str(self.course.id), + 'usage_id': str(self.problem.location), 'handler': 'xmodule_handler', 'suffix': 'problem_get' } @@ -251,7 +249,7 @@ class TestStaffMasqueradeAsSpecificStudent(StaffMasqueradeTestCase, ProblemSubmi Check for staff being able to masquerade as a specific student. """ def setUp(self): - super(TestStaffMasqueradeAsSpecificStudent, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.student_user = self.create_user() self.login_student() self.enroll(self.course, True) @@ -282,7 +280,7 @@ class TestStaffMasqueradeAsSpecificStudent(StaffMasqueradeTestCase, ProblemSubmi The return value is a string like u'1/2'. """ json_data = json.loads(self.look_at_question(self.problem_display_name).content.decode('utf-8')) - progress = '%s/%s' % (str(json_data['current_score']), str(json_data['total_possible'])) + progress = '{}/{}'.format(str(json_data['current_score']), str(json_data['total_possible'])) return progress def assertExpectedLanguageInPreference(self, user, expected_language_code): @@ -320,7 +318,7 @@ class TestStaffMasqueradeAsSpecificStudent(StaffMasqueradeTestCase, ProblemSubmi @ddt.data( 'john', # Non-unicode username - u'fôô@bar', # Unicode username with @, which is what the ENABLE_UNICODE_USERNAME feature allows + 'fôô@bar', # Unicode username with @, which is what the ENABLE_UNICODE_USERNAME feature allows ) @patch.dict('django.conf.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_masquerade_as_specific_student(self, username): @@ -336,32 +334,32 @@ class TestStaffMasqueradeAsSpecificStudent(StaffMasqueradeTestCase, ProblemSubmi self.login(student.email, 'test') # Answer correctly as the student, and check progress. self.submit_answer('Correct', 'Correct') - assert self.get_progress_detail() == u'2/2' + assert self.get_progress_detail() == '2/2' # Log in as staff, and check the problem is unanswered. self.login_staff() - assert self.get_progress_detail() == u'0/2' + assert self.get_progress_detail() == '0/2' # Masquerade as the student, and check we can see the student state. self.update_masquerade(role='student', username=student.username) - assert self.get_progress_detail() == u'2/2' + assert self.get_progress_detail() == '2/2' # Temporarily override the student state. self.submit_answer('Correct', 'Incorrect') - assert self.get_progress_detail() == u'1/2' + assert self.get_progress_detail() == '1/2' # Reload the page and check we see the student state again. self.get_courseware_page() - assert self.get_progress_detail() == u'2/2' + assert self.get_progress_detail() == '2/2' # Become the staff user again, and check the problem is still unanswered. self.update_masquerade(role='staff') - assert self.get_progress_detail() == u'0/2' + assert self.get_progress_detail() == '0/2' # Verify the student state did not change. self.logout() self.login(student.email, 'test') - assert self.get_progress_detail() == u'2/2' + assert self.get_progress_detail() == '2/2' def test_masquerading_with_language_preference(self): """ @@ -437,7 +435,7 @@ class TestGetMasqueradingGroupId(StaffMasqueradeTestCase): Check for staff being able to masquerade as belonging to a group. """ def setUp(self): - super(TestGetMasqueradingGroupId, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user_partition = UserPartition( 0, 'Test User Partition', '', [Group(0, 'Group 1'), Group(1, 'Group 2')], @@ -489,7 +487,7 @@ class MasqueradingKeyValueStoreTest(TestCase): Unit tests for the MasqueradingKeyValueStore class. """ def setUp(self): - super(MasqueradingKeyValueStoreTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.ro_kvs = ReadOnlyKeyValueStore({'a': 42, 'b': None, 'c': 'OpenCraft'}) self.session = FakeSession() self.kvs = MasqueradingKeyValueStore(self.ro_kvs, self.session) diff --git a/lms/djangoapps/courseware/tests/test_middleware.py b/lms/djangoapps/courseware/tests/test_middleware.py index 013dd3de13..dd0e74abf6 100644 --- a/lms/djangoapps/courseware/tests/test_middleware.py +++ b/lms/djangoapps/courseware/tests/test_middleware.py @@ -17,7 +17,7 @@ class CoursewareMiddlewareTestCase(SharedModuleStoreTestCase): @classmethod def setUpClass(cls): - super(CoursewareMiddlewareTestCase, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() def test_process_404(self): diff --git a/lms/djangoapps/courseware/tests/test_model_data.py b/lms/djangoapps/courseware/tests/test_model_data.py index 05be73a91a..fd5362132d 100644 --- a/lms/djangoapps/courseware/tests/test_model_data.py +++ b/lms/djangoapps/courseware/tests/test_model_data.py @@ -5,10 +5,10 @@ Test for lms courseware app, module data (runtime data storage for XBlocks) import json from functools import partial +from unittest.mock import Mock, patch import pytest from django.db import connections, DatabaseError from django.test import TestCase -from mock import Mock, patch from xblock.core import XBlock from xblock.exceptions import KeyValueMultiSaveError from xblock.fields import BlockScope, Scope, ScopeIds @@ -58,7 +58,7 @@ class StudentModuleFactory(cmfStudentModuleFactory): class TestInvalidScopes(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring def setUp(self): - super(TestInvalidScopes, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create(username='user') self.field_data_cache = FieldDataCache([mock_descriptor([mock_field(Scope.user_state, 'a_field')])], course_id, self.user) # lint-amnesty, pylint: disable=line-too-long self.kvs = DjangoKeyValueStore(self.field_data_cache) @@ -76,7 +76,7 @@ class TestInvalidScopes(TestCase): # lint-amnesty, pylint: disable=missing-clas self.assertRaises(InvalidScopeError, self.kvs.set_many, {key: 'value'}) -class OtherUserFailureTestMixin(object): +class OtherUserFailureTestMixin: """ Mixin class to add test cases for failures when a user trying to use the kvs is not the one that instantiated the kvs. @@ -108,7 +108,7 @@ class TestStudentModuleStorage(OtherUserFailureTestMixin, TestCase): databases = {alias for alias in connections} # lint-amnesty, pylint: disable=unnecessary-comprehension def setUp(self): - super(TestStudentModuleStorage, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() student_module = StudentModuleFactory(state=json.dumps({'a_field': 'a_value', 'b_field': 'b_value'})) self.user = student_module.student assert self.user.id == 1 @@ -236,7 +236,7 @@ class TestMissingStudentModule(TestCase): # lint-amnesty, pylint: disable=missi databases = {alias for alias in connections} # lint-amnesty, pylint: disable=unnecessary-comprehension def setUp(self): - super(TestMissingStudentModule, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create(username='user') assert self.user.id == 1 @@ -267,7 +267,7 @@ class TestMissingStudentModule(TestCase): # lint-amnesty, pylint: disable=missi with self.assertNumQueries(1, using='student_module_history'): self.kvs.set(user_state_key('a_field'), 'a_value') - assert 1 == sum((len(cache) for cache in self.field_data_cache.cache.values())) + assert 1 == sum(len(cache) for cache in self.field_data_cache.cache.values()) assert 1 == StudentModule.objects.all().count() student_module = StudentModule.objects.all()[0] @@ -287,7 +287,7 @@ class TestMissingStudentModule(TestCase): # lint-amnesty, pylint: disable=missi assert not self.kvs.has(user_state_key('a_field')) -class StorageTestBase(object): +class StorageTestBase: """ A base class for that gets subclassed when testing each of the scopes. """ diff --git a/lms/djangoapps/courseware/tests/test_module_render.py b/lms/djangoapps/courseware/tests/test_module_render.py index 9b474668b5..5feab1b563 100644 --- a/lms/djangoapps/courseware/tests/test_module_render.py +++ b/lms/djangoapps/courseware/tests/test_module_render.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Test for lms courseware app, module render unit """ @@ -12,7 +11,6 @@ from functools import partial import pytest import ddt import pytz -import six from bson import ObjectId from completion.waffle import ENABLE_COMPLETION_TRACKING_SWITCH # lint-amnesty, pylint: disable=wrong-import-order from completion.models import BlockCompletion # lint-amnesty, pylint: disable=wrong-import-order @@ -30,12 +28,10 @@ from edx_toggles.toggles.testutils import override_waffle_switch # lint-amnesty from edx_when.field_data import DateLookupFieldData # lint-amnesty, pylint: disable=wrong-import-order from freezegun import freeze_time # lint-amnesty, pylint: disable=wrong-import-order from milestones.tests.utils import MilestonesTestCaseMixin # lint-amnesty, pylint: disable=wrong-import-order -from mock import MagicMock, Mock, patch # lint-amnesty, pylint: disable=wrong-import-order +from unittest.mock import MagicMock, Mock, patch # lint-amnesty, pylint: disable=wrong-import-order from opaque_keys.edx.asides import AsideUsageKeyV2 # lint-amnesty, pylint: disable=wrong-import-order from opaque_keys.edx.keys import CourseKey, UsageKey # lint-amnesty, pylint: disable=wrong-import-order from pyquery import PyQuery # lint-amnesty, pylint: disable=wrong-import-order -from six import text_type # lint-amnesty, pylint: disable=wrong-import-order -from six.moves import range # lint-amnesty, pylint: disable=wrong-import-order from web_fragments.fragment import Fragment # lint-amnesty, pylint: disable=wrong-import-order from xblock.completable import CompletableXBlockMixin # lint-amnesty, pylint: disable=wrong-import-order from xblock.core import XBlock, XBlockAside # lint-amnesty, pylint: disable=wrong-import-order @@ -188,7 +184,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): @classmethod def setUpClass(cls): - super(ModuleRenderTestCase, cls).setUpClass() + super().setUpClass() cls.course_key = ToyCourseFactory.create().id cls.toy_course = modulestore().get_course(cls.course_key) @@ -198,7 +194,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ Set up the course and user context """ - super(ModuleRenderTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() OverrideFieldData.provider_classes = None self.mock_user = UserFactory() @@ -214,7 +210,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.callback_url = reverse( 'xqueue_callback', kwargs=dict( - course_id=text_type(self.course_key), + course_id=str(self.course_key), userid=str(self.mock_user.id), mod_id=self.mock_module.id, dispatch=self.dispatch @@ -223,7 +219,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): def tearDown(self): OverrideFieldData.provider_classes = None - super(ModuleRenderTestCase, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments + super().tearDown() def test_get_module(self): assert render.get_module('dummyuser', None, 'invalid location', None) is None @@ -254,7 +250,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): # See if the url got rewritten to the target link # note if the URL mapping changes then this assertion will break - assert '/courses/' + text_type(self.course_key) + '/jump_to_id/vertical_test' in html + assert '/courses/' + str(self.course_key) + '/jump_to_id/vertical_test' in html def test_xqueue_callback_success(self): """ @@ -273,7 +269,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): request = self.request_factory.post(self.callback_url, data) render.xqueue_callback( request, - text_type(self.course_key), + str(self.course_key), self.mock_user.id, self.mock_module.id, self.dispatch @@ -296,7 +292,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): request = self.request_factory.post(self.callback_url, {}) render.xqueue_callback( request, - text_type(self.course_key), + str(self.course_key), self.mock_user.id, self.mock_module.id, self.dispatch @@ -307,7 +303,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): request = self.request_factory.post(self.callback_url, data) render.xqueue_callback( request, - text_type(self.course_key), + str(self.course_key), self.mock_user.id, self.mock_module.id, self.dispatch @@ -318,8 +314,8 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): return reverse( 'xblock_handler', args=[ - text_type(self.course_key), - quote_slashes(text_type(self.course_key.make_usage_key('videosequence', 'Toy_Videos'))), + str(self.course_key), + quote_slashes(str(self.course_key.make_usage_key('videosequence', 'Toy_Videos'))), 'xmodule_handler', 'goto_position' ] @@ -385,7 +381,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): assert 200 == response.status_code assert json.loads(response.content.decode('utf-8')) == {'success': True} - response = self.client.post(dispatch_url, {'position': u"Φυσικά"}) + response = self.client.post(dispatch_url, {'position': "Φυσικά"}) assert 200 == response.status_code assert json.loads(response.content.decode('utf-8')) == {'success': True} @@ -503,7 +499,7 @@ class ModuleRenderTestCase(SharedModuleStoreTestCase, LoginEnrollmentTestCase): Ensure that the resource hasher works and does not fail on unicode, decoded or otherwise. """ - resources = ['ASCII text', u'❄ I am a special snowflake.', "❄ So am I, but I didn't tell you."] + resources = ['ASCII text', '❄ I am a special snowflake.', "❄ So am I, but I didn't tell you."] assert hash_resource(resources) == '50c2ae79fbce9980e0803848914b0a09' @@ -514,12 +510,12 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas """ @classmethod def setUpClass(cls): - super(TestHandleXBlockCallback, cls).setUpClass() + super().setUpClass() cls.course_key = ToyCourseFactory.create().id cls.toy_course = modulestore().get_course(cls.course_key) def setUp(self): - super(TestHandleXBlockCallback, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.location = self.course_key.make_usage_key('chapter', 'Overview') self.mock_user = UserFactory.create() @@ -533,7 +529,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas # Construct a 'standard' xqueue_callback url self.callback_url = reverse( 'xqueue_callback', kwargs={ - 'course_id': text_type(self.course_key), + 'course_id': str(self.course_key), 'userid': str(self.mock_user.id), 'mod_id': self.mock_module.id, 'dispatch': self.dispatch @@ -563,8 +559,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas request.user = self.mock_user response = render.handle_xblock_callback( request, - text_type(course.id), - quote_slashes(text_type(block.scope_ids.usage_id)), + str(course.id), + quote_slashes(str(block.scope_ids.usage_id)), handler, '', ) @@ -577,12 +573,12 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas """ request = RequestFactory().post('dummy_url', data={'position': 1}) csrf_token = get_token(request) - request._post = {'csrfmiddlewaretoken': '{}-dummy'.format(csrf_token)} # pylint: disable=protected-access + request._post = {'csrfmiddlewaretoken': f'{csrf_token}-dummy'} # pylint: disable=protected-access request.user = self.mock_user response = render.handle_xblock_callback( request, - text_type(self.course_key), - quote_slashes(text_type(self.location)), + str(self.course_key), + quote_slashes(str(self.location)), 'xmodule_handler', 'goto_position', ) @@ -598,8 +594,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas request.user = self.mock_user response = render.handle_xblock_callback( request, - text_type(self.course_key), - quote_slashes(text_type(self.location)), + str(self.course_key), + quote_slashes(str(self.location)), 'xmodule_handler', 'goto_position', ) @@ -611,7 +607,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas with pytest.raises(Http404): render.handle_xblock_callback( request, - text_type(self.course_key), + str(self.course_key), 'invalid Location', 'dummy_handler' 'dummy_dispatch' @@ -623,7 +619,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas data={'file_id': (self._mock_file(), ) * (settings.MAX_FILEUPLOADS_PER_INPUT + 1)} ) request.user = self.mock_user - assert render.handle_xblock_callback(request, text_type(self.course_key), quote_slashes(text_type(self.location)), 'dummy_handler').content.decode('utf-8') == json.dumps({'success': (f'Submission aborted! Maximum {settings.MAX_FILEUPLOADS_PER_INPUT:d} files may be submitted at once')}, indent=2) # pylint: disable=line-too-long + assert render.handle_xblock_callback(request, str(self.course_key), quote_slashes(str(self.location)), 'dummy_handler').content.decode('utf-8') == json.dumps({'success': (f'Submission aborted! Maximum {settings.MAX_FILEUPLOADS_PER_INPUT:d} files may be submitted at once')}, indent=2) # pylint: disable=line-too-long def test_too_large_file(self): inputfile = self._mock_file(size=1 + settings.STUDENT_FILEUPLOAD_MAX_SIZE) @@ -632,15 +628,15 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas data={'file_id': inputfile} ) request.user = self.mock_user - assert render.handle_xblock_callback(request, text_type(self.course_key), quote_slashes(text_type(self.location)), 'dummy_handler').content.decode('utf-8') == json.dumps({'success': (u'Submission aborted! Your file "%s" is too large (max size: %d MB)' % (inputfile.name, (settings.STUDENT_FILEUPLOAD_MAX_SIZE / (1000 ** 2))))}, indent=2) # pylint: disable=line-too-long + assert render.handle_xblock_callback(request, str(self.course_key), quote_slashes(str(self.location)), 'dummy_handler').content.decode('utf-8') == json.dumps({'success': ('Submission aborted! Your file "%s" is too large (max size: %d MB)' % (inputfile.name, (settings.STUDENT_FILEUPLOAD_MAX_SIZE / (1000 ** 2))))}, indent=2) # pylint: disable=line-too-long def test_xmodule_dispatch(self): request = self.request_factory.post('dummy_url', data={'position': 1}) request.user = self.mock_user response = render.handle_xblock_callback( request, - text_type(self.course_key), - quote_slashes(text_type(self.location)), + str(self.course_key), + quote_slashes(str(self.location)), 'xmodule_handler', 'goto_position', ) @@ -653,7 +649,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas render.handle_xblock_callback( request, 'bad_course_id', - quote_slashes(text_type(self.location)), + quote_slashes(str(self.location)), 'xmodule_handler', 'goto_position', ) @@ -664,8 +660,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas with pytest.raises(Http404): render.handle_xblock_callback( request, - text_type(self.course_key), - quote_slashes(text_type(self.course_key.make_usage_key('chapter', 'bad_location'))), + str(self.course_key), + quote_slashes(str(self.course_key.make_usage_key('chapter', 'bad_location'))), 'xmodule_handler', 'goto_position', ) @@ -676,8 +672,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas with pytest.raises(Http404): render.handle_xblock_callback( request, - text_type(self.course_key), - quote_slashes(text_type(self.location)), + str(self.course_key), + quote_slashes(str(self.location)), 'xmodule_handler', 'bad_dispatch', ) @@ -688,8 +684,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas with pytest.raises(Http404): render.handle_xblock_callback( request, - text_type(self.course_key), - quote_slashes(text_type(self.location)), + str(self.course_key), + quote_slashes(str(self.location)), 'bad_handler', 'bad_dispatch', ) @@ -708,8 +704,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas response = render.handle_xblock_callback( request, - text_type(course.id), - quote_slashes(text_type(block.scope_ids.usage_id)), + str(course.id), + quote_slashes(str(block.scope_ids.usage_id)), 'set_score', '', ) @@ -740,8 +736,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas with patch('completion.models.BlockCompletionManager.submit_completion') as mock_complete: render.handle_xblock_callback( request, - text_type(course.id), - quote_slashes(text_type(block.scope_ids.usage_id)), + str(course.id), + quote_slashes(str(block.scope_ids.usage_id)), signal, '', ) @@ -781,9 +777,9 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas def get_usage_key(): """return usage key""" return ( - quote_slashes(text_type(AsideUsageKeyV2(block.scope_ids.usage_id, "aside"))) + quote_slashes(str(AsideUsageKeyV2(block.scope_ids.usage_id, "aside"))) if is_xblock_aside - else text_type(block.scope_ids.usage_id) + else str(block.scope_ids.usage_id) ) with patch( @@ -796,7 +792,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas ) as mocked_webob_to_django_response: render.handle_xblock_callback( request, - text_type(course.id), + str(course.id), get_usage_key(), 'complete', '', @@ -822,7 +818,7 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas ), self.assertRaises(Http404): render.handle_xblock_callback( request, - text_type(course.id), + str(course.id), "foo@bar", 'complete', '', @@ -873,8 +869,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas mock_masq.return_value = True response = render.handle_xblock_callback( request, - text_type(course.id), - quote_slashes(text_type(block.scope_ids.usage_id)), + str(course.id), + quote_slashes(str(block.scope_ids.usage_id)), 'complete', '', ) @@ -896,8 +892,8 @@ class TestHandleXBlockCallback(SharedModuleStoreTestCase, LoginEnrollmentTestCas render.handle_xblock_callback( request, - text_type(course.id), - quote_slashes(text_type(descriptor.location)), + str(course.id), + quote_slashes(str(descriptor.location)), 'xmodule_handler', 'problem_check', ) @@ -912,17 +908,17 @@ class TestXBlockView(SharedModuleStoreTestCase, LoginEnrollmentTestCase): """ @classmethod def setUpClass(cls): - super(TestXBlockView, cls).setUpClass() + super().setUpClass() cls.course_key = ToyCourseFactory.create().id cls.toy_course = modulestore().get_course(cls.course_key) def setUp(self): - super(TestXBlockView, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() - self.location = text_type(self.course_key.make_usage_key('html', 'toyhtml')) + self.location = str(self.course_key.make_usage_key('html', 'toyhtml')) self.request_factory = RequestFactory() - self.view_args = [text_type(self.course_key), quote_slashes(self.location), 'student_view'] + self.view_args = [str(self.course_key), quote_slashes(self.location), 'student_view'] self.xblock_view_url = reverse('xblock_view', args=self.view_args) def test_xblock_view_handler(self): @@ -972,7 +968,7 @@ class TestTOC(ModuleStoreTestCase): """ self.course_key = ToyCourseFactory.create().id # pylint: disable=attribute-defined-outside-init self.chapter = 'Overview' # lint-amnesty, pylint: disable=attribute-defined-outside-init - chapter_url = '%s/%s/%s' % ('/courses', self.course_key, self.chapter) + chapter_url = '{}/{}/{}'.format('/courses', self.course_key, self.chapter) factory = RequestFactoryNoCsrf() self.request = factory.get(chapter_url) # lint-amnesty, pylint: disable=attribute-defined-outside-init self.request.user = UserFactory() @@ -1000,15 +996,15 @@ class TestTOC(ModuleStoreTestCase): self.setup_request_and_course(setup_finds, setup_sends) expected = ([{'active': True, 'sections': - [{'url_name': 'Toy_Videos', 'display_name': u'Toy Videos', 'graded': True, - 'format': u'Lecture Sequence', 'due': None, 'active': False}, - {'url_name': 'Welcome', 'display_name': u'Welcome', 'graded': True, + [{'url_name': 'Toy_Videos', 'display_name': 'Toy Videos', 'graded': True, + 'format': 'Lecture Sequence', 'due': None, 'active': False}, + {'url_name': 'Welcome', 'display_name': 'Welcome', 'graded': True, 'format': '', 'due': None, 'active': False}, {'url_name': 'video_123456789012', 'display_name': 'Test Video', 'graded': True, 'format': '', 'due': None, 'active': False}, {'url_name': 'video_4f66f493ac8f', 'display_name': 'Video', 'graded': True, 'format': '', 'due': None, 'active': False}], - 'url_name': 'Overview', 'display_name': u'Overview', 'display_id': u'overview'}, + 'url_name': 'Overview', 'display_name': 'Overview', 'display_id': 'overview'}, {'active': False, 'sections': [{'url_name': 'toyvideo', 'display_name': 'toyvideo', 'graded': True, 'format': '', 'due': None, 'active': False}], @@ -1040,15 +1036,15 @@ class TestTOC(ModuleStoreTestCase): self.setup_request_and_course(setup_finds, setup_sends) section = 'Welcome' expected = ([{'active': True, 'sections': - [{'url_name': 'Toy_Videos', 'display_name': u'Toy Videos', 'graded': True, - 'format': u'Lecture Sequence', 'due': None, 'active': False}, - {'url_name': 'Welcome', 'display_name': u'Welcome', 'graded': True, + [{'url_name': 'Toy_Videos', 'display_name': 'Toy Videos', 'graded': True, + 'format': 'Lecture Sequence', 'due': None, 'active': False}, + {'url_name': 'Welcome', 'display_name': 'Welcome', 'graded': True, 'format': '', 'due': None, 'active': True}, {'url_name': 'video_123456789012', 'display_name': 'Test Video', 'graded': True, 'format': '', 'due': None, 'active': False}, {'url_name': 'video_4f66f493ac8f', 'display_name': 'Video', 'graded': True, 'format': '', 'due': None, 'active': False}], - 'url_name': 'Overview', 'display_name': u'Overview', 'display_id': u'overview'}, + 'url_name': 'Overview', 'display_name': 'Overview', 'display_id': 'overview'}, {'active': False, 'sections': [{'url_name': 'toyvideo', 'display_name': 'toyvideo', 'graded': True, 'format': '', 'due': None, 'active': False}], @@ -1070,16 +1066,16 @@ class TestProctoringRendering(SharedModuleStoreTestCase): """Check the Table of Contents for a course""" @classmethod def setUpClass(cls): - super(TestProctoringRendering, cls).setUpClass() + super().setUpClass() cls.course_key = ToyCourseFactory.create(enable_proctored_exams=True).id def setUp(self): """ Set up the initial mongo datastores """ - super(TestProctoringRendering, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.chapter = 'Overview' - chapter_url = '%s/%s/%s' % ('/courses', self.course_key, self.chapter) + chapter_url = '{}/{}/{}'.format('/courses', self.course_key, self.chapter) factory = RequestFactoryNoCsrf() self.request = factory.get(chapter_url) self.request.user = UserFactory.create() @@ -1218,7 +1214,7 @@ class TestProctoringRendering(SharedModuleStoreTestCase): # we expect there not to be a 'proctoring' key in the dict assert 'proctoring' not in section_actual assert actual['previous_of_active_section'] is None - assert actual['next_of_active_section']['url_name'] == u'Welcome' + assert actual['next_of_active_section']['url_name'] == 'Welcome' @ddt.data( ( @@ -1344,8 +1340,8 @@ class TestProctoringRendering(SharedModuleStoreTestCase): ) exam_id = create_exam( - course_id=text_type(self.course_key), - content_id=text_type(sequence.location), + course_id=str(self.course_key), + content_id=str(sequence.location), exam_name='foo', time_limit_mins=10, is_proctored=True, @@ -1354,7 +1350,7 @@ class TestProctoringRendering(SharedModuleStoreTestCase): if attempt_status: attempt_id = create_exam_attempt( - six.text_type(exam_id).encode('utf-8'), + str(exam_id).encode('utf-8'), self.request.user.id, taking_as_proctored=True ) @@ -1392,7 +1388,7 @@ class TestGatedSubsectionRendering(SharedModuleStoreTestCase, MilestonesTestCase @classmethod def setUpClass(cls): - super(TestGatedSubsectionRendering, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() cls.course.enable_subsection_gating = True cls.course.save() @@ -1402,7 +1398,7 @@ class TestGatedSubsectionRendering(SharedModuleStoreTestCase, MilestonesTestCase """ Set up the initial test data """ - super(TestGatedSubsectionRendering, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.chapter = ItemFactory.create( parent=self.course, @@ -1419,7 +1415,7 @@ class TestGatedSubsectionRendering(SharedModuleStoreTestCase, MilestonesTestCase category='sequential', display_name="Gated Sequential" ) - self.request = RequestFactoryNoCsrf().get('%s/%s/%s' % ('/courses', self.course.id, self.chapter.display_name)) + self.request = RequestFactoryNoCsrf().get(f'/courses/{self.course.id}/{self.chapter.display_name}') self.request.user = UserFactory() self.field_data_cache = FieldDataCache.cache_for_descriptor_descendents( self.course.id, self.request.user, self.course, depth=2 @@ -1476,7 +1472,7 @@ class TestHtmlModifiers(ModuleStoreTestCase): """ def setUp(self): - super(TestHtmlModifiers, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course = CourseFactory.create() self.request = RequestFactoryNoCsrf().get('/') self.request.user = self.user @@ -1598,7 +1594,7 @@ class TestHtmlModifiers(ModuleStoreTestCase): ) result_fragment = module.render(STUDENT_VIEW) - assert '/courses/{course_id}/bar/content'.format(course_id=text_type(self.course.id)) in result_fragment.content + assert '/courses/{course_id}/bar/content'.format(course_id=str(self.course.id)) in result_fragment.content class XBlockWithJsonInitData(XBlock): @@ -1611,8 +1607,8 @@ class XBlockWithJsonInitData(XBlock): """ A simple view that returns just enough to test. """ - frag = Fragment(u"Hello there!") - frag.add_javascript(u'alert("Hi!");') + frag = Fragment("Hello there!") + frag.add_javascript('alert("Hi!");') frag.initialize_js('ThumbsBlock', self.the_json_data) return frag @@ -1659,7 +1655,7 @@ class DetachedXBlock(XBlock): """ A simple view that returns just enough to test. """ - frag = Fragment(u"Hello there!") + frag = Fragment("Hello there!") return frag @@ -1670,11 +1666,11 @@ class TestStaffDebugInfo(SharedModuleStoreTestCase): @classmethod def setUpClass(cls): - super(TestStaffDebugInfo, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() def setUp(self): - super(TestStaffDebugInfo, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create() self.request = RequestFactoryNoCsrf().get('/') self.request.user = self.user @@ -1865,12 +1861,12 @@ class TestAnonymousStudentId(SharedModuleStoreTestCase, LoginEnrollmentTestCase) @classmethod def setUpClass(cls): - super(TestAnonymousStudentId, cls).setUpClass() + super().setUpClass() cls.course_key = ToyCourseFactory.create().id cls.course = modulestore().get_course(cls.course_key) def setUp(self): - super(TestAnonymousStudentId, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory() @patch('lms.djangoapps.courseware.module_render.has_access', Mock(return_value=True, autospec=True)) @@ -1935,11 +1931,11 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): @classmethod def setUpClass(cls): - super(TestModuleTrackingContext, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() def setUp(self): - super(TestModuleTrackingContext, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create() self.request = RequestFactoryNoCsrf().get('/') @@ -1956,7 +1952,7 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): ) def test_context_contains_display_name(self, mock_tracker): - problem_display_name = u'Option Response Problem' + problem_display_name = 'Option Response Problem' module_info = self.handle_callback_and_get_module_info(mock_tracker, problem_display_name) assert problem_display_name == module_info['display_name'] @@ -1970,7 +1966,7 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): Check that related xblock asides populate information in the 'problem_check' event in case the 'get_event_context' method is exist """ - problem_display_name = u'Test Problem' + problem_display_name = 'Test Problem' def get_event_context(self, event_type, event): # pylint: disable=unused-argument """ @@ -2011,8 +2007,8 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): with patch('lms.djangoapps.courseware.module_render.tracker') as mock_tracker_for_context: render.handle_xblock_callback( self.request, - text_type(self.course.id), - quote_slashes(text_type(descriptor.location)), + str(self.course.id), + quote_slashes(str(descriptor.location)), 'xmodule_handler', 'problem_check', ) @@ -2051,15 +2047,15 @@ class TestModuleTrackingContext(SharedModuleStoreTestCase): information about their library block source in events. We patch the modulestore to avoid having to create a library. """ - original_usage_key = UsageKey.from_string(u'block-v1:A+B+C+type@problem+block@abcd1234') + original_usage_key = UsageKey.from_string('block-v1:A+B+C+type@problem+block@abcd1234') original_usage_version = ObjectId() mock_get_original_usage = lambda _, key: (original_usage_key, original_usage_version) with patch('xmodule.modulestore.mixed.MixedModuleStore.get_block_original_usage', mock_get_original_usage): module_info = self.handle_callback_and_get_module_info(mock_tracker) assert 'original_usage_key' in module_info - assert module_info['original_usage_key'] == text_type(original_usage_key) + assert module_info['original_usage_key'] == str(original_usage_key) assert 'original_usage_version' in module_info - assert module_info['original_usage_version'] == text_type(original_usage_version) + assert module_info['original_usage_version'] == str(original_usage_version) class TestXmoduleRuntimeEvent(TestSubmittingProblems): @@ -2068,7 +2064,7 @@ class TestXmoduleRuntimeEvent(TestSubmittingProblems): """ def setUp(self): - super(TestXmoduleRuntimeEvent, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.homework = self.add_graded_section_to_course('homework') self.problem = self.add_dropdown_to_section(self.homework.location, 'p1', 1) self.grade_dict = {'value': 0.18, 'max_value': 32} @@ -2120,8 +2116,8 @@ class TestXmoduleRuntimeEvent(TestSubmittingProblems): 'raw_earned': self.grade_dict['value'], 'weight': None, 'user_id': self.student_user.id, - 'course_id': text_type(self.course.id), - 'usage_id': text_type(self.problem.location), + 'course_id': str(self.course.id), + 'usage_id': str(self.problem.location), 'only_if_higher': None, 'modified': datetime.now().replace(tzinfo=pytz.UTC), 'score_db_table': 'csm', @@ -2138,7 +2134,7 @@ class TestRebindModule(TestSubmittingProblems): """ def setUp(self): - super(TestRebindModule, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.homework = self.add_graded_section_to_course('homework') self.lti = ItemFactory.create(category='lti', parent=self.homework) self.problem = ItemFactory.create(category='problem', parent=self.homework) @@ -2218,7 +2214,7 @@ class TestEventPublishing(ModuleStoreTestCase, LoginEnrollmentTestCase): """ Set up the course and user context """ - super(TestEventPublishing, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.mock_user = UserFactory() self.mock_user.id = 1 @@ -2254,14 +2250,14 @@ class LMSXBlockServiceBindingTest(SharedModuleStoreTestCase): @classmethod def setUpClass(cls): - super(LMSXBlockServiceBindingTest, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() def setUp(self): """ Set up the user and other fields that will be used to instantiate the runtime. """ - super(LMSXBlockServiceBindingTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory() self.student_data = Mock() self.track_function = Mock() @@ -2345,12 +2341,12 @@ class TestFilteredChildren(SharedModuleStoreTestCase): @classmethod def setUpClass(cls): - super(TestFilteredChildren, cls).setUpClass() + super().setUpClass() cls.course = CourseFactory.create() # pylint: disable=attribute-defined-outside-init def setUp(self): - super(TestFilteredChildren, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.users = {number: UserFactory() for number in USER_NUMBERS} self._old_has_access = render.has_access @@ -2429,7 +2425,7 @@ class TestFilteredChildren(SharedModuleStoreTestCase): ItemFactory(category=child_type, parent=self.parent).scope_ids.usage_id # lint-amnesty, pylint: disable=no-member for child_type in BLOCK_TYPES ] - for user in six.itervalues(self.users) + for user in self.users.values() } self.all_children = sum(list(self.children_for_user.values()), []) @@ -2487,7 +2483,7 @@ class TestFilteredChildren(SharedModuleStoreTestCase): """ Used to assert that sets of children are equivalent. """ - assert set(child_usage_ids) == set((child.scope_ids.usage_id for child in block.get_children())) + assert set(child_usage_ids) == {child.scope_ids.usage_id for child in block.get_children()} @ddt.ddt @@ -2497,7 +2493,7 @@ class TestDisabledXBlockTypes(ModuleStoreTestCase): """ def setUp(self): - super(TestDisabledXBlockTypes, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() XBlockConfiguration(name='video', enabled=False).save() @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) diff --git a/lms/djangoapps/courseware/tests/test_navigation.py b/lms/djangoapps/courseware/tests/test_navigation.py index b79d74375e..54282d0355 100644 --- a/lms/djangoapps/courseware/tests/test_navigation.py +++ b/lms/djangoapps/courseware/tests/test_navigation.py @@ -5,12 +5,10 @@ This test file will run through some LMS test scenarios regarding access and nav import time +from unittest.mock import patch from django.conf import settings from django.test.utils import override_settings from django.urls import reverse -from mock import patch -from six import text_type -from six.moves import range from edx_toggles.toggles.testutils import override_waffle_flag from lms.djangoapps.courseware.tests.factories import GlobalStaffFactory @@ -31,7 +29,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): @classmethod def setUpClass(cls): # pylint: disable=super-method-not-called - with super(TestNavigation, cls).setUpClassAndTestData(): + with super().setUpClassAndTestData(): cls.test_course = CourseFactory.create() cls.test_course_proctored = CourseFactory.create() cls.course = CourseFactory.create() @@ -75,12 +73,12 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): cls.user = UserFactory() def setUp(self): - super(TestNavigation, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # Create student accounts and activate them. for i in range(len(self.STUDENT_INFO)): email, password = self.STUDENT_INFO[i] - username = 'u{0}'.format(i) + username = f'u{i}' self.create_account(username, email, password) self.activate_user(email) @@ -89,7 +87,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): for line in response.content.decode('utf-8').split('\n'): if tabname in line and 'active' in line: return - raise AssertionError(u"assertTabActive failed: {} not active".format(tabname)) + raise AssertionError(f"assertTabActive failed: {tabname} not active") def assertTabInactive(self, tabname, response): # lint-amnesty, pylint: disable=useless-return ''' Check if the progress tab is active in the tab set ''' @@ -118,7 +116,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): ) for (displayname, accordion, tabs) in test_data: response = self.client.get(reverse('courseware_section', kwargs={ - 'course_id': text_type(self.course.id), + 'course_id': str(self.course.id), 'chapter': 'Chrome', 'section': displayname, })) @@ -129,7 +127,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.assertTabActive('courseware', response) response = self.client.get(reverse('courseware_section', kwargs={ - 'course_id': text_type(self.course.id), + 'course_id': str(self.course.id), 'chapter': 'Chrome', 'section': 'pdf_textbooks_tab', })) @@ -169,9 +167,9 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.enroll(self.test_course, True) resp = self.client.get(reverse('courseware', - kwargs={'course_id': text_type(self.course.id)})) + kwargs={'course_id': str(self.course.id)})) self.assertRedirects(resp, reverse( - 'courseware_section', kwargs={'course_id': text_type(self.course.id), + 'courseware_section', kwargs={'course_id': str(self.course.id), 'chapter': 'Overview', 'section': 'Welcome'})) @@ -188,14 +186,14 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): section_url = reverse( 'courseware_section', kwargs={ - 'course_id': text_type(self.course.id), + 'course_id': str(self.course.id), 'chapter': 'Overview', 'section': 'Welcome', }, ) self.client.get(section_url) resp = self.client.get( - reverse('courseware', kwargs={'course_id': text_type(self.course.id)}), + reverse('courseware', kwargs={'course_id': str(self.course.id)}), ) self.assertRedirects(resp, section_url) @@ -212,7 +210,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): section_url = reverse( 'courseware_section', kwargs={ - 'course_id': text_type(self.course.id), + 'course_id': str(self.course.id), 'chapter': 'factory_chapter', 'section': 'factory_section', } @@ -222,7 +220,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): # And now hitting the courseware tab should redirect to 'factory_chapter' url = reverse( 'courseware', - kwargs={'course_id': text_type(self.course.id)} + kwargs={'course_id': str(self.course.id)} ) resp = self.client.get(url) self.assertRedirects(resp, section_url) @@ -235,7 +233,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.login(email, password) self.enroll(self.test_course, True) - test_course_id = text_type(self.test_course.id) + test_course_id = str(self.test_course.id) url = reverse( 'courseware', @@ -289,7 +287,7 @@ class TestNavigation(SharedModuleStoreTestCase, LoginEnrollmentTestCase): self.login(email, password) self.enroll(self.test_course_proctored, True) - test_course_id = text_type(self.test_course_proctored.id) + test_course_id = str(self.test_course_proctored.id) with patch.dict(settings.FEATURES, {'ENABLE_SPECIAL_EXAMS': False}): url = reverse( diff --git a/lms/djangoapps/courseware/tests/test_rules.py b/lms/djangoapps/courseware/tests/test_rules.py index 015218b819..e09fb42bec 100644 --- a/lms/djangoapps/courseware/tests/test_rules.py +++ b/lms/djangoapps/courseware/tests/test_rules.py @@ -3,8 +3,8 @@ Tests for permissions defined in courseware.rules """ +from unittest.mock import patch import ddt -from mock import patch from common.djangoapps.course_modes.tests.factories import CourseModeFactory from common.djangoapps.student.models import CourseEnrollment diff --git a/lms/djangoapps/courseware/tests/test_self_paced_overrides.py b/lms/djangoapps/courseware/tests/test_self_paced_overrides.py index 83057e2ab3..a30ae41daa 100644 --- a/lms/djangoapps/courseware/tests/test_self_paced_overrides.py +++ b/lms/djangoapps/courseware/tests/test_self_paced_overrides.py @@ -2,9 +2,9 @@ import datetime +from unittest.mock import patch import pytz from django.test.utils import override_settings -from mock import patch from lms.djangoapps.courseware.access import has_access from lms.djangoapps.courseware.tests.factories import BetaTesterFactory @@ -28,7 +28,7 @@ class SelfPacedDateOverrideTest(ModuleStoreTestCase): def setUp(self): self.reset_setting_cache_variables() - super(SelfPacedDateOverrideTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.non_staff_user, __ = self.create_non_staff_user() self.now = datetime.datetime.now(pytz.UTC).replace(microsecond=0) @@ -36,7 +36,7 @@ class SelfPacedDateOverrideTest(ModuleStoreTestCase): def tearDown(self): self.reset_setting_cache_variables() - super(SelfPacedDateOverrideTest, self).tearDown() # lint-amnesty, pylint: disable=super-with-arguments + super().tearDown() def reset_setting_cache_variables(self): """ @@ -122,7 +122,7 @@ class SelfPacedDateOverrideTest(ModuleStoreTestCase): # Only the released xblocks should be visible when the course is instructor-paced. xblocks = get_accessible_discussion_xblocks(course, self.non_staff_user) - assert all(((xblock.display_name == 'released') for xblock in xblocks)) + assert all((xblock.display_name == 'released') for xblock in xblocks) @patch.dict('lms.djangoapps.courseware.access.settings.FEATURES', {'DISABLE_START_DATES': False}) def test_self_paced_discussion_xblock_visibility(self): @@ -136,4 +136,4 @@ class SelfPacedDateOverrideTest(ModuleStoreTestCase): # The scheduled xblocks should be visible when the course is self-paced. xblocks = get_accessible_discussion_xblocks(course, self.non_staff_user) assert len(xblocks) == 2 - assert any(((xblock.display_name == 'scheduled') for xblock in xblocks)) + assert any((xblock.display_name == 'scheduled') for xblock in xblocks) diff --git a/lms/djangoapps/courseware/tests/test_services.py b/lms/djangoapps/courseware/tests/test_services.py index 55cca7da79..17104f0252 100644 --- a/lms/djangoapps/courseware/tests/test_services.py +++ b/lms/djangoapps/courseware/tests/test_services.py @@ -24,7 +24,7 @@ class TestUserStateService(ModuleStoreTestCase): """ Creating pre-requisites for the test cases. """ - super(TestUserStateService, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory.create() self.course = CourseFactory.create() chapter = ItemFactory.create( diff --git a/lms/djangoapps/courseware/tests/test_split_module.py b/lms/djangoapps/courseware/tests/test_split_module.py index f0fdb0d65f..8a443c5349 100644 --- a/lms/djangoapps/courseware/tests/test_split_module.py +++ b/lms/djangoapps/courseware/tests/test_split_module.py @@ -3,10 +3,8 @@ Test for split test XModule """ -import six +from unittest.mock import MagicMock from django.urls import reverse -from mock import MagicMock -from six import text_type from lms.djangoapps.courseware.model_data import FieldDataCache from lms.djangoapps.courseware.module_render import get_module_for_descriptor @@ -30,7 +28,7 @@ class SplitTestBase(SharedModuleStoreTestCase): @classmethod def setUpClass(cls): - super(SplitTestBase, cls).setUpClass() + super().setUpClass() cls.partition = UserPartition( 0, 'first_partition', @@ -58,7 +56,7 @@ class SplitTestBase(SharedModuleStoreTestCase): ) def setUp(self): - super(SplitTestBase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.student = UserFactory.create() CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id) @@ -75,7 +73,7 @@ class SplitTestBase(SharedModuleStoreTestCase): return ItemFactory.create( parent_location=parent.location, category="video", - display_name=u"Group {} Sees This Video".format(group), + display_name=f"Group {group} Sees This Video", ) def _problem(self, parent, group): @@ -86,7 +84,7 @@ class SplitTestBase(SharedModuleStoreTestCase): return ItemFactory.create( parent_location=parent.location, category="problem", - display_name=u"Group {} Sees This Problem".format(group), + display_name=f"Group {group} Sees This Problem", data="

No Problem Defined Yet!

", ) @@ -98,8 +96,8 @@ class SplitTestBase(SharedModuleStoreTestCase): return ItemFactory.create( parent_location=parent.location, category="html", - display_name=u"Group {} Sees This HTML".format(group), - data=u"Some HTML for group {}".format(group), + display_name=f"Group {group} Sees This HTML", + data=f"Some HTML for group {group}", ) def test_split_test_0(self): @@ -114,30 +112,30 @@ class SplitTestBase(SharedModuleStoreTestCase): UserCourseTagFactory( user=self.student, course_id=self.course.id, - key='xblock.partition_service.partition_{0}'.format(self.partition.id), + key=f'xblock.partition_service.partition_{self.partition.id}', value=str(user_tag) ) resp = self.client.get(reverse( 'courseware_section', - kwargs={'course_id': text_type(self.course.id), + kwargs={'course_id': str(self.course.id), 'chapter': self.chapter.url_name, 'section': self.sequential.url_name} )) unicode_content = resp.content.decode(resp.charset) # Assert we see the proper icon in the top display - assert u'