Просмотр исходного кода

ref: replace self.assertRaises with pytest.raises (#35685)

* add flake8 plugin to detect assertRaises

* ref: replace self.assertRaises with pytest.raises

* non-sed fixes
anthony sottile 2 лет назад
Родитель
Сommit
284e980df0

+ 4 - 3
fixtures/schema_validation.py

@@ -1,9 +1,10 @@
+import pytest
 from jsonschema import ValidationError
 
 
 def invalid_schema(func):
     def inner(self, *args, **kwargs):
-        with self.assertRaises(ValidationError):
+        with pytest.raises(ValidationError):
             func(self)
 
     return inner
@@ -12,9 +13,9 @@ def invalid_schema(func):
 def invalid_schema_with_error_message(message):
     def decorator(func):
         def inner(self, *args, **kwargs):
-            with self.assertRaises(ValidationError) as cm:
+            with pytest.raises(ValidationError) as excinfo:
                 func(self)
-            assert cm.exception.message == message
+            assert excinfo.value.message == message
 
         return inner
 

+ 11 - 10
tests/sentry/api/bases/test_organization.py

@@ -1,6 +1,7 @@
 from datetime import timedelta
 from unittest import mock
 
+import pytest
 from django.db.models import F
 from django.test import RequestFactory
 from django.utils import timezone
@@ -101,14 +102,14 @@ class OrganizationPermissionTest(OrganizationPermissionBase):
         user = self.create_user()
         self.create_member(user=user, organization=self.org, role="member")
 
-        with self.assertRaises(TwoFactorRequired):
+        with pytest.raises(TwoFactorRequired):
             self.has_object_perm("GET", self.org, user=user)
 
     def test_org_requires_2fa_with_superuser_not_active(self):
         self.org_require_2fa()
         user = self.create_user(is_superuser=True)
         self.create_member(user=user, organization=self.org, role="member")
-        with self.assertRaises(SuperuserRequired):
+        with pytest.raises(SuperuserRequired):
             assert self.has_object_perm("GET", self.org, user=user)
 
     @mock.patch("sentry.api.utils.get_cached_organization_member")
@@ -121,10 +122,10 @@ class OrganizationPermissionTest(OrganizationPermissionBase):
             flags=OrganizationMember.flags["member-limit:restricted"],
         )
 
-        with self.assertRaises(MemberDisabledOverLimit) as err:
+        with pytest.raises(MemberDisabledOverLimit) as excinfo:
             self.has_object_perm("GET", self.org, user=user)
 
