Browse Source

ref: fix more test types issues with BaseManager typechecked (#72532)

<!-- Describe your PR here. -->
anthony sottile 9 months ago
parent
commit
3a2ab0f1e0

+ 4 - 4
src/sentry/issues/escalating.py

@@ -7,7 +7,7 @@ from __future__ import annotations
 import logging
 import math
 from collections import defaultdict
-from collections.abc import Mapping, Sequence
+from collections.abc import Iterable, Mapping, Sequence
 from datetime import datetime, timedelta
 from typing import Any, TypedDict
 
@@ -75,7 +75,7 @@ GroupsCountResponse = TypedDict(
 ParsedGroupsCount = dict[int, GroupCount]
 
 
-def query_groups_past_counts(groups: Sequence[Group]) -> list[GroupsCountResponse]:
+def query_groups_past_counts(groups: Iterable[Group]) -> list[GroupsCountResponse]:
     """Query Snuba for the counts for every group bucketed into hours.
 
     It optimizes the query by guaranteeing that we look at group_ids that are from the same project id.
@@ -92,7 +92,7 @@ def query_groups_past_counts(groups: Sequence[Group]) -> list[GroupsCountRespons
     than 7 days old) will skew the optimization since we may only get one page and less elements than the max
     ELEMENTS_PER_SNUBA_PAGE.
     """
-    all_results = []  # type: ignore[var-annotated]
+    all_results: list[GroupsCountResponse] = []
     if not groups:
         return all_results
 
@@ -121,7 +121,7 @@ def _process_groups(
 ) -> list[GroupsCountResponse]:
     """Given a list of groups, query Snuba for their hourly bucket count.
     The category defines which Snuba dataset and entity we query."""
-    all_results = []  # type: ignore[var-annotated]
+    all_results: list[GroupsCountResponse] = []
     if not groups:
         return all_results
 

+ 8 - 1
src/sentry/quotas/base.py

@@ -1,5 +1,6 @@
 from __future__ import annotations
 
+from collections.abc import Iterable
 from dataclasses import dataclass
 from enum import IntEnum, unique
 from typing import TYPE_CHECKING, Any, Literal
@@ -15,6 +16,7 @@ from sentry.utils.services import Service
 
 if TYPE_CHECKING:
     from sentry.models.project import Project
+    from sentry.models.projectkey import ProjectKey
     from sentry.monitors.models import Monitor
 
 
@@ -313,7 +315,12 @@ class Quota(Service):
     def __init__(self, **options):
         pass
 
-    def get_quotas(self, project, key=None, keys=None):
+    def get_quotas(
+        self,
+        project: Project,
+        key: ProjectKey | None = None,
+        keys: Iterable[ProjectKey] | None = None,
+    ) -> list[QuotaConfig]:
         """
         Returns a quotas for the given project and its organization.
 

+ 7 - 1
src/sentry/quotas/redis.py

@@ -1,3 +1,6 @@
+from __future__ import annotations
+
+from collections.abc import Iterable
 from time import time
 
 import rb
@@ -61,7 +64,10 @@ class RedisQuota(Quota):
         return f"{self.namespace}:{local_key}:{int((timestamp - shift) // interval)}"
 
     def get_quotas(
-        self, project: Project, key: ProjectKey | None = None, keys: list[ProjectKey] | None = None
+        self,
+        project: Project,
+        key: ProjectKey | None = None,
+        keys: Iterable[ProjectKey] | None = None,
     ) -> list[QuotaConfig]:
         if key:
             key.project = project

+ 9 - 7
src/sentry/relay/config/__init__.py

@@ -1,6 +1,8 @@
+from __future__ import annotations
+
 import logging
 import uuid
-from collections.abc import Mapping, MutableMapping, Sequence
+from collections.abc import Iterable, Mapping, MutableMapping, Sequence
 from datetime import datetime, timezone
 from typing import Any, Literal, NotRequired, TypedDict
 
@@ -110,7 +112,7 @@ def get_exposed_features(project: Project) -> Sequence[str]:
 
 
 def get_public_key_configs(
-    project: Project, full_config: bool, project_keys: Sequence[ProjectKey] | None = None
+    project: Project, full_config: bool, project_keys: Iterable[ProjectKey] | None = None
 ) -> list[Mapping[str, Any]]:
     public_keys: list[Mapping[str, Any]] = []
     for project_key in project_keys or ():
@@ -225,7 +227,7 @@ def _get_generic_project_filters() -> GenericFiltersConfig:
     }
 
 
-def get_quotas(project: Project, keys: Sequence[ProjectKey] | None = None) -> list[str]:
+def get_quotas(project: Project, keys: Iterable[ProjectKey] | None = None) -> list[str]:
     try:
         computed_quotas = [
             quota.to_json() for quota in quotas.backend.get_quotas(project, keys=keys)
@@ -327,8 +329,8 @@ def get_metrics_config(timeout: TimeChecker, project: Project) -> Mapping[str, A
 
 
 def get_project_config(
-    project: Project, full_config: bool = True, project_keys: Sequence[ProjectKey] | None = None
-) -> "ProjectConfig":
+    project: Project, full_config: bool = True, project_keys: Iterable[ProjectKey] | None = None
+) -> ProjectConfig:
     """Constructs the ProjectConfig information.
     :param project: The project to load configuration for. Ensure that
         organization is bound on this object; otherwise it will be loaded from
@@ -737,8 +739,8 @@ def _get_mobile_performance_profiles(organization: Organization) -> list[dict[st
 
 
 def _get_project_config(
-    project: Project, full_config: bool = True, project_keys: Sequence[ProjectKey] | None = None
-) -> "ProjectConfig":
+    project: Project, full_config: bool = True, project_keys: Iterable[ProjectKey] | None = None
+) -> ProjectConfig:
     if project.status != ObjectStatus.ACTIVE:
         return ProjectConfig(project, disabled=True)
 

+ 2 - 0
tests/sentry/api/endpoints/test_sentry_app_rotate_secret.py

@@ -55,6 +55,7 @@ class SentryAppRotateSecretTest(APITestCase):
 
     def test_valid_call(self):
         self.login_as(self.user)
+        assert self.sentry_app.application is not None
         old_secret = self.sentry_app.application.client_secret
         response = self.client.post(self.url)
         new_secret = response.data["clientSecret"]
@@ -64,6 +65,7 @@ class SentryAppRotateSecretTest(APITestCase):
     def test_superuser_has_access(self):
         superuser = self.create_user(is_superuser=True)
         self.login_as(user=superuser, superuser=True)
+        assert self.sentry_app.application is not None
         old_secret = self.sentry_app.application.client_secret
         response = self.client.post(self.url)
         new_secret = response.data["clientSecret"]

+ 3 - 3
tests/sentry/hybridcloud/test_log.py

@@ -56,7 +56,7 @@ def test_audit_log_event_bad_actor_user_id() -> None:
         ).drain_shard()
 
     with assume_test_silo_mode(SiloMode.CONTROL):
-        log = AuditLogEntry.objects.first()
+        log = AuditLogEntry.objects.get()
         assert log.actor_id is None
 
 
@@ -81,7 +81,7 @@ def test_audit_log_event_bad_target_user_id() -> None:
         ).drain_shard()
 
     with assume_test_silo_mode(SiloMode.CONTROL):
-        log = AuditLogEntry.objects.first()
+        log = AuditLogEntry.objects.get()
         assert log.actor_id is None
         assert log.target_user_id is None
 
@@ -112,5 +112,5 @@ def test_user_ip_event() -> None:
         RegionOutbox(shard_scope=OutboxScope.USER_IP_SCOPE, shard_identifier=user.id).drain_shard()
 
     with assume_test_silo_mode(SiloMode.CONTROL):
-        assert UserIP.objects.last().ip_address == "1.0.0.5"
+        assert UserIP.objects.get(ip_address="1.0.0.5")
         assert UserIP.objects.count() == 2

+ 5 - 5
tests/sentry/issues/test_occurrence_consumer.py

@@ -186,7 +186,7 @@ class IssueOccurrenceProcessMessageTest(IssueOccurrenceTestBase):
         assert result is not None
         occurrence = result[0]
         assert occurrence is not None
-        group = Group.objects.filter(grouphash__hash=occurrence.fingerprint[0]).first()
+        group = Group.objects.filter(grouphash__hash=occurrence.fingerprint[0]).get()
         assert group.priority == PriorityLevel.LOW
 
     @with_feature("projects:issue-priority")
@@ -204,7 +204,7 @@ class IssueOccurrenceProcessMessageTest(IssueOccurrenceTestBase):
         occurrence = result[0]
         assert occurrence is not None
         assert mock_get_severity_score.call_count == 0
-        group = Group.objects.filter(grouphash__hash=occurrence.fingerprint[0]).first()
+        group = Group.objects.filter(grouphash__hash=occurrence.fingerprint[0]).get()
         assert group.priority == PriorityLevel.HIGH
         assert "severity" not in group.data["metadata"]
 
@@ -215,7 +215,7 @@ class IssueOccurrenceProcessMessageTest(IssueOccurrenceTestBase):
         assert result is not None
         occurrence = result[0]
         assert occurrence is not None
-        group = Group.objects.filter(grouphash__hash=occurrence.fingerprint[0]).first()
+        group = Group.objects.filter(grouphash__hash=occurrence.fingerprint[0]).get()
         assignee = GroupAssignee.objects.get(group=group)
         assert assignee.user_id == self.user.id
 
@@ -226,7 +226,7 @@ class IssueOccurrenceProcessMessageTest(IssueOccurrenceTestBase):
         assert result is not None
         occurrence = result[0]
         assert occurrence is not None
-        group = Group.objects.filter(grouphash__hash=occurrence.fingerprint[0]).first()
+        group = Group.objects.filter(grouphash__hash=occurrence.fingerprint[0]).get()
         assignee = GroupAssignee.objects.get(group=group)
         assert assignee.team_id == self.team.id
 
@@ -238,7 +238,7 @@ class IssueOccurrenceProcessMessageTest(IssueOccurrenceTestBase):
         assert result is not None
         occurrence = result[0]
         assert occurrence is not None
-        group = Group.objects.filter(grouphash__hash=occurrence.fingerprint[0]).first()
+        group = Group.objects.filter(grouphash__hash=occurrence.fingerprint[0]).get()
         with pytest.raises(GroupAssignee.DoesNotExist):
             GroupAssignee.objects.get(group=group)
 

+ 2 - 2
tests/sentry/sentry_apps/test_sentry_app_component_preparer.py

@@ -24,7 +24,7 @@ class TestPreparerIssueLink(TestCase):
         with assume_test_silo_mode(SiloMode.REGION):
             self.project = Organization.objects.get(
                 id=self.install.organization_id
-            ).project_set.first()
+            ).project_set.get()
 
         self.preparer = SentryAppComponentPreparer(
             component=self.component, install=self.install, project_slug=self.project.slug
@@ -111,7 +111,7 @@ class TestPreparerStacktraceLink(TestCase):
         with assume_test_silo_mode(SiloMode.REGION):
             self.project = Organization.objects.get(
                 id=self.install.organization_id
-            ).project_set.first()
+            ).project_set.get()
 
         self.preparer = SentryAppComponentPreparer(
             component=self.component, install=self.install, project_slug=self.project.slug

+ 4 - 1
tests/sentry/utils/test_snuba.py

@@ -53,7 +53,7 @@ class SnubaUtilsTest(TestCase):
             project_id=self.proj1.id, group_id=self.proj1group2.id, release_id=self.release1.id
         )
 
