refactor: pyupgrade second iteration (#27441)

This commit is contained in:
Usama Sadiq
2021-05-03 17:11:32 +05:00
committed by GitHub
parent 4a0731ce61
commit 11ec4a9aaa
14 changed files with 25 additions and 25 deletions

View File

@@ -34,7 +34,7 @@ class WikiAccessMiddleware(MiddlewareMixin):
# See if we are able to view the course. If we are, redirect to it
try:
get_course_overview_with_access(request.user, 'load', course_id)
return redirect("/courses/{course_id}/wiki/{path}".format(course_id=str(course_id), path=wiki_path)) # lint-amnesty, pylint: disable=line-too-long
return redirect(f"/courses/{str(course_id)}/wiki/{wiki_path}") # lint-amnesty, pylint: disable=line-too-long
except Http404:
# Even though we came from the course, we can't see it. So don't worry about it.
pass
@@ -57,7 +57,7 @@ class WikiAccessMiddleware(MiddlewareMixin):
if course_id:
# This is a /courses/org/name/run/wiki request
course_path = "/courses/{}".format(str(course_id))
course_path = f"/courses/{str(course_id)}"
# HACK: django-wiki monkeypatches the reverse function to enable
# urls to be rewritten
reverse._transform_url = lambda url: course_path + url # pylint: disable=protected-access

View File

@@ -769,7 +769,7 @@ def get_cms_course_link(course, page='course'):
"""
# This is fragile, but unfortunately the problem is that within the LMS we
# can't use the reverse calls from the CMS
return "//{}/{}/{}".format(settings.CMS_BASE, page, str(course.id))
return f"//{settings.CMS_BASE}/{page}/{str(course.id)}"
def get_cms_block_link(block, page):

View File

@@ -384,7 +384,7 @@ class OfflineComputedGradeLog(models.Model):
nstudents = models.IntegerField(default=0)
def __str__(self):
return "[OCGLog] {}: {}".format(str(self.course_id), self.created)
return f"[OCGLog] {str(self.course_id)}: {self.created}"
class StudentFieldOverride(TimeStampedModel):

View File

@@ -117,7 +117,7 @@ class ProgressTab(EnrolledTab):
return reverse_func(self.view_name, args=[str(course.id)])
tab_dict['link_func'] = link_func
super(ProgressTab, self).__init__(tab_dict) # pylint: disable=super-with-arguments
super().__init__(tab_dict) # pylint: disable=super-with-arguments
@classmethod
def is_enabled(cls, course, user=None):

View File

@@ -71,9 +71,9 @@ class CoursesTest(ModuleStoreTestCase):
org='org', number='num', display_name='name'
)
cms_url = "//{}/course/{}".format(CMS_BASE_TEST, str(self.course.id))
cms_url = f"//{CMS_BASE_TEST}/course/{str(self.course.id)}"
assert cms_url == get_cms_course_link(self.course)
cms_url = "//{}/course/{}".format(CMS_BASE_TEST, str(self.course.location))
cms_url = f"//{CMS_BASE_TEST}/course/{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)

View File

@@ -246,8 +246,8 @@ class TestTemplates(TestDiscussionXBlock):
fragment = self.block.student_view()
read_only = 'false' if permissions[0] else 'true'
assert f'data-discussion-id="{self.discussion_id}"' in fragment.content
assert 'data-user-create-comment="{}"'.format(json.dumps(permissions[1])) in fragment.content
assert 'data-user-create-subcomment="{}"'.format(json.dumps(permissions[2])) in fragment.content
assert f'data-user-create-comment="{json.dumps(permissions[1])}"' in fragment.content
assert f'data-user-create-subcomment="{json.dumps(permissions[2])}"' in fragment.content
assert f'data-read-only="{read_only}"' in fragment.content

View File

@@ -538,7 +538,7 @@ class EntranceExamTestCases(LoginEnrollmentTestCase, ModuleStoreTestCase, Milest
Tests entrance exam xblock has `entrance_exam_passed` key in json response.
"""
request_factory = RequestFactoryNoCsrf()
data = {'input_{}_2_1'.format(str(self.problem_1.location.html_id())): 'choice_2'}
data = {f'input_{str(self.problem_1.location.html_id())}_2_1': 'choice_2'}
request = request_factory.post(
'problem_check',
data=data

View File

@@ -42,7 +42,7 @@ class TestLTI(BaseTestXmodule):
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 = str(urllib.parse.quote('{}-{}'.format(hostname, self.item_descriptor.location.html_id())))
resource_link_id = str(urllib.parse.quote(f'{hostname}-{self.item_descriptor.location.html_id()}'))
sourcedId = "{context}:{resource_link}:{user_id}".format(
context=urllib.parse.quote(context_id),

View File

@@ -1592,7 +1592,7 @@ class TestHtmlModifiers(ModuleStoreTestCase):
)
result_fragment = module.render(STUDENT_VIEW)
assert '/courses/{course_id}/bar/content'.format(course_id=str(self.course.id)) in result_fragment.content
assert f'/courses/{str(self.course.id)}/bar/content' in result_fragment.content
class XBlockWithJsonInitData(XBlock):

View File

@@ -125,7 +125,7 @@ class SplitTestBase(SharedModuleStoreTestCase):
unicode_content = resp.content.decode(resp.charset)
# Assert we see the proper icon in the top display
assert '<button class="{} inactive nav-item tab"'.format(self.ICON_CLASSES[user_tag]) in unicode_content
assert f'<button class="{self.ICON_CLASSES[user_tag]} inactive nav-item tab"' in unicode_content
# And proper tooltips
for tooltip in self.TOOLTIPS[user_tag]:

View File

@@ -382,7 +382,7 @@ class EntranceExamsTabsTestCase(LoginEnrollmentTestCase, ModuleStoreTestCase, Mi
)
milestone = {
'name': 'Test Milestone',
'namespace': '{}.entrance_exams'.format(str(self.course.id)),
'namespace': f'{str(self.course.id)}.entrance_exams',
'description': 'Testing Courseware Tabs'
}
self.user.is_staff = False

View File

@@ -585,7 +585,7 @@ class ViewsTestCase(BaseViewsTestCase):
if enrollment:
self.assertRedirects(response, courseware_url)
else:
self.assertRedirects(response, '/courses/{}/about'.format(str(self.course_key)))
self.assertRedirects(response, f'/courses/{str(self.course_key)}/about')
def test_enroll_staff_with_invalid_data(self):
"""
@@ -596,7 +596,7 @@ class ViewsTestCase(BaseViewsTestCase):
__, enroll_url = self._create_url_for_enroll_staff()
response = self.client.post(enroll_url, data={'test': "test"})
assert response.status_code == 302
self.assertRedirects(response, '/courses/{}/about'.format(str(self.course_key)))
self.assertRedirects(response, f'/courses/{str(self.course_key)}/about')
def assert_enrollment_link_present(self, is_anonymous):
"""

View File

@@ -1390,7 +1390,7 @@ def submission_history(request, course_id, learner_identifier, location):
try:
history_entries = list(user_state_client.get_history(found_user_name, usage_key))
except DjangoXBlockUserStateClient.DoesNotExist:
return HttpResponse(escape(_(u'User {username} has never accessed problem {location}').format(
return HttpResponse(escape(_('User {username} has never accessed problem {location}').format(
username=found_user_name,
location=location
)))
@@ -1720,7 +1720,7 @@ def render_xblock(request, usage_key_string, check_if_enrolled=True):
requested_view = request.GET.get('view', 'student_view')
if requested_view != 'student_view' and requested_view != 'public_view': # lint-amnesty, pylint: disable=consider-using-in
return HttpResponseBadRequest(
"Rendering of the xblock view '{}' is not supported.".format(bleach.clean(requested_view, strip=True))
f"Rendering of the xblock view '{bleach.clean(requested_view, strip=True)}' is not supported."
)
staff_access = has_access(request.user, 'staff', course_key)
@@ -1954,7 +1954,7 @@ def financial_assistance_request(request):
return HttpResponseBadRequest('Could not parse request course key.')
except KeyError as err:
# Thrown if fields are missing
return HttpResponseBadRequest('The field {} is required.'.format(str(err)))
return HttpResponseBadRequest(f'The field {str(err)} is required.')
zendesk_submitted = create_zendesk_ticket(
legal_name,

View File

@@ -161,7 +161,7 @@ class CoursewareContextTestCase(ModuleStoreTestCase):
def assertThreadCorrect(thread, discussion, expected_title): # pylint: disable=invalid-name
"""Asserts that the given thread has the expected set of properties"""
assert set(thread.keys()) == set(['commentable_id', 'courseware_url', 'courseware_title'])
assert set(thread.keys()) == {'commentable_id', 'courseware_url', 'courseware_title'}
assert thread.get('courseware_url') == reverse('jump_to', kwargs={'course_id': str(self.course.id), 'location': str(discussion.location)})
assert thread.get('courseware_title') == expected_title
@@ -652,16 +652,16 @@ class CategoryMapTestCase(CategoryMapTestMixin, ModuleStoreTestCase):
category_map = utils.get_discussion_category_map(self.course, self.user)
chapter1 = category_map["subcategories"]["Chapter 1"]
chapter1_discussions = set(["Discussion A", "Discussion B", "Discussion A (1)", "Discussion A (2)"])
chapter1_discussions_with_types = set([("Discussion A", TYPE_ENTRY), ("Discussion B", TYPE_ENTRY),
("Discussion A (1)", TYPE_ENTRY), ("Discussion A (2)", TYPE_ENTRY)])
chapter1_discussions = {"Discussion A", "Discussion B", "Discussion A (1)", "Discussion A (2)"}
chapter1_discussions_with_types = {("Discussion A", TYPE_ENTRY), ("Discussion B", TYPE_ENTRY),
("Discussion A (1)", TYPE_ENTRY), ("Discussion A (2)", TYPE_ENTRY)}
assert set(chapter1['children']) == chapter1_discussions_with_types
assert set(chapter1['entries'].keys()) == chapter1_discussions
chapter2 = category_map["subcategories"]["Chapter 2"]
subsection1 = chapter2["subcategories"]["Section 1"]["subcategories"]["Subsection 1"]
subsection1_discussions = set(["Discussion", "Discussion (1)"])
subsection1_discussions_with_types = set([("Discussion", TYPE_ENTRY), ("Discussion (1)", TYPE_ENTRY)])
subsection1_discussions = {"Discussion", "Discussion (1)"}
subsection1_discussions_with_types = {("Discussion", TYPE_ENTRY), ("Discussion (1)", TYPE_ENTRY)}
assert set(subsection1['children']) == subsection1_discussions_with_types
assert set(subsection1['entries'].keys()) == subsection1_discussions