refactor: pyupgrade second iteration (#27462)

This commit is contained in:
Usama Sadiq
2021-05-11 11:25:22 +05:00
committed by GitHub
parent 46993bff00
commit 13ef0c7762
14 changed files with 22 additions and 24 deletions

View File

@@ -107,7 +107,7 @@ class GoogleAnalyticsTrackingPixel:
param_name = fields.event_label.metadata['param_name']
parameters[param_name] = str(self.course_id)
return "https://www.google-analytics.com/collect?{params}".format(params=urlencode(parameters))
return f"https://www.google-analytics.com/collect?{urlencode(parameters)}"
def _get_tracking_id(self):
tracking_id = get_config_value_from_site_or_settings("GOOGLE_ANALYTICS_ACCOUNT", site=self.site)

View File

@@ -144,7 +144,7 @@ class Command(BaseCommand):
try:
_, created = ApiAccessConfig.objects.get_or_create(enabled=True)
except Exception as e:
msg = 'Unable to create ApiAccessConfig. Exception is {}: {}'.format(type(e).__name__, e)
msg = f'Unable to create ApiAccessConfig. Exception is {type(e).__name__}: {e}'
raise CommandError(msg) # lint-amnesty, pylint: disable=raise-missing-from
if created:

View File

@@ -156,7 +156,7 @@ def update_xblocks_cache(course_id):
# Ideally we'd like to accept a CourseLocator; however, CourseLocator is not JSON-serializable (by default) so
# Celery's delayed tasks fail to start. For this reason, callers should pass the course key as a Unicode string.
if not isinstance(course_id, str):
raise ValueError('course_id must be a string. {} is not acceptable.'.format(type(course_id)))
raise ValueError(f'course_id must be a string. {type(course_id)} is not acceptable.')
course_key = CourseKey.from_string(course_id)
log.info('Starting XBlockCaches update for course_key: %s', course_id)

View File

@@ -236,7 +236,7 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
)
# Assert Newly created bookmark.
assert response.data['id'] == ('{},{}'.format(self.user.username, str(self.vertical_2.location)))
assert response.data['id'] == (f'{self.user.username},{str(self.vertical_2.location)}')
assert response.data['course_id'] == self.course_id
assert response.data['usage_id'] == str(self.vertical_2.location)
assert response.data['created'] is not None
@@ -334,7 +334,7 @@ class BookmarksListViewTests(BookmarksViewsTestsBase):
def test_listed_event_for_different_page_size_values(self, mock_tracker, page_size, expected_bookmarks_count,
expected_page_size, expected_page_number):
""" Test that edx.course.bookmark.listed event values are as expected for different page size values """
query_parameters = 'course_id={}&page_size={}'.format(quote(self.course_id), page_size)
query_parameters = f'course_id={quote(self.course_id)}&page_size={page_size}'
self.send_get(client=self.client, url=reverse('bookmarks'), query_parameters=query_parameters)
@@ -468,7 +468,7 @@ class BookmarksDetailViewTests(BookmarksViewsTestsBase):
"""
Test that delete bookmark returns 204 status code with success.
"""
query_parameters = 'course_id={}'.format(quote(self.course_id))
query_parameters = f'course_id={quote(self.course_id)}'
response = self.send_get(client=self.client, url=reverse('bookmarks'), query_parameters=query_parameters)
bookmarks_data = response.data['results']
assert len(bookmarks_data) == 4

View File

@@ -110,25 +110,25 @@ class Command(BaseCommand):
))
cache.set(SITE_PATHWAY_IDS_CACHE_KEY_TPL.format(domain=site.domain), pathway_ids, None)
logger.info('Caching details for {} programs.'.format(len(programs)))
logger.info(f'Caching details for {len(programs)} programs.')
cache.set_many(programs, None)
logger.info('Caching details for {} pathways.'.format(len(pathways)))
logger.info(f'Caching details for {len(pathways)} pathways.')
cache.set_many(pathways, None)
logger.info('Caching programs uuids for {} courses.'.format(len(courses)))
logger.info(f'Caching programs uuids for {len(courses)} courses.')
cache.set_many(courses, None)
logger.info('Caching programs uuids for {} catalog courses.'.format(len(catalog_courses)))
logger.info(f'Caching programs uuids for {len(catalog_courses)} catalog courses.')
cache.set_many(catalog_courses, None)
logger.info(str('Caching program UUIDs by {} program types.'.format(len(programs_by_type))))
logger.info(str(f'Caching program UUIDs by {len(programs_by_type)} program types.'))
cache.set_many(programs_by_type, None)
logger.info(str('Caching program UUIDs by {} program type slugs.'.format(len(programs_by_type_slug))))
logger.info(str(f'Caching program UUIDs by {len(programs_by_type_slug)} program type slugs.'))
cache.set_many(programs_by_type_slug, None)
logger.info('Caching programs uuids for {} organizations'.format(len(organizations)))
logger.info(f'Caching programs uuids for {len(organizations)} organizations')
cache.set_many(organizations, None)
if failure:

