Skip to content

Commit

Permalink
Enable ruff's UP (pyupgrade) set of rules
Browse files Browse the repository at this point in the history
  • Loading branch information
marcospri committed Oct 24, 2024
1 parent 8f708be commit 8ae69dd
Show file tree
Hide file tree
Showing 30 changed files with 68 additions and 70 deletions.
2 changes: 1 addition & 1 deletion lms/config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Configuration for the Pyramid application."""

import os
from collections.abc import Callable
from dataclasses import dataclass
from typing import Callable

from pyramid.config import Configurator
from pyramid.config import aslist as _aslist
Expand Down
4 changes: 2 additions & 2 deletions lms/error_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
We have them in their own module to avoid any circular dependency problems.
"""

from enum import Enum
from enum import Enum, StrEnum


class ErrorCode(str, Enum):
class ErrorCode(StrEnum):
BLACKBOARD_MISSING_INTEGRATION = "blackboard_missing_integration"
CANVAS_INVALID_SCOPE = "canvas_invalid_scope"
VITALSOURCE_STUDENT_PAY_NO_LICENSE = "vitalsource_student_pay_no_license"
Expand Down
4 changes: 2 additions & 2 deletions lms/models/event.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from enum import Enum
from enum import Enum, StrEnum

import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB
Expand All @@ -11,7 +11,7 @@
class EventType(Base):
__tablename__ = "event_type"

class Type(str, Enum):
class Type(StrEnum):
CONFIGURED_LAUNCH = "configured_launch"
DEEP_LINKING = "deep_linking"
AUDIT_TRAIL = "audit"
Expand Down
4 changes: 2 additions & 2 deletions lms/models/grouping.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from enum import Enum
from enum import Enum, StrEnum
from typing import TYPE_CHECKING, TypedDict

import sqlalchemy as sa
Expand All @@ -18,7 +18,7 @@


class Grouping(CreatedUpdatedMixin, Base):
class Type(str, Enum):
class Type(StrEnum):
COURSE = "course"
CANVAS_SECTION = "canvas_section"
CANVAS_GROUP = "canvas_group"
Expand Down
6 changes: 3 additions & 3 deletions lms/models/lti_role.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
import re
from dataclasses import dataclass
from enum import Enum, unique
from enum import Enum, StrEnum, unique

import sqlalchemy as sa
from sqlalchemy.ext.hybrid import hybrid_property
Expand All @@ -13,7 +13,7 @@


@unique
class RoleType(str, Enum):
class RoleType(StrEnum):
"""Enum for the different types of role a user can have."""

INSTRUCTOR = "instructor"
Expand All @@ -23,7 +23,7 @@ class RoleType(str, Enum):


@unique
class RoleScope(str, Enum):
class RoleScope(StrEnum):
"""Enum for the different scopes of a role."""

COURSE = "course"
Expand Down
4 changes: 2 additions & 2 deletions lms/models/oauth2_token.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Database model for persisting OAuth 2 tokens."""

import datetime
from enum import Enum, unique
from enum import Enum, StrEnum, unique

import sqlalchemy as sa
from sqlalchemy.orm import Mapped, mapped_column
Expand All @@ -12,7 +12,7 @@


@unique
class Service(str, Enum):
class Service(StrEnum):
"""Enum of the different APIs that OAuth tokens may be used for."""

LMS = "lms"
Expand Down
4 changes: 2 additions & 2 deletions lms/product/blackboard/_plugin/grouping.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from enum import Enum
from enum import Enum, StrEnum

from lms.models import Course, Grouping
from lms.product.plugin.grouping import GroupError, GroupingPlugin
from lms.services.exceptions import ExternalRequestError


class ErrorCodes(str, Enum):
class ErrorCodes(StrEnum):
"""Error codes that the FE is going to check for."""

GROUP_SET_NOT_FOUND = "blackboard_group_set_not_found"
Expand Down
4 changes: 2 additions & 2 deletions lms/product/canvas/_plugin/grouping.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from enum import Enum
from enum import Enum, StrEnum

from lms.models import Course, Grouping
from lms.product.plugin.grouping import GroupError, GroupingPlugin
from lms.services.exceptions import CanvasAPIError


class ErrorCodes(str, Enum):
class ErrorCodes(StrEnum):
"""Error codes that the FE is going to check for."""

STUDENT_NOT_IN_GROUP = "canvas_student_not_in_group"
Expand Down
4 changes: 2 additions & 2 deletions lms/product/d2l/_plugin/grouping.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from enum import Enum
from enum import Enum, StrEnum

from lms.models import Course, Grouping
from lms.product.plugin.grouping import GroupError, GroupingPlugin
from lms.services import D2LAPIClient
from lms.services.exceptions import ExternalRequestError


class ErrorCodes(str, Enum):
class ErrorCodes(StrEnum):
"""Error codes that the FE is going to check for."""

GROUP_SET_NOT_FOUND = "d2l_group_set_not_found"
Expand Down
4 changes: 2 additions & 2 deletions lms/product/family.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from enum import Enum
from enum import Enum, StrEnum


class Family(str, Enum):
class Family(StrEnum):
"""Enum for which product this relates to."""

BLACKBAUD = "BlackbaudK12"
Expand Down
4 changes: 2 additions & 2 deletions lms/product/moodle/_plugin/grouping.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from enum import Enum
from enum import Enum, StrEnum

from lms.models import Course, Grouping
from lms.product.plugin.grouping import GroupError, GroupingPlugin
from lms.services.exceptions import ExternalRequestError
from lms.services.moodle import MoodleAPIClient


class ErrorCodes(str, Enum):
class ErrorCodes(StrEnum):
"""Error codes that the FE is going to check for."""

GROUP_SET_NOT_FOUND = "moodle_group_set_not_found"
Expand Down
3 changes: 2 additions & 1 deletion lms/product/plugin/course_copy.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any, Callable
from collections.abc import Callable
from typing import Any

from lms.models import File
from lms.services.exceptions import ExternalRequestError, OAuth2TokenError
Expand Down
8 changes: 4 additions & 4 deletions lms/resources/_js_config/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import functools
import re
from datetime import timedelta
from enum import Enum
from enum import Enum, StrEnum
from typing import Any

from lms.error_code import ErrorCode
Expand Down Expand Up @@ -29,7 +29,7 @@
class JSConfig:
"""The config for the app's JavaScript code."""