-    def test_translation(self):
+    def test_translation_no_translation(self):
         # Case 1: No translation
         filter_keys = {"sdk": ["python", "js"]}
         forward, reverse = get_snuba_translators(filter_keys)
@@ -61,6 +61,7 @@ class SnubaUtilsTest(TestCase):
         result = [{"sdk": "python", "count": 123}, {"sdk": "js", "count": 234}]
         assert all(reverse(row) == row for row in result)
 
+    def test_translation_environment_id_to_name_and_back(self):
         # Case 2: Environment ID -> Name and back
         filter_keys = {"environment": [self.proj1env1.id]}
         forward, reverse = get_snuba_translators(filter_keys)
@@ -68,6 +69,7 @@ class SnubaUtilsTest(TestCase):
         row = {"environment": self.proj1env1.name, "count": 123}
         assert reverse(row) == {"environment": self.proj1env1.id, "count": 123}
 
+    def test_translation_both_environment_and_release(self):
         # Case 3, both Environment and Release
         filter_keys = {
             "environment": [self.proj1env1.id],
@@ -89,6 +91,7 @@ class SnubaUtilsTest(TestCase):
             "count": 123,
         }
 
+    def test_translation_two_groups_many_to_many_of_groups(self):
         # Case 4: 2 Groups, many-to-many mapping of Groups
         # to Releases. Reverse translation depends on multiple
         # fields.

