From 05d19479019c9e015a764e249b8e4a4dccd4d797 Mon Sep 17 00:00:00 2001 From: Ivana Kellyer Date: Tue, 17 Nov 2026 16:51:04 +0100 Subject: [PATCH] ci: Type check bodies of core tests with mypy Enable check_untyped_defs and warn_unused_ignores for tests that don't depend on third-party packages (tests/test_*.py, tests/tracing, tests/profiler, tests/utils), so calls into the SDK are checked against its signatures. Fix the errors this surfaced: narrow Optional values with asserts, use the SDK's TypedDicts instead of plain dicts, mark intentionally invalid inputs with targeted ignores, and remove ignores that were never needed. --- pyproject.toml | 40 ++++++++++++++ tests/profiler/test_continuous_profiler.py | 6 ++- tests/test_ai_monitoring.py | 34 ++++++------ tests/test_api.py | 11 +++- tests/test_attributes.py | 4 +- tests/test_basics.py | 6 ++- tests/test_client.py | 61 ++++++++++------------ tests/test_crons.py | 8 ++- tests/test_data_collection.py | 2 +- tests/test_envelope.py | 7 ++- tests/test_exceptiongroup.py | 2 +- tests/test_logs.py | 12 +++-- tests/test_metrics.py | 4 +- tests/test_monitor.py | 2 + tests/test_propagationcontext.py | 3 ++ tests/test_scope.py | 11 ++-- tests/test_serializer.py | 5 +- tests/test_shadowed_module.py | 3 +- tests/test_spotlight.py | 1 + tests/test_transport.py | 3 +- tests/test_utils.py | 27 +++++----- tests/tracing/test_http_headers.py | 1 + tests/tracing/test_integration_tests.py | 5 +- tests/tracing/test_misc.py | 1 + tests/tracing/test_sampling.py | 5 +- tests/tracing/test_span_batcher.py | 2 +- tests/tracing/test_span_streaming.py | 43 +++++++++++---- tests/utils/test_general.py | 7 +-- tests/utils/test_transaction.py | 7 +-- 29 files changed, 212 insertions(+), 111 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 37e2dc83cb..cdeaba0048 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -291,6 +291,46 @@ disallow_subclassing_any = false warn_unused_ignores = false disable_error_code = ["import-not-found", "import-untyped", "annotation-unchecked"] +# Core tests (no third-party dependencies) also have the bodies of untyped +# functions checked. +[[tool.mypy.overrides]] +module = [ + "tests.test_ai_monitoring", + "tests.test_api", + "tests.test_attributes", + "tests.test_basics", + "tests.test_client", + "tests.test_conftest", + "tests.test_crons", + "tests.test_data_collection", + "tests.test_dsc", + "tests.test_envelope", + "tests.test_exceptiongroup", + "tests.test_feature_flags", + "tests.test_full_stack_frames", + "tests.test_gevent", + "tests.test_import", + "tests.test_logs", + "tests.test_lru_cache", + "tests.test_metrics", + "tests.test_monitor", + "tests.test_propagationcontext", + "tests.test_scope", + "tests.test_serializer", + "tests.test_sessions", + "tests.test_shadowed_module", + "tests.test_spotlight", + "tests.test_tracing_utils", + "tests.test_transport", + "tests.test_types", + "tests.test_utils", + "tests.profiler.*", + "tests.tracing.*", + "tests.utils.*", +] +check_untyped_defs = true +warn_unused_ignores = true + # # Tool: Ruff (linting and formatting) # diff --git a/tests/profiler/test_continuous_profiler.py b/tests/profiler/test_continuous_profiler.py index b19e4e8a30..0aa89c4926 100644 --- a/tests/profiler/test_continuous_profiler.py +++ b/tests/profiler/test_continuous_profiler.py @@ -1,6 +1,7 @@ import threading import time from collections import defaultdict +from typing import TYPE_CHECKING from unittest import mock import pytest @@ -16,6 +17,9 @@ ) from tests.conftest import ApproxDict +if TYPE_CHECKING: + from sentry_sdk._types import SDKInfo + try: import gevent except ImportError: @@ -59,7 +63,7 @@ def wait_for_profiler_to_stop(envelopes, timeout=1.0): ), "profiler should have flushed a profile chunk" -mock_sdk_info = { +mock_sdk_info: "SDKInfo" = { "name": "sentry.python", "version": VERSION, "packages": [{"name": "pypi:sentry-sdk", "version": VERSION}], diff --git a/tests/test_ai_monitoring.py b/tests/test_ai_monitoring.py index e6ea0eef6e..062337b900 100644 --- a/tests/test_ai_monitoring.py +++ b/tests/test_ai_monitoring.py @@ -131,7 +131,7 @@ def test_empty_mime_type_returns_image(self): def test_none_mime_type_returns_image(self): """Test that None-like values default to 'image'""" - assert get_modality_from_mime_type(None) == "image" + assert get_modality_from_mime_type(None) == "image" # type: ignore[arg-type] def test_unknown_mime_type_returns_image(self): """Test that unknown MIME types default to 'image'""" @@ -227,9 +227,9 @@ def test_google_format_returns_none(self): def test_non_dict_returns_none(self): """Test that non-dict input returns None""" - assert transform_openai_content_part("string") is None - assert transform_openai_content_part(123) is None - assert transform_openai_content_part(None) is None + assert transform_openai_content_part("string") is None # type: ignore[arg-type] + assert transform_openai_content_part(123) is None # type: ignore[arg-type] + assert transform_openai_content_part(None) is None # type: ignore[arg-type] class TestTransformAnthropicContentPart: @@ -363,9 +363,9 @@ def test_google_format_returns_none(self): def test_non_dict_returns_none(self): """Test that non-dict input returns None""" - assert transform_anthropic_content_part("string") is None - assert transform_anthropic_content_part(123) is None - assert transform_anthropic_content_part(None) is None + assert transform_anthropic_content_part("string") is None # type: ignore[arg-type] + assert transform_anthropic_content_part(123) is None # type: ignore[arg-type] + assert transform_anthropic_content_part(None) is None # type: ignore[arg-type] class TestTransformGoogleContentPart: @@ -450,9 +450,9 @@ def test_anthropic_format_returns_none(self): def test_non_dict_returns_none(self): """Test that non-dict input returns None""" - assert transform_google_content_part("string") is None - assert transform_google_content_part(123) is None - assert transform_google_content_part(None) is None + assert transform_google_content_part("string") is None # type: ignore[arg-type] + assert transform_google_content_part(123) is None # type: ignore[arg-type] + assert transform_google_content_part(None) is None # type: ignore[arg-type] class TestTransformGenericContentPart: @@ -551,9 +551,9 @@ def test_google_format_returns_none(self): def test_non_dict_returns_none(self): """Test that non-dict input returns None""" - assert transform_generic_content_part("string") is None - assert transform_generic_content_part(123) is None - assert transform_generic_content_part(None) is None + assert transform_generic_content_part("string") is None # type: ignore[arg-type] + assert transform_generic_content_part(123) is None # type: ignore[arg-type] + assert transform_generic_content_part(None) is None # type: ignore[arg-type] def test_missing_data_key_returns_none(self): """Test that missing data key (base64/url/file_id) returns None""" @@ -846,10 +846,10 @@ def test_text_block_returns_none(self): def test_non_dict_returns_none(self): """Test that non-dict input returns None""" - assert transform_content_part("string") is None - assert transform_content_part(123) is None - assert transform_content_part(None) is None - assert transform_content_part([1, 2, 3]) is None + assert transform_content_part("string") is None # type: ignore[arg-type] + assert transform_content_part(123) is None # type: ignore[arg-type] + assert transform_content_part(None) is None # type: ignore[arg-type] + assert transform_content_part([1, 2, 3]) is None # type: ignore[arg-type] def test_empty_dict_returns_none(self): """Test that empty dict returns None""" diff --git a/tests/test_api.py b/tests/test_api.py index 473eb3b6a5..03f7ff5e6f 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -73,6 +73,7 @@ def test_traceparent_with_tracing_disabled(sentry_init): sentry_init() propagation_context = get_isolation_scope()._propagation_context + assert propagation_context is not None expected_traceparent = "%s-%s" % ( propagation_context.trace_id, propagation_context.span_id, @@ -83,6 +84,7 @@ def test_traceparent_with_tracing_disabled(sentry_init): def test_baggage_with_tracing_disabled(sentry_init): sentry_init(release="1.0.0", environment="dev") propagation_context = get_isolation_scope()._propagation_context + assert propagation_context is not None expected_baggage = ( "sentry-trace_id={},sentry-environment=dev,sentry-release=1.0.0".format( propagation_context.trace_id @@ -101,7 +103,9 @@ def test_baggage_with_tracing_enabled(sentry_init): expected_baggage_re = r"^sentry-trace_id={},sentry-sample_rand=0\.\d{{6}},sentry-environment=dev,sentry-release=1\.0\.0,sentry-transaction=segment,sentry-sample_rate=1\.0,sentry-sampled={}$".format( segment.trace_id, "true" if segment.sampled else "false" ) - assert re.match(expected_baggage_re, get_baggage()) + baggage = get_baggage() + assert baggage is not None + assert re.match(expected_baggage_re, baggage) def test_baggage_with_dsn(sentry_init): @@ -116,7 +120,9 @@ def test_baggage_with_dsn(sentry_init): expected_baggage_re = r"^sentry-trace_id={},sentry-sample_rand=0\.\d{{6}},sentry-environment=dev,sentry-release=2\.0\.0,sentry-public_key=97333d956c9e40989a0139756c121c34,sentry-transaction=segment,sentry-sample_rate=1\.0,sentry-sampled={}$".format( segment.trace_id, "true" if segment.sampled else "false" ) - assert re.match(expected_baggage_re, get_baggage()) + baggage = get_baggage() + assert baggage is not None + assert re.match(expected_baggage_re, baggage) def test_continue_trace(sentry_init): @@ -135,6 +141,7 @@ def test_continue_trace(sentry_init): assert segment.name == "some name" propagation_context = get_isolation_scope()._propagation_context + assert propagation_context is not None assert propagation_context.trace_id == segment.trace_id == trace_id assert propagation_context.parent_span_id == parent_span_id assert propagation_context.parent_sampled == parent_sampled diff --git a/tests/test_attributes.py b/tests/test_attributes.py index 394d49a313..5306ab5697 100644 --- a/tests/test_attributes.py +++ b/tests/test_attributes.py @@ -170,8 +170,8 @@ class Cat: dictionary = {"color": "tortoiseshell"} with sentry_sdk.new_scope() as scope: - scope.set_attribute("instance", instance) - scope.set_attribute("dictionary", dictionary) + scope.set_attribute("instance", instance) # type: ignore[arg-type] + scope.set_attribute("dictionary", dictionary) # type: ignore[arg-type] # Scope attrs are stored preserialized assert isinstance(scope._attributes["instance"], str) diff --git a/tests/test_basics.py b/tests/test_basics.py index be41c03818..2d4014b271 100644 --- a/tests/test_basics.py +++ b/tests/test_basics.py @@ -7,6 +7,7 @@ import time import weakref from collections import Counter +from typing import Optional import pytest @@ -663,7 +664,7 @@ def test_dedupe_does_not_retain_builtin_exceptions(sentry_init): class Payload: pass - payload_ref = None + payload_ref: "Optional[weakref.ReferenceType[Payload]]" = None def fail(): nonlocal payload_ref @@ -680,6 +681,7 @@ def capture(): capture() gc.collect() + assert payload_ref is not None assert payload_ref() is None @@ -943,7 +945,7 @@ def test_functions_to_trace_with_class(sentry_init, capture_items): assert child_spans[1]["name"] == "tests.test_basics.WorldGreeter.greet" finally: - WorldGreeter.greet = original_function + WorldGreeter.greet = original_function # type: ignore[method-assign] def test_multiple_setup_integrations_calls(): diff --git a/tests/test_client.py b/tests/test_client.py index 897d42af11..97442b4589 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -4,7 +4,6 @@ import subprocess import sys import time -from collections.abc import Mapping from textwrap import dedent from unittest import mock @@ -25,7 +24,7 @@ from sentry_sdk.integrations.executing import ExecutingIntegration from sentry_sdk.serializer import MAX_DATABAG_BREADTH from sentry_sdk.spotlight import DEFAULT_SPOTLIGHT_URL -from sentry_sdk.transport import AsyncHttpTransport, Transport +from sentry_sdk.transport import AsyncHttpTransport, HttpTransportCore, Transport from sentry_sdk.utils import capture_internal_exception try: @@ -39,7 +38,7 @@ running_under_gevent, reason="Async tests not compatible with gevent" ) -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Mapping if TYPE_CHECKING: from collections.abc import Callable @@ -325,7 +324,7 @@ def test_proxy(monkeypatch, testcase, http2): if testcase.get("env_no_proxy") is not None: monkeypatch.setenv("NO_PROXY", testcase["env_no_proxy"]) - kwargs = {} + kwargs: "dict[str, Any]" = {} if http2: kwargs["_experiments"] = {"transport_http2": True} @@ -338,15 +337,14 @@ def test_proxy(monkeypatch, testcase, http2): kwargs["proxy_headers"] = testcase["arg_proxy_headers"] client = Client(testcase["dsn"], **kwargs) + assert isinstance(client.transport, HttpTransportCore) + pool: "Any" = client.transport._pool - proxy = getattr( - client.transport._pool, - "proxy", - getattr(client.transport._pool, "_proxy_url", None), - ) + proxy = getattr(pool, "proxy", getattr(pool, "_proxy_url", None)) if testcase["expected_proxy_scheme"] is None: assert proxy is None else: + assert proxy is not None scheme = ( proxy.scheme.decode("ascii") if isinstance(proxy.scheme, bytes) @@ -358,10 +356,10 @@ def test_proxy(monkeypatch, testcase, http2): proxy_headers = ( dict( (k.decode("ascii"), v.decode("ascii")) - for k, v in client.transport._pool._proxy_headers + for k, v in pool._proxy_headers ) if http2 - else client.transport._pool.proxy_headers + else pool.proxy_headers ) assert proxy_headers == testcase["arg_proxy_headers"] @@ -371,7 +369,7 @@ def test_proxy(monkeypatch, testcase, http2): "http2", [True, False] if sys.version_info >= (3, 8) else [False] ) def test_socks_proxy(testcase, http2): - kwargs = {} + kwargs: "dict[str, Any]" = {} if http2: kwargs["_experiments"] = {"transport_http2": True} @@ -382,11 +380,11 @@ def test_socks_proxy(testcase, http2): kwargs["https_proxy"] = testcase["arg_https_proxy"] client = Client(testcase["dsn"], **kwargs) - assert ("socks" in str(type(client.transport._pool)).lower()) == testcase[ - "should_be_socks_proxy" - ], ( + assert isinstance(client.transport, HttpTransportCore) + pool_type = str(type(client.transport._pool)) + assert ("socks" in pool_type.lower()) == testcase["should_be_socks_proxy"], ( f"Expected {kwargs} to result in SOCKS == {testcase['should_be_socks_proxy']}" - f"but got {str(type(client.transport._pool))}" + f"but got {pool_type}" ) @@ -675,7 +673,7 @@ def test_client_debug_option_disabled(with_client, sentry_init, caplog): def test_weird_chars(sentry_init, capture_events): sentry_init() events = capture_events() - capture_message("föö".encode("latin1")) + capture_message("föö".encode("latin1")) # type: ignore[arg-type] (event,) = events assert json.loads(json.dumps(event)) == event @@ -706,7 +704,7 @@ def test_cyclic_frame_vars(sentry_init, capture_events): events = capture_events() try: - a = {} + a: "dict[str, Any]" = {} a["a"] = a 1 / 0 except Exception: @@ -722,7 +720,7 @@ def test_cyclic_data(sentry_init, capture_events): sentry_init() events = capture_events() - data = {} + data: "dict[str, Any]" = {} data["is_cyclic"] = data other_data = "" @@ -840,7 +838,7 @@ def test_broken_mapping(sentry_init, capture_events): sentry_init() events = capture_events() - class C(Mapping): + class C(Mapping[str, Any]): def broken(self, *args, **kwargs): raise Exception("broken") @@ -870,7 +868,7 @@ def test_mapping_sends_exception(sentry_init, capture_events): sentry_init() events = capture_events() - class C(Mapping): + class C(Mapping[str, Any]): def __iter__(self): try: 1 / 0 @@ -952,7 +950,7 @@ def test_non_string_variables(sentry_init, capture_events): events = capture_events() try: - locals()[42] = True + locals()[42] = True # type: ignore[index] 1 / 0 except ZeroDivisionError: capture_exception() @@ -987,7 +985,7 @@ def __repr__(self): return self.environ["my_representation"] try: - environ = {} + environ: "dict[str, Any]" = {} environ["a"] = TooSmartClass(environ) 1 / 0 except ZeroDivisionError: @@ -1238,7 +1236,7 @@ def raise_exception(self) -> None: ), # If sampler returns invalid value, we should still send the event IssuesSamplerTestConfig( - sampler_function=lambda *_: ( # type: ignore[arg-type, return-value] + sampler_function=lambda *_: ( # type: ignore[arg-type] "This is an invalid return value for the sampler" ), expected_events=1, @@ -1381,7 +1379,7 @@ async def test_async_proxy(monkeypatch, testcase): if testcase.get("env_no_proxy") is not None: monkeypatch.setenv("NO_PROXY", testcase["env_no_proxy"]) - kwargs = { + kwargs: "dict[str, Any]" = { "_experiments": {"transport_async": True}, "integrations": [AsyncioIntegration()], } @@ -1395,15 +1393,13 @@ async def test_async_proxy(monkeypatch, testcase): client = Client(testcase["dsn"], **kwargs) assert isinstance(client.transport, AsyncHttpTransport) + pool: "Any" = client.transport._pool - proxy = getattr( - client.transport._pool, - "proxy", - getattr(client.transport._pool, "_proxy_url", None), - ) + proxy = getattr(pool, "proxy", getattr(pool, "_proxy_url", None)) if testcase["expected_proxy_scheme"] is None: assert proxy is None else: + assert proxy is not None scheme = ( proxy.scheme.decode("ascii") if isinstance(proxy.scheme, bytes) @@ -1413,8 +1409,7 @@ async def test_async_proxy(monkeypatch, testcase): if testcase.get("arg_proxy_headers") is not None: proxy_headers = dict( - (k.decode("ascii"), v.decode("ascii")) - for k, v in client.transport._pool._proxy_headers + (k.decode("ascii"), v.decode("ascii")) for k, v in pool._proxy_headers ) assert proxy_headers == testcase["arg_proxy_headers"] @@ -1605,7 +1600,7 @@ async def test_async_socks_proxy(testcase): # These are just the same tests as the sync ones, but they need to be run in an event loop # and respect the shutdown behavior of the async transport - kwargs = { + kwargs: "dict[str, Any]" = { "_experiments": {"transport_async": True}, "integrations": [AsyncioIntegration()], } diff --git a/tests/test_crons.py b/tests/test_crons.py index dabd7e4710..832122eaaa 100644 --- a/tests/test_crons.py +++ b/tests/test_crons.py @@ -1,4 +1,5 @@ import uuid +from typing import TYPE_CHECKING from unittest import mock import pytest @@ -7,6 +8,9 @@ from sentry_sdk.crons import capture_checkin from sentry_sdk.crons.utils import _get_interval_schedule +if TYPE_CHECKING: + from sentry_sdk._types import MonitorConfig + @sentry_sdk.monitor(monitor_slug="abc123") def _hello_world(name): @@ -241,7 +245,7 @@ def test_monitor_config(sentry_init, capture_envelopes): sentry_init() envelopes = capture_envelopes() - monitor_config = { + monitor_config: "MonitorConfig" = { "schedule": {"type": "crontab", "value": "0 0 * * *"}, "failure_issue_threshold": 5, "recovery_threshold": 5, @@ -266,7 +270,7 @@ def test_monitor_config_with_owner(sentry_init, capture_envelopes): sentry_init() envelopes = capture_envelopes() - monitor_config = { + monitor_config: "MonitorConfig" = { "schedule": {"type": "crontab", "value": "0 0 * * *"}, "owner": "team:6", } diff --git a/tests/test_data_collection.py b/tests/test_data_collection.py index 02170f6da4..e58820ba5c 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"}}) @pytest.mark.parametrize( diff --git a/tests/test_envelope.py b/tests/test_envelope.py index 41cb66191a..51d04f0d41 100644 --- a/tests/test_envelope.py +++ b/tests/test_envelope.py @@ -1,8 +1,13 @@ +from typing import TYPE_CHECKING + import sentry_sdk.client from sentry_sdk import capture_event from sentry_sdk.envelope import Envelope, Item, PayloadRef from sentry_sdk.session import Session +if TYPE_CHECKING: + from sentry_sdk._types import Event + def generate_event_item(): return { @@ -28,7 +33,7 @@ def generate_event_item(): def test_add_and_get_basic_event(): envelope = Envelope() - expected = {"message": "Hello, World!"} + expected: "Event" = {"message": "Hello, World!"} envelope.add_event(expected) assert envelope.get_event() == {"message": "Hello, World!"} diff --git a/tests/test_exceptiongroup.py b/tests/test_exceptiongroup.py index 53800c00e9..1256f43964 100644 --- a/tests/test_exceptiongroup.py +++ b/tests/test_exceptiongroup.py @@ -6,7 +6,7 @@ try: # Python 3.11 - from builtins import ExceptionGroup # type: ignore + from builtins import ExceptionGroup except ImportError: # Python 3.10 and below ExceptionGroup = None # type: ignore[assignment, misc] diff --git a/tests/test_logs.py b/tests/test_logs.py index f594ba21e6..30e89820be 100644 --- a/tests/test_logs.py +++ b/tests/test_logs.py @@ -1,6 +1,7 @@ import os import sys import time +from typing import Any from unittest import mock import pytest @@ -665,7 +666,7 @@ def test_log_array_attributes(sentry_init, capture_envelopes): with sentry_sdk.new_scope() as scope: scope.set_attribute("string_list", ["value1", "value2"]) scope.set_attribute("int_tuple", (3, 2, 1, 4)) - scope.set_attribute("inhomogeneous_tuple", (3, 2.0, 1, 4)) # type: ignore[arg-type] + scope.set_attribute("inhomogeneous_tuple", (3, 2.0, 1, 4)) sentry_sdk.logger.warning( "Hello, world!", @@ -791,6 +792,7 @@ def test_reentrant_add_does_not_deadlock(sentry_init, capture_envelopes): client = sentry_sdk.get_client() batcher = client.log_batcher + assert batcher is not None reentrant_add_called = False original_add_to_envelope = batcher._add_to_envelope @@ -798,11 +800,11 @@ def test_reentrant_add_does_not_deadlock(sentry_init, capture_envelopes): def add_to_envelope_with_reentrant_add(envelope): nonlocal reentrant_add_called # Simulate a GC warning routing back into add() during flush - batcher.add({"fake": "log"}) + batcher.add({"fake": "log"}) # type: ignore[typeddict-item, typeddict-unknown-key] reentrant_add_called = True original_add_to_envelope(envelope) - batcher._add_to_envelope = add_to_envelope_with_reentrant_add + batcher._add_to_envelope = add_to_envelope_with_reentrant_add # type: ignore[method-assign] sentry_sdk.logger.warning("test log") client.flush() @@ -835,7 +837,7 @@ def test_log_batcher_lock_reset_in_child_after_fork(sentry_init): original_lock = batcher._lock original_lock.acquire() - batcher._buffer.append(object()) + batcher._buffer.append(object()) # type: ignore[arg-type] batcher._active.flag = True batcher._flush_event.set() batcher._running = False @@ -886,7 +888,7 @@ def test_flush_loop_swallows_flush_exception(): calls = [] - class ExplodingBatcher(Batcher): + class ExplodingBatcher(Batcher[Any]): def _flush(self): calls.append(1) self._running = False # exit the loop after this one iteration diff --git a/tests/test_metrics.py b/tests/test_metrics.py index efc458c32a..aa7d384737 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -407,7 +407,7 @@ def test_log_array_attributes(sentry_init, capture_envelopes): with sentry_sdk.new_scope() as scope: scope.set_attribute("string_list.attribute", ["value1", "value2"]) scope.set_attribute("int_tuple.attribute", (3, 2, 1, 4)) - scope.set_attribute("inhomogeneous_tuple.attribute", (3, 2.0, 1, 4)) # type: ignore[arg-type] + scope.set_attribute("inhomogeneous_tuple.attribute", (3, 2.0, 1, 4)) sentry_sdk.metrics.count( "test", @@ -543,7 +543,7 @@ def test_metrics_batcher_lock_reset_in_child_after_fork(sentry_init): original_lock = batcher._lock original_lock.acquire() - batcher._buffer.append(object()) + batcher._buffer.append(object()) # type: ignore[arg-type] batcher._active.flag = True batcher._flush_event.set() batcher._running = False diff --git a/tests/test_monitor.py b/tests/test_monitor.py index 8ca884c662..202d06a177 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -48,6 +48,7 @@ def test_monitor_unhealthy(sentry_init): sentry_init(transport=UnhealthyTestTransport()) monitor = sentry_sdk.get_client().monitor + assert monitor is not None # This test calls monitor.run() itself. Stop the background thread # from running health checks too, or it can bump downsample_factor # between our asserts on a slow runner (#8031). @@ -70,6 +71,7 @@ def test_segment_uses_downsampled_rate(sentry_init, capture_record_lost_event_ca record_lost_event_calls = capture_record_lost_event_calls() monitor = sentry_sdk.get_client().monitor + assert monitor is not None # This test calls monitor.run() itself. Stop the background thread # from running health checks too, or it can bump downsample_factor # between our asserts on a slow runner (#8031). diff --git a/tests/test_propagationcontext.py b/tests/test_propagationcontext.py index 3606c5e9c1..1aeed880fc 100644 --- a/tests/test_propagationcontext.py +++ b/tests/test_propagationcontext.py @@ -104,6 +104,7 @@ def test_existing_sample_rand_kept(): ) # If sample_rand was regenerated, the value would be 0.919221 based on the trace_id + assert ctx.dynamic_sampling_context is not None assert ctx.dynamic_sampling_context["sample_rand"] == "0.5" @@ -153,6 +154,7 @@ def mock_random_class(seed): } ) + assert ctx.dynamic_sampling_context is not None assert ctx.dynamic_sampling_context["sample_rand"] == f"{expected_interval[0]:.6f}" assert mock_randrange.call_count == 1 assert mock_randrange.call_args[0] == ( @@ -178,4 +180,5 @@ def mock_random_class(_): } ) + assert ctx.dynamic_sampling_context is not None assert ctx.dynamic_sampling_context["sample_rand"] == "0.999999" diff --git a/tests/test_scope.py b/tests/test_scope.py index 1643206736..4554a4fd35 100644 --- a/tests/test_scope.py +++ b/tests/test_scope.py @@ -238,14 +238,14 @@ def test_load_trace_data_from_env(env, excepted_value): def test_scope_client(): - scope = Scope(ty="test_something") - assert scope._type == "test_something" + scope = Scope(ty=ScopeType.CURRENT) + assert scope._type == ScopeType.CURRENT assert scope.client is not None assert scope.client.__class__ == NonRecordingClient custom_client = Client() - scope = Scope(ty="test_more", client=custom_client) - assert scope._type == "test_more" + scope = Scope(ty=ScopeType.ISOLATION, client=custom_client) + assert scope._type == ScopeType.ISOLATION assert scope.client is not None assert scope.client.__class__ == Client assert scope.client == custom_client @@ -829,11 +829,13 @@ def test_set_tags(): scope = Scope() scope.set_tags({"tag1": "value1", "tag2": "value2"}) event = scope.apply_to_event({}, {}) + assert event is not None assert event["tags"] == {"tag1": "value1", "tag2": "value2"}, "Setting tags failed" scope.set_tags({"tag2": "updated", "tag3": "new"}) event = scope.apply_to_event({}, {}) + assert event is not None assert event["tags"] == { "tag1": "value1", @@ -843,6 +845,7 @@ def test_set_tags(): scope.set_tags({}) event = scope.apply_to_event({}, {}) + assert event is not None assert event["tags"] == { "tag1": "value1", diff --git a/tests/test_serializer.py b/tests/test_serializer.py index f1483aba8d..b7ce0564c1 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -1,5 +1,6 @@ import re from array import array +from typing import Any, Dict import pytest @@ -95,7 +96,7 @@ def test_serialize_sets(extra_normalizer): def test_serialize_custom_mapping(extra_normalizer): - class CustomReprDict(dict): + class CustomReprDict(Dict[str, Any]): def __sentry_repr__(self): return "custom!" @@ -153,7 +154,7 @@ def test_trim_databag_breadth(body_normalizer): def test_no_trimming_if_max_request_body_size_is_always(body_normalizer): - data = { + data: "dict[str, Any]" = { "key{}".format(i): "value{}".format(i) for i in range(MAX_DATABAG_BREADTH + 10) } curr = data diff --git a/tests/test_shadowed_module.py b/tests/test_shadowed_module.py index 858e937241..bd018efa6f 100644 --- a/tests/test_shadowed_module.py +++ b/tests/test_shadowed_module.py @@ -1,5 +1,5 @@ import ast -import importlib +import importlib.util import pathlib import pkgutil import sys @@ -84,6 +84,7 @@ def test_shadowed_modules_when_importing_integrations( return except integrations.DidNotEnable: spec = importlib.util.find_spec(module_path) + assert spec is not None and spec.origin is not None source = pathlib.Path(spec.origin).read_text(encoding="utf-8") tree = ast.parse(source, filename=spec.origin) integration_dependencies = find_unrecognized_dependencies(tree) diff --git a/tests/test_spotlight.py b/tests/test_spotlight.py index 1e304e5e54..4ae59141f2 100644 --- a/tests/test_spotlight.py +++ b/tests/test_spotlight.py @@ -8,6 +8,7 @@ def capture_spotlight_envelopes(monkeypatch): def inner(): envelopes = [] test_spotlight = sentry_sdk.get_client().spotlight + assert test_spotlight is not None old_capture_envelope = test_spotlight.capture_envelope def append_envelope(envelope): diff --git a/tests/test_transport.py b/tests/test_transport.py index e6d18fbbe6..28eb964ae5 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -77,6 +77,7 @@ def make_capturing_server(request, wsgi_capturing_server): @pytest.fixture def capturing_server(): global server + assert server is not None server.clear_captured() return server @@ -350,7 +351,7 @@ def test_socket_options_merge_with_keep_alive(make_client): assert options["socket_options"] == [ (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 42), (socket.SOL_TCP, socket.TCP_KEEPINTVL, 42), - (socket.SOL_TCP, socket.TCP_KEEPIDLE, 45), + (socket.SOL_TCP, socket.TCP_KEEPIDLE, 45), # type: ignore[attr-defined, unused-ignore] (socket.SOL_TCP, socket.TCP_KEEPCNT, 6), ] except AttributeError: diff --git a/tests/test_utils.py b/tests/test_utils.py index 9f0b09a17d..e0a04f16ae 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -311,6 +311,7 @@ def test_sanitize_url(url, expected_result): ) def test_sanitize_url_and_split(url, expected_result): sanitized_url = sanitize_url(url, split=True) + assert isinstance(sanitized_url, Components) assert sanitized_url.scheme == expected_result.scheme assert sanitized_url.netloc == expected_result.netloc @@ -455,9 +456,9 @@ def test_parse_url(url, sanitize, expected_url, expected_query, expected_fragmen [0.0, 1.0, True], ) def test_accepts_valid_sample_rate(rate): - with mock.patch.object(logger, "warning", mock.Mock()): + with mock.patch.object(logger, "warning", mock.Mock()) as warning: result = is_valid_sample_rate(rate, source="Testing") - assert logger.warning.called is False + assert warning.called is False assert result is True @@ -472,9 +473,9 @@ def test_accepts_valid_sample_rate(rate): ], ) def test_warns_on_invalid_sample_rate(rate, StringContaining): - with mock.patch.object(logger, "warning", mock.Mock()): + with mock.patch.object(logger, "warning", mock.Mock()) as warning: result = is_valid_sample_rate(rate, source="Testing") - logger.warning.assert_any_call(StringContaining("Given sample rate is invalid")) + warning.assert_any_call(StringContaining("Given sample rate is invalid")) assert result is False @@ -745,7 +746,7 @@ class TestIntegration(Integration): monkeypatch.setattr(sentry_sdk.integrations, "_MIN_VERSIONS", {"test": min_version}) try: - _check_minimum_version(TestIntegration, parse_version(version)) + _check_minimum_version(TestIntegration, parse_version(version)) # type: ignore[type-abstract] except DidNotEnable: if expected_pass: assert False, ( @@ -790,7 +791,7 @@ def test_is_sentry_url_true( def test_is_sentry_url_no_client(): test_url = "https://asdf@abcd1234.ingest.sentry.io/123456789" - ret_val = is_sentry_url(None, test_url) + ret_val = is_sentry_url(None, test_url) # type: ignore[arg-type] assert not ret_val @@ -804,11 +805,11 @@ def test_is_sentry_url_no_client(): ) def test_get_error_message(error, expected_result): exc_value = Exception() - exc_value.message = error + exc_value.message = error # type: ignore[attr-defined] assert get_error_message(exc_value) == expected_result(exc_value) exc_value = Exception() - exc_value.detail = error + exc_value.detail = error # type: ignore[attr-defined] assert get_error_message(exc_value) == expected_result(exc_value) @@ -1018,7 +1019,7 @@ def test_get_current_thread_meta_bad_explicit_thread(): main_thread = threading.main_thread() - assert (main_thread.ident, main_thread.name) == get_current_thread_meta(thread) + assert (main_thread.ident, main_thread.name) == get_current_thread_meta(thread) # type: ignore[arg-type] @pytest.mark.skipif(gevent is None, reason="gevent not enabled") @@ -1162,7 +1163,7 @@ def test_function(): ... def test_qualname_from_function_none_name(): def test_function(): ... - test_function.__module__ = None + test_function.__module__ = None # type: ignore[assignment] assert ( sentry_sdk.utils.qualname_from_function(test_function) @@ -1176,7 +1177,7 @@ def __str__(self): raise UnicodeDecodeError("utf-8", b"", 0, 1, "reason") obj = BadStr() - result = to_string(obj) + result = to_string(obj) # type: ignore[arg-type] assert result == repr(obj)[1:-1] @@ -1187,11 +1188,11 @@ class NotAnException: with pytest.raises( ValueError, match="Expected Exception object to report, got ") + assert x(None) is None # type: ignore[arg-type] + assert x(42) is None # type: ignore[arg-type] + lambda_name = x(lambda: None) + assert lambda_name is not None and lambda_name.endswith("") assert x(my_lambda) == "tests.utils.test_transaction." assert ( x(my_partial) == "partial()"