class Mode(str, Enum):
class Mode(StrEnum):
OAUTH2_REDIRECT_ERROR = "oauth2-redirect-error"
BASIC_LTI_LAUNCH = "basic-lti-launch"
FILE_PICKER = "content-item-selection"
Expand Down Expand Up @@ -557,7 +557,7 @@ def auth_token(self):
return BearerTokenSchema(self._request).authorization_param(self._lti_user)

@property
@functools.lru_cache()
@functools.lru_cache
def _config(self):
"""
Return the current configuration dict.
Expand Down Expand Up @@ -641,7 +641,7 @@ def _get_product_info(self) -> dict:
return product_info

@property
@functools.lru_cache()
@functools.lru_cache
def _hypothesis_client(self) -> dict[str, Any]:
"""
Return the config object for the Hypothesis client.
Expand Down
2 changes: 1 addition & 1 deletion lms/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def get_policy(request: Request): # noqa: C901, PLR0911
# Routes that require the Google auth policy
return LMSGoogleSecurityPolicy()

if path.startswith(("/api/dashboard")):
if path.startswith("/api/dashboard"):
# For the dashboard API we prefer, in this order:
# - HeadersBearerTokenLTIUserPolicy()
# For requests authorized via an API token, this applies to LMS users
Expand Down
2 changes: 1 addition & 1 deletion lms/services/assignment.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from typing import Sequence
from collections.abc import Sequence

from sqlalchemy import Select, func, select
from sqlalchemy.orm import Session
Expand Down
7 changes: 4 additions & 3 deletions lms/services/canvas_studio.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
from collections.abc import Mapping
from functools import lru_cache
from typing import Literal, Mapping, NotRequired, Type, TypedDict
from typing import Literal, NotRequired, TypedDict
from urllib.parse import urlencode, urljoin, urlparse, urlunparse

import requests
Expand Down Expand Up @@ -383,7 +384,7 @@ def get_transcript_url(self, media_id: str) -> str | None:
def _api_request(
self,
path: str,
schema_cls: Type[RequestsResponseSchema],
schema_cls: type[RequestsResponseSchema],
as_admin=False,
) -> dict:
"""
Expand All @@ -399,7 +400,7 @@ def _api_request(
def _paginated_api_request(
self,
path: str,
schema_cls: Type[RequestsResponseSchema],
schema_cls: type[RequestsResponseSchema],
field: str,
as_admin=False,
) -> list:
Expand Down
4 changes: 2 additions & 2 deletions lms/services/digest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from datetime import UTC, datetime, timezone

from sqlalchemy import distinct, func, or_, select, tuple_
from sqlalchemy.dialects.postgresql import aggregate_order_by
Expand Down Expand Up @@ -73,7 +73,7 @@ def send_instructor_email_digest( # noqa: PLR0913
return

if deduplicate:
task_done_key = f"instructor_email_digest::{context.user_info.h_userid}::{datetime.now(timezone.utc).strftime('%Y-%m-%d')}"
task_done_key = f"instructor_email_digest::{context.user_info.h_userid}::{datetime.now(UTC).strftime('%Y-%m-%d')}"
task_done_data = {
"type": "instructor_email_digest",
"h_userid": context.user_info.h_userid,
Expand Down
2 changes: 1 addition & 1 deletion lms/services/email_preferences.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from collections.abc import Callable
from dataclasses import asdict, dataclass
from datetime import timedelta
from typing import Callable
from urllib.parse import parse_qs, urlparse

from lms.services.exceptions import ExpiredJWTError, InvalidJWTError
Expand Down
2 changes: 1 addition & 1 deletion lms/services/grouping/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def upsert_grouping_memberships(self, user: User, groups: list[Grouping]):
:param user: User the that belongs to the groups
:param groups: List of groups the `user` belongs to
"""
if not user.id or any((group.id is None for group in groups)):
if not user.id or any(group.id is None for group in groups):
# Ensure all ORM objects have their PK populated
self._db.flush()

