Browse Source

ref: misc mypy fixes (#52665)

<!-- Describe your PR here. -->
anthony sottile 1 year ago
parent
commit
8075ed44bc

+ 0 - 12
pyproject.toml

@@ -158,8 +158,6 @@ module = [
     "sentry.api.decorators",
     "sentry.api.decorators",
     "sentry.api.endpoints.accept_organization_invite",
     "sentry.api.endpoints.accept_organization_invite",
     "sentry.api.endpoints.accept_project_transfer",
     "sentry.api.endpoints.accept_project_transfer",
-    "sentry.api.endpoints.api_application_details",
-    "sentry.api.endpoints.api_tokens",
     "sentry.api.endpoints.artifact_lookup",
     "sentry.api.endpoints.artifact_lookup",
     "sentry.api.endpoints.auth_config",
     "sentry.api.endpoints.auth_config",
     "sentry.api.endpoints.auth_login",
     "sentry.api.endpoints.auth_login",
@@ -331,7 +329,6 @@ module = [
     "sentry.api.endpoints.user_subscriptions",
     "sentry.api.endpoints.user_subscriptions",
     "sentry.api.event_search",
     "sentry.api.event_search",
     "sentry.api.fields.actor",
     "sentry.api.fields.actor",
-    "sentry.api.fields.avatar",
     "sentry.api.fields.user",
     "sentry.api.fields.user",
     "sentry.api.helpers.deprecation",
     "sentry.api.helpers.deprecation",
     "sentry.api.helpers.events",
     "sentry.api.helpers.events",
@@ -400,11 +397,6 @@ module = [
     "sentry.apidocs.schema",
     "sentry.apidocs.schema",
     "sentry.audit_log.manager",
     "sentry.audit_log.manager",
     "sentry.auth.access",
     "sentry.auth.access",
-    "sentry.auth.authenticators.base",
-    "sentry.auth.authenticators.recovery_code",
-    "sentry.auth.authenticators.sms",
-    "sentry.auth.authenticators.totp",
-    "sentry.auth.authenticators.u2f",
     "sentry.auth.helper",
     "sentry.auth.helper",
     "sentry.auth.provider",
     "sentry.auth.provider",
     "sentry.auth.providers.dummy",
     "sentry.auth.providers.dummy",
@@ -912,7 +904,6 @@ module = [
     "sentry.tasks.merge",
     "sentry.tasks.merge",
     "sentry.tasks.post_process",
     "sentry.tasks.post_process",
     "sentry.tasks.process_buffer",
     "sentry.tasks.process_buffer",
-    "sentry.tasks.reprocessing",
     "sentry.tasks.reprocessing2",
     "sentry.tasks.reprocessing2",
     "sentry.tasks.sentry_apps",
     "sentry.tasks.sentry_apps",
     "sentry.tasks.servicehooks",
     "sentry.tasks.servicehooks",
@@ -1257,7 +1248,6 @@ module = [
     "tests.sentry.integrations.slack.test_requests",
     "tests.sentry.integrations.slack.test_requests",
     "tests.sentry.integrations.slack.test_unfurl",
     "tests.sentry.integrations.slack.test_unfurl",
     "tests.sentry.integrations.slack.test_uninstall",
     "tests.sentry.integrations.slack.test_uninstall",
-    "tests.sentry.integrations.slack.webhooks.actions.test_status",
     "tests.sentry.integrations.slack.webhooks.commands",
     "tests.sentry.integrations.slack.webhooks.commands",
     "tests.sentry.integrations.slack.webhooks.commands.test_post",
     "tests.sentry.integrations.slack.webhooks.commands.test_post",
     "tests.sentry.integrations.slack.webhooks.events.test_discover_link_shared",
     "tests.sentry.integrations.slack.webhooks.events.test_discover_link_shared",
@@ -1460,10 +1450,8 @@ module = [
     "tests.sentry_plugins.github.test_provider",
     "tests.sentry_plugins.github.test_provider",
     "tests.sentry_plugins.heroku.test_plugin",
     "tests.sentry_plugins.heroku.test_plugin",
     "tests.sentry_plugins.jira.test_plugin",
     "tests.sentry_plugins.jira.test_plugin",
-    "tests.sentry_plugins.opgsenie.test_plugin",
     "tests.sentry_plugins.pagerduty.test_plugin",
     "tests.sentry_plugins.pagerduty.test_plugin",
     "tests.sentry_plugins.pushover.test_plugin",
     "tests.sentry_plugins.pushover.test_plugin",
-    "tests.sentry_plugins.slack.test_plugin",
     "tests.sentry_plugins.test_client",
     "tests.sentry_plugins.test_client",
     "tests.sentry_plugins.trello.test_plugin",
     "tests.sentry_plugins.trello.test_plugin",
     "tests.sentry_plugins.twilio.test_plugin",
     "tests.sentry_plugins.twilio.test_plugin",

+ 2 - 1
src/sentry/api/endpoints/accept_project_transfer.py

@@ -1,12 +1,13 @@
 from django.core.signing import BadSignature, SignatureExpired
 from django.core.signing import BadSignature, SignatureExpired
 from django.http import Http404
 from django.http import Http404
 from django.utils.encoding import force_str
 from django.utils.encoding import force_str
+from rest_framework.authentication import SessionAuthentication
 from rest_framework.permissions import IsAuthenticated
 from rest_framework.permissions import IsAuthenticated
 from rest_framework.request import Request
 from rest_framework.request import Request
 from rest_framework.response import Response
 from rest_framework.response import Response
 
 
 from sentry import audit_log, roles
 from sentry import audit_log, roles
-from sentry.api.base import Endpoint, SessionAuthentication, region_silo_endpoint
+from sentry.api.base import Endpoint, region_silo_endpoint
 from sentry.api.decorators import sudo_required
 from sentry.api.decorators import sudo_required
 from sentry.api.serializers import serialize
 from sentry.api.serializers import serialize
 from sentry.api.serializers.models.organization import (
 from sentry.api.serializers.models.organization import (

+ 3 - 2
src/sentry/api/endpoints/api_application_details.py

@@ -1,13 +1,14 @@
 from django.db import router, transaction
 from django.db import router, transaction
 from rest_framework import serializers
 from rest_framework import serializers
+from rest_framework.authentication import SessionAuthentication
 from rest_framework.permissions import IsAuthenticated
 from rest_framework.permissions import IsAuthenticated
 from rest_framework.request import Request
 from rest_framework.request import Request
 from rest_framework.response import Response
 from rest_framework.response import Response
+from rest_framework.serializers import ListField
 
 
-from sentry.api.base import Endpoint, SessionAuthentication, control_silo_endpoint
+from sentry.api.base import Endpoint, control_silo_endpoint
 from sentry.api.exceptions import ResourceDoesNotExist
 from sentry.api.exceptions import ResourceDoesNotExist
 from sentry.api.serializers import serialize
 from sentry.api.serializers import serialize
-from sentry.api.serializers.rest_framework import ListField
 from sentry.models import ApiApplication, ApiApplicationStatus, ScheduledDeletion
 from sentry.models import ApiApplication, ApiApplicationStatus, ScheduledDeletion
 
 
 
 

+ 2 - 1
src/sentry/api/endpoints/api_tokens.py

@@ -1,12 +1,13 @@
 from django.conf import settings
 from django.conf import settings
 from django.views.decorators.cache import never_cache
 from django.views.decorators.cache import never_cache
 from rest_framework import serializers
 from rest_framework import serializers
+from rest_framework.authentication import SessionAuthentication
 from rest_framework.permissions import IsAuthenticated
 from rest_framework.permissions import IsAuthenticated
 from rest_framework.request import Request
 from rest_framework.request import Request
 from rest_framework.response import Response
 from rest_framework.response import Response
 
 
 from sentry import analytics
 from sentry import analytics
-from sentry.api.base import Endpoint, SessionAuthentication, control_silo_endpoint
+from sentry.api.base import Endpoint, control_silo_endpoint
 from sentry.api.fields import MultipleChoiceField
 from sentry.api.fields import MultipleChoiceField
 from sentry.api.serializers import serialize
 from sentry.api.serializers import serialize
 from sentry.auth.superuser import is_active_superuser
 from sentry.auth.superuser import is_active_superuser

+ 1 - 1
src/sentry/api/endpoints/organization_member/__init__.py

@@ -7,9 +7,9 @@ from rest_framework.request import Request
 
 
 from sentry import roles
 from sentry import roles
 from sentry.api.exceptions import SentryAPIException, status
 from sentry.api.exceptions import SentryAPIException, status
-from sentry.app import locks
 from sentry.auth.access import Access
 from sentry.auth.access import Access
 from sentry.auth.superuser import is_active_superuser
 from sentry.auth.superuser import is_active_superuser
+from sentry.locks import locks
 from sentry.models import Organization, OrganizationMember, OrganizationMemberTeam, Team
 from sentry.models import Organization, OrganizationMember, OrganizationMemberTeam, Team
 from sentry.roles.manager import Role, TeamRole
 from sentry.roles.manager import Role, TeamRole
 from sentry.utils.retries import TimedRetryPolicy
 from sentry.utils.retries import TimedRetryPolicy

+ 4 - 2
src/sentry/api/fields/avatar.py

@@ -48,13 +48,15 @@ class AvatarField(serializers.Field):
             raise ImageTooLarge()
             raise ImageTooLarge()
 
 
         with Image.open(BytesIO(data)) as img:
         with Image.open(BytesIO(data)) as img:
-            if self.is_sentry_app and Image.MIME[img.format] not in SENTRY_APP_ALLOWED_MIMETYPES:
+            if self.is_sentry_app and (
+                img.format is None or Image.MIME[img.format] not in SENTRY_APP_ALLOWED_MIMETYPES
+            ):
                 valid_formats = ", ".join(SENTRY_APP_ALLOWED_MIMETYPES)
                 valid_formats = ", ".join(SENTRY_APP_ALLOWED_MIMETYPES)
                 raise serializers.ValidationError(
                 raise serializers.ValidationError(
                     f"Invalid image format. App icons should be {valid_formats}."
                     f"Invalid image format. App icons should be {valid_formats}."
                 )
                 )
 
 
-            if Image.MIME[img.format] not in ALLOWED_MIMETYPES:
+            if img.format is None or Image.MIME[img.format] not in ALLOWED_MIMETYPES:
                 raise serializers.ValidationError("Invalid image format.")
                 raise serializers.ValidationError("Invalid image format.")
 
 
             width, height = img.size
             width, height = img.size

+ 20 - 8
src/sentry/auth/authenticators/base.py

@@ -1,4 +1,7 @@
+from __future__ import annotations
+
 from enum import Enum
 from enum import Enum
+from typing import TYPE_CHECKING, Any
 
 
 from django.core.cache import cache
 from django.core.cache import cache
 from django.utils import timezone
 from django.utils import timezone
@@ -8,9 +11,14 @@ from rest_framework.request import Request
 from sentry import options
 from sentry import options
 from sentry.utils.otp import TOTP, generate_secret_key
 from sentry.utils.otp import TOTP, generate_secret_key
 
 
+if TYPE_CHECKING:
+    from django.utils.functional import _StrPromise
+
+    from sentry.models import Authenticator
+
 
 
 class ActivationResult:
 class ActivationResult:
-    type = None
+    type: str
 
 
 
 
 class ActivationMessageResult(ActivationResult):
 class ActivationMessageResult(ActivationResult):
@@ -46,14 +54,14 @@ class NewEnrollmentDisallowed(Exception):
 
 
 class AuthenticatorInterface:
 class AuthenticatorInterface:
     type = -1
     type = -1
-    interface_id = None
-    name = None
-    description = None
-    rotation_warning = None
+    interface_id: str
+    name: str | _StrPromise
+    description: str | _StrPromise
+    rotation_warning: str | _StrPromise | None = None
     is_backup_interface = False
     is_backup_interface = False
     enroll_button = _("Enroll")
     enroll_button = _("Enroll")
     configure_button = _("Info")
     configure_button = _("Info")
-    remove_button = _("Remove")
+    remove_button: str | _StrPromise | None = _("Remove")
     is_available = True
     is_available = True
     allow_multi_enrollment = False
     allow_multi_enrollment = False
     allow_rotation_in_place = False
     allow_rotation_in_place = False
@@ -91,14 +99,14 @@ class AuthenticatorInterface:
         """If the interface has an activation method that needs to be
         """If the interface has an activation method that needs to be
         called this returns `True`.
         called this returns `True`.
         """
         """
-        return self.activate.__func__ is not AuthenticatorInterface.activate
+        return type(self).activate is not AuthenticatorInterface.activate
 
 
     @property
     @property
     def can_validate_otp(self):
     def can_validate_otp(self):
         """If the interface is able to validate OTP codes then this returns
         """If the interface is able to validate OTP codes then this returns
         `True`.
         `True`.
         """
         """
-        return self.validate_otp.__func__ is not AuthenticatorInterface.validate_otp
+        return type(self).validate_otp is not AuthenticatorInterface.validate_otp
 
 
     @property
     @property
     def config(self):
     def config(self):
@@ -178,6 +186,10 @@ class AuthenticatorInterface:
 
 
 
 
 class OtpMixin:
 class OtpMixin:
+    # mixed in from base class
+    config: dict[str, Any]
+    authenticator: Authenticator | None
+
     def generate_new_config(self):
     def generate_new_config(self):
         return {"secret": generate_secret_key()}
         return {"secret": generate_secret_key()}
 
 

+ 8 - 2
src/sentry/auth/authenticators/sms.py

@@ -1,15 +1,21 @@
+from __future__ import annotations
+
 import logging
 import logging
 from hashlib import md5
 from hashlib import md5
+from typing import TYPE_CHECKING
 
 
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import gettext_lazy as _
 
 
-from sentry import ratelimits as ratelimiter
+from sentry.ratelimits import backend as ratelimiter
 from sentry.utils.decorators import classproperty
 from sentry.utils.decorators import classproperty
 from sentry.utils.otp import TOTP
 from sentry.utils.otp import TOTP
 from sentry.utils.sms import phone_number_as_e164, send_sms, sms_available
 from sentry.utils.sms import phone_number_as_e164, send_sms, sms_available
 
 
 from .base import ActivationMessageResult, AuthenticatorInterface, OtpMixin
 from .base import ActivationMessageResult, AuthenticatorInterface, OtpMixin
 
 
+if TYPE_CHECKING:
+    from django.utils.functional import _StrPromise
+
 logger = logging.getLogger("sentry.auth")
 logger = logging.getLogger("sentry.auth")
 
 
 
 
@@ -83,7 +89,7 @@ class SmsInterface(OtpMixin, AuthenticatorInterface):
         ctx = {"code": self.make_otp().generate_otp()}
         ctx = {"code": self.make_otp().generate_otp()}
 
 
         if for_enrollment:
         if for_enrollment:
-            text = _(
+            text: _StrPromise | str = _(
                 "%(code)s is your Sentry two-factor enrollment code. "
                 "%(code)s is your Sentry two-factor enrollment code. "
                 "You are about to set up text message based two-factor "
                 "You are about to set up text message based two-factor "
                 "authentication."
                 "authentication."

+ 2 - 2
src/sentry/eventstore/models.py

@@ -21,7 +21,7 @@ from sentry.interfaces.base import Interface, get_interfaces
 from sentry.issues.grouptype import GroupCategory
 from sentry.issues.grouptype import GroupCategory
 from sentry.issues.issue_occurrence import IssueOccurrence
 from sentry.issues.issue_occurrence import IssueOccurrence
 from sentry.models import EventDict
 from sentry.models import EventDict
-from sentry.snuba.events import Column, Columns
+from sentry.snuba.events import Columns
 from sentry.spans.grouping.api import load_span_grouping_config
 from sentry.spans.grouping.api import load_span_grouping_config
 from sentry.utils import json
 from sentry.utils import json
 from sentry.utils.cache import memoize
 from sentry.utils.cache import memoize
@@ -568,7 +568,7 @@ class BaseEvent(metaclass=abc.ABCMeta):
 
 
         return cast(str, trim(message.strip(), settings.SENTRY_MAX_MESSAGE_LENGTH))
         return cast(str, trim(message.strip(), settings.SENTRY_MAX_MESSAGE_LENGTH))
 
 
-    def _get_column_name(self, column: Column) -> str:
+    def _get_column_name(self, column: Columns) -> str:
         # Events are currently populated from the Events dataset
         # Events are currently populated from the Events dataset
         return cast(str, column.value.event_name)
         return cast(str, column.value.event_name)
 
 

+ 2 - 2
src/sentry/tasks/reprocessing.py

@@ -12,13 +12,13 @@ logger = logging.getLogger(__name__)
 
 
 @instrumented_task(name="sentry.tasks.reprocess_events", queue="events.reprocess_events")
 @instrumented_task(name="sentry.tasks.reprocess_events", queue="events.reprocess_events")
 def reprocess_events(project_id, **kwargs):
 def reprocess_events(project_id, **kwargs):
-    from sentry import app
     from sentry.coreapi import insert_data_to_database_legacy
     from sentry.coreapi import insert_data_to_database_legacy
+    from sentry.locks import locks
     from sentry.models import ProcessingIssue
     from sentry.models import ProcessingIssue
 
 
     lock_key = "events:reprocess_events:%s" % project_id
     lock_key = "events:reprocess_events:%s" % project_id
     have_more = False
     have_more = False
-    lock = app.locks.get(lock_key, duration=60, name="reprocess_events")
+    lock = locks.get(lock_key, duration=60, name="reprocess_events")
 
 
     try:
     try:
         with lock.acquire():
         with lock.acquire():

Some files were not shown because too many files changed in this diff