Browse Source

ref: ban exam.patcher (#42222)

blocked on https://github.com/getsentry/getsentry/pull/9091
anthony sottile 2 years ago
parent
commit
458900af44

+ 6 - 8
src/sentry/testutils/cases.py

@@ -40,7 +40,6 @@ from datetime import datetime, timedelta
 from io import BytesIO
 from typing import Dict, List, Optional, Sequence, Union
 from unittest import mock
-from unittest.mock import patch
 from urllib.parse import urlencode
 from uuid import uuid4
 from zlib import compress
@@ -859,14 +858,13 @@ class CliTestCase(TestCase):
 class AcceptanceTestCase(TransactionTestCase):
     browser: Browser
 
-    def setUp(self):
-        patcher = patch(
+    @pytest.fixture(autouse=True)
+    def _setup_today(self):
+        with mock.patch(
             "django.utils.timezone.now",
             return_value=(datetime(2013, 5, 18, 15, 13, 58, 132928, tzinfo=timezone.utc)),
-        )
-        patcher.start()
-        self.addCleanup(patcher.stop)
-        super().setUp()
+        ):
+            yield
 
     def save_cookie(self, name, value, **params):
         self.browser.save_cookie(name=name, value=value, **params)
@@ -1628,7 +1626,7 @@ class ReplaysAcceptanceTestCase(AcceptanceTestCase, SnubaTestCase):
         self.now = datetime.utcnow().replace(tzinfo=pytz.utc)
         super().setUp()
         self.drop_replays()
-        patcher = patch("django.utils.timezone.now", return_value=self.now)
+        patcher = mock.patch("django.utils.timezone.now", return_value=self.now)
         patcher.start()
         self.addCleanup(patcher.stop)
 

+ 7 - 2
tests/sentry/api/endpoints/test_project_rule_details.py

@@ -1,9 +1,10 @@
 from datetime import datetime
 from typing import Any, Mapping
+from unittest import mock
 from unittest.mock import call, patch
 
+import pytest
 import responses
-from exam import patcher
 from freezegun import freeze_time
 from pytz import UTC
 
@@ -260,7 +261,11 @@ class ProjectRuleDetailsTest(ProjectRuleDetailsBaseTestCase):
 
 @region_silo_test
 class UpdateProjectRuleTest(ProjectRuleDetailsBaseTestCase):
-    metrics = patcher("sentry.api.endpoints.project_rule_details.metrics")
+    @pytest.fixture(autouse=True)
+    def _setup_metric_patch(self):
+        with mock.patch("sentry.api.endpoints.project_rule_details.metrics") as self.metrics:
+            yield
+
     method = "PUT"
 
     @patch("sentry.signals.alert_rule_edited.send_robust")

+ 17 - 5
tests/sentry/incidents/test_logic.py

@@ -1,4 +1,5 @@
 from datetime import timedelta
+from unittest import mock
 from unittest.mock import patch
 
 import pytest
@@ -6,7 +7,7 @@ import responses
 from django.conf import settings
 from django.core import mail
 from django.utils import timezone
-from exam import fixture, patcher
+from exam import fixture
 from freezegun import freeze_time
 
 from sentry.constants import ObjectStatus
@@ -78,7 +79,10 @@ pytestmark = [pytest.mark.sentry_metrics]
 
 
 class CreateIncidentTest(TestCase):
-    record_event = patcher("sentry.analytics.base.Analytics.record_event")
+    @pytest.fixture(autouse=True)
+    def _patch_record_event(self):
+        with mock.patch("sentry.analytics.base.Analytics.record_event") as self.record_event:
+            yield
 
     def test_simple(self):
         incident_type = IncidentType.ALERT_TRIGGERED
@@ -133,7 +137,10 @@ class CreateIncidentTest(TestCase):
 
 @freeze_time()
 class UpdateIncidentStatus(TestCase):
-    record_event = patcher("sentry.analytics.base.Analytics.record_event")
+    @pytest.fixture(autouse=True)
+    def _patch_record_event(self):
+        with mock.patch("sentry.analytics.base.Analytics.record_event") as self.record_event:
+            yield
 
     def get_most_recent_incident_activity(self, incident):
         return IncidentActivity.objects.filter(incident=incident).order_by("-id")[:1].get()
@@ -307,8 +314,13 @@ class GetCrashRateMetricsIncidentAggregatesTest(
 
 @freeze_time()
 class CreateIncidentActivityTest(TestCase, BaseIncidentsTest):
-    send_subscriber_notifications = patcher("sentry.incidents.tasks.send_subscriber_notifications")
-    record_event = patcher("sentry.analytics.base.Analytics.record_event")
+    @pytest.fixture(autouse=True)
+    def _setup_patches(self):
+        with mock.patch(
+            "sentry.incidents.tasks.send_subscriber_notifications"
+        ) as self.send_subscriber_notifications:
+            with mock.patch("sentry.analytics.base.Analytics.record_event") as self.record_event:
+                yield
 
     def assert_notifications_sent(self, activity):
         self.send_subscriber_notifications.apply_async.assert_called_once_with(

+ 5 - 2
tests/sentry/incidents/test_models.py

@@ -1,12 +1,12 @@
 import unittest
 from datetime import timedelta
+from unittest import mock
 from unittest.mock import Mock, patch
 
 import pytest
 from django.core.cache import cache
 from django.db import IntegrityError, transaction
 from django.utils import timezone
-from exam import patcher
 from freezegun import freeze_time
 
 from sentry.db.models.manager import BaseManager
@@ -495,7 +495,10 @@ class AlertRuleTriggerActionResolveTest(AlertRuleTriggerActionActivateTest, unit
 
 
 class AlertRuleTriggerActionActivateTest(TestCase):
-    metrics = patcher("sentry.incidents.models.metrics")
+    @pytest.fixture(autouse=True)
+    def _setup_metric_patch(self):
+        with mock.patch("sentry.incidents.models.metrics") as self.metrics:
+            yield
 
     def setUp(self):
         self.old_handlers = AlertRuleTriggerAction._type_registrations

+ 17 - 4
tests/sentry/incidents/test_subscription_processor.py

@@ -1,13 +1,14 @@
 import unittest
 from datetime import datetime, timedelta
 from random import randint
+from unittest import mock
 from unittest.mock import Mock, call, patch
 from uuid import uuid4
 
 import pytest
 import pytz
 from django.utils import timezone
-from exam import fixture, patcher
+from exam import fixture
 from freezegun import freeze_time
 
 from sentry.incidents.logic import (
@@ -58,7 +59,10 @@ pytestmark = [pytest.mark.sentry_metrics]
 
 @freeze_time()
 class ProcessUpdateBaseClass(TestCase, SnubaTestCase):
-    metrics = patcher("sentry.incidents.subscription_processor.metrics")
+    @pytest.fixture(autouse=True)
+    def _setup_metrics_patch(self):
+        with mock.patch("sentry.incidents.subscription_processor.metrics") as self.metrics:
+            yield
 
     def setUp(self):
         super().setUp()
@@ -161,7 +165,10 @@ class ProcessUpdateBaseClass(TestCase, SnubaTestCase):
 
 @freeze_time()
 class ProcessUpdateTest(ProcessUpdateBaseClass):
-    slack_client = patcher("sentry.integrations.slack.SlackClient.post")
+    @pytest.fixture(autouse=True)
+    def _setup_slack_client(self):
+        with mock.patch("sentry.integrations.slack.SlackClient.post") as self.slack_client:
+            yield
 
     @fixture
     def other_project(self):
@@ -1603,7 +1610,13 @@ class ProcessUpdateTest(ProcessUpdateBaseClass):
 
 
 class MetricsCrashRateAlertProcessUpdateTest(ProcessUpdateBaseClass, BaseMetricsTestCase):
-    entity_subscription_metrics = patcher("sentry.snuba.entity_subscription.metrics")
+    @pytest.fixture(autouse=True)
+    def _setup_metrics_patcher(self):
+        with mock.patch(
+            "sentry.snuba.entity_subscription.metrics"
+        ) as self.entity_subscription_metrics:
+            yield
+
     format = "v2"  # TODO: remove once subscriptions migrated
 
     def setUp(self):

+ 10 - 3
tests/sentry/incidents/test_tasks.py

@@ -1,11 +1,12 @@
 from datetime import timedelta
+from unittest import mock
 from unittest.mock import Mock, call, patch
 
 import pytest
 import pytz
 from django.urls import reverse
 from django.utils import timezone
-from exam import fixture, patcher
+from exam import fixture
 from freezegun import freeze_time
 
 from sentry.incidents.logic import (
@@ -48,7 +49,10 @@ class BaseIncidentActivityTest:
 
 
 class TestSendSubscriberNotifications(BaseIncidentActivityTest, TestCase):
-    send_async = patcher("sentry.utils.email.MessageBuilder.send_async")
+    @pytest.fixture(autouse=True)
+    def _setup_send_async_patch(self):
+        with mock.patch("sentry.utils.email.MessageBuilder.send_async") as self.send_async:
+            yield
 
     def test_simple(self):
         activity = create_incident_activity(
@@ -149,7 +153,10 @@ class TestBuildActivityContext(BaseIncidentActivityTest, TestCase):
 
 
 class HandleTriggerActionTest(TestCase):
-    metrics = patcher("sentry.incidents.tasks.metrics")
+    @pytest.fixture(autouse=True)
+    def _setup_metric_patch(self):
+        with mock.patch("sentry.incidents.tasks.metrics") as self.metrics:
+            yield
 
     @fixture
     def alert_rule(self):

+ 15 - 12
tests/sentry/quotas/test_redis.py

@@ -1,7 +1,8 @@
 import time
 from unittest import mock
 
-from exam import fixture, patcher
+import pytest
+from exam import fixture
 
 from sentry.constants import DataCategory
 from sentry.quotas.base import QuotaConfig, QuotaScope
@@ -207,17 +208,19 @@ class RedisQuotaTest(TestCase):
         assert quotas[0].window == 10
         assert quotas[0].reason_code == "project_abuse_limit"
 
-    @patcher.object(RedisQuota, "get_project_quota")
-    def get_project_quota(self):
-        inst = mock.MagicMock()
-        inst.return_value = (0, 60)
-        return inst
-
-    @patcher.object(RedisQuota, "get_organization_quota")
-    def get_organization_quota(self):
-        inst = mock.MagicMock()
-        inst.return_value = (0, 60)
-        return inst
+    @pytest.fixture(autouse=True)
+    def _patch_get_project_quota(self):
+        with mock.patch.object(
+            RedisQuota, "get_project_quota", return_value=(0, 60)
+        ) as self.get_project_quota:
+            yield
+
+    @pytest.fixture(autouse=True)
+    def _patch_get_organization_quota(self):
+        with mock.patch.object(
+            RedisQuota, "get_organization_quota", return_value=(0, 60)
+        ) as self.get_organization_quota:
+            yield
 
     def test_uses_defined_quotas(self):
         self.get_project_quota.return_value = (200, 60)

+ 5 - 2
tests/sentry/snuba/test_query_subscription_consumer.py

@@ -7,7 +7,7 @@ import pytest
 import pytz
 from dateutil.parser import parse as parse_date
 from django.conf import settings
-from exam import fixture, patcher
+from exam import fixture
 
 from sentry.snuba.dataset import Dataset, EntityKey
 from sentry.snuba.models import QuerySubscription, SnubaQuery
@@ -65,7 +65,10 @@ class BaseQuerySubscriptionTest:
 
 
 class HandleMessageTest(BaseQuerySubscriptionTest, TestCase):
-    metrics = patcher("sentry.snuba.query_subscription_consumer.metrics")
+    @pytest.fixture(autouse=True)
+    def _setup_metrics(self):
+        with mock.patch("sentry.snuba.query_subscription_consumer.metrics") as self.metrics:
+            yield
 
     def test_no_subscription(self):
         with mock.patch("sentry.snuba.tasks._snuba_pool") as pool:

+ 5 - 3
tests/sentry/snuba/test_tasks.py

@@ -7,7 +7,6 @@ from uuid import uuid4
 import pytest
 import responses
 from django.utils import timezone
-from exam import patcher
 from snuba_sdk import And, Column, Condition, Entity, Function, Op, Or, Query
 
 from sentry.incidents.logic import query_datasets_to_type
@@ -47,14 +46,17 @@ rh_indexer_record = partial(indexer_record, UseCaseKey.RELEASE_HEALTH)
 
 
 class BaseSnubaTaskTest(metaclass=abc.ABCMeta):
-    metrics = patcher("sentry.snuba.tasks.metrics")
-
     status_translations = {
         QuerySubscription.Status.CREATING: "create",
         QuerySubscription.Status.UPDATING: "update",
         QuerySubscription.Status.DELETING: "delete",
     }
 
+    @pytest.fixture(autouse=True)
+    def _setup_metrics(self):
+        with patch("sentry.snuba.tasks.metrics") as self.metrics:
+            yield
+
     @abc.abstractproperty
     def expected_status(self):
         pass

+ 10 - 0
tests/tools/test_flake8_plugin.py

@@ -89,3 +89,13 @@ from sentry.models import User
     assert errors == [
         "t.py:1:0: S005 Do not import models from sentry.models but the actual module",
     ]
+
+
+def test_S006():
+    S006_py = """\
+from exam import patcher
+"""
+    errors = _run(S006_py)
+    assert errors == [
+        "t.py:1:0: S006 use unittest.mock instead of exam.patcher",
+    ]

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