Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 <env>`
# Run mypy with: `uv run --group typing mypy sentry_sdk`
# Run mypy with: `uv run --group typing mypy sentry_sdk tests`
#

[dependency-groups]
Expand Down Expand Up @@ -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)
#
Expand Down
4 changes: 3 additions & 1 deletion scripts/build_aws_lambda_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
50 changes: 25 additions & 25 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 (
Expand All @@ -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:
Expand All @@ -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


Expand Down Expand Up @@ -422,7 +422,7 @@ def append_envelope(envelope):
@dataclass
class UnwrappedItem:
type: str
payload: dict
payload: "dict[str, Any]"


@pytest.fixture
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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.
Expand Down
19 changes: 10 additions & 9 deletions tests/integrations/anthropic/test_anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -26,38 +26,38 @@ 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+
from anthropic.types.raw_message_delta_event import Delta
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
Expand All @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion tests/integrations/arq/test_arq_crons.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
try:
from zoneinfo import ZoneInfo
except ImportError:
ZoneInfo = None
ZoneInfo = None # type: ignore[assignment, misc]


@pytest.fixture(autouse=True)
Expand Down
6 changes: 3 additions & 3 deletions tests/integrations/asgi/test_asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
3 changes: 2 additions & 1 deletion tests/integrations/boto3/test_trace_propagation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -28,7 +29,7 @@


class _AwsRequestHandler(BaseHTTPRequestHandler):
requests = []
requests: "list[Any]" = []

def do_HEAD(self):
self.__class__.requests.append(self.headers)
Expand Down
2 changes: 1 addition & 1 deletion tests/integrations/bottle/test_bottle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
8 changes: 5 additions & 3 deletions tests/integrations/chalice/test_chalice.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down
Loading
Loading