From a7426c7a5875d0df294b72f41a309ff4e31fdc76 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:32:37 +0000 Subject: [PATCH] ci(ruff): Enable rules for inline imports, prints, unused noqa and pytest.raises Turn on PLC0415, T20, RUF100, PT011 and PT012. Existing violations get a noqa comment so new code is checked without a big cleanup first. RUF100 removes the noqa comments for rules that ruff doesn't enable, most of them left over from the flake8 plugins. Co-Authored-By: Ivana Kellyer <131587164+sentrivana@users.noreply.github.com> --- pyproject.toml | 9 +++ sentry_sdk/_compat.py | 8 +- sentry_sdk/_init_implementation.py | 2 +- sentry_sdk/client.py | 4 +- sentry_sdk/consts.py | 18 ++--- sentry_sdk/crons/decorator.py | 2 +- sentry_sdk/integrations/__init__.py | 4 +- sentry_sdk/integrations/anthropic.py | 2 +- sentry_sdk/integrations/asgi.py | 2 +- sentry_sdk/integrations/beam.py | 6 +- sentry_sdk/integrations/celery/__init__.py | 6 +- sentry_sdk/integrations/celery/beat.py | 2 +- sentry_sdk/integrations/chalice.py | 2 +- .../integrations/cloud_resource_context.py | 4 +- sentry_sdk/integrations/django/__init__.py | 34 ++++----- sentry_sdk/integrations/django/asgi.py | 10 +-- sentry_sdk/integrations/django/caching.py | 8 +- sentry_sdk/integrations/django/middleware.py | 4 +- .../integrations/django/signals_handlers.py | 2 +- sentry_sdk/integrations/django/tasks.py | 2 +- sentry_sdk/integrations/django/templates.py | 6 +- sentry_sdk/integrations/django/views.py | 8 +- sentry_sdk/integrations/flask.py | 2 +- sentry_sdk/integrations/gcp.py | 2 +- sentry_sdk/integrations/grpc/__init__.py | 2 +- sentry_sdk/integrations/litestar.py | 2 +- sentry_sdk/integrations/openai.py | 2 +- .../openai_agents/patches/error_tracing.py | 4 +- .../integrations/pydantic_ai/__init__.py | 2 +- .../integrations/pydantic_ai/patches/tools.py | 4 +- sentry_sdk/integrations/pydantic_ai/utils.py | 2 +- sentry_sdk/integrations/pyramid.py | 2 +- sentry_sdk/integrations/redis/__init__.py | 2 +- .../integrations/redis/_async_common.py | 4 +- sentry_sdk/integrations/redis/_sync_common.py | 4 +- sentry_sdk/integrations/redis/rb.py | 2 +- sentry_sdk/integrations/redis/redis.py | 6 +- .../integrations/redis/redis_cluster.py | 6 +- .../redis/redis_py_cluster_legacy.py | 2 +- sentry_sdk/integrations/rust_tracing.py | 2 +- sentry_sdk/integrations/spark/spark_driver.py | 68 ++++++++--------- sentry_sdk/integrations/spark/spark_worker.py | 6 +- sentry_sdk/integrations/starlette.py | 4 +- sentry_sdk/integrations/starlite.py | 2 +- sentry_sdk/integrations/threading.py | 4 +- sentry_sdk/scope.py | 2 +- sentry_sdk/spotlight.py | 2 +- sentry_sdk/traces.py | 4 +- sentry_sdk/tracing.py | 2 +- sentry_sdk/tracing_utils.py | 4 +- sentry_sdk/transport.py | 12 +-- sentry_sdk/utils.py | 22 +++--- tests/conftest.py | 4 +- tests/integrations/aiohttp/test_aiohttp.py | 4 +- .../integrations/anthropic/test_anthropic.py | 18 ++--- tests/integrations/asgi/test_asgi.py | 16 ++-- tests/integrations/asyncio/test_asyncio.py | 4 +- .../aws_lambda/test_aws_lambda.py | 2 +- tests/integrations/aws_lambda/utils.py | 4 +- tests/integrations/boto3/test_client.py | 4 +- tests/integrations/bottle/test_bottle.py | 2 +- tests/integrations/celery/test_celery.py | 14 ++-- .../celery/test_celery_beat_crons.py | 4 +- tests/integrations/chalice/test_chalice.py | 2 +- tests/integrations/django/myapp/settings.py | 2 +- tests/integrations/django/myapp/views.py | 2 +- tests/integrations/django/test_basic.py | 2 +- .../integrations/django/test_db_query_data.py | 4 +- tests/integrations/flask/test_flask.py | 4 +- tests/integrations/gcp/test_gcp.py | 2 +- tests/integrations/graphene/test_graphene.py | 4 +- tests/integrations/grpc/test_grpc.py | 10 +-- tests/integrations/grpc/test_grpc_aio.py | 18 ++--- .../integrations/langchain/test_langchain.py | 12 +-- .../integrations/langgraph/test_langgraph.py | 8 +- tests/integrations/openai/test_openai.py | 8 +- .../openai_agents/test_openai_agents.py | 6 +- tests/integrations/ray/test_ray.py | 8 +- tests/integrations/requests/test_requests.py | 12 +-- tests/integrations/rq/test_rq.py | 2 +- tests/integrations/socket/test_socket.py | 12 +-- tests/integrations/spark/test_spark.py | 32 ++++---- .../sqlalchemy/test_sqlalchemy.py | 76 +++++++++---------- tests/integrations/stdlib/test_httplib.py | 18 ++--- tests/integrations/wsgi/test_wsgi.py | 18 ++--- tests/profiler/test_continuous_profiler.py | 2 +- tests/profiler/test_transaction_profiler.py | 4 +- tests/test_conftest.py | 8 +- tests/test_data_collection.py | 6 +- tests/test_import.py | 2 +- tests/test_propagationcontext.py | 6 +- tests/test_utils.py | 8 +- tests/tracing/test_integration_tests.py | 4 +- tests/tracing/test_sample_rand.py | 12 ++- tests/tracing/test_sampling.py | 6 +- tests/tracing/test_span_streaming.py | 2 +- tests/utils/test_contextvars.py | 2 +- 97 files changed, 363 insertions(+), 366 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index cfac620006..0250d74fc6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -301,6 +301,11 @@ select = [ "I", # Note: B and N rules are NOT enabled by default in flake8 # They were only active through the plugins, which may not have been fully enabled + "PLC0415", # Import not at the top level of the file + "PT011", # pytest.raises() too broad + "PT012", # pytest.raises() block with more than one statement + "RUF100", # Unused noqa directive + "T20", # print() and pprint() calls ] # Use ONLY the same ignores as the original flake8 config + compatibility for this codebase @@ -317,6 +322,10 @@ ignore = [ "E721", # Use isinstance instead of type() == - existing pattern in this codebase ] +[tool.ruff.lint.per-file-ignores] +"scripts/**" = ["T20"] +"tests/**" = ["PLC0415", "T20"] + [tool.ruff.format] # ruff format already excludes the same files as specified in extend-exclude # Ensure Python 3.7 compatibility - avoid using Python 3.9+ syntax features diff --git a/sentry_sdk/_compat.py b/sentry_sdk/_compat.py index f62175c09f..64dcabddcf 100644 --- a/sentry_sdk/_compat.py +++ b/sentry_sdk/_compat.py @@ -35,11 +35,11 @@ def check_uwsgi_thread_support() -> bool: # --py-call-uwsgi-fork-hooks to force uWSGI to run regular cpython # after-fork hooks that take care of cleaning up stale thread data. try: - from uwsgi import opt # type: ignore + from uwsgi import opt # type: ignore # noqa: PLC0415 except ImportError: return True - from sentry_sdk.consts import FALSE_VALUES + from sentry_sdk.consts import FALSE_VALUES # noqa: PLC0415 def enabled(option: str) -> bool: value = opt.get(option, False) @@ -61,7 +61,7 @@ def enabled(option: str) -> bool: lazy_mode = enabled("lazy-apps") or enabled("lazy") if lazy_mode and not threads_enabled: - from warnings import warn + from warnings import warn # noqa: PLC0415 warn( Warning( @@ -75,7 +75,7 @@ def enabled(option: str) -> bool: return False elif not lazy_mode and (not threads_enabled or not fork_hooks_on): - from warnings import warn + from warnings import warn # noqa: PLC0415 warn( Warning( diff --git a/sentry_sdk/_init_implementation.py b/sentry_sdk/_init_implementation.py index 923fcf6df8..a4de802ae4 100644 --- a/sentry_sdk/_init_implementation.py +++ b/sentry_sdk/_init_implementation.py @@ -67,7 +67,7 @@ def _init(*args: "Optional[str]", **kwargs: "Any") -> "ContextManager[Any]": # Use `ClientConstructor` to define the argument types of `init` and # `ContextManager[Any]` to tell static analyzers about the return type. - class init(sentry_sdk.consts.ClientConstructor, _InitGuard): # noqa: N801 + class init(sentry_sdk.consts.ClientConstructor, _InitGuard): pass else: diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index 16bb8ac02b..eec943176c 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -653,7 +653,7 @@ def _record_lost_event( # Setup Spotlight before creating batchers so _capture_envelope can use it. # setup_spotlight handles all config/env var resolution per the SDK spec. - from sentry_sdk.spotlight import setup_spotlight + from sentry_sdk.spotlight import setup_spotlight # noqa: PLC0415 self.spotlight = setup_spotlight(self.options) if self.spotlight is not None and not self.options["dsn"]: @@ -1559,7 +1559,7 @@ async def __aexit__(self, exc_type: "Any", exc_value: "Any", tb: "Any") -> None: # Use `ClientConstructor` to define the argument types of `init` and # `Dict[str, Any]` to tell static analyzers about the return type. - class get_options(ClientConstructor, Dict[str, Any]): # noqa: N801 + class get_options(ClientConstructor, Dict[str, Any]): pass class Client(ClientConstructor, _Client): diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 95decc19bc..985897a396 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -1388,10 +1388,10 @@ def __init__( environment: "Optional[str]" = None, server_name: "Optional[str]" = None, shutdown_timeout: float = 2, - integrations: "Sequence[sentry_sdk.integrations.Integration]" = [], # noqa: B006 + integrations: "Sequence[sentry_sdk.integrations.Integration]" = [], ignore_spans: "Optional[IgnoreSpansConfig]" = None, - in_app_include: "List[str]" = [], # noqa: B006 - in_app_exclude: "List[str]" = [], # noqa: B006 + in_app_include: "List[str]" = [], + in_app_exclude: "List[str]" = [], default_integrations: bool = True, dist: "Optional[str]" = None, transport: "Optional[Union[sentry_sdk.transport.Transport, Type[sentry_sdk.transport.Transport], Callable[[Event], None]]]" = None, @@ -1401,7 +1401,7 @@ def __init__( data_collection: "Optional[DataCollectionUserOptions]" = None, http_proxy: "Optional[str]" = None, https_proxy: "Optional[str]" = None, - ignore_errors: "Sequence[Union[type, str]]" = [], # noqa: B006 + ignore_errors: "Sequence[Union[type, str]]" = [], max_request_body_size: str = "medium", socket_options: "Optional[List[Tuple[int, int, int | bytes]]]" = None, keep_alive: "Optional[bool]" = None, @@ -1423,7 +1423,7 @@ def __init__( disabled_integrations: "Optional[Sequence[Union[sentry_sdk.integrations.Integration, type[sentry_sdk.integrations.Integration]]]]" = None, auto_session_tracking: bool = True, send_client_reports: bool = True, - _experiments: "Experiments" = {}, # noqa: B006 + _experiments: "Experiments" = {}, proxy_headers: "Optional[Dict[str, str]]" = None, instrumenter: "Optional[str]" = INSTRUMENTER.SENTRY, before_send_transaction: "Optional[TransactionProcessor]" = None, @@ -1431,10 +1431,8 @@ def __init__( enable_tracing: "Optional[bool]" = None, include_local_variables: "Optional[bool]" = True, include_source_context: "Optional[bool]" = True, - trace_propagation_targets: "Optional[Sequence[str]]" = [ # noqa: B006 - MATCH_ALL - ], - functions_to_trace: "Sequence[Dict[str, str]]" = [], # noqa: B006 + trace_propagation_targets: "Optional[Sequence[str]]" = [MATCH_ALL], + functions_to_trace: "Sequence[Dict[str, str]]" = [], event_scrubber: "Optional[sentry_sdk.scrubber.EventScrubber]" = None, max_value_length: "Optional[int]" = DEFAULT_MAX_VALUE_LENGTH, enable_backpressure_handling: bool = True, @@ -1912,7 +1910,7 @@ def __init__( def _get_default_options() -> "dict[str, Any]": - import inspect + import inspect # noqa: PLC0415 a = inspect.getfullargspec(ClientConstructor.__init__) defaults = a.defaults or () diff --git a/sentry_sdk/crons/decorator.py b/sentry_sdk/crons/decorator.py index fd4677709d..3238a88bd4 100644 --- a/sentry_sdk/crons/decorator.py +++ b/sentry_sdk/crons/decorator.py @@ -26,7 +26,7 @@ R = TypeVar("R") -class monitor: # noqa: N801 +class monitor: """ Decorator/context manager to capture checkin events for a monitor. diff --git a/sentry_sdk/integrations/__init__.py b/sentry_sdk/integrations/__init__.py index e61365cc7f..0bc406b01a 100644 --- a/sentry_sdk/integrations/__init__.py +++ b/sentry_sdk/integrations/__init__.py @@ -30,7 +30,7 @@ def iter_default_integrations( with_auto_enabling_integrations: bool, ) -> "Iterator[Type[Integration]]": """Returns an iterator of the default integration classes:""" - from importlib import import_module + from importlib import import_module # noqa: PLC0415 if with_auto_enabling_integrations: all_import_strings = integrations + auto_enabling_integrations @@ -315,7 +315,7 @@ def _check_minimum_version( return -class DidNotEnable(Exception): # noqa: N818 +class DidNotEnable(Exception): """ The integration could not be enabled due to a trivial user error like `flask` not being installed for the `FlaskIntegration`. diff --git a/sentry_sdk/integrations/anthropic.py b/sentry_sdk/integrations/anthropic.py index 6af004f209..a7b6f9e512 100644 --- a/sentry_sdk/integrations/anthropic.py +++ b/sentry_sdk/integrations/anthropic.py @@ -281,7 +281,7 @@ def setup_once() -> None: AsyncMessageStream.close = _wrap_async_close(AsyncMessageStream.close) # type: ignore[method-assign] try: - from functools import cached_property + from functools import cached_property # noqa: PLC0415 except ImportError: return diff --git a/sentry_sdk/integrations/asgi.py b/sentry_sdk/integrations/asgi.py index 9c35351ebb..b1ef63ff84 100644 --- a/sentry_sdk/integrations/asgi.py +++ b/sentry_sdk/integrations/asgi.py @@ -97,7 +97,7 @@ def _looks_like_asgi3(app: "Any") -> bool: elif inspect.isfunction(app): return iscoroutinefunction(app) else: - call = getattr(app, "__call__", None) # noqa + call = getattr(app, "__call__", None) return iscoroutinefunction(call) diff --git a/sentry_sdk/integrations/beam.py b/sentry_sdk/integrations/beam.py index 31f45f73de..5141cfb231 100644 --- a/sentry_sdk/integrations/beam.py +++ b/sentry_sdk/integrations/beam.py @@ -32,7 +32,7 @@ class BeamIntegration(Integration): @staticmethod def setup_once() -> None: - from apache_beam.transforms.core import DoFn, ParDo # type: ignore + from apache_beam.transforms.core import DoFn, ParDo # type: ignore # noqa: PLC0415 ignore_logger("root") ignore_logger("bundle_processor.create") @@ -94,11 +94,11 @@ def _inspect(self: "Any") -> "Any": # getfullargspec is deprecated in more recent beam versions and get_function_args_defaults # (which uses Signatures internally) should be used instead. try: - from apache_beam.transforms.core import get_function_args_defaults + from apache_beam.transforms.core import get_function_args_defaults # noqa: PLC0415 return get_function_args_defaults(process_func) except ImportError: - from apache_beam.typehints.decorators import getfullargspec # type: ignore + from apache_beam.typehints.decorators import getfullargspec # type: ignore # noqa: PLC0415 return getfullargspec(process_func) diff --git a/sentry_sdk/integrations/celery/__init__.py b/sentry_sdk/integrations/celery/__init__.py index 38c76b67c6..69c5751bea 100644 --- a/sentry_sdk/integrations/celery/__init__.py +++ b/sentry_sdk/integrations/celery/__init__.py @@ -497,7 +497,7 @@ def _inner(*args: "Any", **kwargs: "Any") -> "Any": def _patch_build_tracer() -> None: - import celery.app.trace as trace # type: ignore + import celery.app.trace as trace # type: ignore # noqa: PLC0415 original_build_tracer = trace.build_tracer @@ -527,7 +527,7 @@ def _patch_task_apply_async() -> None: def _patch_celery_send_task() -> None: - from celery import Celery + from celery import Celery # noqa: PLC0415 Celery.send_task = _wrap_task_run(Celery.send_task) @@ -535,7 +535,7 @@ def _patch_celery_send_task() -> None: def _patch_worker_exit() -> None: # Need to flush queue before worker shutdown because a crashing worker will # call os._exit - from billiard.pool import Worker # type: ignore + from billiard.pool import Worker # type: ignore # noqa: PLC0415 original_workloop = Worker.workloop diff --git a/sentry_sdk/integrations/celery/beat.py b/sentry_sdk/integrations/celery/beat.py index fbe3593c87..5bbece4e9d 100644 --- a/sentry_sdk/integrations/celery/beat.py +++ b/sentry_sdk/integrations/celery/beat.py @@ -188,7 +188,7 @@ def _wrap_beat_scheduler( if already_patched: return original_function - from sentry_sdk.integrations.celery import CeleryIntegration + from sentry_sdk.integrations.celery import CeleryIntegration # noqa: PLC0415 def sentry_patched_scheduler(*args: "Any", **kwargs: "Any") -> None: integration = sentry_sdk.get_client().get_integration(CeleryIntegration) diff --git a/sentry_sdk/integrations/chalice.py b/sentry_sdk/integrations/chalice.py index 9baa0e5cdd..16deb0950c 100644 --- a/sentry_sdk/integrations/chalice.py +++ b/sentry_sdk/integrations/chalice.py @@ -163,7 +163,7 @@ def setup_once() -> None: if version < (1, 20): old_get_view_function_response = Chalice._get_view_function_response else: - from chalice.app import RestAPIEventHandler + from chalice.app import RestAPIEventHandler # noqa: PLC0415 old_get_view_function_response = ( RestAPIEventHandler._get_view_function_response diff --git a/sentry_sdk/integrations/cloud_resource_context.py b/sentry_sdk/integrations/cloud_resource_context.py index f6285d0a9b..6eb22af0e7 100644 --- a/sentry_sdk/integrations/cloud_resource_context.py +++ b/sentry_sdk/integrations/cloud_resource_context.py @@ -27,7 +27,7 @@ ) -class CLOUD_PROVIDER: # noqa: N801 +class CLOUD_PROVIDER: """ Name of the cloud provider. see https://opentelemetry.io/docs/reference/specification/resource/semantic_conventions/cloud/ @@ -41,7 +41,7 @@ class CLOUD_PROVIDER: # noqa: N801 TENCENT = "tencent_cloud" -class CLOUD_PLATFORM: # noqa: N801 +class CLOUD_PLATFORM: """ The cloud platform. see https://opentelemetry.io/docs/reference/specification/resource/semantic_conventions/cloud/ diff --git a/sentry_sdk/integrations/django/__init__.py b/sentry_sdk/integrations/django/__init__.py index 294b5b56ff..439f023891 100644 --- a/sentry_sdk/integrations/django/__init__.py +++ b/sentry_sdk/integrations/django/__init__.py @@ -187,7 +187,7 @@ def setup_once() -> None: ignore_logger("django.server") ignore_logger("django.request") - from django.core.handlers.wsgi import WSGIHandler + from django.core.handlers.wsgi import WSGIHandler # noqa: PLC0415 old_app = WSGIHandler.__call__ @@ -197,7 +197,7 @@ def sentry_patched_wsgi_handler( ) -> "_ScopedResponse": bound_old_app = old_app.__get__(self, WSGIHandler) - from django.conf import settings + from django.conf import settings # noqa: PLC0415 use_x_forwarded_for = settings.USE_X_FORWARDED_HOST @@ -280,7 +280,7 @@ def _django_queryset_repr( # If we fail to import, return `NotImplemented`. It's at least # unlikely that we have a query set in `value` when importing # `QuerySet` fails. - from django.db.models.query import QuerySet + from django.db.models.query import QuerySet # noqa: PLC0415 except Exception: return NotImplemented @@ -349,7 +349,7 @@ def _patch_drf() -> None: with capture_internal_exceptions(): try: - from rest_framework.views import APIView # type: ignore + from rest_framework.views import APIView # type: ignore # noqa: PLC0415 except ImportError: pass else: @@ -369,7 +369,7 @@ def sentry_patched_drf_initial( with capture_internal_exceptions(): try: - from rest_framework.request import Request # type: ignore + from rest_framework.request import Request # type: ignore # noqa: PLC0415 except ImportError: pass else: @@ -407,7 +407,7 @@ def sentry_patched_drf_authenticate(self: "Request") -> "Any": def _patch_channels() -> None: try: - from channels.http import AsgiHandler # type: ignore + from channels.http import AsgiHandler # type: ignore # noqa: PLC0415 except ImportError: return @@ -424,14 +424,14 @@ def _patch_channels() -> None: + CONTEXTVARS_ERROR_MESSAGE ) - from sentry_sdk.integrations.django.asgi import patch_channels_asgi_handler_impl + from sentry_sdk.integrations.django.asgi import patch_channels_asgi_handler_impl # noqa: PLC0415 patch_channels_asgi_handler_impl(AsgiHandler) def _patch_django_asgi_handler() -> None: try: - from django.core.handlers.asgi import ASGIHandler + from django.core.handlers.asgi import ASGIHandler # noqa: PLC0415 except ImportError: return @@ -445,7 +445,7 @@ def _patch_django_asgi_handler() -> None: "We detected that you are using Django 3." + CONTEXTVARS_ERROR_MESSAGE ) - from sentry_sdk.integrations.django.asgi import patch_django_asgi_handler_impl + from sentry_sdk.integrations.django.asgi import patch_django_asgi_handler_impl # noqa: PLC0415 patch_django_asgi_handler_impl(ASGIHandler) @@ -623,7 +623,7 @@ def _patch_get_response() -> None: """ patch get_response, because at that point we have the Django request object """ - from django.core.handlers.base import BaseHandler + from django.core.handlers.base import BaseHandler # noqa: PLC0415 old_get_response = BaseHandler.get_response @@ -638,7 +638,7 @@ def sentry_patched_get_response( BaseHandler.get_response = sentry_patched_get_response if hasattr(BaseHandler, "get_response_async"): - from sentry_sdk.integrations.django.asgi import patch_get_response_async + from sentry_sdk.integrations.django.asgi import patch_get_response_async # noqa: PLC0415 patch_get_response_async(BaseHandler, _before_get_response) @@ -725,7 +725,7 @@ def _patch_response_for_exception() -> None: too, along with the status code Django picked for them. """ try: - from django.core.handlers import exception as exception_handler + from django.core.handlers import exception as exception_handler # noqa: PLC0415 except ImportError: # Django < 1.10 does this in `BaseHandler`, nothing to patch here return @@ -839,16 +839,16 @@ def _set_user_info(request: "WSGIRequest", event: "Event") -> None: def install_sql_hook() -> None: """If installed this causes Django's queries to be captured.""" try: - from django.db.backends.utils import CursorWrapper + from django.db.backends.utils import CursorWrapper # noqa: PLC0415 except ImportError: - from django.db.backends.util import CursorWrapper + from django.db.backends.util import CursorWrapper # noqa: PLC0415 try: # django 1.6 and 1.7 compatibility - from django.db.backends import BaseDatabaseWrapper + from django.db.backends import BaseDatabaseWrapper # noqa: PLC0415 except ImportError: # django 1.8 or later - from django.db.backends.base.base import BaseDatabaseWrapper + from django.db.backends.base.base import BaseDatabaseWrapper # noqa: PLC0415 try: real_execute = CursorWrapper.execute @@ -1077,7 +1077,7 @@ def _set_db_data( def add_template_context_repr_sequence() -> None: try: - from django.template.context import BaseContext + from django.template.context import BaseContext # noqa: PLC0415 add_repr_sequence_type(BaseContext) except Exception: diff --git a/sentry_sdk/integrations/django/asgi.py b/sentry_sdk/integrations/django/asgi.py index df287e6436..9816b05334 100644 --- a/sentry_sdk/integrations/django/asgi.py +++ b/sentry_sdk/integrations/django/asgi.py @@ -57,7 +57,7 @@ def asgi_request_event_processor(event: "Event", hint: "dict[str, Any]") -> "Eve # if the request is gone we are fine not logging the data from # it. This might happen if the processor is pushed away to # another thread. - from sentry_sdk.integrations.django import ( + from sentry_sdk.integrations.django import ( # noqa: PLC0415 DjangoRequestExtractor, _set_user_info, ) @@ -86,7 +86,7 @@ def asgi_request_event_processor(event: "Event", hint: "dict[str, Any]") -> "Eve def patch_django_asgi_handler_impl(cls: "Any") -> None: - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 old_app = cls.__call__ @@ -138,9 +138,9 @@ async def sentry_patched_get_response_async( def patch_channels_asgi_handler_impl(cls: "Any") -> None: - import channels # type: ignore + import channels # type: ignore # noqa: PLC0415 - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 if channels.__version__ < "3.0.0": old_app = cls.__call__ @@ -170,7 +170,7 @@ async def sentry_patched_asgi_handler( def wrap_async_view(callback: "Any") -> "Any": - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 @functools.wraps(callback) async def sentry_wrapped_callback( diff --git a/sentry_sdk/integrations/django/caching.py b/sentry_sdk/integrations/django/caching.py index 2cfc0cd2e1..8690bab05b 100644 --- a/sentry_sdk/integrations/django/caching.py +++ b/sentry_sdk/integrations/django/caching.py @@ -38,7 +38,7 @@ def _patch_cache_method( address: "Optional[str]", port: "Optional[int]", ) -> None: - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 original_method = getattr(cache, method_name) @@ -213,11 +213,11 @@ def _get_address_port( def should_enable_cache_spans() -> bool: - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 client = sentry_sdk.get_client() integration = client.get_integration(DjangoIntegration) - from django.conf import settings + from django.conf import settings # noqa: PLC0415 return integration is not None and ( (client.spotlight is not None and settings.DEBUG is True) @@ -235,7 +235,7 @@ def sentry_get_item(self: "CacheHandler", alias: str) -> "Any": cache = original_get_item(self, alias) if should_enable_cache_spans(): - from django.conf import settings + from django.conf import settings # noqa: PLC0415 address, port = _get_address_port( settings.CACHES[alias or "default"] diff --git a/sentry_sdk/integrations/django/middleware.py b/sentry_sdk/integrations/django/middleware.py index 01ed8962e0..5f18549b10 100644 --- a/sentry_sdk/integrations/django/middleware.py +++ b/sentry_sdk/integrations/django/middleware.py @@ -38,7 +38,7 @@ def patch_django_middlewares() -> None: - from django.core.handlers import base + from django.core.handlers import base # noqa: PLC0415 old_import_string = base.import_string @@ -65,7 +65,7 @@ def sentry_patched_load_middleware(*args: "Any", **kwargs: "Any") -> "Any": def _wrap_middleware(middleware: "Any", middleware_name: str) -> "Any": - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 def _check_middleware_span( old_method: "Callable[..., Any]", diff --git a/sentry_sdk/integrations/django/signals_handlers.py b/sentry_sdk/integrations/django/signals_handlers.py index 1df42c47fa..93e155ddbb 100644 --- a/sentry_sdk/integrations/django/signals_handlers.py +++ b/sentry_sdk/integrations/django/signals_handlers.py @@ -44,7 +44,7 @@ def patch_signals() -> None: This only wraps sync receivers. Django>=5.0 introduced async receivers, but since we don't create transactions for ASGI Django, we don't wrap them. """ - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 old_live_receivers = Signal._live_receivers diff --git a/sentry_sdk/integrations/django/tasks.py b/sentry_sdk/integrations/django/tasks.py index 303040d042..9b4face45e 100644 --- a/sentry_sdk/integrations/django/tasks.py +++ b/sentry_sdk/integrations/django/tasks.py @@ -25,7 +25,7 @@ def patch_tasks() -> None: @wraps(old_task_enqueue) def _sentry_enqueue(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 integration = sentry_sdk.get_client().get_integration(DjangoIntegration) if integration is None: diff --git a/sentry_sdk/integrations/django/templates.py b/sentry_sdk/integrations/django/templates.py index 1c0986dd9e..0f77f3213c 100644 --- a/sentry_sdk/integrations/django/templates.py +++ b/sentry_sdk/integrations/django/templates.py @@ -53,9 +53,9 @@ def _get_template_name_description(template_name: str) -> str: def patch_templates() -> None: - from django.template.response import SimpleTemplateResponse + from django.template.response import SimpleTemplateResponse # noqa: PLC0415 - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 real_rendered_content = SimpleTemplateResponse.rendered_content @@ -87,7 +87,7 @@ def rendered_content(self: "SimpleTemplateResponse") -> str: if DJANGO_VERSION < (1, 7): return - import django.shortcuts + import django.shortcuts # noqa: PLC0415 real_render = django.shortcuts.render diff --git a/sentry_sdk/integrations/django/views.py b/sentry_sdk/integrations/django/views.py index d37d54117d..4be88586c6 100644 --- a/sentry_sdk/integrations/django/views.py +++ b/sentry_sdk/integrations/django/views.py @@ -13,10 +13,10 @@ def patch_views() -> None: - from django.core.handlers.base import BaseHandler - from django.template.response import SimpleTemplateResponse + from django.core.handlers.base import BaseHandler # noqa: PLC0415 + from django.template.response import SimpleTemplateResponse # noqa: PLC0415 - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 old_make_view_atomic = BaseHandler.make_view_atomic old_render = SimpleTemplateResponse.render @@ -65,7 +65,7 @@ def sentry_patched_make_view_atomic( def _wrap_sync_view(callback: "Any") -> "Any": - from sentry_sdk.integrations.django import DjangoIntegration + from sentry_sdk.integrations.django import DjangoIntegration # noqa: PLC0415 @functools.wraps(callback) def sentry_wrapped_callback(request: "Any", *args: "Any", **kwargs: "Any") -> "Any": diff --git a/sentry_sdk/integrations/flask.py b/sentry_sdk/integrations/flask.py index b99a3b49eb..b3aaa29246 100644 --- a/sentry_sdk/integrations/flask.py +++ b/sentry_sdk/integrations/flask.py @@ -74,7 +74,7 @@ def __init__( @staticmethod def setup_once() -> None: try: - from quart import Quart # type: ignore + from quart import Quart # type: ignore # noqa: PLC0415 if Flask == Quart: # This is Quart masquerading as Flask, don't enable the Flask diff --git a/sentry_sdk/integrations/gcp.py b/sentry_sdk/integrations/gcp.py index c0debc8094..d6feb25017 100644 --- a/sentry_sdk/integrations/gcp.py +++ b/sentry_sdk/integrations/gcp.py @@ -200,7 +200,7 @@ def __init__(self, timeout_warning: bool = False) -> None: @staticmethod def setup_once() -> None: - import __main__ as gcp_functions + import __main__ as gcp_functions # noqa: PLC0415 if not hasattr(gcp_functions, "worker_v1"): logger.warning( diff --git a/sentry_sdk/integrations/grpc/__init__.py b/sentry_sdk/integrations/grpc/__init__.py index bf74ff1351..5e074f0e41 100644 --- a/sentry_sdk/integrations/grpc/__init__.py +++ b/sentry_sdk/integrations/grpc/__init__.py @@ -175,7 +175,7 @@ class GRPCIntegration(Integration): @staticmethod def setup_once() -> None: - import grpc + import grpc # noqa: PLC0415 grpc.insecure_channel = _wrap_channel_sync(grpc.insecure_channel) grpc.secure_channel = _wrap_channel_sync(grpc.secure_channel) diff --git a/sentry_sdk/integrations/litestar.py b/sentry_sdk/integrations/litestar.py index 593ac158aa..612c4fbfe8 100644 --- a/sentry_sdk/integrations/litestar.py +++ b/sentry_sdk/integrations/litestar.py @@ -144,7 +144,7 @@ def resolve_middleware_wrapper(self: "BaseRouteHandler") -> "list[Middleware]": def enable_span_for_middleware(middleware: "Middleware") -> "Middleware": if ( - not hasattr(middleware, "__call__") # noqa: B004 + not hasattr(middleware, "__call__") or middleware is SentryLitestarASGIMiddleware ): return middleware diff --git a/sentry_sdk/integrations/openai.py b/sentry_sdk/integrations/openai.py index 04ae33daff..4c30002efa 100644 --- a/sentry_sdk/integrations/openai.py +++ b/sentry_sdk/integrations/openai.py @@ -129,7 +129,7 @@ def __init__( self.tiktoken_encoding = None if tiktoken_encoding_name is not None: - import tiktoken + import tiktoken # noqa: PLC0415 self.tiktoken_encoding = tiktoken.get_encoding(tiktoken_encoding_name) diff --git a/sentry_sdk/integrations/openai_agents/patches/error_tracing.py b/sentry_sdk/integrations/openai_agents/patches/error_tracing.py index 2135ecd753..3716aece8f 100644 --- a/sentry_sdk/integrations/openai_agents/patches/error_tracing.py +++ b/sentry_sdk/integrations/openai_agents/patches/error_tracing.py @@ -24,7 +24,7 @@ def _patch_error_tracing() -> None: # Try newer location first (agents.util._error_tracing) try: - from agents.util import _error_tracing + from agents.util import _error_tracing # noqa: PLC0415 error_tracing_module = _error_tracing except (ImportError, AttributeError): @@ -33,7 +33,7 @@ def _patch_error_tracing() -> None: # Try older location (agents._utils) if error_tracing_module is None: try: - import agents._utils + import agents._utils # noqa: PLC0415 error_tracing_module = agents._utils except (ImportError, AttributeError): diff --git a/sentry_sdk/integrations/pydantic_ai/__init__.py b/sentry_sdk/integrations/pydantic_ai/__init__.py index a3215aa284..8dda4d3e5e 100644 --- a/sentry_sdk/integrations/pydantic_ai/__init__.py +++ b/sentry_sdk/integrations/pydantic_ai/__init__.py @@ -129,7 +129,7 @@ def setup_once() -> None: return try: - from pydantic_ai.capabilities import Hooks + from pydantic_ai.capabilities import Hooks # noqa: PLC0415 except ImportError: return diff --git a/sentry_sdk/integrations/pydantic_ai/patches/tools.py b/sentry_sdk/integrations/pydantic_ai/patches/tools.py index a88e1d5712..c4bde8d1c7 100644 --- a/sentry_sdk/integrations/pydantic_ai/patches/tools.py +++ b/sentry_sdk/integrations/pydantic_ai/patches/tools.py @@ -85,7 +85,7 @@ async def wrapped_execute_tool_call( exc_info = sys.exc_info() with capture_internal_exceptions(): # Avoid circular import due to multi-file integration structure - from sentry_sdk.integrations.pydantic_ai import ( + from sentry_sdk.integrations.pydantic_ai import ( # noqa: PLC0415 PydanticAIIntegration, ) @@ -158,7 +158,7 @@ async def wrapped_call_tool( exc_info = sys.exc_info() with capture_internal_exceptions(): # Avoid circular import due to multi-file integration structure - from sentry_sdk.integrations.pydantic_ai import ( + from sentry_sdk.integrations.pydantic_ai import ( # noqa: PLC0415 PydanticAIIntegration, ) diff --git a/sentry_sdk/integrations/pydantic_ai/utils.py b/sentry_sdk/integrations/pydantic_ai/utils.py index c847c143b5..6a2a8f60bb 100644 --- a/sentry_sdk/integrations/pydantic_ai/utils.py +++ b/sentry_sdk/integrations/pydantic_ai/utils.py @@ -63,7 +63,7 @@ def _should_send_prompts_legacy() -> bool: if not should_send_default_pii(): return False - from . import PydanticAIIntegration + from . import PydanticAIIntegration # noqa: PLC0415 # Get the integration instance from the client integration = sentry_sdk.get_client().get_integration(PydanticAIIntegration) diff --git a/sentry_sdk/integrations/pyramid.py b/sentry_sdk/integrations/pyramid.py index 49f734f52b..d1bc6e81e1 100644 --- a/sentry_sdk/integrations/pyramid.py +++ b/sentry_sdk/integrations/pyramid.py @@ -69,7 +69,7 @@ def __init__(self, transaction_style: str = "route_name") -> None: @staticmethod def setup_once() -> None: - from pyramid import router + from pyramid import router # noqa: PLC0415 old_call_view = router._call_view diff --git a/sentry_sdk/integrations/redis/__init__.py b/sentry_sdk/integrations/redis/__init__.py index 7095721ed2..7f3c06ff37 100644 --- a/sentry_sdk/integrations/redis/__init__.py +++ b/sentry_sdk/integrations/redis/__init__.py @@ -35,7 +35,7 @@ def __init__( @staticmethod def setup_once() -> None: try: - from redis import StrictRedis, client + from redis import StrictRedis, client # noqa: PLC0415 except ImportError: raise DidNotEnable("Redis client not installed") diff --git a/sentry_sdk/integrations/redis/_async_common.py b/sentry_sdk/integrations/redis/_async_common.py index 956fe91154..a121ab9f4a 100644 --- a/sentry_sdk/integrations/redis/_async_common.py +++ b/sentry_sdk/integrations/redis/_async_common.py @@ -38,7 +38,7 @@ def patch_redis_async_pipeline( ) -> None: old_execute = pipeline_cls.execute - from sentry_sdk.integrations.redis import RedisIntegration + from sentry_sdk.integrations.redis import RedisIntegration # noqa: PLC0415 async def _sentry_execute(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": client = sentry_sdk.get_client() @@ -106,7 +106,7 @@ def patch_redis_async_client( ) -> None: old_execute_command = cls.execute_command - from sentry_sdk.integrations.redis import RedisIntegration + from sentry_sdk.integrations.redis import RedisIntegration # noqa: PLC0415 async def _sentry_execute_command( self: "Any", name: str, *args: "Any", **kwargs: "Any" diff --git a/sentry_sdk/integrations/redis/_sync_common.py b/sentry_sdk/integrations/redis/_sync_common.py index fcb1822094..739cbfbb15 100644 --- a/sentry_sdk/integrations/redis/_sync_common.py +++ b/sentry_sdk/integrations/redis/_sync_common.py @@ -35,7 +35,7 @@ def patch_redis_pipeline( ) -> None: old_execute = pipeline_cls.execute - from sentry_sdk.integrations.redis import RedisIntegration + from sentry_sdk.integrations.redis import RedisIntegration # noqa: PLC0415 def sentry_patched_execute(self: "Any", *args: "Any", **kwargs: "Any") -> "Any": client = sentry_sdk.get_client() @@ -104,7 +104,7 @@ def patch_redis_client( """ old_execute_command = cls.execute_command - from sentry_sdk.integrations.redis import RedisIntegration + from sentry_sdk.integrations.redis import RedisIntegration # noqa: PLC0415 def sentry_patched_execute_command( self: "Any", name: str, *args: "Any", **kwargs: "Any" diff --git a/sentry_sdk/integrations/redis/rb.py b/sentry_sdk/integrations/redis/rb.py index e2ce863fe8..05c4455a35 100644 --- a/sentry_sdk/integrations/redis/rb.py +++ b/sentry_sdk/integrations/redis/rb.py @@ -10,7 +10,7 @@ def _patch_rb() -> None: try: - import rb.clients # type: ignore + import rb.clients # type: ignore # noqa: PLC0415 except ImportError: pass else: diff --git a/sentry_sdk/integrations/redis/redis.py b/sentry_sdk/integrations/redis/redis.py index e704c9bc6a..349ee5bed6 100644 --- a/sentry_sdk/integrations/redis/redis.py +++ b/sentry_sdk/integrations/redis/redis.py @@ -20,7 +20,7 @@ def _get_redis_command_args(command: "Any") -> "Sequence[Any]": return command[0] -def _patch_redis(StrictRedis: "Any", client: "Any") -> None: # noqa: N803 +def _patch_redis(StrictRedis: "Any", client: "Any") -> None: patch_redis_client( StrictRedis, is_cluster=False, @@ -45,11 +45,11 @@ def _patch_redis(StrictRedis: "Any", client: "Any") -> None: # noqa: N803 ) try: - import redis.asyncio + import redis.asyncio # noqa: PLC0415 except ImportError: pass else: - from sentry_sdk.integrations.redis._async_common import ( + from sentry_sdk.integrations.redis._async_common import ( # noqa: PLC0415 patch_redis_async_client, patch_redis_async_pipeline, ) diff --git a/sentry_sdk/integrations/redis/redis_cluster.py b/sentry_sdk/integrations/redis/redis_cluster.py index b6c95e6abd..059ddc3497 100644 --- a/sentry_sdk/integrations/redis/redis_cluster.py +++ b/sentry_sdk/integrations/redis/redis_cluster.py @@ -76,7 +76,7 @@ def _set_cluster_db_data( def _patch_redis_cluster() -> None: """Patches the cluster module on redis SDK (as opposed to rediscluster library)""" try: - from redis import RedisCluster, cluster + from redis import RedisCluster, cluster # noqa: PLC0415 except ImportError: pass else: @@ -93,11 +93,11 @@ def _patch_redis_cluster() -> None: ) try: - from redis.asyncio import cluster as async_cluster + from redis.asyncio import cluster as async_cluster # noqa: PLC0415 except ImportError: pass else: - from sentry_sdk.integrations.redis._async_common import ( + from sentry_sdk.integrations.redis._async_common import ( # noqa: PLC0415 patch_redis_async_client, patch_redis_async_pipeline, ) diff --git a/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py b/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py index 3437aa1f2f..d8c266b595 100644 --- a/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py +++ b/sentry_sdk/integrations/redis/redis_py_cluster_legacy.py @@ -15,7 +15,7 @@ def _patch_rediscluster() -> None: try: - import rediscluster # type: ignore + import rediscluster # type: ignore # noqa: PLC0415 except ImportError: return diff --git a/sentry_sdk/integrations/rust_tracing.py b/sentry_sdk/integrations/rust_tracing.py index d02b7fb5ab..c8d5a10d60 100644 --- a/sentry_sdk/integrations/rust_tracing.py +++ b/sentry_sdk/integrations/rust_tracing.py @@ -200,7 +200,7 @@ def on_new_span( if message is not None: sentry_span_name = message elif module_path is not None and name is not None: - sentry_span_name = f"{module_path}::{name}" # noqa: E231 + sentry_span_name = f"{module_path}::{name}" elif name is not None: sentry_span_name = name else: diff --git a/sentry_sdk/integrations/spark/spark_driver.py b/sentry_sdk/integrations/spark/spark_driver.py index a83532b6a6..620845ad05 100644 --- a/sentry_sdk/integrations/spark/spark_driver.py +++ b/sentry_sdk/integrations/spark/spark_driver.py @@ -25,7 +25,7 @@ def _set_app_properties() -> None: Set properties in driver that propagate to worker processes, allowing for workers to have access to those properties. This allows worker integration to have access to app_name and application_id. """ - from pyspark import SparkContext + from pyspark import SparkContext # noqa: PLC0415 spark_context = SparkContext._active_spark_context if spark_context: @@ -43,7 +43,7 @@ def _start_sentry_listener(sc: "SparkContext") -> None: """ Start java gateway server to add custom `SparkListener` """ - from pyspark.java_gateway import ensure_callback_server_started + from pyspark.java_gateway import ensure_callback_server_started # noqa: PLC0415 gw = sc._gateway ensure_callback_server_started(gw) @@ -92,7 +92,7 @@ def _activate_integration(sc: "SparkContext") -> None: def _patch_spark_context_init() -> None: - from pyspark import SparkContext + from pyspark import SparkContext # noqa: PLC0415 spark_context_init = SparkContext._do_init @@ -108,7 +108,7 @@ def _sentry_patched_spark_context_init( def _setup_sentry_tracing() -> None: - from pyspark import SparkContext + from pyspark import SparkContext # noqa: PLC0415 if SparkContext._active_spark_context is not None: _activate_integration(SparkContext._active_spark_context) @@ -117,79 +117,79 @@ def _setup_sentry_tracing() -> None: class SparkListener: - def onApplicationEnd(self, applicationEnd: "Any") -> None: # noqa: N802,N803 + def onApplicationEnd(self, applicationEnd: "Any") -> None: pass - def onApplicationStart(self, applicationStart: "Any") -> None: # noqa: N802,N803 + def onApplicationStart(self, applicationStart: "Any") -> None: pass - def onBlockManagerAdded(self, blockManagerAdded: "Any") -> None: # noqa: N802,N803 + def onBlockManagerAdded(self, blockManagerAdded: "Any") -> None: pass - def onBlockManagerRemoved(self, blockManagerRemoved: "Any") -> None: # noqa: N802,N803 + def onBlockManagerRemoved(self, blockManagerRemoved: "Any") -> None: pass - def onBlockUpdated(self, blockUpdated: "Any") -> None: # noqa: N802,N803 + def onBlockUpdated(self, blockUpdated: "Any") -> None: pass - def onEnvironmentUpdate(self, environmentUpdate: "Any") -> None: # noqa: N802,N803 + def onEnvironmentUpdate(self, environmentUpdate: "Any") -> None: pass - def onExecutorAdded(self, executorAdded: "Any") -> None: # noqa: N802,N803 + def onExecutorAdded(self, executorAdded: "Any") -> None: pass - def onExecutorBlacklisted(self, executorBlacklisted: "Any") -> None: # noqa: N802,N803 + def onExecutorBlacklisted(self, executorBlacklisted: "Any") -> None: pass - def onExecutorBlacklistedForStage( # noqa: N802 + def onExecutorBlacklistedForStage( self, - executorBlacklistedForStage: "Any", # noqa: N803 + executorBlacklistedForStage: "Any", ) -> None: pass - def onExecutorMetricsUpdate(self, executorMetricsUpdate: "Any") -> None: # noqa: N802,N803 + def onExecutorMetricsUpdate(self, executorMetricsUpdate: "Any") -> None: pass - def onExecutorRemoved(self, executorRemoved: "Any") -> None: # noqa: N802,N803 + def onExecutorRemoved(self, executorRemoved: "Any") -> None: pass - def onJobEnd(self, jobEnd: "Any") -> None: # noqa: N802,N803 + def onJobEnd(self, jobEnd: "Any") -> None: pass - def onJobStart(self, jobStart: "Any") -> None: # noqa: N802,N803 + def onJobStart(self, jobStart: "Any") -> None: pass - def onNodeBlacklisted(self, nodeBlacklisted: "Any") -> None: # noqa: N802,N803 + def onNodeBlacklisted(self, nodeBlacklisted: "Any") -> None: pass - def onNodeBlacklistedForStage(self, nodeBlacklistedForStage: "Any") -> None: # noqa: N802,N803 + def onNodeBlacklistedForStage(self, nodeBlacklistedForStage: "Any") -> None: pass - def onNodeUnblacklisted(self, nodeUnblacklisted: "Any") -> None: # noqa: N802,N803 + def onNodeUnblacklisted(self, nodeUnblacklisted: "Any") -> None: pass - def onOtherEvent(self, event: "Any") -> None: # noqa: N802,N803 + def onOtherEvent(self, event: "Any") -> None: pass - def onSpeculativeTaskSubmitted(self, speculativeTask: "Any") -> None: # noqa: N802,N803 + def onSpeculativeTaskSubmitted(self, speculativeTask: "Any") -> None: pass - def onStageCompleted(self, stageCompleted: "Any") -> None: # noqa: N802,N803 + def onStageCompleted(self, stageCompleted: "Any") -> None: pass - def onStageSubmitted(self, stageSubmitted: "Any") -> None: # noqa: N802,N803 + def onStageSubmitted(self, stageSubmitted: "Any") -> None: pass - def onTaskEnd(self, taskEnd: "Any") -> None: # noqa: N802,N803 + def onTaskEnd(self, taskEnd: "Any") -> None: pass - def onTaskGettingResult(self, taskGettingResult: "Any") -> None: # noqa: N802,N803 + def onTaskGettingResult(self, taskGettingResult: "Any") -> None: pass - def onTaskStart(self, taskStart: "Any") -> None: # noqa: N802,N803 + def onTaskStart(self, taskStart: "Any") -> None: pass - def onUnpersistRDD(self, unpersistRDD: "Any") -> None: # noqa: N802,N803 + def onUnpersistRDD(self, unpersistRDD: "Any") -> None: pass class Java: @@ -207,14 +207,14 @@ def _add_breadcrumb( level=level, message=message, data=data ) - def onJobStart(self, jobStart: "Any") -> None: # noqa: N802,N803 + def onJobStart(self, jobStart: "Any") -> None: sentry_sdk.get_isolation_scope().clear_breadcrumbs() message = "Job {} Started".format(jobStart.jobId()) self._add_breadcrumb(level="info", message=message) _set_app_properties() - def onJobEnd(self, jobEnd: "Any") -> None: # noqa: N802,N803 + def onJobEnd(self, jobEnd: "Any") -> None: level = "" message = "" data = {"result": jobEnd.jobResult().toString()} @@ -228,7 +228,7 @@ def onJobEnd(self, jobEnd: "Any") -> None: # noqa: N802,N803 self._add_breadcrumb(level=level, message=message, data=data) - def onStageSubmitted(self, stageSubmitted: "Any") -> None: # noqa: N802,N803 + def onStageSubmitted(self, stageSubmitted: "Any") -> None: stage_info = stageSubmitted.stageInfo() message = "Stage {} Submitted".format(stage_info.stageId()) @@ -240,8 +240,8 @@ def onStageSubmitted(self, stageSubmitted: "Any") -> None: # noqa: N802,N803 self._add_breadcrumb(level="info", message=message, data=data) _set_app_properties() - def onStageCompleted(self, stageCompleted: "Any") -> None: # noqa: N802,N803 - from py4j.protocol import Py4JJavaError # type: ignore + def onStageCompleted(self, stageCompleted: "Any") -> None: + from py4j.protocol import Py4JJavaError # type: ignore # noqa: PLC0415 stage_info = stageCompleted.stageInfo() message = "" diff --git a/sentry_sdk/integrations/spark/spark_worker.py b/sentry_sdk/integrations/spark/spark_worker.py index 5906472748..b8ab3a1660 100644 --- a/sentry_sdk/integrations/spark/spark_worker.py +++ b/sentry_sdk/integrations/spark/spark_worker.py @@ -22,7 +22,7 @@ class SparkWorkerIntegration(Integration): @staticmethod def setup_once() -> None: - import pyspark.daemon as original_daemon + import pyspark.daemon as original_daemon # noqa: PLC0415 original_daemon.worker_main = _sentry_worker_main @@ -57,7 +57,7 @@ def _capture_exception(exc_info: "ExcInfo") -> None: def _tag_task_context() -> None: - from pyspark.taskcontext import TaskContext + from pyspark.taskcontext import TaskContext # noqa: PLC0415 scope = sentry_sdk.get_isolation_scope() @@ -98,7 +98,7 @@ def process_event(event: "Event", hint: "Hint") -> "Optional[Event]": def _sentry_worker_main(*args: "Optional[Any]", **kwargs: "Optional[Any]") -> None: - import pyspark.worker as original_worker + import pyspark.worker as original_worker # noqa: PLC0415 try: original_worker.main(*args, **kwargs) diff --git a/sentry_sdk/integrations/starlette.py b/sentry_sdk/integrations/starlette.py index 33d50bba81..c5a18fbf06 100644 --- a/sentry_sdk/integrations/starlette.py +++ b/sentry_sdk/integrations/starlette.py @@ -740,13 +740,13 @@ def patch_templates() -> None: # (markupsafe is a dependency of Jinja2) # In this case we do not need to patch the Jinja2Templates class try: - from markupsafe import Markup + from markupsafe import Markup # noqa: PLC0415 except ImportError: return # Nothing to do # https://github.com/Kludex/starlette/commit/96479daca2e4bd8157f68d914fd162aa94eff73a try: - from starlette.templating import Jinja2Templates + from starlette.templating import Jinja2Templates # noqa: PLC0415 except ImportError: return diff --git a/sentry_sdk/integrations/starlite.py b/sentry_sdk/integrations/starlite.py index 398412c762..70a1540263 100644 --- a/sentry_sdk/integrations/starlite.py +++ b/sentry_sdk/integrations/starlite.py @@ -129,7 +129,7 @@ def resolve_middleware_wrapper(self: "BaseRouteHandler") -> "list[Middleware]": def enable_span_for_middleware(middleware: "Middleware") -> "Middleware": if ( - not hasattr(middleware, "__call__") # noqa: B004 + not hasattr(middleware, "__call__") or middleware is SentryStarliteASGIMiddleware ): return middleware diff --git a/sentry_sdk/integrations/threading.py b/sentry_sdk/integrations/threading.py index f3ba046332..4fde3a3d14 100644 --- a/sentry_sdk/integrations/threading.py +++ b/sentry_sdk/integrations/threading.py @@ -49,12 +49,12 @@ def setup_once() -> None: old_start = Thread.start try: - from django import VERSION as django_version # noqa: N811 + from django import VERSION as django_version # noqa: PLC0415 except ImportError: django_version = None try: - import channels # type: ignore[import-untyped] + import channels # type: ignore[import-untyped] # noqa: PLC0415 channels_version = channels.__version__ except (ImportError, AttributeError): diff --git a/sentry_sdk/scope.py b/sentry_sdk/scope.py index 78f974a533..e7e044ab0b 100644 --- a/sentry_sdk/scope.py +++ b/sentry_sdk/scope.py @@ -378,7 +378,7 @@ def get_global_scope(cls) -> "Scope": return _global_scope def set_global_attributes(self) -> None: - from sentry_sdk.client import SDK_INFO + from sentry_sdk.client import SDK_INFO # noqa: PLC0415 self.set_attribute(SPANDATA.SENTRY_SDK_NAME, SDK_INFO["name"]) self.set_attribute(SPANDATA.SENTRY_SDK_VERSION, SDK_INFO["version"]) diff --git a/sentry_sdk/spotlight.py b/sentry_sdk/spotlight.py index 93cf33be13..21165160c8 100644 --- a/sentry_sdk/spotlight.py +++ b/sentry_sdk/spotlight.py @@ -118,7 +118,7 @@ class SpotlightMiddleware(MiddlewareMixin): # type: ignore[misc] def __init__(self: "Self", get_response: "Callable[..., HttpResponse]") -> None: super().__init__(get_response) - import sentry_sdk.api + import sentry_sdk.api # noqa: PLC0415 self.sentry_sdk = sentry_sdk.api diff --git a/sentry_sdk/traces.py b/sentry_sdk/traces.py index 0d317be083..30a8eac35c 100644 --- a/sentry_sdk/traces.py +++ b/sentry_sdk/traces.py @@ -174,7 +174,7 @@ def start_span( :return: The span that has been started. :rtype: StreamedSpan """ - from sentry_sdk.tracing_utils import has_span_streaming_enabled + from sentry_sdk.tracing_utils import has_span_streaming_enabled # noqa: PLC0415 client = sentry_sdk.get_client() if client.is_active() and not has_span_streaming_enabled(client.options): @@ -864,7 +864,7 @@ def make_db_query(sql): # Function implementation pass """ - from sentry_sdk.tracing_utils import ( + from sentry_sdk.tracing_utils import ( # noqa: PLC0415 create_streaming_span_decorator, ) diff --git a/sentry_sdk/tracing.py b/sentry_sdk/tracing.py index 38922773ea..c55b3ab5be 100644 --- a/sentry_sdk/tracing.py +++ b/sentry_sdk/tracing.py @@ -1466,7 +1466,7 @@ def calculate_interest_rate(amount, rate, years): # Function implementation pass """ - from sentry_sdk.tracing_utils import create_span_decorator + from sentry_sdk.tracing_utils import create_span_decorator # noqa: PLC0415 decorator = create_span_decorator( op=op, diff --git a/sentry_sdk/tracing_utils.py b/sentry_sdk/tracing_utils.py index 4d4c35ce39..dd91da3b4d 100644 --- a/sentry_sdk/tracing_utils.py +++ b/sentry_sdk/tracing_utils.py @@ -723,7 +723,7 @@ def _fill_sample_rand(self) -> None: ) return - self.baggage.sentry_items["sample_rand"] = f"{sample_rand:.6f}" # noqa: E231 + self.baggage.sentry_items["sample_rand"] = f"{sample_rand:.6f}" def _sample_rand(self) -> "Optional[str]": """Convenience method to get the sample_rand value from the baggage.""" @@ -859,7 +859,7 @@ def populate_from_transaction( options = client.options or {} sentry_items["trace_id"] = transaction.trace_id - sentry_items["sample_rand"] = f"{transaction._sample_rand:.6f}" # noqa: E231 + sentry_items["sample_rand"] = f"{transaction._sample_rand:.6f}" if options.get("environment"): sentry_items["environment"] = options["environment"] diff --git a/sentry_sdk/transport.py b/sentry_sdk/transport.py index 85308c7797..00fd57749d 100644 --- a/sentry_sdk/transport.py +++ b/sentry_sdk/transport.py @@ -73,10 +73,10 @@ KEEP_ALIVE_SOCKET_OPTIONS = [] for option in [ - (socket.SOL_SOCKET, lambda: getattr(socket, "SO_KEEPALIVE"), 1), # noqa: B009 - (socket.SOL_TCP, lambda: getattr(socket, "TCP_KEEPIDLE"), 45), # noqa: B009 - (socket.SOL_TCP, lambda: getattr(socket, "TCP_KEEPINTVL"), 10), # noqa: B009 - (socket.SOL_TCP, lambda: getattr(socket, "TCP_KEEPCNT"), 6), # noqa: B009 + (socket.SOL_SOCKET, lambda: getattr(socket, "SO_KEEPALIVE"), 1), + (socket.SOL_TCP, lambda: getattr(socket, "TCP_KEEPIDLE"), 45), + (socket.SOL_TCP, lambda: getattr(socket, "TCP_KEEPINTVL"), 10), + (socket.SOL_TCP, lambda: getattr(socket, "TCP_KEEPCNT"), 6), ]: try: KEEP_ALIVE_SOCKET_OPTIONS.append((option[0], option[1](), option[2])) @@ -217,7 +217,7 @@ class HttpTransportCore(Transport): TIMEOUT = 30 # seconds def __init__(self: "Self", options: "Dict[str, Any]") -> None: - from sentry_sdk.consts import VERSION + from sentry_sdk.consts import VERSION # noqa: PLC0415 Transport.__init__(self, options) assert self.parsed_dsn is not None @@ -821,7 +821,7 @@ def _make_pool(self: "Self") -> "Union[PoolManager, ProxyManager]": use_socks_proxy = True try: # Check if PySocks dependency is available - from urllib3.contrib.socks import SOCKSProxyManager + from urllib3.contrib.socks import SOCKSProxyManager # noqa: PLC0415 except ImportError: use_socks_proxy = False logger.warning( diff --git a/sentry_sdk/utils.py b/sentry_sdk/utils.py index 6d4d46993f..e679cb134e 100644 --- a/sentry_sdk/utils.py +++ b/sentry_sdk/utils.py @@ -592,7 +592,7 @@ def serialize_frame( max_value_length: "Optional[int]" = None, custom_repr: "Optional[Callable[..., Optional[str]]]" = None, ) -> "Dict[str, Any]": - from sentry_sdk.serializer import serialize + from sentry_sdk.serializer import serialize # noqa: PLC0415 f_code = getattr(frame, "f_code", None) if not f_code: @@ -1364,8 +1364,8 @@ def _is_contextvars_broken() -> bool: Returns whether gevent/eventlet have patched the stdlib in a way where thread locals are now more "correct" than contextvars. """ try: - import gevent - from gevent.monkey import is_object_patched + import gevent # noqa: PLC0415 + from gevent.monkey import is_object_patched # noqa: PLC0415 # Get the MAJOR and MINOR version numbers of Gevent version_tuple = tuple( @@ -1391,8 +1391,8 @@ def _is_contextvars_broken() -> bool: pass try: - import greenlet - from eventlet.patcher import is_monkey_patched # type: ignore + import greenlet # noqa: PLC0415 + from eventlet.patcher import is_monkey_patched # type: ignore # noqa: PLC0415 greenlet_version = parse_version(greenlet.__version__) @@ -1454,7 +1454,7 @@ def _get_contextvars() -> "Tuple[bool, type]": # `aiocontextvars` is absolutely required for functional # contextvars on Python 3.6. try: - from aiocontextvars import ContextVar + from aiocontextvars import ContextVar # noqa: PLC0415 return True, ContextVar except ImportError: @@ -1462,7 +1462,7 @@ def _get_contextvars() -> "Tuple[bool, type]": else: # On Python 3.7 contextvars are functional. try: - from contextvars import ContextVar + from contextvars import ContextVar # noqa: PLC0415 return True, ContextVar except ImportError: @@ -1470,7 +1470,7 @@ def _get_contextvars() -> "Tuple[bool, type]": # Fall back to basic thread-local usage. - from threading import local + from threading import local # noqa: PLC0415 return False, _make_threadlocal_contextvars(local) @@ -1546,7 +1546,7 @@ def transaction_from_function(func: "Callable[..., Any]") -> "Optional[str]": disable_capture_event = ContextVar("disable_capture_event") -class ServerlessTimeoutWarning(Exception): # noqa: N818 +class ServerlessTimeoutWarning(Exception): """Raised when a serverless method is about to reach its timeout.""" pass @@ -1799,7 +1799,7 @@ def is_sentry_url(client: "sentry_sdk.client.BaseClient", url: str) -> bool: def _generate_installed_modules() -> "Iterator[Tuple[str, str]]": try: - from importlib import metadata + from importlib import metadata # noqa: PLC0415 yielded = set() for dist in metadata.distributions(): @@ -1817,7 +1817,7 @@ def _generate_installed_modules() -> "Iterator[Tuple[str, str]]": except ImportError: # < py3.8 try: - import pkg_resources + import pkg_resources # noqa: PLC0415 except ImportError: return diff --git a/tests/conftest.py b/tests/conftest.py index 0b7f2e9def..b75c2868f3 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -57,7 +57,7 @@ import sentry_sdk import sentry_sdk.utils from sentry_sdk.envelope import Envelope, parse_json -from sentry_sdk.integrations import ( # noqa: F401 +from sentry_sdk.integrations import ( _DEFAULT_INTEGRATIONS, _installed_integrations, _processed_integrations, @@ -1675,7 +1675,7 @@ def inner( class MockServerRequestHandler(BaseHTTPRequestHandler): - def do_GET(self): # noqa: N802 + def do_GET(self): # Process an HTTP GET request and return a response. # If the path ends with /status/, return status code . # Otherwise return a 200 response. diff --git a/tests/integrations/aiohttp/test_aiohttp.py b/tests/integrations/aiohttp/test_aiohttp.py index 701ea7d889..ee1d7ec301 100644 --- a/tests/integrations/aiohttp/test_aiohttp.py +++ b/tests/integrations/aiohttp/test_aiohttp.py @@ -408,8 +408,8 @@ async def hello(request): async def test_traces_sampler_gets_request_object_in_sampling_context( sentry_init, aiohttp_client, - DictionaryContaining, # noqa: N803 - ObjectDescribedBy, # noqa: N803 + DictionaryContaining, + ObjectDescribedBy, ): traces_sampler = mock.Mock() sentry_init( diff --git a/tests/integrations/anthropic/test_anthropic.py b/tests/integrations/anthropic/test_anthropic.py index 2e6fe7c0dc..58ef6fb0fa 100644 --- a/tests/integrations/anthropic/test_anthropic.py +++ b/tests/integrations/anthropic/test_anthropic.py @@ -2074,7 +2074,7 @@ def test_streaming_create_message_api_error( if span_streaming: items = capture_items("transaction", "span") - with pytest.raises(APIStatusError), mock.patch.object( + with pytest.raises(APIStatusError), mock.patch.object( # noqa: PT012 client._client, "send", return_value=response, @@ -2121,7 +2121,7 @@ def test_streaming_create_message_api_error( elif stream_gen_ai_spans: items = capture_items("transaction", "span") - with pytest.raises(APIStatusError), mock.patch.object( + with pytest.raises(APIStatusError), mock.patch.object( # noqa: PT012 client._client, "send", return_value=response, @@ -2169,7 +2169,7 @@ def test_streaming_create_message_api_error( else: events = capture_events() - with pytest.raises(APIStatusError), mock.patch.object( + with pytest.raises(APIStatusError), mock.patch.object( # noqa: PT012 client._client, "send", return_value=response, @@ -3617,7 +3617,7 @@ async def test_streaming_create_message_async_api_error( if span_streaming: items = capture_items("transaction", "span") - with pytest.raises(APIStatusError), mock.patch.object( + with pytest.raises(APIStatusError), mock.patch.object( # noqa: PT012 client._client, "send", return_value=response, @@ -3664,7 +3664,7 @@ async def test_streaming_create_message_async_api_error( elif stream_gen_ai_spans: items = capture_items("transaction", "span") - with pytest.raises(APIStatusError), mock.patch.object( + with pytest.raises(APIStatusError), mock.patch.object( # noqa: PT012 client._client, "send", return_value=response, @@ -3713,7 +3713,7 @@ async def test_streaming_create_message_async_api_error( else: events = capture_events() - with pytest.raises(APIStatusError), mock.patch.object( + with pytest.raises(APIStatusError), mock.patch.object( # noqa: PT012 client._client, "send", return_value=response, @@ -4206,7 +4206,7 @@ async def test_stream_messages_async_api_error( if span_streaming: items = capture_items("transaction", "span") - with pytest.raises(APIStatusError), mock.patch.object( + with pytest.raises(APIStatusError), mock.patch.object( # noqa: PT012 client._client, "send", return_value=response, @@ -4253,7 +4253,7 @@ async def test_stream_messages_async_api_error( elif stream_gen_ai_spans: items = capture_items("transaction", "span") - with pytest.raises(APIStatusError), mock.patch.object( + with pytest.raises(APIStatusError), mock.patch.object( # noqa: PT012 client._client, "send", return_value=response, @@ -4299,7 +4299,7 @@ async def test_stream_messages_async_api_error( else: events = capture_events() - with pytest.raises(APIStatusError), mock.patch.object( + with pytest.raises(APIStatusError), mock.patch.object( # noqa: PT012 client._client, "send", return_value=response, diff --git a/tests/integrations/asgi/test_asgi.py b/tests/integrations/asgi/test_asgi.py index cae3a24cb4..8a16c4e261 100644 --- a/tests/integrations/asgi/test_asgi.py +++ b/tests/integrations/asgi/test_asgi.py @@ -184,7 +184,7 @@ async def app(scope, receive, send): def test_invalid_transaction_style(asgi3_app): - with pytest.raises(ValueError) as exp: + with pytest.raises(ValueError) as exp: # noqa: PT011 SentryAsgiMiddleware(asgi3_app, transaction_style="URL") assert ( @@ -281,7 +281,7 @@ async def test_capture_transaction_with_error( asgi3_app_with_error, capture_events, capture_items, - DictionaryContaining, # noqa: N803 + DictionaryContaining, span_streaming, ): sentry_init( @@ -357,7 +357,7 @@ async def test_has_trace_if_performance_enabled( ) app = SentryAsgiMiddleware(asgi3_app_with_error_and_msg) - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 async with TestClient(app) as client: if span_streaming: items = capture_items("event", "span") @@ -418,7 +418,7 @@ async def test_has_trace_if_performance_disabled( sentry_init() app = SentryAsgiMiddleware(asgi3_app_with_error_and_msg) - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 async with TestClient(app) as client: events = capture_events() await client.get("/") @@ -453,7 +453,7 @@ async def test_trace_from_headers_if_performance_enabled( trace_id = "582b43a4192642f0b136d5159a501701" sentry_trace_header = "{}-{}-{}".format(trace_id, "6e8f22c393e68f19", 1) - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 async with TestClient(app) as client: if span_streaming: items = capture_items("event", "span") @@ -513,7 +513,7 @@ async def test_trace_from_headers_if_performance_disabled( trace_id = "582b43a4192642f0b136d5159a501701" sentry_trace_header = "{}-{}-{}".format(trace_id, "6e8f22c393e68f19", 1) - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 async with TestClient(app) as client: events = capture_events() await client.get("/", headers={"sentry-trace": sentry_trace_header}) @@ -552,7 +552,7 @@ async def test_websocket( request_url = "/ws" - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011, PT012 client = TestClient(asgi3_ws_app) if span_streaming: items = capture_items("event", "span") @@ -609,7 +609,7 @@ async def test_auto_session_tracking_with_aggregates( "endpoint": asgi3_app, "client": ("127.0.0.1", 60457), } - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 envelopes = capture_envelopes() async with TestClient(app, scope=scope) as client: scope["route"] = "/some/fine/url" diff --git a/tests/integrations/asyncio/test_asyncio.py b/tests/integrations/asyncio/test_asyncio.py index 962df3574b..20e79394f0 100644 --- a/tests/integrations/asyncio/test_asyncio.py +++ b/tests/integrations/asyncio/test_asyncio.py @@ -328,7 +328,7 @@ def test_patch_asyncio(mock_get_running_loop): @minimum_python_38 @patch("asyncio.get_running_loop") @patch("sentry_sdk.integrations.asyncio.Task") -def test_sentry_task_factory_no_factory(MockTask, mock_get_running_loop): # noqa: N803 +def test_sentry_task_factory_no_factory(MockTask, mock_get_running_loop): mock_loop = mock_get_running_loop.return_value mock_coro = MagicMock() @@ -386,7 +386,7 @@ def test_sentry_task_factory_with_factory(mock_get_running_loop): @patch("sentry_sdk.integrations.asyncio.Task") def test_sentry_task_factory_context_no_factory( MockTask, - mock_get_running_loop, # noqa: N803 + mock_get_running_loop, ): mock_loop = mock_get_running_loop.return_value mock_coro = MagicMock() diff --git a/tests/integrations/aws_lambda/test_aws_lambda.py b/tests/integrations/aws_lambda/test_aws_lambda.py index 72c7faa190..fff8ffc320 100644 --- a/tests/integrations/aws_lambda/test_aws_lambda.py +++ b/tests/integrations/aws_lambda/test_aws_lambda.py @@ -100,7 +100,7 @@ def lambda_client(): """ return boto3.client( "lambda", - endpoint_url=f"http://127.0.0.1:{SAM_PORT}", # noqa: E231 + endpoint_url=f"http://127.0.0.1:{SAM_PORT}", aws_access_key_id="dummy", aws_secret_access_key="dummy", region_name="us-east-1", diff --git a/tests/integrations/aws_lambda/utils.py b/tests/integrations/aws_lambda/utils.py index ac14fd56ef..6fab712014 100644 --- a/tests/integrations/aws_lambda/utils.py +++ b/tests/integrations/aws_lambda/utils.py @@ -94,7 +94,7 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: }, ) - dsn = f"http://123@{get_host_ip()}:9999/0" # noqa: E231 + dsn = f"http://123@{get_host_ip()}:9999/0" print("[LocalLambdaStack] Using Sentry DSN: %s" % dsn) print( @@ -216,7 +216,7 @@ def wait_for_stack(cls, timeout=60, port=SAM_PORT): try: # Try to connect to SAM - response = requests.get(f"http://127.0.0.1:{port}/") # noqa: E231 + response = requests.get(f"http://127.0.0.1:{port}/") if response.status_code == 200 or response.status_code == 404: return diff --git a/tests/integrations/boto3/test_client.py b/tests/integrations/boto3/test_client.py index 0b864ac1e0..69fc62e958 100644 --- a/tests/integrations/boto3/test_client.py +++ b/tests/integrations/boto3/test_client.py @@ -662,7 +662,7 @@ def fail_attribute_extraction(exception): ) def invoke_failing_client_method(): - with pytest.raises(ValueError) as exc_info: + with pytest.raises(ValueError) as exc_info: # noqa: PT011 client.head_object(Bucket="bucket", Key="foo") assert exc_info.value is original_exception @@ -750,7 +750,7 @@ def respond(request, **kwargs): def invoke_client_method_and_read_body(): body = client.get_object(Bucket="bucket", Key="foo")["Body"] - with pytest.raises(OSError) as exc_info: + with pytest.raises(OSError) as exc_info: # noqa: PT011 body.read() assert exc_info.value is original_exception diff --git a/tests/integrations/bottle/test_bottle.py b/tests/integrations/bottle/test_bottle.py index 7f8ad7fa3f..ce1413f003 100644 --- a/tests/integrations/bottle/test_bottle.py +++ b/tests/integrations/bottle/test_bottle.py @@ -396,7 +396,7 @@ def index(): client = get_client() - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 try: client.get("/") except ZeroDivisionError as e: diff --git a/tests/integrations/celery/test_celery.py b/tests/integrations/celery/test_celery.py index 56c7e9b781..6744182f95 100644 --- a/tests/integrations/celery/test_celery.py +++ b/tests/integrations/celery/test_celery.py @@ -573,7 +573,7 @@ def dummy_task(self): # Curious: Cannot use delay() here or py2.7-celery-4.2 crashes res = dummy_task.apply_async() - with pytest.raises(Exception): # noqa: B017 + with pytest.raises(Exception): # noqa: PT011 # Celery 4.1 raises a gibberish exception res.wait() @@ -653,7 +653,7 @@ def test_traces_sampler_gets_task_info_in_sampling_context( span_streaming, init_celery, celery_invocation, - DictionaryContaining, # noqa:N803 + DictionaryContaining, ): traces_sampler = mock.Mock(return_value=1.0) celery = init_celery( @@ -1000,7 +1000,7 @@ def test_messaging_system( ) # Does not need to be a real URL, since we use always eager - celery.conf.broker_url = f"{system}://example.com" # noqa: E231 + celery.conf.broker_url = f"{system}://example.com" @celery.task() def task(): ... @@ -1036,7 +1036,7 @@ def publish(*args, **kwargs): traces_sample_rate=1.0, trace_lifecycle="stream" if span_streaming else "static", ) - celery = Celery(__name__, broker=f"{system}://example.com") # noqa: E231 + celery = Celery(__name__, broker=f"{system}://example.com") @celery.task() def task(): ... @@ -1111,7 +1111,7 @@ def tests_span_origin_consumer( traces_sample_rate=1.0, trace_lifecycle="stream" if span_streaming else "static", ) - celery.conf.broker_url = "redis://example.com" # noqa: E231 + celery.conf.broker_url = "redis://example.com" @celery.task() def task(): ... @@ -1151,7 +1151,7 @@ def publish(*args, **kwargs): traces_sample_rate=1.0, trace_lifecycle="stream" if span_streaming else "static", ) - celery = Celery(__name__, broker="redis://example.com") # noqa: E231 + celery = Celery(__name__, broker="redis://example.com") @celery.task() def task(): ... @@ -1202,7 +1202,7 @@ def test_send_task_wrapped( traces_sample_rate=1.0, trace_lifecycle="stream" if span_streaming else "static", ) - celery = Celery(__name__, broker="redis://example.com") # noqa: E231 + celery = Celery(__name__, broker="redis://example.com") if span_streaming: items = capture_items("span") diff --git a/tests/integrations/celery/test_celery_beat_crons.py b/tests/integrations/celery/test_celery_beat_crons.py index bec10644cb..2cf3559426 100644 --- a/tests/integrations/celery/test_celery_beat_crons.py +++ b/tests/integrations/celery/test_celery_beat_crons.py @@ -451,7 +451,7 @@ def test_exclude_beat_tasks_option( with mock.patch( "sentry_sdk.integrations.celery.beat.Scheduler", fake_scheduler - ) as Scheduler: # noqa: N806 + ) as Scheduler: with mock.patch( "sentry_sdk.integrations.celery.sentry_sdk.get_client", return_value=fake_client, @@ -507,7 +507,7 @@ def test_exclude_redbeat_tasks_option( with mock.patch( "sentry_sdk.integrations.celery.beat.RedBeatScheduler", fake_redbeat_scheduler - ) as RedBeatScheduler: # noqa: N806 + ) as RedBeatScheduler: with mock.patch( "sentry_sdk.integrations.celery.sentry_sdk.get_client", return_value=fake_client, diff --git a/tests/integrations/chalice/test_chalice.py b/tests/integrations/chalice/test_chalice.py index 69f023efd4..6deb002a26 100644 --- a/tests/integrations/chalice/test_chalice.py +++ b/tests/integrations/chalice/test_chalice.py @@ -117,7 +117,7 @@ def every_hour(event): "id": "event-id", "resources": ["arn:aws:events:us-west-1:120987654312:rule/my-schedule"], } - with pytest.raises(Exception) as exc_info: + with pytest.raises(Exception) as exc_info: # noqa: PT011 every_hour(lambda_event, context=context) assert str(exc_info.value) == "schedule event!" diff --git a/tests/integrations/django/myapp/settings.py b/tests/integrations/django/myapp/settings.py index d70adf63ec..a04bf36531 100644 --- a/tests/integrations/django/myapp/settings.py +++ b/tests/integrations/django/myapp/settings.py @@ -63,7 +63,7 @@ def process_response(self, request, response): return response -def TestFunctionMiddleware(get_response): # noqa: N802 +def TestFunctionMiddleware(get_response): def middleware(request): return get_response(request) diff --git a/tests/integrations/django/myapp/views.py b/tests/integrations/django/myapp/views.py index 4261f341df..b5e4825175 100644 --- a/tests/integrations/django/myapp/views.py +++ b/tests/integrations/django/myapp/views.py @@ -237,7 +237,7 @@ def template_test3(request, *args, **kwargs): @csrf_exempt def template_test4(request, *args, **kwargs): User.objects.create_user("john", "lennon@thebeatles.com", "johnpassword") - my_queryset = User.objects.all() # noqa + my_queryset = User.objects.all() template_context = { "user_age": 25, diff --git a/tests/integrations/django/test_basic.py b/tests/integrations/django/test_basic.py index 59afe9be6b..8d7a10cc6a 100644 --- a/tests/integrations/django/test_basic.py +++ b/tests/integrations/django/test_basic.py @@ -796,7 +796,7 @@ def test_sql_psycopg2_placeholders( items = capture_items("event") sentry_sdk.get_isolation_scope().clear_breadcrumbs() - with pytest.raises(DataError): + with pytest.raises(DataError): # noqa: PT012 names = ["foo", "bar"] identifiers = [psycopg2.sql.Identifier(name) for name in names] placeholders = [ diff --git a/tests/integrations/django/test_db_query_data.py b/tests/integrations/django/test_db_query_data.py index 0739b0992b..393c6620bb 100644 --- a/tests/integrations/django/test_db_query_data.py +++ b/tests/integrations/django/test_db_query_data.py @@ -623,7 +623,7 @@ def test_no_query_source_if_duration_too_short( # trigger Django to open a new connection by marking the existing one as None. connections["postgres"].connection = None - class fake_record_sql_queries: # noqa: N801 + class fake_record_sql_queries: def __init__(self, *args, **kwargs): self._ctx_mgr = record_sql_queries(*args, **kwargs) @@ -729,7 +729,7 @@ def test_query_source_if_duration_over_threshold( # trigger Django to open a new connection by marking the existing one as None. connections["postgres"].connection = None - class fake_record_sql_queries: # noqa: N801 + class fake_record_sql_queries: def __init__(self, *args, **kwargs): self._ctx_mgr = record_sql_queries(*args, **kwargs) diff --git a/tests/integrations/flask/test_flask.py b/tests/integrations/flask/test_flask.py index 498f74d82e..ce2eb4b1e1 100644 --- a/tests/integrations/flask/test_flask.py +++ b/tests/integrations/flask/test_flask.py @@ -917,7 +917,7 @@ def test_tracing_error(sentry_init, capture_events, capture_items, app, span_str def error(): 1 / 0 - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 with app.test_client() as client: response = client.get("/error") assert response.status_code == 500 @@ -960,7 +960,7 @@ def test_error_has_trace_context_if_tracing_disabled(sentry_init, capture_events def error(): 1 / 0 - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 with app.test_client() as client: response = client.get("/error") assert response.status_code == 500 diff --git a/tests/integrations/gcp/test_gcp.py b/tests/integrations/gcp/test_gcp.py index 57854ad5a4..389adbf6ca 100644 --- a/tests/integrations/gcp/test_gcp.py +++ b/tests/integrations/gcp/test_gcp.py @@ -302,7 +302,7 @@ def cloud_function(functionhandler, event): def test_traces_sampler_gets_correct_values_in_sampling_context( run_cloud_function, - DictionaryContaining, # noqa:N803 + DictionaryContaining, ): # TODO: There are some decent sized hacks below. For more context, see the # long comment in the test of the same name in the AWS integration. The diff --git a/tests/integrations/graphene/test_graphene.py b/tests/integrations/graphene/test_graphene.py index 724f68b220..63296d50cb 100644 --- a/tests/integrations/graphene/test_graphene.py +++ b/tests/integrations/graphene/test_graphene.py @@ -43,10 +43,10 @@ class Query(ObjectType): hello = String(first_name=String(default_value="stranger")) goodbye = String() - def resolve_hello(root, info, first_name): # noqa: N805 + def resolve_hello(root, info, first_name): return "Hello {}!".format(first_name) - def resolve_goodbye(root, info): # noqa: N805 + def resolve_goodbye(root, info): raise RuntimeError("oh no!") diff --git a/tests/integrations/grpc/test_grpc.py b/tests/integrations/grpc/test_grpc.py index f50a2f62d1..e5a19f2f1c 100644 --- a/tests/integrations/grpc/test_grpc.py +++ b/tests/integrations/grpc/test_grpc.py @@ -44,7 +44,7 @@ def _set_up( server.start() # Create channel connected to our server - channel = grpc.insecure_channel(f"localhost:{port}") # noqa: E231 + channel = grpc.insecure_channel(f"localhost:{port}") return server, channel @@ -759,7 +759,7 @@ class TestService(gRPCTestServiceServicer): events = [] @staticmethod - def TestServe(request, context): # noqa: N802 + def TestServe(request, context): client = sentry_sdk.get_client() span_streaming = has_span_streaming_enabled(client.options) @@ -783,16 +783,16 @@ def TestServe(request, context): # noqa: N802 return gRPCTestMessage(text=request.text) @staticmethod - def TestUnaryStream(request, context): # noqa: N802 + def TestUnaryStream(request, context): for _ in range(3): yield gRPCTestMessage(text=request.text) @staticmethod - def TestStreamStream(request, context): # noqa: N802 + def TestStreamStream(request, context): for r in request: yield r @staticmethod - def TestStreamUnary(request, context): # noqa: N802 + def TestStreamUnary(request, context): requests = [r for r in request] return requests.pop() diff --git a/tests/integrations/grpc/test_grpc_aio.py b/tests/integrations/grpc/test_grpc_aio.py index 217dc110d2..ae8cd72791 100644 --- a/tests/integrations/grpc/test_grpc_aio.py +++ b/tests/integrations/grpc/test_grpc_aio.py @@ -51,7 +51,7 @@ async def inner(span_streaming: bool): await asyncio.create_task(server.start()) # Create channel connected to our server - channel = grpc.aio.insecure_channel(f"localhost:{port}") # noqa: E231 + channel = grpc.aio.insecure_channel(f"localhost:{port}") return server, channel @@ -88,9 +88,7 @@ async def test_noop_for_unimplemented_method( items = capture_items("span") try: - async with grpc.aio.insecure_channel( - f"localhost:{port}" # noqa: E231 - ) as channel: + async with grpc.aio.insecure_channel(f"localhost:{port}") as channel: stub = gRPCTestServiceStub(channel) with pytest.raises(grpc.RpcError) as exc: await stub.TestServe(gRPCTestMessage(text="test")) @@ -105,9 +103,7 @@ async def test_noop_for_unimplemented_method( events = capture_events() try: - async with grpc.aio.insecure_channel( - f"localhost:{port}" # noqa: E231 - ) as channel: + async with grpc.aio.insecure_channel(f"localhost:{port}") as channel: stub = gRPCTestServiceStub(channel) with pytest.raises(grpc.RpcError) as exc: await stub.TestServe(gRPCTestMessage(text="test")) @@ -539,7 +535,7 @@ def __init__(self): super().__init__("test") @classmethod - async def TestServe(cls, request, context): # noqa: N802 + async def TestServe(cls, request, context): client = sentry_sdk.get_client() span_streaming = has_span_streaming_enabled(client.options) @@ -569,16 +565,16 @@ async def TestServe(cls, request, context): # noqa: N802 return gRPCTestMessage(text=request.text) @classmethod - async def TestUnaryStream(cls, request, context): # noqa: N802 + async def TestUnaryStream(cls, request, context): for _ in range(3): yield gRPCTestMessage(text=request.text) @classmethod - async def TestStreamStream(cls, request, context): # noqa: N802 + async def TestStreamStream(cls, request, context): async for r in request: yield r @classmethod - async def TestStreamUnary(cls, request, context): # noqa: N802 + async def TestStreamUnary(cls, request, context): requests = [r async for r in request] return requests.pop() diff --git a/tests/integrations/langchain/test_langchain.py b/tests/integrations/langchain/test_langchain.py index fe3886ce02..75d51a4be7 100644 --- a/tests/integrations/langchain/test_langchain.py +++ b/tests/integrations/langchain/test_langchain.py @@ -3623,14 +3623,14 @@ def _llm_type(self) -> str: if span_streaming or stream_gen_ai_spans: items = capture_items("event") - with start_transaction(), pytest.raises(ValueError): + with start_transaction(), pytest.raises(ValueError): # noqa: PT011 list(agent_executor.stream({"input": "How many letters in the word eudca"})) (error,) = (item.payload for item in items) else: events = capture_events() - with start_transaction(), pytest.raises(ValueError): + with start_transaction(), pytest.raises(ValueError): # noqa: PT011 list(agent_executor.stream({"input": "How many letters in the word eudca"})) error = events[0] @@ -3698,7 +3698,7 @@ def _llm_type(self) -> str: agent=agent, tools=[get_word_length], verbose=True ) - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 list( agent_executor.stream( {"input": "How many letters in the word eudca"} @@ -3737,7 +3737,7 @@ def _llm_type(self) -> str: agent=agent, tools=[get_word_length], verbose=True ) - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 list( agent_executor.stream( {"input": "How many letters in the word eudca"} @@ -3777,7 +3777,7 @@ def _llm_type(self) -> str: agent=agent, tools=[get_word_length], verbose=True ) - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 list( agent_executor.stream( {"input": "How many letters in the word eudca"} @@ -3857,7 +3857,7 @@ def test_langchain_tool_error( with patch.object( llm.client._client._client, "send", side_effect=[tool_response] - ), start_transaction(name="tx"), pytest.raises(ValueError): + ), start_transaction(name="tx"), pytest.raises(ValueError): # noqa: PT011 agent.invoke({"messages": [HumanMessage(content="hi")]}) error_events = [event for event in events if event.get("level") == "error"] diff --git a/tests/integrations/langgraph/test_langgraph.py b/tests/integrations/langgraph/test_langgraph.py index 7b6a6cc3d9..9b0cd82d73 100644 --- a/tests/integrations/langgraph/test_langgraph.py +++ b/tests/integrations/langgraph/test_langgraph.py @@ -34,7 +34,7 @@ def mock_langgraph_imports(): mock_state_graph, mock_pregel = mock_langgraph_imports() -from sentry_sdk.integrations.langgraph import ( # noqa: E402 +from sentry_sdk.integrations.langgraph import ( LanggraphIntegration, _parse_langgraph_messages, _wrap_pregel_ainvoke, @@ -614,7 +614,7 @@ def original_invoke(self, *args, **kwargs): if span_streaming or stream_gen_ai_spans: items = capture_items("span") - with start_transaction(), pytest.raises( + with start_transaction(), pytest.raises( # noqa: PT012 Exception, match="Graph execution failed" ): wrapped_invoke = _wrap_pregel_invoke(original_invoke) @@ -634,7 +634,7 @@ def original_invoke(self, *args, **kwargs): else: events = capture_events() - with start_transaction(), pytest.raises( + with start_transaction(), pytest.raises( # noqa: PT012 Exception, match="Graph execution failed" ): wrapped_invoke = _wrap_pregel_invoke(original_invoke) @@ -676,7 +676,7 @@ async def original_ainvoke(self, *args, **kwargs): raise Exception("Async graph execution failed") async def run_error_test(): - with start_transaction(), pytest.raises( + with start_transaction(), pytest.raises( # noqa: PT012 Exception, match="Async graph execution failed" ): wrapped_ainvoke = _wrap_pregel_ainvoke(original_ainvoke) diff --git a/tests/integrations/openai/test_openai.py b/tests/integrations/openai/test_openai.py index e578b03fdc..cf78d2dff0 100644 --- a/tests/integrations/openai/test_openai.py +++ b/tests/integrations/openai/test_openai.py @@ -1796,7 +1796,7 @@ def test_streaming_chat_completion_no_prompts( assert SPANDATA.GEN_AI_RESPONSE_TEXT not in span["attributes"] try: - import tiktoken # type: ignore # noqa # pylint: disable=unused-import + import tiktoken # type: ignore # pylint: disable=unused-import assert span["attributes"]["gen_ai.usage.output_tokens"] == 2 assert span["attributes"]["gen_ai.usage.input_tokens"] == 7 @@ -2497,7 +2497,7 @@ def test_streaming_chat_completion( assert "hello world" in span["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] try: - import tiktoken # type: ignore # noqa # pylint: disable=unused-import + import tiktoken # type: ignore # pylint: disable=unused-import assert ( span["attributes"]["gen_ai.usage.output_tokens"] @@ -2708,7 +2708,7 @@ async def test_streaming_chat_completion_async_no_prompts( assert SPANDATA.GEN_AI_RESPONSE_TEXT not in span["attributes"] try: - import tiktoken # type: ignore # noqa # pylint: disable=unused-import + import tiktoken # type: ignore # pylint: disable=unused-import assert span["attributes"]["gen_ai.usage.output_tokens"] == 2 assert span["attributes"]["gen_ai.usage.input_tokens"] == 7 @@ -2993,7 +2993,7 @@ async def test_streaming_chat_completion_async( assert "hello world" in span["attributes"][SPANDATA.GEN_AI_RESPONSE_TEXT] try: - import tiktoken # type: ignore # noqa # pylint: disable=unused-import + import tiktoken # type: ignore # pylint: disable=unused-import assert ( span["attributes"]["gen_ai.usage.output_tokens"] diff --git a/tests/integrations/openai_agents/test_openai_agents.py b/tests/integrations/openai_agents/test_openai_agents.py index b36436592b..c30d909fc4 100644 --- a/tests/integrations/openai_agents/test_openai_agents.py +++ b/tests/integrations/openai_agents/test_openai_agents.py @@ -4994,7 +4994,7 @@ async def test_run_streamed_error_handling( items = capture_items("event", "span") - with pytest.raises(Exception, match="Model Error"): + with pytest.raises(Exception, match="Model Error"): # noqa: PT012 result = agents.Runner.run_streamed( test_agent, "Test input", run_config=test_run_config ) @@ -5034,7 +5034,7 @@ async def test_run_streamed_error_handling( items = capture_items("event", "span", "transaction") - with pytest.raises(Exception, match="Model Error"): + with pytest.raises(Exception, match="Model Error"): # noqa: PT012 result = agents.Runner.run_streamed( test_agent, "Test input", run_config=test_run_config ) @@ -5074,7 +5074,7 @@ async def test_run_streamed_error_handling( ) events = capture_events() - with pytest.raises(Exception, match="Model Error"): + with pytest.raises(Exception, match="Model Error"): # noqa: PT012 result = agents.Runner.run_streamed( test_agent, "Test input", run_config=test_run_config ) diff --git a/tests/integrations/ray/test_ray.py b/tests/integrations/ray/test_ray.py index aa8b00dc00..70cc82489a 100644 --- a/tests/integrations/ray/test_ray.py +++ b/tests/integrations/ray/test_ray.py @@ -340,12 +340,12 @@ def example_task(): with sentry_sdk.traces.start_span( name="ray test parent", attributes={"sentry.op": "task"} ): - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 future = example_task.remote() ray.get(future) else: with sentry_sdk.start_transaction(op="task", name="ray test transaction"): - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 future = example_task.remote() ray.get(future) @@ -530,13 +530,13 @@ def increment(self): with sentry_sdk.traces.start_span( name="ray test parent", attributes={"sentry.op": "task"} ): - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 counter = Counter.remote() future = counter.increment.remote() ray.get(future) else: with sentry_sdk.start_transaction(op="task", name="ray test transaction"): - with pytest.raises(ZeroDivisionError): + with pytest.raises(ZeroDivisionError): # noqa: PT012 counter = Counter.remote() future = counter.increment.remote() ray.get(future) diff --git a/tests/integrations/requests/test_requests.py b/tests/integrations/requests/test_requests.py index 7df431901b..a974bd574d 100644 --- a/tests/integrations/requests/test_requests.py +++ b/tests/integrations/requests/test_requests.py @@ -16,7 +16,7 @@ def test_crumb_capture(sentry_init, capture_events): sentry_init(integrations=[StdlibIntegration()], send_default_pii=True) events = capture_events() - url = f"http://localhost:{PORT}/hello-world" # noqa:E231 + url = f"http://localhost:{PORT}/hello-world" response = requests.get(url) capture_message("Testing!") @@ -45,7 +45,7 @@ def test_crumb_capture_span_streaming(sentry_init, capture_events, send_default_ ) events = capture_events() - url = f"http://localhost:{PORT}/hello-world" # noqa:E231 + url = f"http://localhost:{PORT}/hello-world" response = requests.get(url) capture_message("Testing!") @@ -90,7 +90,7 @@ def test_crumb_capture_client_error(sentry_init, capture_events, status_code, le events = capture_events() - url = f"http://localhost:{PORT}/status/{status_code}" # noqa:E231 + url = f"http://localhost:{PORT}/status/{status_code}" response = requests.get(url) assert response.status_code == status_code @@ -145,7 +145,7 @@ def test_crumb_capture_client_error_span_streaming( events = capture_events() - url = f"http://localhost:{PORT}/status/{status_code}" # noqa:E231 + url = f"http://localhost:{PORT}/status/{status_code}" response = requests.get(url) assert response.status_code == status_code @@ -185,7 +185,7 @@ def test_omit_url_data_if_parsing_fails(sentry_init, capture_events): events = capture_events() - url = f"http://localhost:{PORT}/ok" # noqa:E231 + url = f"http://localhost:{PORT}/ok" with mock.patch( "sentry_sdk.integrations.stdlib.parse_url", @@ -219,7 +219,7 @@ def test_omit_url_data_if_parsing_fails_span_streaming(sentry_init, capture_even events = capture_events() - url = f"http://localhost:{PORT}/ok" # noqa:E231 + url = f"http://localhost:{PORT}/ok" with mock.patch( "sentry_sdk.integrations.stdlib.parse_url", diff --git a/tests/integrations/rq/test_rq.py b/tests/integrations/rq/test_rq.py index a56666efb1..8174162c8a 100644 --- a/tests/integrations/rq/test_rq.py +++ b/tests/integrations/rq/test_rq.py @@ -500,7 +500,7 @@ def test_traces_sampler_gets_correct_values_in_sampling_context( sentry_init, DictionaryContaining, ObjectDescribedBy, - span_streaming, # noqa:N803 + span_streaming, ): traces_sampler = mock.Mock(return_value=True) sentry_init( diff --git a/tests/integrations/socket/test_socket.py b/tests/integrations/socket/test_socket.py index 7578d954e6..8d77986a08 100644 --- a/tests/integrations/socket/test_socket.py +++ b/tests/integrations/socket/test_socket.py @@ -29,7 +29,7 @@ def test_getaddrinfo_trace(sentry_init, capture_events, capture_items, span_stre assert dns_span["attributes"]["sentry.op"] == "socket.dns" assert dns_span["attributes"]["sentry.origin"] == "auto.socket.socket" - assert dns_span["name"] == f"localhost:{PORT}" # noqa: E231 + assert dns_span["name"] == f"localhost:{PORT}" assert dns_span["attributes"]["server.address"] == "localhost" assert dns_span["attributes"]["server.port"] == PORT else: @@ -42,7 +42,7 @@ def test_getaddrinfo_trace(sentry_init, capture_events, capture_items, span_stre (span,) = event["spans"] assert span["op"] == "socket.dns" - assert span["description"] == f"localhost:{PORT}" # noqa: E231 + assert span["description"] == f"localhost:{PORT}" assert span["data"] == ApproxDict( { "host": "localhost", @@ -75,12 +75,12 @@ def test_create_connection_trace( dns_span, connect_span, _root = spans assert connect_span["attributes"]["sentry.op"] == "socket.connection" - assert connect_span["name"] == f"localhost:{PORT}" # noqa: E231 + assert connect_span["name"] == f"localhost:{PORT}" assert connect_span["attributes"]["server.address"] == "localhost" assert connect_span["attributes"]["server.port"] == PORT assert dns_span["attributes"]["sentry.op"] == "socket.dns" - assert dns_span["name"] == f"localhost:{PORT}" # noqa: E231 + assert dns_span["name"] == f"localhost:{PORT}" assert dns_span["attributes"]["server.address"] == "localhost" assert dns_span["attributes"]["server.port"] == PORT else: @@ -94,7 +94,7 @@ def test_create_connection_trace( # as getaddrinfo gets called in create_connection it should also contain a dns span assert connect_span["op"] == "socket.connection" - assert connect_span["description"] == f"localhost:{PORT}" # noqa: E231 + assert connect_span["description"] == f"localhost:{PORT}" assert connect_span["data"] == ApproxDict( { "address": ["localhost", PORT], @@ -104,7 +104,7 @@ def test_create_connection_trace( ) assert dns_span["op"] == "socket.dns" - assert dns_span["description"] == f"localhost:{PORT}" # noqa: E231 + assert dns_span["description"] == f"localhost:{PORT}" assert dns_span["data"] == ApproxDict( { "host": "localhost", diff --git a/tests/integrations/spark/test_spark.py b/tests/integrations/spark/test_spark.py index e5c536713d..8aadd0435d 100644 --- a/tests/integrations/spark/test_spark.py +++ b/tests/integrations/spark/test_spark.py @@ -98,7 +98,7 @@ def test_sentry_listener_on_job_start(sentry_listener): with patch.object(listener, "_add_breadcrumb") as mock_add_breadcrumb: class MockJobStart: - def jobId(self): # noqa: N802 + def jobId(self): return "sample-job-id-start" mock_job_start = MockJobStart() @@ -119,14 +119,14 @@ def test_sentry_listener_on_job_end(sentry_listener, job_result, level): with patch.object(listener, "_add_breadcrumb") as mock_add_breadcrumb: class MockJobResult: - def toString(self): # noqa: N802 + def toString(self): return job_result class MockJobEnd: - def jobId(self): # noqa: N802 + def jobId(self): return "sample-job-id-end" - def jobResult(self): # noqa: N802 + def jobResult(self): result = MockJobResult() return result @@ -146,17 +146,17 @@ def test_sentry_listener_on_stage_submitted(sentry_listener): with patch.object(listener, "_add_breadcrumb") as mock_add_breadcrumb: class StageInfo: - def stageId(self): # noqa: N802 + def stageId(self): return "sample-stage-id-submit" def name(self): return "run-job" - def attemptId(self): # noqa: N802 + def attemptId(self): return 14 class MockStageSubmitted: - def stageInfo(self): # noqa: N802 + def stageInfo(self): stageinf = StageInfo() return stageinf @@ -177,17 +177,17 @@ def test_sentry_listener_on_stage_submitted_no_attempt_id(sentry_listener): with patch.object(listener, "_add_breadcrumb") as mock_add_breadcrumb: class StageInfo: - def stageId(self): # noqa: N802 + def stageId(self): return "sample-stage-id-submit" def name(self): return "run-job" - def attemptNumber(self): # noqa: N802 + def attemptNumber(self): return 14 class MockStageSubmitted: - def stageInfo(self): # noqa: N802 + def stageInfo(self): stageinf = StageInfo() return stageinf @@ -208,14 +208,14 @@ def test_sentry_listener_on_stage_submitted_no_attempt_id_or_number(sentry_liste with patch.object(listener, "_add_breadcrumb") as mock_add_breadcrumb: class StageInfo: - def stageId(self): # noqa: N802 + def stageId(self): return "sample-stage-id-submit" def name(self): return "run-job" class MockStageSubmitted: - def stageInfo(self): # noqa: N802 + def stageInfo(self): stageinf = StageInfo() return stageinf @@ -246,20 +246,20 @@ def get(self): raise Py4JJavaError("msg", JavaException()) class StageInfo: - def stageId(self): # noqa: N802 + def stageId(self): return "sample-stage-id-submit" def name(self): return "run-job" - def attemptId(self): # noqa: N802 + def attemptId(self): return 14 - def failureReason(self): # noqa: N802 + def failureReason(self): return FailureReason() class MockStageCompleted: - def stageInfo(self): # noqa: N802 + def stageInfo(self): return StageInfo() return MockStageCompleted() diff --git a/tests/integrations/sqlalchemy/test_sqlalchemy.py b/tests/integrations/sqlalchemy/test_sqlalchemy.py index e08bb0a423..a0492bd158 100644 --- a/tests/integrations/sqlalchemy/test_sqlalchemy.py +++ b/tests/integrations/sqlalchemy/test_sqlalchemy.py @@ -32,7 +32,7 @@ def test_orm_queries( }, ) - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -53,7 +53,7 @@ class Address(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") @@ -108,7 +108,7 @@ def test_transactions( traces_sample_rate=1.0, ) - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -129,7 +129,7 @@ class Address(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() if span_streaming: @@ -139,7 +139,7 @@ class Address(Base): session.query(Person).first() for _ in range(2): - with pytest.raises(IntegrityError): + with pytest.raises(IntegrityError): # noqa: PT012 with session.begin_nested(): session.add(Person(id=1, name="bob")) session.add(Person(id=1, name="bob")) @@ -185,7 +185,7 @@ class Address(Base): session.query(Person).first() for _ in range(2): - with pytest.raises(IntegrityError): + with pytest.raises(IntegrityError): # noqa: PT012 with session.begin_nested(): session.add(Person(id=1, name="bob")) session.add(Person(id=1, name="bob")) @@ -238,7 +238,7 @@ def test_transactions_no_engine_url( traces_sample_rate=1.0, ) - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -260,7 +260,7 @@ class Address(Base): engine.url = None Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() if span_streaming: @@ -270,7 +270,7 @@ class Address(Base): session.query(Person).first() for _ in range(2): - with pytest.raises(IntegrityError): + with pytest.raises(IntegrityError): # noqa: PT012 with session.begin_nested(): session.add(Person(id=1, name="bob")) session.add(Person(id=1, name="bob")) @@ -297,7 +297,7 @@ class Address(Base): session.query(Person).first() for _ in range(2): - with pytest.raises(IntegrityError): + with pytest.raises(IntegrityError): # noqa: PT012 with session.begin_nested(): session.add(Person(id=1, name="bob")) session.add(Person(id=1, name="bob")) @@ -458,7 +458,7 @@ def test_query_source_disabled( items = capture_items("span") with sentry_sdk.traces.start_span(name="custom parent"): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -470,7 +470,7 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") @@ -498,7 +498,7 @@ class Person(Base): events = capture_events() with start_transaction(name="test_transaction", sampled=True): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -510,7 +510,7 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") @@ -560,7 +560,7 @@ def test_query_source_enabled( items = capture_items("span") with sentry_sdk.traces.start_span(name="custom parent"): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -572,7 +572,7 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") @@ -599,7 +599,7 @@ class Person(Base): events = capture_events() with start_transaction(name="test_transaction", sampled=True): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -611,7 +611,7 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") @@ -654,7 +654,7 @@ def test_query_source( items = capture_items("span") with sentry_sdk.traces.start_span(name="custom parent"): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -666,7 +666,7 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") @@ -708,7 +708,7 @@ class Person(Base): events = capture_events() with start_transaction(name="test_transaction", sampled=True): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -720,7 +720,7 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") @@ -786,7 +786,7 @@ def test_query_source_with_module_in_search_path( if span_streaming: items = capture_items("span") with sentry_sdk.traces.start_span(name="custom parent"): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -798,7 +798,7 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") @@ -844,7 +844,7 @@ class Person(Base): else: events = capture_events() with start_transaction(name="test_transaction", sampled=True): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -856,7 +856,7 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") @@ -914,7 +914,7 @@ def test_no_query_source_if_duration_too_short( items = capture_items("span") with sentry_sdk.traces.start_span(name="custom parent"): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -926,13 +926,13 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") session.add(bob) - class fake_record_sql_queries: # noqa: N801 + class fake_record_sql_queries: def __init__(self, *args, **kwargs): self._ctx_mgr = record_sql_queries(*args, **kwargs) @@ -972,7 +972,7 @@ def __exit__(self, type, value, traceback): events = capture_events() with start_transaction(name="test_transaction", sampled=True): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -984,13 +984,13 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") session.add(bob) - class fake_record_sql_queries: # noqa: N801 + class fake_record_sql_queries: def __init__(self, *args, **kwargs): self._ctx_mgr = record_sql_queries(*args, **kwargs) @@ -1045,7 +1045,7 @@ def test_query_source_if_duration_over_threshold( items = capture_items("span") with sentry_sdk.traces.start_span(name="custom parent"): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -1057,13 +1057,13 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") session.add(bob) - class fake_record_sql_queries: # noqa: N801 + class fake_record_sql_queries: def __init__(self, *args, **kwargs): self._ctx_mgr = record_sql_queries(*args, **kwargs) @@ -1120,7 +1120,7 @@ def __exit__(self, type, value, traceback): events = capture_events() with start_transaction(name="test_transaction", sampled=True): - Base = declarative_base() # noqa: N806 + Base = declarative_base() class Person(Base): __tablename__ = "person" @@ -1132,13 +1132,13 @@ class Person(Base): ) Base.metadata.create_all(engine) - Session = sessionmaker(bind=engine) # noqa: N806 + Session = sessionmaker(bind=engine) session = Session() bob = Person(name="Bob") session.add(bob) - class fake_record_sql_queries: # noqa: N801 + class fake_record_sql_queries: def __init__(self, *args, **kwargs): self._ctx_mgr = record_sql_queries(*args, **kwargs) diff --git a/tests/integrations/stdlib/test_httplib.py b/tests/integrations/stdlib/test_httplib.py index 068714d4dc..e94a339205 100644 --- a/tests/integrations/stdlib/test_httplib.py +++ b/tests/integrations/stdlib/test_httplib.py @@ -153,7 +153,7 @@ def test_crumb_capture_client_error(sentry_init, capture_events, status_code, le sentry_init(integrations=[StdlibIntegration()], send_default_pii=True) events = capture_events() - url = f"http://localhost:{PORT}/status/{status_code}" # noqa:E231 + url = f"http://localhost:{PORT}/status/{status_code}" try: urlopen(url) except HTTPError: @@ -204,7 +204,7 @@ def test_crumb_capture_client_error_span_streaming( ) events = capture_events() - url = f"http://localhost:{PORT}/status/{status_code}" # noqa:E231 + url = f"http://localhost:{PORT}/status/{status_code}" try: urlopen(url) except HTTPError: @@ -356,7 +356,7 @@ def test_httplib_misuse(sentry_init, capture_events, request): conn.request("GET", "/200") - with pytest.raises(Exception): # noqa: B017 + with pytest.raises(Exception): # noqa: PT011 # This raises an exception, because we didn't call `getresponse` for # the previous request yet. # @@ -1324,7 +1324,7 @@ def test_http_timeout( if span_streaming: items = capture_items("span") - with pytest.raises(TimeoutError): + with pytest.raises(TimeoutError): # noqa: PT012 with sentry_sdk.traces.start_span( name="name", attributes={ @@ -1340,11 +1340,11 @@ def test_http_timeout( assert len(spans) == 2 span = spans[0] assert span["attributes"]["sentry.op"] == "http.client" - assert span["name"] == f"GET http://localhost:{PORT}/bla" # noqa: E231 + assert span["name"] == f"GET http://localhost:{PORT}/bla" else: envelopes = capture_envelopes() - with pytest.raises(TimeoutError): + with pytest.raises(TimeoutError): # noqa: PT012 with start_transaction(op="op", name="name"): conn = HTTPConnection("localhost", port=PORT) conn.request("GET", "/bla") @@ -1356,7 +1356,7 @@ def test_http_timeout( span = transaction["spans"][0] assert span["op"] == "http.client" - assert span["description"] == f"GET http://localhost:{PORT}/bla" # noqa: E231 + assert span["description"] == f"GET http://localhost:{PORT}/bla" @pytest.mark.parametrize("tunnel_port", [8080, None]) @@ -1691,6 +1691,4 @@ def test_crumb_url_query_data_collection_span_streaming( assert crumb["data"][SPANDATA.URL_FULL] == f"{base_url}#frag" else: assert crumb["data"][SPANDATA.URL_QUERY] == expected_query - assert ( - crumb["data"][SPANDATA.URL_FULL] == f"{base_url}?{expected_query}#frag" # noqa: E231 - ) + assert crumb["data"][SPANDATA.URL_FULL] == f"{base_url}?{expected_query}#frag" diff --git a/tests/integrations/wsgi/test_wsgi.py b/tests/integrations/wsgi/test_wsgi.py index 2cda3a1b98..f6133847b9 100644 --- a/tests/integrations/wsgi/test_wsgi.py +++ b/tests/integrations/wsgi/test_wsgi.py @@ -78,7 +78,7 @@ def test_script_name_is_respected( with pytest.raises(ZeroDivisionError): # setting url with PATH_INFO: bark/, HTTP_HOST: dogs.are.great and SCRIPT_NAME: woof/woof/ - client.get(path_info, f"https://dogs.are.great/{script_name}") # noqa: E231 + client.get(path_info, f"https://dogs.are.great/{script_name}") (event,) = events @@ -146,7 +146,7 @@ def test_transaction_with_error( crashing_app, capture_events, capture_items, - DictionaryContaining, # noqa:N803 + DictionaryContaining, span_streaming, ): def dogpark(environ, start_response): @@ -165,7 +165,7 @@ def dogpark(environ, start_response): else: events = capture_events() - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 client.get("http://dogs.are.great/sit/stay/rollover/") sentry_sdk.flush() @@ -213,7 +213,7 @@ def test_transaction_no_error( sentry_init, capture_events, capture_items, - DictionaryContaining, # noqa:N803 + DictionaryContaining, span_streaming, send_pii, ): @@ -300,7 +300,7 @@ def dogpark(environ, start_response): else: events = capture_events() - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 client.get("http://dogs.are.great/sit/stay/rollover/") sentry_sdk.flush() @@ -359,7 +359,7 @@ def dogpark(environ, start_response): client = Client(app) events = capture_events() - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 client.get("http://dogs.are.great/sit/stay/rollover/") msg_event, error_event = events @@ -397,7 +397,7 @@ def dogpark(environ, start_response): trace_id = "582b43a4192642f0b136d5159a501701" sentry_trace_header = "{}-{}-{}".format(trace_id, "6e8f22c393e68f19", 1) - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 client.get( "http://dogs.are.great/sit/stay/rollover/", headers={"sentry-trace": sentry_trace_header}, @@ -444,7 +444,7 @@ def dogpark(environ, start_response): trace_id = "582b43a4192642f0b136d5159a501701" sentry_trace_header = "{}-{}-{}".format(trace_id, "6e8f22c393e68f19", 1) - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 client.get( "http://dogs.are.great/sit/stay/rollover/", headers={"sentry-trace": sentry_trace_header}, @@ -464,7 +464,7 @@ def dogpark(environ, start_response): @pytest.mark.parametrize("span_streaming", [True, False]) def test_traces_sampler_gets_correct_values_in_sampling_context( sentry_init, - DictionaryContaining, # noqa:N803 + DictionaryContaining, span_streaming, ): def app(environ, start_response): diff --git a/tests/profiler/test_continuous_profiler.py b/tests/profiler/test_continuous_profiler.py index 782d6fb846..a1ea0dc7d7 100644 --- a/tests/profiler/test_continuous_profiler.py +++ b/tests/profiler/test_continuous_profiler.py @@ -89,7 +89,7 @@ def client_options( ], ) def test_continuous_profiler_invalid_mode(mode, make_options, teardown_profiling): - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 setup_continuous_profiler( make_options(mode=mode), mock_sdk_info, diff --git a/tests/profiler/test_transaction_profiler.py b/tests/profiler/test_transaction_profiler.py index 742555f003..6198abd8bb 100644 --- a/tests/profiler/test_transaction_profiler.py +++ b/tests/profiler/test_transaction_profiler.py @@ -62,7 +62,7 @@ def experimental_options(mode=None, sample_rate=None): ], ) def test_profiler_invalid_mode(mode, make_options, teardown_profiling): - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 setup_profiler(make_options(mode)) @@ -822,7 +822,7 @@ def ensure_running(self) -> None: ) @mock.patch("sentry_sdk.profiler.transaction_profiler.MAX_PROFILE_DURATION_NS", 5) def test_profile_processing( - DictionaryContaining, # noqa: N803 + DictionaryContaining, samples, expected, ): diff --git a/tests/test_conftest.py b/tests/test_conftest.py index a36fe17894..362ad2f8c4 100644 --- a/tests/test_conftest.py +++ b/tests/test_conftest.py @@ -24,7 +24,7 @@ def test_string_containing( test_string, expected_result, - StringContaining, # noqa: N803 + StringContaining, ): assert (test_string == StringContaining("dogs")) is expected_result @@ -50,14 +50,14 @@ def test_string_containing( def test_dictionary_containing( test_dict, expected_result, - DictionaryContaining, # noqa: N803 + DictionaryContaining, ): assert ( test_dict == DictionaryContaining({"dogs": "yes", "cats": "maybe"}) ) is expected_result -class Animal: # noqa: B903 +class Animal: def __init__(self, name=None, age=None, description=None): self.name = name self.age = age @@ -98,7 +98,7 @@ def test_object_described_by( type_and_attrs_result, type_only_result, attrs_only_result, - ObjectDescribedBy, # noqa: N803 + ObjectDescribedBy, ): assert ( test_obj == ObjectDescribedBy(type=Dog, attrs={"name": "Maisey", "age": 7}) diff --git a/tests/test_data_collection.py b/tests/test_data_collection.py index ff1eed11e0..34b433a56b 100644 --- a/tests/test_data_collection.py +++ b/tests/test_data_collection.py @@ -8,12 +8,12 @@ def test_kvcb_invalid_mode(sentry_init): - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 sentry_init(data_collection={"cookies": {"mode": "nope"}}) # type: ignore Purposely ignoring to test invalid option def test_stack_frame_variables_invalid_mode(sentry_init): - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 sentry_init(data_collection={"stack_frame_variables": {"mode": "nope"}}) @@ -28,7 +28,7 @@ def test_stack_frame_variables_invalid_mode(sentry_init): ], ) def test_frame_context_lines_invalid_value(sentry_init, value): - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 sentry_init(data_collection={"frame_context_lines": value}) diff --git a/tests/test_import.py b/tests/test_import.py index e5b07817cb..6c673e9552 100644 --- a/tests/test_import.py +++ b/tests/test_import.py @@ -1,5 +1,5 @@ # As long as this file can be imported, we are good. -from sentry_sdk import * # noqa: F403, F401 +from sentry_sdk import * # noqa: F403 def test_import(): diff --git a/tests/test_propagationcontext.py b/tests/test_propagationcontext.py index 43f712b38b..3606c5e9c1 100644 --- a/tests/test_propagationcontext.py +++ b/tests/test_propagationcontext.py @@ -131,7 +131,7 @@ def test_existing_sample_rand_kept(): def test_sample_rand_filled(parent_sampled, sample_rate, expected_interval): """When continuing a trace, we want to fill in the sample_rand value if it's missing.""" if sample_rate is not None: - sample_rate_str = f",sentry-sample_rate={sample_rate}" # noqa: E231 + sample_rate_str = f",sentry-sample_rate={sample_rate}" else: sample_rate_str = "" @@ -153,9 +153,7 @@ def mock_random_class(seed): } ) - assert ( - ctx.dynamic_sampling_context["sample_rand"] == f"{expected_interval[0]:.6f}" # noqa: E231 - ) + assert ctx.dynamic_sampling_context["sample_rand"] == f"{expected_interval[0]:.6f}" assert mock_randrange.call_count == 1 assert mock_randrange.call_args[0] == ( int(expected_interval[0] * 1000000), diff --git a/tests/test_utils.py b/tests/test_utils.py index 0bea9a6705..91d95e7cce 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -485,7 +485,7 @@ def test_accepts_valid_sample_rate(rate): 1.231, # wrong value ], ) -def test_warns_on_invalid_sample_rate(rate, StringContaining): # noqa: N803 +def test_warns_on_invalid_sample_rate(rate, StringContaining): with mock.patch.object(logger, "warning", mock.Mock()): result = is_valid_sample_rate(rate, source="Testing") logger.warning.assert_any_call(StringContaining("Given sample rate is invalid")) @@ -913,12 +913,12 @@ def test_is_sentry_url_no_client(): ], ) def test_get_error_message(error, expected_result): - with pytest.raises(BaseException) as exc_value: + with pytest.raises(BaseException) as exc_value: # noqa: PT011, PT012 exc_value.message = error raise Exception assert get_error_message(exc_value) == expected_result(exc_value) - with pytest.raises(BaseException) as exc_value: + with pytest.raises(BaseException) as exc_value: # noqa: PT011, PT012 exc_value.detail = error raise Exception assert get_error_message(exc_value) == expected_result(exc_value) @@ -1296,7 +1296,7 @@ def test_exc_info_from_error_dont_get_an_exc(): class NotAnException: pass - with pytest.raises(ValueError) as exc: + with pytest.raises(ValueError) as exc: # noqa: PT011 exc_info_from_error(NotAnException()) assert "Expected Exception object to report, got