From 649700022a077d05ff27fc9241e0782144735f97 Mon Sep 17 00:00:00 2001 From: Ivana Kellyer Date: Tue, 17 Nov 2026 16:23:21 +0100 Subject: [PATCH] ci: Type check tests with mypy Run mypy over tests in addition to sentry_sdk. Tests are checked leniently: only module-level code and annotated functions, with missing third-party imports allowed, since most integration test dependencies aren't installed in the typing environment. Fix the errors this surfaced, including a wrong error sampler signature in test_client, a missing importlib.util import in test_quart, a dead Python 2 branch, and invalid type comments. --- .github/workflows/ci.yml | 2 +- AGENTS.md | 2 +- CONTRIBUTING.md | 4 +- pyproject.toml | 17 ++++++- scripts/build_aws_lambda_layer.py | 4 +- tests/conftest.py | 50 +++++++++---------- .../integrations/anthropic/test_anthropic.py | 19 +++---- tests/integrations/arq/test_arq_crons.py | 2 +- tests/integrations/asgi/test_asgi.py | 6 +-- .../lambda_functions/InitError/index.py | 2 +- .../ClientContextTrace/index.py | 1 + .../boto3/test_trace_propagation.py | 3 +- tests/integrations/bottle/test_bottle.py | 2 +- tests/integrations/chalice/test_chalice.py | 8 +-- .../test_clickhouse_driver.py | 10 ++-- .../test_cloud_resource_context.py | 13 ++--- tests/integrations/django/myapp/middleware.py | 2 +- tests/integrations/django/myapp/settings.py | 5 +- tests/integrations/django/myapp/views.py | 2 +- tests/integrations/fastapi/test_fastapi.py | 2 + tests/integrations/fastmcp/test_fastmcp.py | 10 ++-- tests/integrations/flask/test_flask.py | 9 ++-- tests/integrations/gql/test_gql.py | 1 + tests/integrations/grpc/test_grpc.py | 4 +- tests/integrations/huey/test_huey.py | 1 + .../huggingface_hub/test_huggingface_hub.py | 19 +++---- .../integrations/langchain/test_langchain.py | 3 +- tests/integrations/litellm/test_litellm.py | 2 +- tests/integrations/mcp/test_mcp.py | 4 +- tests/integrations/openai/test_openai.py | 13 ++--- .../openai_agents/test_openai_agents.py | 10 ++-- .../integrations/pyreqwest/test_pyreqwest.py | 3 +- tests/integrations/quart/test_quart.py | 11 ++-- tests/integrations/rq/test_rq.py | 7 +-- .../integrations/starlette/test_starlette.py | 1 + tests/integrations/stdlib/test_subprocess.py | 4 +- .../strawberry/test_strawberry.py | 4 +- tests/integrations/typesafe/test_typesafe.py | 2 +- tests/profiler/test_continuous_profiler.py | 2 +- tests/test_client.py | 10 ++-- tests/test_data_collection.py | 2 +- tests/test_exceptiongroup.py | 2 +- tests/test_tracing_utils.py | 3 +- tests/test_transport.py | 2 +- tests/test_utils.py | 2 +- 45 files changed, 159 insertions(+), 128 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6e4db7f59e..0171bcac82 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,7 +41,7 @@ jobs: run: uv run python scripts/find_raise_from_none.py - name: Mypy - run: uv run --group typing mypy sentry_sdk + run: uv run --group typing mypy sentry_sdk tests build_lambda_layer: name: Build Package diff --git a/AGENTS.md b/AGENTS.md index 6c9c5b6eba..4eb7041198 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ Use **tox** for testing (not pytest directly): ## Type Checking Mypy and its type stubs live in the opt-in `typing` dependency group: -- Run `uv run --group typing mypy sentry_sdk` before committing (must pass with zero errors) +- Run `uv run --group typing mypy sentry_sdk tests` before committing (must pass with zero errors) - Strict mode enabled (`check_untyped_defs`, `disallow_untyped_defs`) ## Linting & Formatting diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 11a1a66ceb..ea6702da52 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -97,10 +97,10 @@ uv run ruff format tests sentry_sdk #### Typing -We use `mypy` for typing our codebase. Use the following command to typecheck the source: +We use `mypy` for typing our codebase. Use the following command to typecheck the source and the tests: ``` -uv run --group typing mypy sentry_sdk +uv run --group typing mypy sentry_sdk tests ``` ##### Install Coding Style Pre-commit Hooks diff --git a/pyproject.toml b/pyproject.toml index 8eef8da39f..37e2dc83cb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,7 +2,7 @@ # Project dev dependencies (PEP 735 groups). # `dev` is installed by default; `typing` is opt-in via `uv run --group typing`. # Run tox with: `uv run tox -e ` -# Run mypy with: `uv run --group typing mypy sentry_sdk` +# Run mypy with: `uv run --group typing mypy sentry_sdk tests` # [dependency-groups] @@ -276,6 +276,21 @@ ignore_missing_imports = true module = "dramatiq.*" ignore_missing_imports = true +# Tests are only checked at the module level and where they're annotated. +# - Bodies of untyped test functions are not checked, so type: ignore comments +# in them would be reported as unused. +# - Most integration test dependencies are not installed in the typing +# environment. +[[tool.mypy.overrides]] +module = "tests.*" +check_untyped_defs = false +disallow_untyped_defs = false +disallow_incomplete_defs = false +disallow_untyped_decorators = false +disallow_subclassing_any = false +warn_unused_ignores = false +disable_error_code = ["import-not-found", "import-untyped", "annotation-unchecked"] + # # Tool: Ruff (linting and formatting) # diff --git a/scripts/build_aws_lambda_layer.py b/scripts/build_aws_lambda_layer.py index 9ee1515ec3..f80250719b 100644 --- a/scripts/build_aws_lambda_layer.py +++ b/scripts/build_aws_lambda_layer.py @@ -100,7 +100,9 @@ def zip(self) -> None: ) -def build_packaged_zip(base_dir=None, out_zip_filename=None): +def build_packaged_zip( + base_dir: "Optional[str]" = None, out_zip_filename: "Optional[str]" = None +) -> None: if base_dir is None: base_dir = tempfile.mkdtemp() diff --git a/tests/conftest.py b/tests/conftest.py index c85151a85b..370432913e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -31,15 +31,15 @@ try: from werkzeug.wrappers import Request, Response except ImportError: - Request = None - Response = None + Request = None # type: ignore[assignment, misc] + Response = None # type: ignore[assignment, misc] try: from starlette.testclient import TestClient # Catch RuntimeError to prevent the following exception in aws_lambda tests. # RuntimeError: The starlette.testclient module requires the httpx package to be installed. except (ImportError, RuntimeError): - TestClient = None + TestClient = None # type: ignore[assignment, misc] import sentry_sdk import sentry_sdk.utils @@ -55,28 +55,28 @@ try: import openai except ImportError: - openai = None + openai = None # type: ignore[assignment] try: import anthropic except ImportError: - anthropic = None + anthropic = None # type: ignore[assignment] try: import google except ImportError: - google = None + google = None # type: ignore[assignment] -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Dict from tests import _warning_recorder, _warning_recorder_mgr if TYPE_CHECKING: from collections.abc import Iterator - from typing import Any, Callable, MutableMapping + from typing import Callable, MutableMapping try: from httpx import ( @@ -91,11 +91,11 @@ Response as HttpxResponse, ) except ImportError: - ASGITransport = None - HttpxRequest = None - HttpxResponse = None - AsyncByteStream = None - AsyncClient = None + ASGITransport = None # type: ignore[assignment, misc] + HttpxRequest = None # type: ignore[assignment, misc] + HttpxResponse = None # type: ignore[assignment, misc] + AsyncByteStream = None # type: ignore[assignment, misc] + AsyncClient = None # type: ignore[assignment, misc] try: @@ -118,14 +118,14 @@ JSONRPCRequest, ) except ImportError: - create_memory_object_stream = None - create_task_group = None - EndOfStream = None - - JSONRPCMessage = None - JSONRPCNotification = None - JSONRPCRequest = None - SessionMessage = None + create_memory_object_stream = None # type: ignore[assignment, misc] + create_task_group = None # type: ignore[assignment] + EndOfStream = None # type: ignore[assignment, misc] + + JSONRPCMessage = None # type: ignore[assignment, misc] + JSONRPCNotification = None # type: ignore[assignment, misc] + JSONRPCRequest = None # type: ignore[assignment, misc] + SessionMessage = None # type: ignore[assignment, misc] _IS_MCP_V2 = False @@ -422,7 +422,7 @@ def append_envelope(envelope): @dataclass class UnwrappedItem: type: str - payload: dict + payload: "dict[str, Any]" @pytest.fixture @@ -822,7 +822,7 @@ async def inner(server, method: str, params, request_id: str | None = None): read_stream_writer, read_stream = create_memory_object_stream(0) # type: ignore write_stream, write_stream_reader = create_memory_object_stream(0) # type: ignore - result = {} + result: "dict[str, Any]" = {} async def run_server(): await server.run( @@ -995,7 +995,7 @@ async def __aiter__(self): stream = StreamingBodyStream(body_receiver) response = HttpxResponse(status_code=200, headers=[], stream=stream) # type: ignore - asyncio.create_task(run_app()) + asyncio.create_task(run_app()) # type: ignore[unused-awaitable] return response def parse_sse_data_package(sse_chunk): @@ -1601,7 +1601,7 @@ def werkzeug_set_cookie(client, servername, key, value): client.set_cookie(key, value) -class ApproxDict(dict): +class ApproxDict(Dict[Any, Any]): def __eq__(self, other): # For an ApproxDict to equal another dict, the other dict just needs to contain # all the keys from the ApproxDict with the same values. diff --git a/tests/integrations/anthropic/test_anthropic.py b/tests/integrations/anthropic/test_anthropic.py index a6167afa90..1cfe11ccbb 100644 --- a/tests/integrations/anthropic/test_anthropic.py +++ b/tests/integrations/anthropic/test_anthropic.py @@ -9,7 +9,7 @@ from unittest.mock import AsyncMock except ImportError: - class AsyncMock(mock.MagicMock): + class AsyncMock(mock.MagicMock): # type: ignore[no-redef] async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs) @@ -26,30 +26,30 @@ async def __call__(self, *args, **kwargs): try: from anthropic.types import ThinkingBlock, ThinkingDelta except ImportError: - ThinkingBlock = None - ThinkingDelta = None + ThinkingBlock = None # type: ignore[assignment, misc] + ThinkingDelta = None # type: ignore[assignment, misc] try: from anthropic import APIStatusError from anthropic.types import ErrorResponse, OverloadedError except ImportError: - ErrorResponse = None - OverloadedError = None - APIStatusError = None + ErrorResponse = None # type: ignore[assignment, misc] + OverloadedError = None # type: ignore[assignment, misc] + APIStatusError = None # type: ignore[assignment, misc] try: from anthropic.types import InputJSONDelta except ImportError: try: - from anthropic.types import InputJsonDelta as InputJSONDelta + from anthropic.types import InputJsonDelta as InputJSONDelta # type: ignore[attr-defined, no-redef] except ImportError: pass try: from anthropic.lib.streaming import TextEvent except ImportError: - TextEvent = None + TextEvent = None # type: ignore[assignment, misc] try: # 0.27+ @@ -57,7 +57,7 @@ async def __call__(self, *args, **kwargs): from anthropic.types.tool_use_block import ToolUseBlock except ImportError: # pre 0.27 - from anthropic.types.message_delta_event import Delta + from anthropic.types.message_delta_event import Delta # type: ignore[attr-defined, no-redef] try: from anthropic.types.text_block import TextBlock @@ -77,6 +77,7 @@ async def __call__(self, *args, **kwargs): from sentry_sdk.utils import package_version ANTHROPIC_VERSION = package_version("anthropic") +assert ANTHROPIC_VERSION is not None EXAMPLE_MESSAGE = Message( id="msg_01XFDUDYJgAACzvnptvVoYEL", diff --git a/tests/integrations/arq/test_arq_crons.py b/tests/integrations/arq/test_arq_crons.py index 88686e02b1..01922a7fd3 100644 --- a/tests/integrations/arq/test_arq_crons.py +++ b/tests/integrations/arq/test_arq_crons.py @@ -13,7 +13,7 @@ try: from zoneinfo import ZoneInfo except ImportError: - ZoneInfo = None + ZoneInfo = None # type: ignore[assignment, misc] @pytest.fixture(autouse=True) diff --git a/tests/integrations/asgi/test_asgi.py b/tests/integrations/asgi/test_asgi.py index 81e0934a95..c00a1db15e 100644 --- a/tests/integrations/asgi/test_asgi.py +++ b/tests/integrations/asgi/test_asgi.py @@ -514,15 +514,15 @@ def mock_asgi2_app(): class MockAsgi2App: - def __call__(): + def __call__(self): pass class MockAsgi3App(MockAsgi2App): - def __await__(): + def __await__(self): pass - async def __call__(): + async def __call__(self): pass diff --git a/tests/integrations/aws_lambda/lambda_functions/InitError/index.py b/tests/integrations/aws_lambda/lambda_functions/InitError/index.py index 20b4fcc111..f54df56420 100644 --- a/tests/integrations/aws_lambda/lambda_functions/InitError/index.py +++ b/tests/integrations/aws_lambda/lambda_functions/InitError/index.py @@ -1,3 +1,3 @@ # We have no handler() here and try to call a non-existing function. -func() # noqa: F821 +func() # type: ignore[name-defined] # noqa: F821 diff --git a/tests/integrations/aws_lambda/lambda_functions_with_embedded_sdk/ClientContextTrace/index.py b/tests/integrations/aws_lambda/lambda_functions_with_embedded_sdk/ClientContextTrace/index.py index 043961d343..cbec9ec35e 100644 --- a/tests/integrations/aws_lambda/lambda_functions_with_embedded_sdk/ClientContextTrace/index.py +++ b/tests/integrations/aws_lambda/lambda_functions_with_embedded_sdk/ClientContextTrace/index.py @@ -14,6 +14,7 @@ # `sam local` drops `ClientContext`; pass the event's `client_context` to the runtime # instead, like lambda does for a synchronous `Invoke`. bootstrap = get_lambda_bootstrap() +assert bootstrap is not None handle_event_request = bootstrap.handle_event_request diff --git a/tests/integrations/boto3/test_trace_propagation.py b/tests/integrations/boto3/test_trace_propagation.py index ebcc66dae4..37269a96d3 100644 --- a/tests/integrations/boto3/test_trace_propagation.py +++ b/tests/integrations/boto3/test_trace_propagation.py @@ -2,6 +2,7 @@ import json from http.server import BaseHTTPRequestHandler, HTTPServer from threading import Thread +from typing import Any from urllib.parse import parse_qs, urlparse import boto3 @@ -28,7 +29,7 @@ class _AwsRequestHandler(BaseHTTPRequestHandler): - requests = [] + requests: "list[Any]" = [] def do_HEAD(self): self.__class__.requests.append(self.headers) diff --git a/tests/integrations/bottle/test_bottle.py b/tests/integrations/bottle/test_bottle.py index 94877808da..fb968e9224 100644 --- a/tests/integrations/bottle/test_bottle.py +++ b/tests/integrations/bottle/test_bottle.py @@ -313,7 +313,7 @@ def index(): "integrations", [ [BottleIntegration()], - [BottleIntegration(), LoggingIntegration(event_level="ERROR")], + [BottleIntegration(), LoggingIntegration(event_level=logging.ERROR)], ], ) def test_errors_not_reported_twice( diff --git a/tests/integrations/chalice/test_chalice.py b/tests/integrations/chalice/test_chalice.py index 9d791f535a..2bf5ccc1ca 100644 --- a/tests/integrations/chalice/test_chalice.py +++ b/tests/integrations/chalice/test_chalice.py @@ -10,6 +10,9 @@ from sentry_sdk.integrations.chalice import CHALICE_VERSION, ChaliceIntegration from sentry_sdk.utils import parse_version +CHALICE_VERSION_TUPLE = parse_version(CHALICE_VERSION) +assert CHALICE_VERSION_TUPLE is not None + def _populate_lambda_context(context): fn = context.function_name @@ -26,7 +29,6 @@ def _generate_lambda_context(self): # Monkeypatch of the function _generate_lambda_context # from the class LocalGateway # for mock the timeout - # type: () -> LambdaContext if self._config.lambda_timeout is None: timeout = 10 * 1000 else: @@ -125,7 +127,7 @@ def every_hour(event): @pytest.mark.skipif( - parse_version(CHALICE_VERSION) >= (1, 26, 0), + CHALICE_VERSION_TUPLE >= (1, 26, 0), reason="different behavior based on chalice version", ) def test_bad_request_old(client: RequestHandler) -> None: @@ -139,7 +141,7 @@ def test_bad_request_old(client: RequestHandler) -> None: @pytest.mark.skipif( - parse_version(CHALICE_VERSION) < (1, 26, 0), + CHALICE_VERSION_TUPLE < (1, 26, 0), reason="different behavior based on chalice version", ) def test_bad_request(client: RequestHandler) -> None: diff --git a/tests/integrations/clickhouse_driver/test_clickhouse_driver.py b/tests/integrations/clickhouse_driver/test_clickhouse_driver.py index d4ac66551b..1960819004 100644 --- a/tests/integrations/clickhouse_driver/test_clickhouse_driver.py +++ b/tests/integrations/clickhouse_driver/test_clickhouse_driver.py @@ -5,6 +5,8 @@ ``` """ +from typing import Any + import clickhouse_driver from clickhouse_driver import Client, connect @@ -37,7 +39,7 @@ def test_clickhouse_client_breadcrumbs(sentry_init, capture_events) -> None: (event,) = events - expected_breadcrumbs = [ + expected_breadcrumbs: "list[dict[str, Any]]" = [ { "category": "query", "data": { @@ -142,7 +144,7 @@ def test_clickhouse_client_breadcrumbs_with_data_collection( (event,) = events - expected_breadcrumbs = [ + expected_breadcrumbs: "list[dict[str, Any]]" = [ { "category": "query", "data": { @@ -244,7 +246,7 @@ def test_clickhouse_client_breadcrumbs_with_data_collection_disabled( (event,) = events - expected_breadcrumbs = [ + expected_breadcrumbs: "list[dict[str, Any]]" = [ { "category": "query", "data": { @@ -563,7 +565,7 @@ def test_clickhouse_dbapi_breadcrumbs(sentry_init, capture_events) -> None: (event,) = events - expected_breadcrumbs = [ + expected_breadcrumbs: "list[dict[str, Any]]" = [ { "category": "query", "data": { diff --git a/tests/integrations/cloud_resource_context/test_cloud_resource_context.py b/tests/integrations/cloud_resource_context/test_cloud_resource_context.py index 49732b00a5..51ced09798 100644 --- a/tests/integrations/cloud_resource_context/test_cloud_resource_context.py +++ b/tests/integrations/cloud_resource_context/test_cloud_resource_context.py @@ -92,16 +92,9 @@ }, } -try: - # Python 3 - GCP_GCE_EXAMPLE_METADATA_PLAYLOAD_BYTES = bytes( - json.dumps(GCP_GCE_EXAMPLE_METADATA_PLAYLOAD), "utf-8" - ) -except TypeError: - # Python 2 - GCP_GCE_EXAMPLE_METADATA_PLAYLOAD_BYTES = bytes( - json.dumps(GCP_GCE_EXAMPLE_METADATA_PLAYLOAD) - ).encode("utf-8") +GCP_GCE_EXAMPLE_METADATA_PLAYLOAD_BYTES = bytes( + json.dumps(GCP_GCE_EXAMPLE_METADATA_PLAYLOAD), "utf-8" +) def test_is_aws_http_error(): diff --git a/tests/integrations/django/myapp/middleware.py b/tests/integrations/django/myapp/middleware.py index 4d9c6882e2..bcde8af4d5 100644 --- a/tests/integrations/django/myapp/middleware.py +++ b/tests/integrations/django/myapp/middleware.py @@ -18,7 +18,7 @@ async def middleware(request): else: - def middleware(request): + def middleware(request): # type: ignore[misc] response = get_response(request) return response diff --git a/tests/integrations/django/myapp/settings.py b/tests/integrations/django/myapp/settings.py index a04bf36531..543a5add82 100644 --- a/tests/integrations/django/myapp/settings.py +++ b/tests/integrations/django/myapp/settings.py @@ -18,6 +18,7 @@ sentry_sdk.init(integrations=[DjangoIntegration()]) import os +from typing import Any from django.utils.deprecation import MiddlewareMixin @@ -108,7 +109,9 @@ def middleware(request): # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases -DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}} +DATABASES: "dict[str, dict[str, Any]]" = { + "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"} +} try: import psycopg2 # noqa diff --git a/tests/integrations/django/myapp/views.py b/tests/integrations/django/myapp/views.py index b5e4825175..6a78bd8f5e 100644 --- a/tests/integrations/django/myapp/views.py +++ b/tests/integrations/django/myapp/views.py @@ -392,7 +392,7 @@ async def post_echo_async(request): return HttpResponse(request.body) -post_echo_async.csrf_exempt = True +post_echo_async.csrf_exempt = True # type: ignore[attr-defined] @csrf_exempt diff --git a/tests/integrations/fastapi/test_fastapi.py b/tests/integrations/fastapi/test_fastapi.py index 4937354e92..d68b9cbf28 100644 --- a/tests/integrations/fastapi/test_fastapi.py +++ b/tests/integrations/fastapi/test_fastapi.py @@ -32,7 +32,9 @@ from sentry_sdk.utils import parse_version FASTAPI_VERSION = parse_version(fastapi.__version__) +assert FASTAPI_VERSION is not None STARLETTE_VERSION = parse_version(starlette.__version__) +assert STARLETTE_VERSION is not None PICTURE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "photo.jpg") diff --git a/tests/integrations/fastmcp/test_fastmcp.py b/tests/integrations/fastmcp/test_fastmcp.py index cd709fbcb2..c5f8ffe1c1 100644 --- a/tests/integrations/fastmcp/test_fastmcp.py +++ b/tests/integrations/fastmcp/test_fastmcp.py @@ -28,7 +28,7 @@ from unittest.mock import AsyncMock except ImportError: - class AsyncMock(mock.MagicMock): + class AsyncMock(mock.MagicMock): # type: ignore[no-redef] async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs) @@ -49,7 +49,7 @@ async def __call__(self, *args, **kwargs): # Try to import both FastMCP implementations try: - from mcp.server.fastmcp import FastMCP as MCPFastMCP + from mcp.server.fastmcp import FastMCP as MCPFastMCP # type: ignore[attr-defined] HAS_MCP_FASTMCP = True except ImportError: @@ -66,7 +66,7 @@ async def __call__(self, *args, **kwargs): # Try to import request_ctx for context testing try: - from mcp.server.lowlevel.server import request_ctx + from mcp.server.lowlevel.server import request_ctx # type: ignore[attr-defined] except ImportError: request_ctx = None @@ -513,7 +513,7 @@ async def test_fastmcp_prompt_sync( @mcp.prompt() def code_help_prompt(language: str): """Get help for a programming language""" - message = Message( + message = Message( # type: ignore[misc] { "role": "user", "content": { @@ -580,7 +580,7 @@ async def test_fastmcp_prompt_sync_no_sensitive_data( @mcp.prompt() def code_help_prompt(language: str): """Get help for a programming language""" - message = Message( + message = Message( # type: ignore[misc] { "role": "user", "content": { diff --git a/tests/integrations/flask/test_flask.py b/tests/integrations/flask/test_flask.py index 94579b0dc6..edd6456da5 100644 --- a/tests/integrations/flask/test_flask.py +++ b/tests/integrations/flask/test_flask.py @@ -20,7 +20,7 @@ try: from werkzeug.wrappers.request import UnsupportedMediaType except ImportError: - from werkzeug.exceptions import BadRequest as UnsupportedMediaType + from werkzeug.exceptions import BadRequest as UnsupportedMediaType # type: ignore[assignment] import sentry_sdk import sentry_sdk.integrations.flask as flask_sentry @@ -561,7 +561,10 @@ def index(): "integrations", [ [flask_sentry.FlaskIntegration()], - [flask_sentry.FlaskIntegration(), LoggingIntegration(event_level="ERROR")], + [ + flask_sentry.FlaskIntegration(), + LoggingIntegration(event_level=logging.ERROR), + ], ], ) def test_errors_not_reported_twice(sentry_init, integrations, capture_events, app): @@ -589,7 +592,7 @@ def test_logging(sentry_init, capture_events, app): sentry_init( integrations=[ flask_sentry.FlaskIntegration(), - LoggingIntegration(event_level="ERROR"), + LoggingIntegration(event_level=logging.ERROR), ], ) diff --git a/tests/integrations/gql/test_gql.py b/tests/integrations/gql/test_gql.py index 933098d661..d692d1c6cd 100644 --- a/tests/integrations/gql/test_gql.py +++ b/tests/integrations/gql/test_gql.py @@ -10,6 +10,7 @@ from sentry_sdk.utils import parse_version GQL_VERSION = parse_version(__version__) +assert GQL_VERSION is not None @responses.activate diff --git a/tests/integrations/grpc/test_grpc.py b/tests/integrations/grpc/test_grpc.py index 9a5a910908..949d7a92a5 100644 --- a/tests/integrations/grpc/test_grpc.py +++ b/tests/integrations/grpc/test_grpc.py @@ -1,5 +1,5 @@ from concurrent import futures -from typing import List, Optional, Tuple +from typing import Any, List, Optional, Tuple from unittest import mock from unittest.mock import Mock @@ -489,7 +489,7 @@ def test_span_origin( class TestService(gRPCTestServiceServicer): - events = [] + events: "list[Any]" = [] @staticmethod def TestServe(request, context): diff --git a/tests/integrations/huey/test_huey.py b/tests/integrations/huey/test_huey.py index a6cae1b192..8ad45963be 100644 --- a/tests/integrations/huey/test_huey.py +++ b/tests/integrations/huey/test_huey.py @@ -13,6 +13,7 @@ from tests.integrations.utils import DATA_COLLECTION_QUEUES_CASES HUEY_VERSION = parse_version(HUEY_VERSION) +assert HUEY_VERSION is not None try: from huey.api import chord, group diff --git a/tests/integrations/huggingface_hub/test_huggingface_hub.py b/tests/integrations/huggingface_hub/test_huggingface_hub.py index d554a7a78e..eea83f3474 100644 --- a/tests/integrations/huggingface_hub/test_huggingface_hub.py +++ b/tests/integrations/huggingface_hub/test_huggingface_hub.py @@ -29,7 +29,6 @@ @pytest.fixture def mock_hf_text_generation_api(httpx2_mock): - # type: () -> Any """Mock HuggingFace text generation API""" model_name = "test-model" @@ -82,7 +81,6 @@ def mock_hf_text_generation_api(httpx2_mock): @pytest.fixture def mock_hf_api_with_errors(httpx2_mock): - # type: () -> Any """Mock HuggingFace API that always raises errors for any request""" model_name = "test-model" @@ -136,7 +134,6 @@ def mock_hf_api_with_errors(httpx2_mock): @pytest.fixture def mock_hf_text_generation_api_streaming(httpx2_mock): - # type: () -> Any """Mock streaming HuggingFace text generation API""" model_name = "test-model" @@ -184,7 +181,6 @@ def mock_hf_text_generation_api_streaming(httpx2_mock): @pytest.fixture def mock_hf_chat_completion_api(httpx2_mock): - # type: () -> Any """Mock HuggingFace chat completion API""" model_name = "test-model" @@ -245,7 +241,6 @@ def mock_hf_chat_completion_api(httpx2_mock): @pytest.fixture def mock_hf_chat_completion_api_tools(httpx2_mock): - # type: () -> Any """Mock HuggingFace chat completion API with tool calls.""" model_name = "test-model" @@ -315,7 +310,6 @@ def mock_hf_chat_completion_api_tools(httpx2_mock): @pytest.fixture def mock_hf_chat_completion_api_streaming(httpx2_mock): - # type: () -> Any """Mock streaming HuggingFace chat completion API""" model_name = "test-model" @@ -365,7 +359,6 @@ def mock_hf_chat_completion_api_streaming(httpx2_mock): @pytest.fixture def mock_hf_chat_completion_api_streaming_tools(httpx2_mock): - # type: () -> Any """Mock streaming HuggingFace chat completion API with tool calls.""" model_name = "test-model" @@ -1124,7 +1117,7 @@ def test_chat_completion_with_tools( ] items = capture_items("span") - client.chat_completion( + client.chat_completion( # type: ignore[call-overload] messages=[{"role": "user", "content": "What is the weather in Paris?"}], tools=tools, tool_choice="auto", @@ -1209,7 +1202,7 @@ def test_chat_completion_with_tools_no_sensitive_data( ] items = capture_items("span") - client.chat_completion( + client.chat_completion( # type: ignore[call-overload] messages=[{"role": "user", "content": "What is the weather in Paris?"}], tools=tools, tool_choice="auto", @@ -1293,7 +1286,7 @@ def test_chat_completion_streaming_with_tools( items = capture_items("span") _ = list( - client.chat_completion( + client.chat_completion( # type: ignore[call-overload] messages=[{"role": "user", "content": "What is the weather in Paris?"}], stream=True, tools=tools, @@ -1385,7 +1378,7 @@ def test_chat_completion_streaming_with_tools_no_sensitive_data( items = capture_items("span") _ = list( - client.chat_completion( + client.chat_completion( # type: ignore[call-overload] messages=[{"role": "user", "content": "What is the weather in Paris?"}], stream=True, tools=tools, @@ -1649,7 +1642,7 @@ def test_chat_completion_data_collection_tools( captured = capture_items("span") - client.chat_completion( + client.chat_completion( # type: ignore[call-overload] messages=[{"role": "user", "content": "What is the weather in Paris?"}], tools=DATA_COLLECTION_TOOLS, tool_choice="auto", @@ -1736,7 +1729,7 @@ def test_chat_completion_streaming_data_collection_tools( captured = capture_items("span") - for _ in client.chat_completion( + for _ in client.chat_completion( # type: ignore[call-overload] messages=[{"role": "user", "content": "What is the weather in Paris?"}], tools=DATA_COLLECTION_TOOLS, tool_choice="auto", diff --git a/tests/integrations/langchain/test_langchain.py b/tests/integrations/langchain/test_langchain.py index 7301b8c639..a1ee29d24e 100644 --- a/tests/integrations/langchain/test_langchain.py +++ b/tests/integrations/langchain/test_langchain.py @@ -26,7 +26,7 @@ from langchain_google_genai import ChatGoogleGenerativeAI except ImportError: ChatGoogleGenerativeAI = None - google = None + google = None # type: ignore[assignment] import sentry_sdk from sentry_sdk.integrations.langchain import ( @@ -73,6 +73,7 @@ ) LANGCHAIN_VERSION = package_version("langchain") +assert LANGCHAIN_VERSION is not None LANGCHAIN_OPENAI_VERSION = package_version("langchain-openai") diff --git a/tests/integrations/litellm/test_litellm.py b/tests/integrations/litellm/test_litellm.py index 22c36d8a93..6fcc79a04c 100644 --- a/tests/integrations/litellm/test_litellm.py +++ b/tests/integrations/litellm/test_litellm.py @@ -13,7 +13,7 @@ from unittest.mock import AsyncMock except ImportError: - class AsyncMock(mock.MagicMock): + class AsyncMock(mock.MagicMock): # type: ignore[no-redef] async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs) diff --git a/tests/integrations/mcp/test_mcp.py b/tests/integrations/mcp/test_mcp.py index 978272031d..311c13171a 100644 --- a/tests/integrations/mcp/test_mcp.py +++ b/tests/integrations/mcp/test_mcp.py @@ -29,7 +29,7 @@ from unittest.mock import AsyncMock except ImportError: - class AsyncMock(mock.MagicMock): + class AsyncMock(mock.MagicMock): # type: ignore[no-redef] async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs) @@ -39,7 +39,7 @@ async def __call__(self, *args, **kwargs): MCP_PACKAGE_VERSION = package_version("mcp") try: - from mcp.server.lowlevel.server import ( # type: ignore[import-not-found] + from mcp.server.lowlevel.server import ( # type: ignore[attr-defined] request_ctx, ) except ImportError: diff --git a/tests/integrations/openai/test_openai.py b/tests/integrations/openai/test_openai.py index 5f06e7863c..0b5f5dadb0 100644 --- a/tests/integrations/openai/test_openai.py +++ b/tests/integrations/openai/test_openai.py @@ -8,12 +8,12 @@ try: from openai import NOT_GIVEN except ImportError: - NOT_GIVEN = None + NOT_GIVEN = None # type: ignore[assignment] try: from openai import Omit, omit except ImportError: - omit = None - Omit = None + omit = None # type: ignore[assignment] + Omit = None # type: ignore[assignment, misc] from openai import AsyncOpenAI, AsyncStream, OpenAI, OpenAIError, Stream from openai.types import CompletionUsage, CreateEmbeddingResponse, Embedding @@ -33,8 +33,8 @@ PromptTokensDetails, ) except ImportError: - CompletionTokensDetails = None - PromptTokensDetails = None + CompletionTokensDetails = None # type: ignore[assignment, misc] + PromptTokensDetails = None # type: ignore[assignment, misc] try: from openai.types.chat import ( @@ -79,12 +79,13 @@ from unittest.mock import AsyncMock except ImportError: - class AsyncMock(mock.MagicMock): + class AsyncMock(mock.MagicMock): # type: ignore[no-redef] async def __call__(self, *args, **kwargs): return super(AsyncMock, self).__call__(*args, **kwargs) OPENAI_VERSION = package_version("openai") +assert OPENAI_VERSION is not None if SKIP_RESPONSES_TESTS: diff --git a/tests/integrations/openai_agents/test_openai_agents.py b/tests/integrations/openai_agents/test_openai_agents.py index 98519f6bf8..e4849dc6d5 100644 --- a/tests/integrations/openai_agents/test_openai_agents.py +++ b/tests/integrations/openai_agents/test_openai_agents.py @@ -45,23 +45,23 @@ try: from agents import ApplyPatchTool, ShellTool except ImportError: - ShellTool = None - ApplyPatchTool = None + ShellTool = None # type: ignore[assignment, misc] + ApplyPatchTool = None # type: ignore[assignment, misc] try: from agents import ToolSearchTool except ImportError: - ToolSearchTool = None + ToolSearchTool = None # type: ignore[assignment, misc] try: from agents import CustomTool except ImportError: - CustomTool = None + CustomTool = None # type: ignore[assignment, misc] try: from agents import ProgrammaticToolCallingTool except ImportError: - ProgrammaticToolCallingTool = None + ProgrammaticToolCallingTool = None # type: ignore[assignment, misc] from typing import Any, cast diff --git a/tests/integrations/pyreqwest/test_pyreqwest.py b/tests/integrations/pyreqwest/test_pyreqwest.py index 3094e25b42..8c2fefed69 100644 --- a/tests/integrations/pyreqwest/test_pyreqwest.py +++ b/tests/integrations/pyreqwest/test_pyreqwest.py @@ -3,6 +3,7 @@ from contextlib import contextmanager from http.server import BaseHTTPRequestHandler, HTTPServer from threading import Thread +from typing import Any from unittest import mock import pytest @@ -18,7 +19,7 @@ class PyreqwestMockHandler(BaseHTTPRequestHandler): - captured_requests = [] + captured_requests: "list[Any]" = [] def do_GET(self) -> None: self.captured_requests.append( diff --git a/tests/integrations/quart/test_quart.py b/tests/integrations/quart/test_quart.py index 721fb045a2..cb8856a205 100644 --- a/tests/integrations/quart/test_quart.py +++ b/tests/integrations/quart/test_quart.py @@ -1,4 +1,5 @@ -import importlib +import importlib.util +import logging import sys import threading @@ -22,6 +23,7 @@ from importlib_metadata import version QUART_VERSION = parse_version(version("quart")) +assert QUART_VERSION is not None def quart_app_factory(): @@ -264,7 +266,10 @@ async def login(): "integrations", [ [quart_sentry.QuartIntegration()], - [quart_sentry.QuartIntegration(), LoggingIntegration(event_level="ERROR")], + [ + quart_sentry.QuartIntegration(), + LoggingIntegration(event_level=logging.ERROR), + ], ], ) async def test_errors_not_reported_twice(sentry_init, integrations, capture_events): @@ -294,7 +299,7 @@ async def test_logging(sentry_init, capture_events): sentry_init( integrations=[ quart_sentry.QuartIntegration(), - LoggingIntegration(event_level="ERROR"), + LoggingIntegration(event_level=logging.ERROR), ], ) app = quart_app_factory() diff --git a/tests/integrations/rq/test_rq.py b/tests/integrations/rq/test_rq.py index eda55c5517..cacd7a6690 100644 --- a/tests/integrations/rq/test_rq.py +++ b/tests/integrations/rq/test_rq.py @@ -10,6 +10,9 @@ from sentry_sdk.utils import parse_version from tests.integrations.utils import DATA_COLLECTION_QUEUES_CASES +RQ_VERSION = parse_version(rq.__version__) +assert RQ_VERSION is not None + @pytest.fixture(autouse=True) def _patch_rq_get_server_version(monkeypatch): @@ -334,9 +337,7 @@ def test_traces_sampler_gets_correct_values_in_sampling_context( ) -@pytest.mark.skipif( - parse_version(rq.__version__) < (1, 5), reason="At least rq-1.5 required" -) +@pytest.mark.skipif(RQ_VERSION < (1, 5), reason="At least rq-1.5 required") def test_job_with_retries( sentry_init, capture_items, diff --git a/tests/integrations/starlette/test_starlette.py b/tests/integrations/starlette/test_starlette.py index 860e8e074c..f74b5ab447 100644 --- a/tests/integrations/starlette/test_starlette.py +++ b/tests/integrations/starlette/test_starlette.py @@ -35,6 +35,7 @@ from tests.integrations.conftest import parametrize_test_configurable_status_codes STARLETTE_VERSION = parse_version(starlette.__version__) +assert STARLETTE_VERSION is not None PICTURE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "photo.jpg") diff --git a/tests/integrations/stdlib/test_subprocess.py b/tests/integrations/stdlib/test_subprocess.py index 4969f7db7b..c634af9b72 100644 --- a/tests/integrations/stdlib/test_subprocess.py +++ b/tests/integrations/stdlib/test_subprocess.py @@ -2,7 +2,7 @@ import platform import subprocess import sys -from collections.abc import Mapping +from typing import Any, Mapping import pytest @@ -13,7 +13,7 @@ from tests.conftest import ApproxDict -class ImmutableDict(Mapping): +class ImmutableDict(Mapping[Any, Any]): def __init__(self, inner): self.inner = inner diff --git a/tests/integrations/strawberry/test_strawberry.py b/tests/integrations/strawberry/test_strawberry.py index e36171af87..95c242ee6c 100644 --- a/tests/integrations/strawberry/test_strawberry.py +++ b/tests/integrations/strawberry/test_strawberry.py @@ -56,7 +56,7 @@ def hello(self) -> str: @strawberry.field def error(self) -> int: - return 1 / 0 + return 1 / 0 # type: ignore[return-value] @strawberry.type @@ -95,7 +95,7 @@ class Message: class Subscription: @strawberry.subscription async def message_added(self) -> Optional[AsyncGenerator[Message, None]]: - message = Message(content="Hello, world!") + message = Message(content="Hello, world!") # type: ignore[call-arg] yield message diff --git a/tests/integrations/typesafe/test_typesafe.py b/tests/integrations/typesafe/test_typesafe.py index 5b4a1a4725..a2eec14bdd 100644 --- a/tests/integrations/typesafe/test_typesafe.py +++ b/tests/integrations/typesafe/test_typesafe.py @@ -18,7 +18,7 @@ try: from typesafe_sdk import Image except ImportError: - Image = None + Image = None # type: ignore[assignment, misc] import sentry_sdk from sentry_sdk.consts import OP, SPANDATA diff --git a/tests/profiler/test_continuous_profiler.py b/tests/profiler/test_continuous_profiler.py index b9a7beaaf1..b19e4e8a30 100644 --- a/tests/profiler/test_continuous_profiler.py +++ b/tests/profiler/test_continuous_profiler.py @@ -19,7 +19,7 @@ try: import gevent except ImportError: - gevent = None + gevent = None # type: ignore[assignment] requires_gevent = pytest.mark.skipif(gevent is None, reason="gevent not enabled") diff --git a/tests/test_client.py b/tests/test_client.py index 71b416ab61..897d42af11 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -43,9 +43,9 @@ if TYPE_CHECKING: from collections.abc import Callable - from typing import Any, Optional, Union + from typing import Optional, Union - from sentry_sdk._types import Event + from sentry_sdk._types import Event, Hint maximum_python_312 = pytest.mark.skipif( @@ -1158,7 +1158,7 @@ class IssuesSamplerTestConfig: def __init__( self, expected_events: int, - sampler_function: "Optional[Callable[[Event], Union[float, bool]]]" = None, + sampler_function: "Optional[Callable[[Event, Hint], Union[float, bool]]]" = None, sample_rate: "Optional[float]" = None, exception_to_raise: "type[Exception]" = Exception, ) -> None: @@ -1171,7 +1171,7 @@ def __init__( self.sample_rate = sample_rate self.exception_to_raise = exception_to_raise - def init_sdk(self, sentry_init: "Callable[[*Any], None]") -> None: + def init_sdk(self, sentry_init: "Callable[..., None]") -> None: sentry_init( error_sampler=self.sampler_function_mock, sample_rate=self.sample_rate ) @@ -1238,7 +1238,7 @@ def raise_exception(self) -> None: ), # If sampler returns invalid value, we should still send the event IssuesSamplerTestConfig( - sampler_function=lambda *_: ( + sampler_function=lambda *_: ( # type: ignore[arg-type, return-value] "This is an invalid return value for the sampler" ), expected_events=1, diff --git a/tests/test_data_collection.py b/tests/test_data_collection.py index 5c6e8f3cad..02170f6da4 100644 --- a/tests/test_data_collection.py +++ b/tests/test_data_collection.py @@ -3,7 +3,7 @@ def test_kvcb_invalid_mode(sentry_init): with pytest.raises(ValueError, match="Invalid collection mode 'nope'"): - sentry_init(data_collection={"cookies": {"mode": "nope"}}) # type: ignore Purposely ignoring to test invalid option + sentry_init(data_collection={"cookies": {"mode": "nope"}}) # type: ignore # Purposely ignoring to test invalid option @pytest.mark.parametrize( diff --git a/tests/test_exceptiongroup.py b/tests/test_exceptiongroup.py index 5946873d28..53800c00e9 100644 --- a/tests/test_exceptiongroup.py +++ b/tests/test_exceptiongroup.py @@ -9,7 +9,7 @@ from builtins import ExceptionGroup # type: ignore except ImportError: # Python 3.10 and below - ExceptionGroup = None + ExceptionGroup = None # type: ignore[assignment, misc] minimum_python_311 = pytest.mark.skipif( diff --git a/tests/test_tracing_utils.py b/tests/test_tracing_utils.py index 9ccb826adc..956ae90e6c 100644 --- a/tests/test_tracing_utils.py +++ b/tests/test_tracing_utils.py @@ -14,9 +14,10 @@ from tests.conftest import TestTransportWithOptions -def id_function(val: object) -> str: +def id_function(val: object) -> "Optional[str]": if isinstance(val, ShouldBeIncludedTestCase): return val.id + return None @dataclass(frozen=True) diff --git a/tests/test_transport.py b/tests/test_transport.py index 410acaa0d7..e6d18fbbe6 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -12,7 +12,7 @@ try: import httpcore except (ImportError, ModuleNotFoundError): - httpcore = None + httpcore = None # type: ignore[assignment] try: import gevent # noqa: F401 diff --git a/tests/test_utils.py b/tests/test_utils.py index fa6e63dc41..9f0b09a17d 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -51,7 +51,7 @@ class TestIntegration(Integration): try: import gevent except ImportError: - gevent = None + gevent = None # type: ignore[assignment] def _normalize_distribution_name(name: str) -> str: