Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Aug 6, 2024
1 parent 7606bd8 commit 4450d42
Show file tree
Hide file tree
Showing 43 changed files with 84 additions and 91 deletions.
2 changes: 1 addition & 1 deletion authentication/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def process_exception(self, request, exception):
url = self.get_redirect_uri(request, exception)

if url: # noqa: RET503
url += ("?" in url and "&" or "?") + "message={}&backend={}".format( # noqa: UP030, UP032
url += ("?" in url and "&" or "?") + "message={}&backend={}".format( # noqa: UP032
quote(message), backend_name
)
return redirect(url)
2 changes: 1 addition & 1 deletion authentication/pipeline/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def create_user_via_email(
created_user = create_user_with_generated_username(serializer, username)
if created_user is None:
raise IntegrityError( # noqa: TRY301
f"Failed to create User with generated username ({username})" # noqa: EM103, UP032
f"Failed to create User with generated username ({username})"
)
except Exception as exc:
raise UserCreationFailedException(backend, current_partial) from exc
Expand Down
6 changes: 3 additions & 3 deletions cms/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ def get_context(self, request, *args, **kwargs):
.exclude(Q(category=UPCOMING_WEBINAR) & Q(date__lt=now_in_utc().date()))
.order_by("-category", "date")
)
webinars_dict = defaultdict(list) # noqa: PIE807
webinars_dict = defaultdict(list)
for webinar in webinars:
webinar.detail_page_url = webinar.detail_page_url(request)
webinars_dict[webinar.category].append(webinar)
Expand Down Expand Up @@ -1026,7 +1026,7 @@ def get_url_parts(self, request=None):
# of the Course/Program instead (e.g.: "/courses/course-v1:edX+DemoX+Demo_Course")
re.sub(
self.slugged_page_path_pattern,
fr"\1{self.product.readable_id}\3", # noqa: UP032
rf"\1{self.product.readable_id}\3",
url_parts[2],
),
)
Expand Down Expand Up @@ -1505,7 +1505,7 @@ class Meta:
def can_create_at(cls, parent):
# You can only create one of these page under course / program.
return (
super().can_create_at(parent) # noqa: UP008
super().can_create_at(parent)
and parent.get_children().type(cls).count() == 0
)