Expand Down
7 changes: 4 additions & 3 deletions lms/services/h_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import itertools
import json
import re
from collections.abc import Iterator, Sequence
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Iterator, Sequence, TypedDict
from datetime import UTC, datetime, timezone
from typing import TypedDict

from h_api.bulk_api import BulkAPI, CommandBuilder

Expand Down Expand Up @@ -41,7 +42,7 @@ def _rfc3339_format(date: datetime) -> str:
Which looks like: 2018-11-13T20:20:39+00:00
"""
if not date.tzinfo:
date = date.replace(tzinfo=timezone.utc)
date = date.replace(tzinfo=UTC)

return date.isoformat()

Expand Down
4 changes: 2 additions & 2 deletions lms/services/lti_grading/_v13.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from datetime import datetime, timezone
from datetime import UTC, datetime, timezone
from urllib.parse import urlparse

from lms.models import ApplicationInstance, Assignment, LMSUser, LTIRegistration
Expand Down Expand Up @@ -133,7 +133,7 @@ def record_result(self, grading_id, score=None, pre_record_hook=None, comment=No
payload = self._record_score_payload(
score,
grading_id,
datetime.now(timezone.utc).isoformat(),
datetime.now(UTC).isoformat(),
)
if comment:
payload["comment"] = self._misc_plugin.format_grading_comment_for_lms(
Expand Down
4 changes: 2 additions & 2 deletions lms/services/moodle.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from enum import Enum
from enum import Enum, StrEnum
from typing import Literal, NotRequired, TypedDict

from lms.services.aes import AESService
from lms.services.exceptions import ExternalRequestError
from lms.services.http import HTTPService


class Function(str, Enum):
class Function(StrEnum):
GET_COURSE_GROUPINGS = "core_group_get_course_groupings"
"""Returns all groupings in specified course."""

Expand Down
10 changes: 5 additions & 5 deletions lms/tasks/email_digests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from datetime import datetime, timedelta, timezone
from datetime import UTC, datetime, timedelta, timezone

from sqlalchemy import Boolean, not_, select

Expand Down Expand Up @@ -43,10 +43,10 @@ def send_instructor_email_digest_tasks():
EST is 5 hours behind UTC (ignoring daylight savings for simplicity: we
don't need complete accuracy in the timing).
"""
now = datetime.now(timezone.utc)
now = datetime.now(UTC)
weekday = EmailPrefs.DAYS[now.weekday()]
created_before = datetime(
year=now.year, month=now.month, day=now.day, hour=5, tzinfo=timezone.utc
year=now.year, month=now.month, day=now.day, hour=5, tzinfo=UTC
)

with app.request_context() as request:
Expand Down Expand Up @@ -158,9 +158,9 @@ def send_instructor_email_digest(
if task_done_data:
created_after = max(
datetime.fromisoformat(task_done_data["created_before"]).replace(
tzinfo=timezone.utc
tzinfo=UTC
),
created_after.replace(tzinfo=timezone.utc), # type:ignore
created_after.replace(tzinfo=UTC), # type:ignore
)

digest_service = request.find_service(DigestService)
Expand Down
2 changes: 1 addition & 1 deletion lms/views/api/grading.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ class CanvasPreRecordHook:
# https://erau.instructure.com/doc/api/file.assignment_tools.html

# We use a set date in the past when no other date is available to avoid creating new submissions.
DEFAULT_SUBMISSION_DATE = datetime.datetime(2001, 1, 1, tzinfo=timezone.utc)
DEFAULT_SUBMISSION_DATE = datetime.datetime(2001, 1, 1, tzinfo=datetime.UTC)

def __init__(self, request):
self.request = request
Expand Down
2 changes: 1 addition & 1 deletion tests/bdd/steps/the_fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def set_base_dir(self, base_dir):
)

if not os.path.isdir(self.base_dir):
raise EnvironmentError(f"Cannot find fixture dir: {self.base_dir}")
raise OSError(f"Cannot find fixture dir: {self.base_dir}")

def set_fixture(self, name, value):
self.fixtures[name] = value
Expand Down
Loading

0 comments on commit 8ae69dd

Please sign in to comment.