-        assert err.exception.detail == {
+        assert excinfo.value.detail == {
             "detail": {
                 "code": "member-disabled-over-limit",
                 "message": "Organization over member limit",
@@ -255,7 +256,7 @@ class GetProjectIdsTest(BaseOrganizationEndpointTest):
         self.run_test([self.project_1, self.project_2])
 
     def test_ids_no_teams(self):
-        with self.assertRaises(PermissionDenied):
+        with pytest.raises(PermissionDenied):
             self.run_test([], project_ids=[self.project_1.id])
 
         self.run_test(
@@ -272,13 +273,13 @@ class GetProjectIdsTest(BaseOrganizationEndpointTest):
 
         self.org.flags.allow_joinleave = False
         self.org.save()
-        with self.assertRaises(PermissionDenied):
+        with pytest.raises(PermissionDenied):
             self.run_test([self.project_1], user=self.member, project_ids=[self.project_1.id])
 
     def test_ids_teams(self):
         membership = self.create_team_membership(user=self.user, team=self.team_1)
         self.run_test([self.project_1], project_ids=[self.project_1.id])
-        with self.assertRaises(PermissionDenied):
+        with pytest.raises(PermissionDenied):
             self.run_test([], project_ids=[self.project_2.id])
         membership.delete()
         self.create_team_membership(user=self.user, team=self.team_3)
@@ -407,9 +408,9 @@ class GetEnvironmentsTest(BaseOrganizationEndpointTest):
         self.run_test([self.env_1, self.env_2], [self.env_1.name, self.env_2.name])
 
     def test_invalid_params(self):
-        with self.assertRaises(ResourceDoesNotExist):
+        with pytest.raises(ResourceDoesNotExist):
             self.run_test([], ["fake"])
-        with self.assertRaises(ResourceDoesNotExist):
+        with pytest.raises(ResourceDoesNotExist):
             self.run_test([self.env_1, self.env_2], ["fake", self.env_2.name])
 
 
@@ -464,7 +465,7 @@ class GetFilterParamsTest(BaseOrganizationEndpointTest):
 
     @freeze_time("2018-12-11 03:21:34")
     def test_no_params(self):
-        with self.assertRaises(NoProjects):
+        with pytest.raises(NoProjects):
             self.run_test([])
         self.run_test(
             expected_projects=[self.project_1, self.project_2],

+ 5 - 4
tests/sentry/api/bases/test_sentryapps.py

@@ -1,6 +1,7 @@
 import unittest
 from unittest.mock import patch
 
+import pytest
 from django.http import Http404
 
 from sentry.api.bases.sentryapps import (
@@ -30,7 +31,7 @@ class SentryAppPermissionTest(TestCase):
     def test_request_user_is_not_app_owner_fails(self):
         self.request.user = self.create_user()
 
-        with self.assertRaises(Http404):
+        with pytest.raises(Http404):
             self.permission.has_object_permission(self.request, None, self.sentry_app)
 
     def test_has_permission(self):
@@ -57,7 +58,7 @@ class SentryAppBaseEndpointTest(TestCase):
         assert kwargs["sentry_app"] == self.sentry_app
 
     def test_raises_when_sentry_app_not_found(self):
-        with self.assertRaises(Http404):
+        with pytest.raises(Http404):
             self.endpoint.convert_args(self.request, "notanapp")
 
 
@@ -88,7 +89,7 @@ class SentryAppInstallationPermissionTest(TestCase):
         assert self.permission.has_object_permission(self.request, None, self.installation)
 
     def test_request_user_not_in_organization(self):
-        with self.assertRaises(Http404):
+        with pytest.raises(Http404):
             self.permission.has_object_permission(self.request, None, self.installation)
 
 
@@ -112,7 +113,7 @@ class SentryAppInstallationBaseEndpointTest(TestCase):
         assert kwargs["installation"] == self.installation
 
     def test_raises_when_sentry_app_not_found(self):
-        with self.assertRaises(Http404):
+        with pytest.raises(Http404):
             self.endpoint.convert_args(self.request, "1234")
 
 

+ 2 - 1
tests/sentry/api/endpoints/test_doc_integration_details.py

@@ -1,3 +1,4 @@
+import pytest
 from rest_framework import status
 
 from sentry.api.serializers.base import serialize
@@ -257,7 +258,7 @@ class DeleteDocIntegrationDetailsTest(DocIntegrationDetailsTest):
         assert features.exists()
         assert self.doc_delete.avatar.exists()
         self.get_success_response(self.doc_delete.slug, status_code=status.HTTP_204_NO_CONTENT)
-        with self.assertRaises(DocIntegration.DoesNotExist):
+        with pytest.raises(DocIntegration.DoesNotExist):
             DocIntegration.objects.get(id=self.doc_delete.id)
         assert not features.exists()
         assert not self.doc_delete.avatar.exists()

+ 9 - 8
tests/sentry/api/helpers/test_group_index.py

@@ -1,5 +1,6 @@
 from unittest.mock import Mock, patch
 
+import pytest
 from django.http import QueryDict
 
 from sentry.api.helpers.group_index import (
@@ -27,8 +28,8 @@ class ValidateSearchFilterPermissionsTest(TestCase):
     @patch("sentry.analytics.record")
     def test_negative(self, mock_record):
         query = "!has:user"
-        with self.feature({"organizations:advanced-search": False}), self.assertRaisesRegex(
-            ValidationError, ".*negative search.*"
+        with self.feature({"organizations:advanced-search": False}), pytest.raises(
+            ValidationError, match=".*negative search.*"
         ):
             self.run_test(query)
 
@@ -36,8 +37,8 @@ class ValidateSearchFilterPermissionsTest(TestCase):
         self.assert_analytics_recorded(mock_record)
 
         query = "!something:123"
-        with self.feature({"organizations:advanced-search": False}), self.assertRaisesRegex(
-            ValidationError, ".*negative search.*"
+        with self.feature({"organizations:advanced-search": False}), pytest.raises(
+            ValidationError, match=".*negative search.*"
         ):
             self.run_test(query)
 
@@ -47,8 +48,8 @@ class ValidateSearchFilterPermissionsTest(TestCase):
     @patch("sentry.analytics.record")
     def test_wildcard(self, mock_record):
         query = "abc:hello*"
-        with self.feature({"organizations:advanced-search": False}), self.assertRaisesRegex(
-            ValidationError, ".*wildcard search.*"
+        with self.feature({"organizations:advanced-search": False}), pytest.raises(
+            ValidationError, match=".*wildcard search.*"
         ):
             self.run_test(query)
 
@@ -56,8 +57,8 @@ class ValidateSearchFilterPermissionsTest(TestCase):
         self.assert_analytics_recorded(mock_record)
 
         query = "raw * search"
-        with self.feature({"organizations:advanced-search": False}), self.assertRaisesRegex(
-            ValidationError, ".*wildcard search.*"
+        with self.feature({"organizations:advanced-search": False}), pytest.raises(
+            ValidationError, match=".*wildcard search.*"
         ):
             self.run_test(query)
 

+ 5 - 5
tests/sentry/api/test_authentication.py

@@ -41,35 +41,35 @@ class TestClientIdSecretAuthentication(TestCase):
         request = HttpRequest()
         request.json_body = None
 
-        with self.assertRaises(AuthenticationFailed):
+        with pytest.raises(AuthenticationFailed):
             self.auth.authenticate(request)
 
     def test_missing_client_id(self):
         request = HttpRequest()
         request.json_body = {"client_secret": self.api_app.client_secret}
 
-        with self.assertRaises(AuthenticationFailed):
+        with pytest.raises(AuthenticationFailed):
             self.auth.authenticate(request)
 
     def test_missing_client_secret(self):
         request = HttpRequest()
         request.json_body = {"client_id": self.api_app.client_id}
 
-        with self.assertRaises(AuthenticationFailed):
+        with pytest.raises(AuthenticationFailed):
             self.auth.authenticate(request)
 
     def test_incorrect_client_id(self):
         request = HttpRequest()
         request.json_body = {"client_id": "notit", "client_secret": self.api_app.client_secret}
 
-        with self.assertRaises(AuthenticationFailed):
+        with pytest.raises(AuthenticationFailed):
             self.auth.authenticate(request)
 
     def test_incorrect_client_secret(self):
         request = HttpRequest()
         request.json_body = {"client_id": self.api_app.client_id, "client_secret": "notit"}
 
-        with self.assertRaises(AuthenticationFailed):
+        with pytest.raises(AuthenticationFailed):
             self.auth.authenticate(request)
 
 

+ 4 - 4
tests/sentry/api/test_event_search.py

@@ -174,7 +174,7 @@ class ParseSearchQueryTest(SimpleTestCase):
             expect_error = True
 
         if expect_error:
-            with self.assertRaises(InvalidSearchQuery, msg=failure_help):
+            with pytest.raises(InvalidSearchQuery):
                 parse_search_query(query)
             return
 
@@ -353,7 +353,7 @@ class ParseSearchQueryBackendTest(SimpleTestCase):
         ]
 
         # malformed key
-        with self.assertRaises(InvalidSearchQuery):
+        with pytest.raises(InvalidSearchQuery):
             parse_search_query('has:"hi there"')
 
     def test_not_has_tag(self):
@@ -403,8 +403,8 @@ class ParseSearchQueryBackendTest(SimpleTestCase):
             parse_search_query("count_if(measurements.fcp, greater, 5s):3s")
 
     def test_is_query_unsupported(self):
-        with self.assertRaisesRegex(
-            InvalidSearchQuery, ".*queries are not supported in this search.*"
+        with pytest.raises(
+            InvalidSearchQuery, match=".*queries are not supported in this search.*"
         ):
             parse_search_query("is:unassigned")
 

+ 2 - 2
tests/sentry/api/test_issue_search.py

@@ -87,10 +87,10 @@ class ParseSearchQueryTest(unittest.TestCase):
             ]
 
     def test_is_query_invalid(self):
-        with self.assertRaises(InvalidSearchQuery) as cm:
+        with pytest.raises(InvalidSearchQuery) as excinfo:
             parse_search_query("is:wrong")
 
-        assert str(cm.exception).startswith('Invalid value for "is" search, valid values are')
+        assert str(excinfo.value).startswith('Invalid value for "is" search, valid values are')
 
     def test_is_query_inbox(self):
         assert parse_search_query("is:for_review") == [

+ 6 - 5
tests/sentry/api/test_paginator.py

@@ -1,6 +1,7 @@
 from datetime import timedelta
 from unittest import TestCase as SimpleTestCase
 
+import pytest
 from django.utils import timezone
 
 from sentry.api.paginator import (
@@ -123,11 +124,11 @@ class OffsetPaginatorTest(TestCase):
         queryset = User.objects.all()
         paginator = OffsetPaginator(queryset)
         cursor = Cursor(10, -1)
-        with self.assertRaises(BadPaginationError):
+        with pytest.raises(BadPaginationError):
             paginator.get_result(cursor=cursor)
 
         cursor = Cursor(-10, 1)
-        with self.assertRaises(BadPaginationError):
+        with pytest.raises(BadPaginationError):
             paginator.get_result(cursor=cursor)
 
     def test_order_by_multiple(self):
@@ -171,7 +172,7 @@ class OffsetPaginatorTest(TestCase):
         assert len(result1) == 3, result1
 
         paginator = OffsetPaginator(queryset, max_offset=0)
-        with self.assertRaises(BadPaginationError):
+        with pytest.raises(BadPaginationError):
             paginator.get_result()
 
 
@@ -612,14 +613,14 @@ class CombinedQuerysetPaginatorTest(APITestCase):
         assert list(result) == page1_results
 
     def test_order_by_invalid_key(self):
-        with self.assertRaises(AssertionError):
+        with pytest.raises(AssertionError):
             rule_intermediary = CombinedQuerysetIntermediary(Rule.objects.all(), "dontexist")
             CombinedQuerysetPaginator(
                 intermediaries=[rule_intermediary],
             )
 
     def test_mix_date_and_not_date(self):
-        with self.assertRaises(AssertionError):
+        with pytest.raises(AssertionError):
             rule_intermediary = CombinedQuerysetIntermediary(Rule.objects.all(), "date_added")
             rule_intermediary2 = CombinedQuerysetIntermediary(Rule.objects.all(), "label")
             CombinedQuerysetPaginator(

+ 4 - 3
tests/sentry/api/test_utils.py

@@ -1,6 +1,7 @@
 import datetime
 import unittest
 
+import pytest
 from django.utils import timezone
 from freezegun import freeze_time
 
@@ -24,7 +25,7 @@ class GetDateRangeFromParamsTest(unittest.TestCase):
         start, end = get_date_range_from_params({"statsPeriod": "91d"})
         assert end - datetime.timedelta(days=91) == start
 
-        with self.assertRaises(InvalidParams):
+        with pytest.raises(InvalidParams):
             get_date_range_from_params({"statsPeriod": "9000000d"})
 
     def test_date_range(self):
@@ -33,7 +34,7 @@ class GetDateRangeFromParamsTest(unittest.TestCase):
         assert start == datetime.datetime(2018, 11, 1, tzinfo=timezone.utc)
         assert end == datetime.datetime(2018, 11, 7, tzinfo=timezone.utc)
 
-        with self.assertRaises(InvalidParams):
+        with pytest.raises(InvalidParams):
             get_date_range_from_params(
                 {"start": "2018-11-01T00:00:00", "end": "2018-11-01T00:00:00"}
             )
@@ -58,5 +59,5 @@ class GetDateRangeFromParamsTest(unittest.TestCase):
     @freeze_time("2018-12-11 03:21:34")
     def test_relative_date_range_incomplete(self):
 
-        with self.assertRaises(InvalidParams):
+        with pytest.raises(InvalidParams):
             start, end = get_date_range_from_params({"statsPeriodStart": "14d"})

Некоторые файлы не были показаны из-за большого количества измененных файлов