View File

@@ -206,7 +206,7 @@ def get_programs_by_uuids(uuids):
missing_uuids = set(uuid_strings) - {program['uuid'] for program in programs}
if missing_uuids:
logger.info(
'Failed to get details for {count} programs. Retrying.'.format(count=len(missing_uuids))
f'Failed to get details for {len(missing_uuids)} programs. Retrying.'
)
retried_programs = cache.get_many([PROGRAM_CACHE_KEY_TPL.format(uuid=uuid) for uuid in missing_uuids])
@@ -287,7 +287,7 @@ def get_pathways(site, pathway_id=None):
missing_ids = set(pathway_ids) - {pathway['id'] for pathway in pathways}
if missing_ids:
logger.info(
'Failed to get details for {count} pathways. Retrying.'.format(count=len(missing_ids))
f'Failed to get details for {len(missing_ids)} pathways. Retrying.'
)
retried_pathways = cache.get_many(
@@ -330,7 +330,7 @@ def format_price(price, symbol='$', code='USD'):
:return: A formatted price string, i.e. '$10 USD', '$10.52 USD'.
"""
if int(price) == price:
return '{}{} {}'.format(symbol, int(price), code)
return f'{symbol}{int(price)} {code}'
return f'{symbol}{price:0.2f} {code}'

View File

@@ -1,4 +1,3 @@
from contextlib import contextmanager
from datetime import datetime

View File

@@ -247,7 +247,7 @@ class BlockStructureModel(TimeStampedModel):
Returns a string representation of this model.
"""
return ', '.join(
'{}: {}'.format(field_name, str(getattr(self, field_name)))
f'{field_name}: {str(getattr(self, field_name))}'
for field_name in self.UNIQUENESS_FIELDS
)

View File

@@ -128,7 +128,7 @@ class Command(BaseCommand):
)
continue
elif count != 0:
raise Exception("Database count: {} does not match input count: {}".format(count, len(ids)))
raise Exception(f"Database count: {count} does not match input count: {len(ids)}")
values = [[row[column.upper()] for column in columns] for row in rows]

View File

@@ -306,7 +306,7 @@ class Command(BaseCommand):
for course_key in course_keys[:COURSES_TO_SHOW]:
print(" ", course_key)
if len(course_keys) > COURSES_TO_SHOW:
print(" (+ {} more)".format(len(course_keys) - COURSES_TO_SHOW))
print(f" (+ {len(course_keys) - COURSES_TO_SHOW} more)")
def get_receiver_names():

View File

@@ -14,7 +14,6 @@ from django.contrib.auth.models import AnonymousUser, User # lint-amnesty, pyli
from django.db.models import signals
from edx_proctoring.exceptions import ProctoredExamNotFoundException
from edx_when.api import set_dates_for_course
from mock import patch # lint-amnesty, pylint: disable=reimported
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locator import LibraryLocator
from edx_toggles.toggles.testutils import override_waffle_flag

View File

@@ -83,7 +83,7 @@ class ContentLibrary(models.Model):
return LibraryLocatorV2(org=self.org.short_name, slug=self.slug)
def __str__(self):
return "ContentLibrary ({})".format(str(self.library_key))
return f"ContentLibrary ({str(self.library_key)})"
class ContentLibraryPermission(models.Model):

View File

@@ -75,7 +75,7 @@ class BaseCoursewareTests(SharedModuleStoreTestCase):
)
cls.instructor = UserFactory(
username='instructor',
email=u'instructor@example.com',
email='instructor@example.com',
password='foo',
is_staff=False
)

View File

@@ -4,7 +4,7 @@ Tests for the create_credentials_api_configuration command
from unittest import TestCase
import mock
from unittest import mock
import pytest
from django.core.management import call_command