Expand Down
4 changes: 2 additions & 2 deletions compliance/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ def mock_cybersource_wsdl(mocked_responses, settings, service_version=SERVICE_VE
Mocks the responses to achieve a functional WSDL
"""
# in order for zeep to load the wsdl, it will load the wsdl and the accompanying xsd definitions
with open(f"{DATA_DIR}/CyberSourceTransaction_{service_version}.wsdl") as wsdl: # noqa: PTH123, UP015
with open(f"{DATA_DIR}/CyberSourceTransaction_{service_version}.wsdl") as wsdl: # noqa: PTH123
mocked_responses.add(
mocked_responses.GET,
settings.CYBERSOURCE_WSDL_URL,
body=wsdl.read(),
status=status.HTTP_200_OK,
)
with open(f"{DATA_DIR}/CyberSourceTransaction_{SERVICE_VERSION}.xsd") as xsd: # noqa: PTH123, UP015
with open(f"{DATA_DIR}/CyberSourceTransaction_{SERVICE_VERSION}.xsd") as xsd: # noqa: PTH123
mocked_responses.add(
mocked_responses.GET,
f"http://localhost/service/CyberSourceTransaction_{service_version}.xsd",
Expand Down
4 changes: 2 additions & 2 deletions courses/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def get_user_enrollments(user):
for program_enrollment in program_enrollments
)
)
program_course_ids = {course.id for course in program_courses} # noqa: C401
program_course_ids = {course.id for course in program_courses}
course_run_enrollments = (
CourseRunEnrollment.objects.select_related("run__course__coursepage", "company")
.filter(user=user)
Expand Down Expand Up @@ -316,7 +316,7 @@ def defer_enrollment(
to_run = CourseRun.objects.get(courseware_id=to_courseware_id)
if from_enrollment.run == to_run:
raise ValidationError(
f"Cannot defer to the same course run (run: {to_run.courseware_id})" # noqa: EM103, UP032
f"Cannot defer to the same course run (run: {to_run.courseware_id})"
)
if not force and not to_run.is_not_beyond_enrollment:
raise ValidationError(
Expand Down
3 changes: 1 addition & 2 deletions courses/credentials.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Digital courseware credentials"""

import logging
from typing import Union
from urllib.parse import urljoin

from django.conf import settings
Expand Down Expand Up @@ -81,7 +80,7 @@ def build_course_run_credential(certificate: CourseRunCertificate) -> dict:


def build_digital_credential(
certificate: ProgramCertificate | CourseRunCertificate, # noqa: FA100
certificate: ProgramCertificate | CourseRunCertificate,
learner_did: LearnerDID,
) -> dict:
"""Function for building certificate digital credentials"""
Expand Down
4 changes: 2 additions & 2 deletions courses/management/commands/defer_enrollment.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ def handle(self, *args, **options): # noqa: ARG002
if isinstance(exc, CourseRunEnrollment.DoesNotExist):
message = f"'from' course run enrollment does not exist ({from_courseware_id})"
elif isinstance(exc, CourseRun.DoesNotExist):
message = f"'to' course does not exist ({to_courseware_id})" # noqa: UP032
message = f"'to' course does not exist ({to_courseware_id})"
else:
message = str(exc)
raise CommandError(message) # noqa: B904, TRY200
except ValidationError as exc:
raise CommandError(f"Invalid enrollment deferral - {exc}") # noqa: B904, EM103, TRY200, UP032
raise CommandError(f"Invalid enrollment deferral - {exc}") # noqa: B904, TRY200
else:
if not to_enrollment:
raise CommandError(
Expand Down
2 changes: 1 addition & 1 deletion courses/management/commands/revoke_certificate.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def handle(self, *args, **options): # noqa: ARG002

if updated:
msg = "Certificate for {} has been {}".format(
f"run: {run}" if run else f"program: {program}", # noqa: UP032
f"run: {run}" if run else f"program: {program}",
"revoked" if revoke else "un-revoked",
)
self.stdout.write(self.style.SUCCESS(msg))
Expand Down
4 changes: 2 additions & 2 deletions courses/management/commands/sync_grades_and_certificates.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,10 @@ def handle( # noqa: C901, PLR0915
else:
grade_status = "already exists"

grade_summary = [f"passed: {course_run_grade.passed}"] # noqa: UP032
grade_summary = [f"passed: {course_run_grade.passed}"]
if override_grade is not None:
grade_summary.append(
f"value override: {course_run_grade.grade}" # noqa: UP032
f"value override: {course_run_grade.grade}"
)

if created_cert:
Expand Down
2 changes: 1 addition & 1 deletion courses/management/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def fetch_enrollment(user, command_options):
enrollment = CourseRunEnrollment.all_objects.filter(**query_params).first()

if not enrollment:
raise CommandError(f"Enrollment not found for: {enrolled_obj}") # noqa: EM103, UP032
raise CommandError(f"Enrollment not found for: {enrolled_obj}")
if not enrollment.active and not force:
raise CommandError(
"The given enrollment is not active ({}).\n" # noqa: EM103, UP032, RUF100
Expand Down
2 changes: 1 addition & 1 deletion courses/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def catalog_image_url(self):


validate_url_path_field = RegexValidator(
fr"^[{detail_path_char_pattern}]+$", # noqa: UP032
rf"^[{detail_path_char_pattern}]+$",
f"This field is used to produce URL paths. It must contain only characters that match this pattern: [{detail_path_char_pattern}]",
)

Expand Down
2 changes: 1 addition & 1 deletion courses/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ def get_instructors(self, instance):

def get_topics(self, instance):
"""List all topics in all courses in the program"""
topics = { # noqa: C401
topics = {
topic.name
for course in instance.courses.all()
if course.page
Expand Down
8 changes: 4 additions & 4 deletions courses/views_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,11 +283,11 @@ def test_course_view( # noqa: PLR0913
class_name = "enrolled"

assert (
f'<a class="enroll-button {class_name}" href="{url}">'.encode() # noqa: UP012
f'<a class="enroll-button {class_name}" href="{url}">'.encode()
in resp.content
) is has_button
assert (
b"Please Sign In to MITx PRO to enroll in a course" # noqa: UP012
b"Please Sign In to MITx PRO to enroll in a course"
in resp.content
) is (is_anonymous and has_product and has_unexpired_run)

Expand Down Expand Up @@ -349,11 +349,11 @@ def test_program_view( # noqa: PLR0913
class_name = "enrolled"

assert (
f'<a class="enroll-button {class_name}" href="{url}">'.encode() # noqa: UP012
f'<a class="enroll-button {class_name}" href="{url}">'.encode()
in resp.content
) is has_button
assert (
b"Please Sign In to MITx PRO to enroll in a course" # noqa: UP012
b"Please Sign In to MITx PRO to enroll in a course"
in resp.content
) is (is_anonymous and has_product and has_unexpired_run)

Expand Down
4 changes: 2 additions & 2 deletions courseware/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ def get_edx_api_client(user, ttl_in_seconds=OPENEDX_AUTH_DEFAULT_TTL_IN_SECONDS)
auth = get_valid_edx_api_auth(user, ttl_in_seconds=ttl_in_seconds)
except OpenEdxApiAuth.DoesNotExist:
raise NoEdxApiAuthError( # noqa: B904, TRY200
f"{str(user)} does not have an associated OpenEdxApiAuth" # noqa: EM103, UP032
f"{user!s} does not have an associated OpenEdxApiAuth"
)
return EdxApi(
{"access_token": auth.access_token},
Expand Down Expand Up @@ -799,7 +799,7 @@ def create_oauth_application():
defaults=dict( # noqa: C408
redirect_uris=urljoin(
settings.OPENEDX_BASE_REDIRECT_URL,
f"/auth/complete/{settings.MITXPRO_OAUTH_PROVIDER}/", # noqa: UP032
f"/auth/complete/{settings.MITXPRO_OAUTH_PROVIDER}/",
),
client_type="confidential",
authorization_grant_type="authorization-code",
Expand Down
17 changes: 8 additions & 9 deletions ecommerce/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
import uuid
from base64 import b64encode
from collections import defaultdict
from datetime import timedelta
from typing import NamedTuple, Optional # noqa: UP035
from collections.abc import Iterable
from datetime import timedelta
from typing import NamedTuple
from urllib.parse import quote_plus, urljoin

from django.conf import settings
Expand Down Expand Up @@ -792,10 +792,9 @@ def enroll_user_in_order_items(order):
):
voucher_target = voucher.product.content_object
voucher_enrollment = first_or_none(
# noqa: UP034
enrollment
for enrollment in successful_run_enrollments
if enrollment.run == voucher_target
enrollment
for enrollment in successful_run_enrollments
if enrollment.run == voucher_target
)
if voucher_enrollment is not None:
voucher.enrollment = voucher_enrollment
Expand Down Expand Up @@ -954,9 +953,9 @@ class ValidatedBasket(NamedTuple):
basket: Basket
basket_item: BasketItem
product_version: ProductVersion
coupon_version: CouponVersion | None # noqa: FA100
run_selection_ids: Iterable[int] | None # noqa: FA100
data_consent_users: Iterable[DataConsentUser] | None # noqa: FA100
coupon_version: CouponVersion | None
run_selection_ids: Iterable[int] | None
data_consent_users: Iterable[DataConsentUser] | None


def _validate_basket_contents(basket):
Expand Down
8 changes: 4 additions & 4 deletions ecommerce/api_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -705,9 +705,9 @@ def test_get_by_reference_number(
same_order = Order.objects.get_by_reference_number(order.reference_number)
assert same_order.id == order.id
if hubspot_api_key:
mock_hubspot_syncs.order.assert_called_with(order.id) # noqa: PGH005
mock_hubspot_syncs.order.assert_called_with(order.id)
else:
mock_hubspot_syncs.order.assert_not_called() # noqa: PGH005
mock_hubspot_syncs.order.assert_not_called()


def test_get_by_reference_number_missing(validated_basket):
Expand Down Expand Up @@ -771,9 +771,9 @@ def test_create_unfulfilled_order( # noqa: PLR0913
assert CouponRedemption.objects.count() == 0

if hubspot_api_key:
mock_hubspot_syncs.order.assert_called_with(order.id) # noqa: PGH005
mock_hubspot_syncs.order.assert_called_with(order.id)
else:
mock_hubspot_syncs.order.assert_not_called() # noqa: PGH005
mock_hubspot_syncs.order.assert_not_called()


@pytest.mark.parametrize("has_program_run", [True, False])
Expand Down
4 changes: 1 addition & 3 deletions ecommerce/mail_api_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,7 @@ def test_send_course_run_enrollment_welcome_email(settings, mocker, enabled):
enrollment = CourseRunEnrollmentFactory.create()

run_start_date = enrollment.run.start_date
run_start_time = run_start_date.astimezone(datetime.UTC).strftime(
EMAIL_TIME_FORMAT
)
run_start_time = run_start_date.astimezone(datetime.UTC).strftime(EMAIL_TIME_FORMAT)
run_end_date = enrollment.run.end_date
date_range = (
f"{run_start_date.strftime(EMAIL_DATE_FORMAT)} - "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def handle(self, *args, **kwargs): # noqa: ARG002
codes = Coupon.objects.filter(enabled=True, payment=payment).all()
else:
try:
with open(kwargs["codefile"]) as file: # noqa: PTH123, UP015
with open(kwargs["codefile"]) as file: # noqa: PTH123
procCodes = [line.strip() for line in file]
except Exception as e: # noqa: BLE001
raise CommandError( # noqa: B904, TRY200
Expand Down
8 changes: 4 additions & 4 deletions ecommerce/views_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,9 +225,9 @@ def test_zero_price_checkout( # noqa: PLR0913
assert CourseRunSelection.objects.filter(basket__user=user).count() == 0
assert CouponSelection.objects.filter(basket__user=user).count() == 0
if hubspot_api_key:
mock_hubspot_syncs.order.assert_called_with(order.id) # noqa: PGH005
mock_hubspot_syncs.order.assert_called_with(order.id)
else:
mock_hubspot_syncs.order.assert_not_called() # noqa: PGH005
mock_hubspot_syncs.order.assert_not_called()


@pytest.mark.parametrize("hubspot_api_key", [None, "fake-key"])
Expand Down Expand Up @@ -287,9 +287,9 @@ def test_order_fulfilled( # noqa: PLR0913
assert CouponSelection.objects.filter(basket__user=user).count() == 0

if hubspot_api_key:
mock_hubspot_syncs.order.assert_called_with(order.id) # noqa: PGH005
mock_hubspot_syncs.order.assert_called_with(order.id)
else:
mock_hubspot_syncs.order.assert_not_called() # noqa: PGH005
mock_hubspot_syncs.order.assert_not_called()


def test_order_affiliate(basket_client, mocker, basket_and_coupons):
Expand Down
2 changes: 1 addition & 1 deletion localdev/seed/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def check_settings():
missing.append(variable)
if missing:
raise ImproperlyConfigured(
f"Missing required voucher settings: {missing}" # noqa: EM103, UP032
f"Missing required voucher settings: {missing}"
)


Expand Down
2 changes: 1 addition & 1 deletion localdev/seed/management/commands/delete_seed_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,4 @@ def handle(self, *args, **options): # noqa: ARG002
else:
self.stdout.write(self.style.SUCCESS("RESULTS"))
for k, v in results.report.items():
self.stdout.write(f"{k}: {v}") # noqa: UP032
self.stdout.write(f"{k}: {v}")
2 changes: 1 addition & 1 deletion localdev/seed/management/commands/seed_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ def handle(self, *args, **options): # noqa: ARG002
else:
self.stdout.write(self.style.SUCCESS("RESULTS"))
for k, v in results.report.items():
self.stdout.write(f"{k}: {v}") # noqa: UP032
self.stdout.write(f"{k}: {v}")
2 changes: 1 addition & 1 deletion mitxpro/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""

import copy
from collections.abc import Iterable # noqa: UP035
from collections.abc import Iterable

from django.conf import settings
from django.core.exceptions import ValidationError
Expand Down
6 changes: 3 additions & 3 deletions mitxpro/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@
DEFAULT_DATABASE_CONFIG = dj_database_url.parse(
get_string(
name="DATABASE_URL",
default="sqlite:///{}".format(os.path.join(BASE_DIR, "db.sqlite3")), # noqa: PTH118, UP030
default="sqlite:///{}".format(os.path.join(BASE_DIR, "db.sqlite3")), # noqa: PTH118
description="The connection url to the Postgres database",
required=True,
write_app_json=False,
Expand Down Expand Up @@ -426,7 +426,7 @@
)
if CLOUDFRONT_DIST:
STATIC_URL = urljoin(
f"https://{CLOUDFRONT_DIST}.cloudfront.net", # noqa: UP032
f"https://{CLOUDFRONT_DIST}.cloudfront.net",
STATIC_URL,
)

Expand Down Expand Up @@ -682,7 +682,7 @@
)
if MITXPRO_USE_S3:
if CLOUDFRONT_DIST:
AWS_S3_CUSTOM_DOMAIN = f"{CLOUDFRONT_DIST}.cloudfront.net" # noqa: UP032
AWS_S3_CUSTOM_DOMAIN = f"{CLOUDFRONT_DIST}.cloudfront.net"
DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"

FEATURES = get_features()
Expand Down
2 changes: 1 addition & 1 deletion mitxpro/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def create_tempfile_csv(rows_iter):
writer = csv.writer(f, delimiter=",")
for row in rows_iter:
writer.writerow(row)
with open(f.name) as user_csv: # noqa: PTH123, UP015
with open(f.name) as user_csv: # noqa: PTH123
return SimpleUploadedFile(
f.name, user_csv.read().encode("utf8"), content_type="application/csv"
)
Expand Down
2 changes: 1 addition & 1 deletion repl.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
for app in settings.INSTALLED_APPS:
try: # noqa: SIM105
exec( # noqa: S102
f"from {app}.models import *" # noqa: UP032
f"from {app}.models import *"
)
except ModuleNotFoundError: # noqa: PERF203
pass
2 changes: 1 addition & 1 deletion sheets/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def get_metadata_for_matching_files(self, query, file_fields="id, name"):
)
return self.pygsheets_client.drive.list(
**extra_list_params,
fields=f"files({file_fields})", # noqa: UP032
fields=f"files({file_fields})",
q=query,
)

Expand Down
Loading

0 comments on commit 4450d42

Please sign in to comment.