+ 4 - 4
tests/sentry/web/frontend/test_organization_auth_settings.py

@@ -435,7 +435,7 @@ class OrganizationAuthSettingsTest(AuthProviderTestCase):
             target_object=auth_provider.id,
             event=audit_log.get_event_id("SSO_EDIT"),
             actor=self.user,
-        ).first()
+        ).get()
 
         assert result.data == {"require_link": "to False", "default_role": "to owner"}
 
@@ -466,7 +466,7 @@ class OrganizationAuthSettingsTest(AuthProviderTestCase):
             target_object=auth_provider.id,
             event=audit_log.get_event_id("SSO_EDIT"),
             actor=self.user,
-        ).first()
+        ).get()
 
         assert result.data == {"require_link": "to False"}
 
@@ -497,7 +497,7 @@ class OrganizationAuthSettingsTest(AuthProviderTestCase):
             target_object=auth_provider.id,
             event=audit_log.get_event_id("SSO_EDIT"),
             actor=self.user,
-        ).first()
+        ).get()
         assert result.data == {"default_role": "to owner"}
 
     def test_edit_sso_settings__no_change(self):
@@ -681,7 +681,7 @@ class OrganizationAuthSettingsSAML2Test(AuthProviderTestCase):
             target_object=auth_provider.id,
             event=audit_log.get_event_id("SSO_EDIT"),
             actor=self.user,
-        ).first()
+        ).get()
 
         assert audit_logs.data == {
             "x509cert": "to bar_x509_cert",

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