From 3aae0ccf62465c0b9e580a75ccec1bdbb6dbc02f Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Mon, 31 Aug 2026 10:13:29 +0200 Subject: [PATCH 1/2] chore(litestar): Remove transaction-based tracing --- sentry_sdk/integrations/litestar.py | 149 ++---- tests/integrations/litestar/test_litestar.py | 523 ++++++------------- 2 files changed, 220 insertions(+), 452 deletions(-) diff --git a/sentry_sdk/integrations/litestar.py b/sentry_sdk/integrations/litestar.py index e88c0c3ede..80ee01b9ae 100644 --- a/sentry_sdk/integrations/litestar.py +++ b/sentry_sdk/integrations/litestar.py @@ -14,7 +14,6 @@ from sentry_sdk.integrations.logging import ignore_logger_for_events from sentry_sdk.scope import should_send_default_pii from sentry_sdk.tracing import SOURCE_FOR_STYLE, TransactionSource -from sentry_sdk.tracing_utils import has_span_streaming_enabled from sentry_sdk.utils import ( ensure_integration_enabled, event_from_exception, @@ -169,100 +168,60 @@ async def _create_span_call( return await old_call(self, scope, receive, send) middleware_name = self.__class__.__name__ - if has_span_streaming_enabled(client.options): - if sentry_sdk.traces.get_current_span() is None: - return await old_call(self, scope, receive, send) - with sentry_sdk.traces.start_span( - name=middleware_name, - attributes={ - "sentry.op": OP.MIDDLEWARE_LITESTAR, - "sentry.origin": LitestarIntegration.origin, - }, - ) as middleware_span: - middleware_span.set_attribute(SPANDATA.MIDDLEWARE_NAME, middleware_name) - - # Creating spans for the "receive" callback - async def _sentry_receive( - *args: "Any", **kwargs: "Any" - ) -> "Union[HTTPReceiveMessage, WebSocketReceiveMessage]": - if client.get_integration(LitestarIntegration) is None: - return await receive(*args, **kwargs) - if sentry_sdk.traces.get_current_span() is None: - return await receive(*args, **kwargs) - with sentry_sdk.traces.start_span( - name=getattr(receive, "__qualname__", str(receive)), - attributes={ - "sentry.op": OP.MIDDLEWARE_LITESTAR_RECEIVE, - "sentry.origin": LitestarIntegration.origin, - }, - ) as span: - span.set_attribute(SPANDATA.MIDDLEWARE_NAME, middleware_name) - return await receive(*args, **kwargs) - - receive_name = getattr(receive, "__name__", str(receive)) - receive_patched = receive_name == "_sentry_receive" - new_receive = _sentry_receive if not receive_patched else receive - - # Creating spans for the "send" callback - async def _sentry_send(message: "Message") -> None: - if client.get_integration(LitestarIntegration) is None: - return await send(message) - if sentry_sdk.traces.get_current_span() is None: - return await send(message) - with sentry_sdk.traces.start_span( - name=getattr(send, "__qualname__", str(send)), - attributes={ - "sentry.op": OP.MIDDLEWARE_LITESTAR_SEND, - "sentry.origin": LitestarIntegration.origin, - }, - ) as span: - span.set_attribute(SPANDATA.MIDDLEWARE_NAME, middleware_name) - return await send(message) - - send_name = getattr(send, "__name__", str(send)) - send_patched = send_name == "_sentry_send" - new_send = _sentry_send if not send_patched else send - - return await old_call(self, scope, new_receive, new_send) - else: - with sentry_sdk.start_span( - op=OP.MIDDLEWARE_LITESTAR, - name=middleware_name, - origin=LitestarIntegration.origin, - ) as middleware_span: - # Creating spans for the "receive" callback - async def _sentry_receive( - *args: "Any", **kwargs: "Any" - ) -> "Union[HTTPReceiveMessage, WebSocketReceiveMessage]": - if client.get_integration(LitestarIntegration) is None: - return await receive(*args, **kwargs) - with sentry_sdk.start_span( - op=OP.MIDDLEWARE_LITESTAR_RECEIVE, - name=getattr(receive, "__qualname__", str(receive)), - origin=LitestarIntegration.origin, - ): - return await receive(*args, **kwargs) - - receive_name = getattr(receive, "__name__", str(receive)) - receive_patched = receive_name == "_sentry_receive" - new_receive = _sentry_receive if not receive_patched else receive - - # Creating spans for the "send" callback - async def _sentry_send(message: "Message") -> None: - if client.get_integration(LitestarIntegration) is None: - return await send(message) - with sentry_sdk.start_span( - op=OP.MIDDLEWARE_LITESTAR_SEND, - name=getattr(send, "__qualname__", str(send)), - origin=LitestarIntegration.origin, - ): - return await send(message) - - send_name = getattr(send, "__name__", str(send)) - send_patched = send_name == "_sentry_send" - new_send = _sentry_send if not send_patched else send - - return await old_call(self, scope, new_receive, new_send) + if sentry_sdk.traces.get_current_span() is None: + return await old_call(self, scope, receive, send) + with sentry_sdk.traces.start_span( + name=middleware_name, + attributes={ + "sentry.op": OP.MIDDLEWARE_LITESTAR, + "sentry.origin": LitestarIntegration.origin, + }, + ) as middleware_span: + middleware_span.set_attribute(SPANDATA.MIDDLEWARE_NAME, middleware_name) + + # Creating spans for the "receive" callback + async def _sentry_receive( + *args: "Any", **kwargs: "Any" + ) -> "Union[HTTPReceiveMessage, WebSocketReceiveMessage]": + if client.get_integration(LitestarIntegration) is None: + return await receive(*args, **kwargs) + if sentry_sdk.traces.get_current_span() is None: + return await receive(*args, **kwargs) + with sentry_sdk.traces.start_span( + name=getattr(receive, "__qualname__", str(receive)), + attributes={ + "sentry.op": OP.MIDDLEWARE_LITESTAR_RECEIVE, + "sentry.origin": LitestarIntegration.origin, + }, + ) as span: + span.set_attribute(SPANDATA.MIDDLEWARE_NAME, middleware_name) + return await receive(*args, **kwargs) + + receive_name = getattr(receive, "__name__", str(receive)) + receive_patched = receive_name == "_sentry_receive" + new_receive = _sentry_receive if not receive_patched else receive + + # Creating spans for the "send" callback + async def _sentry_send(message: "Message") -> None: + if client.get_integration(LitestarIntegration) is None: + return await send(message) + if sentry_sdk.traces.get_current_span() is None: + return await send(message) + with sentry_sdk.traces.start_span( + name=getattr(send, "__qualname__", str(send)), + attributes={ + "sentry.op": OP.MIDDLEWARE_LITESTAR_SEND, + "sentry.origin": LitestarIntegration.origin, + }, + ) as span: + span.set_attribute(SPANDATA.MIDDLEWARE_NAME, middleware_name) + return await send(message) + + send_name = getattr(send, "__name__", str(send)) + send_patched = send_name == "_sentry_send" + new_send = _sentry_send if not send_patched else send + + return await old_call(self, scope, new_receive, new_send) not_yet_patched = old_call.__name__ not in ["_create_span_call"] diff --git a/tests/integrations/litestar/test_litestar.py b/tests/integrations/litestar/test_litestar.py index 31527a7db7..a8f025aaf8 100644 --- a/tests/integrations/litestar/test_litestar.py +++ b/tests/integrations/litestar/test_litestar.py @@ -97,51 +97,34 @@ async def body_json(data: "dict[str, Any]") -> "dict[str, Any]": ), ], ) -@pytest.mark.parametrize("span_streaming", [True, False]) def test_catch_exceptions( sentry_init, capture_exceptions, - capture_events, capture_items, test_url, expected_error, expected_message, expected_tx_name, - span_streaming, ): sentry_init( integrations=[LitestarIntegration()], - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", ) litestar_app = litestar_app_factory() client = TestClient(litestar_app) exceptions = capture_exceptions() - if span_streaming: - items = capture_items("event") + items = capture_items("event") - try: - client.get(test_url) - except Exception: - pass + try: + client.get(test_url) + except Exception: + pass - (exc,) = exceptions - assert isinstance(exc, expected_error) - assert str(exc) == expected_message + (exc,) = exceptions + assert isinstance(exc, expected_error) + assert str(exc) == expected_message - (event,) = (item.payload for item in items) - else: - events = capture_events() - - try: - client.get(test_url) - except Exception: - pass - - (exc,) = exceptions - assert isinstance(exc, expected_error) - assert str(exc) == expected_message - - (event,) = events + (event,) = (item.payload for item in items) assert expected_tx_name in event["transaction"] assert event["exception"]["values"][0]["mechanism"]["type"] == "litestar" @@ -163,61 +146,42 @@ def test_catch_exceptions( ), ], ) -@pytest.mark.parametrize("span_streaming", [True, False]) def test_transaction_name_and_source( sentry_init, - capture_events, test_url, expected_tx_name, capture_items, - span_streaming, ): sentry_init( traces_sample_rate=1.0, integrations=[LitestarIntegration()], - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", ) litestar_app = litestar_app_factory() client = TestClient(litestar_app) + items = capture_items("span") - if span_streaming: - items = capture_items("span") + try: + client.get(test_url) + except Exception: + pass - try: - client.get(test_url) - except Exception: - pass - - sentry_sdk.flush() - spans = [item.payload for item in items] - - spans = [span for span in spans if expected_tx_name in span["name"]] - assert len(spans) == 1 - assert spans[0]["attributes"]["sentry.segment.name.source"] == "component" - else: - events = capture_events() + sentry_sdk.flush() + spans = [item.payload for item in items] - try: - client.get(test_url) - except Exception: - pass + spans = [span for span in spans if expected_tx_name in span["name"]] + assert len(spans) == 1 + assert spans[0]["attributes"]["sentry.segment.name.source"] == "component" - (_, transaction) = events - assert expected_tx_name in transaction["transaction"] - assert transaction["transaction_info"] == {"source": "component"} - -@pytest.mark.parametrize("span_streaming", [True, False]) def test_middleware_spans( sentry_init, - capture_events, capture_items, - span_streaming, ): sentry_init( traces_sample_rate=1.0, integrations=[LitestarIntegration()], - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", ) logging_config = LoggingMiddlewareConfig() @@ -234,56 +198,32 @@ def test_middleware_spans( client = TestClient( litestar_app, raise_server_exceptions=False, base_url="http://testserver.local" ) - if span_streaming: - items = capture_items("span") - - client.get("/message") - - sentry_sdk.flush() - spans = [item.payload for item in items] - - expected = {"SessionMiddleware", "LoggingMiddleware", "RateLimitMiddleware"} - found = set() - - litestar_spans = ( - span - for span in spans - if span["attributes"]["sentry.op"] == "middleware.litestar" - ) + items = capture_items("span") - for span in litestar_spans: - assert span["name"] in expected - assert span["name"] not in found - found.add(span["name"]) - assert span["name"] == span["attributes"]["middleware.name"] - else: - events = capture_events() - - client.get("/message") + client.get("/message") - (_, transaction_event) = events + sentry_sdk.flush() + spans = [item.payload for item in items] - expected = {"SessionMiddleware", "LoggingMiddleware", "RateLimitMiddleware"} - found = set() + expected = {"SessionMiddleware", "LoggingMiddleware", "RateLimitMiddleware"} + found = set() - litestar_spans = ( - span - for span in transaction_event["spans"] - if span["op"] == "middleware.litestar" - ) + litestar_spans = ( + span + for span in spans + if span["attributes"]["sentry.op"] == "middleware.litestar" + ) - for span in litestar_spans: - assert span["description"] in expected - assert span["description"] not in found - found.add(span["description"]) + for span in litestar_spans: + assert span["name"] in expected + assert span["name"] not in found + found.add(span["name"]) + assert span["name"] == span["attributes"]["middleware.name"] -@pytest.mark.parametrize("span_streaming", [True, False]) def test_middleware_callback_spans( sentry_init, - capture_events, capture_items, - span_streaming, ): class SampleMiddleware(AbstractMiddleware): async def __call__(self, scope, receive, send) -> None: @@ -298,94 +238,60 @@ async def do_stuff(message): sentry_init( traces_sample_rate=1.0, integrations=[LitestarIntegration()], - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", ) litestar_app = litestar_app_factory(middleware=[SampleMiddleware]) client = TestClient(litestar_app, raise_server_exceptions=False) - if span_streaming: - items = capture_items("span") - - client.get("/message") - - spans = [item.payload for item in items] + items = capture_items("span") - expected_litestar_spans = [ - { - "name": "SampleMiddleware", - "attributes": ApproxDict( - { - "middleware.name": "SampleMiddleware", - "sentry.op": "middleware.litestar", - }, - ), - }, - { - "name": "SentryAsgiMiddleware._run_app.._sentry_wrapped_send", - "attributes": ApproxDict( - { - "middleware.name": "SampleMiddleware", - "sentry.op": "middleware.litestar.send", - } - ), - }, - { - "name": "SentryAsgiMiddleware._run_app.._sentry_wrapped_send", - "attributes": ApproxDict( - { - "middleware.name": "SampleMiddleware", - "sentry.op": "middleware.litestar.send", - } - ), - }, - ] + client.get("/message") - def is_matching_span(expected_span, actual_span): - return ( - expected_span["name"] == actual_span["name"] - and expected_span["attributes"] == actual_span["attributes"] - ) - - sentry_sdk.flush() - spans = [item.payload for item in items] - actual_litestar_spans = list( - span - for span in spans - if "middleware.litestar" in span["attributes"].get("sentry.op") + spans = [item.payload for item in items] + + expected_litestar_spans = [ + { + "name": "SampleMiddleware", + "attributes": ApproxDict( + { + "middleware.name": "SampleMiddleware", + "sentry.op": "middleware.litestar", + }, + ), + }, + { + "name": "SentryAsgiMiddleware._run_app.._sentry_wrapped_send", + "attributes": ApproxDict( + { + "middleware.name": "SampleMiddleware", + "sentry.op": "middleware.litestar.send", + } + ), + }, + { + "name": "SentryAsgiMiddleware._run_app.._sentry_wrapped_send", + "attributes": ApproxDict( + { + "middleware.name": "SampleMiddleware", + "sentry.op": "middleware.litestar.send", + } + ), + }, + ] + + def is_matching_span(expected_span, actual_span): + return ( + expected_span["name"] == actual_span["name"] + and expected_span["attributes"] == actual_span["attributes"] ) - else: - events = capture_events() - client.get("/message") - - (_, transaction_events) = events - - expected_litestar_spans = [ - { - "op": "middleware.litestar", - "description": "SampleMiddleware", - }, - { - "op": "middleware.litestar.send", - "description": "SentryAsgiMiddleware._run_app.._sentry_wrapped_send", - }, - { - "op": "middleware.litestar.send", - "description": "SentryAsgiMiddleware._run_app.._sentry_wrapped_send", - }, - ] - - def is_matching_span(expected_span, actual_span): - return ( - expected_span["op"] == actual_span["op"] - and expected_span["description"] == actual_span["description"] - ) - - actual_litestar_spans = list( - span - for span in transaction_events["spans"] - if "middleware.litestar" in span["op"] - ) + sentry_sdk.flush() + spans = [item.payload for item in items] + actual_litestar_spans = list( + span + for span in spans + if "middleware.litestar" in span["attributes"].get("sentry.op") + ) assert len(actual_litestar_spans) == 3 @@ -396,8 +302,9 @@ def is_matching_span(expected_span, actual_span): ) -@pytest.mark.parametrize("span_streaming", [True, False]) -def test_middleware_receive_send(sentry_init, capture_items, span_streaming): +def test_middleware_receive_send( + sentry_init, +): class SampleReceiveSendMiddleware(AbstractMiddleware): async def __call__(self, scope, receive, send): message = await receive() @@ -412,7 +319,7 @@ async def __call__(self, scope, receive, send): sentry_init( traces_sample_rate=1.0, integrations=[LitestarIntegration()], - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", ) litestar_app = litestar_app_factory(middleware=[SampleReceiveSendMiddleware]) @@ -421,12 +328,9 @@ async def __call__(self, scope, receive, send): client.get("/message") -@pytest.mark.parametrize("span_streaming", [True, False]) def test_middleware_partial_receive_send( sentry_init, - capture_events, capture_items, - span_streaming, ): class SamplePartialReceiveSendMiddleware(AbstractMiddleware): async def __call__(self, scope, receive, send): @@ -451,95 +355,60 @@ async def my_send(*args, **kwargs): sentry_init( traces_sample_rate=1.0, integrations=[LitestarIntegration()], - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", ) litestar_app = litestar_app_factory(middleware=[SamplePartialReceiveSendMiddleware]) client = TestClient(litestar_app, raise_server_exceptions=False) + items = capture_items("span") - if span_streaming: - items = capture_items("span") - - # See SamplePartialReceiveSendMiddleware.__call__ above for assertions of correct behavior - client.get("/message") - - sentry_sdk.flush() - spans = [item.payload for item in items] - - expected_litestar_spans = [ - { - "name": "SamplePartialReceiveSendMiddleware", - "attributes": ApproxDict( - { - "middleware.name": "SamplePartialReceiveSendMiddleware", - "sentry.op": "middleware.litestar", - } - ), - }, - { - "name": "TestClientTransport.create_receive..receive", - "attributes": ApproxDict( - { - "middleware.name": "SamplePartialReceiveSendMiddleware", - "sentry.op": "middleware.litestar.receive", - } - ), - }, - { - "name": "SentryAsgiMiddleware._run_app.._sentry_wrapped_send", - "attributes": ApproxDict( - { - "middleware.name": "SamplePartialReceiveSendMiddleware", - "sentry.op": "middleware.litestar.send", - } - ), - }, - ] + # See SamplePartialReceiveSendMiddleware.__call__ above for assertions of correct behavior + client.get("/message") - def is_matching_span(expected_span, actual_span): - return ( - actual_span["name"].startswith(expected_span["name"]) - and expected_span["attributes"] == actual_span["attributes"] - ) + sentry_sdk.flush() + spans = [item.payload for item in items] - actual_litestar_spans = list( - span - for span in spans - if "middleware.litestar" in span["attributes"].get("sentry.op") + expected_litestar_spans = [ + { + "name": "SamplePartialReceiveSendMiddleware", + "attributes": ApproxDict( + { + "middleware.name": "SamplePartialReceiveSendMiddleware", + "sentry.op": "middleware.litestar", + } + ), + }, + { + "name": "TestClientTransport.create_receive..receive", + "attributes": ApproxDict( + { + "middleware.name": "SamplePartialReceiveSendMiddleware", + "sentry.op": "middleware.litestar.receive", + } + ), + }, + { + "name": "SentryAsgiMiddleware._run_app.._sentry_wrapped_send", + "attributes": ApproxDict( + { + "middleware.name": "SamplePartialReceiveSendMiddleware", + "sentry.op": "middleware.litestar.send", + } + ), + }, + ] + + def is_matching_span(expected_span, actual_span): + return ( + actual_span["name"].startswith(expected_span["name"]) + and expected_span["attributes"] == actual_span["attributes"] ) - else: - events = capture_events() - - # See SamplePartialReceiveSendMiddleware.__call__ above for assertions of correct behavior - client.get("/message") - - (_, transaction_events) = events - - expected_litestar_spans = [ - { - "op": "middleware.litestar", - "description": "SamplePartialReceiveSendMiddleware", - }, - { - "op": "middleware.litestar.receive", - "description": "TestClientTransport.create_receive..receive", - }, - { - "op": "middleware.litestar.send", - "description": "SentryAsgiMiddleware._run_app.._sentry_wrapped_send", - }, - ] - def is_matching_span(expected_span, actual_span): - return expected_span["op"] == actual_span["op"] and actual_span[ - "description" - ].startswith(expected_span["description"]) - - actual_litestar_spans = list( - span - for span in transaction_events["spans"] - if "middleware.litestar" in span["op"] - ) + actual_litestar_spans = list( + span + for span in spans + if "middleware.litestar" in span["attributes"].get("sentry.op") + ) assert len(actual_litestar_spans) == 3 for expected_span in expected_litestar_spans: @@ -549,17 +418,14 @@ def is_matching_span(expected_span, actual_span): ) -@pytest.mark.parametrize("span_streaming", [True, False]) def test_span_origin( sentry_init, - capture_events, capture_items, - span_streaming, ): sentry_init( integrations=[LitestarIntegration()], traces_sample_rate=1.0, - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", ) logging_config = LoggingMiddlewareConfig() @@ -576,40 +442,26 @@ def test_span_origin( client = TestClient( litestar_app, raise_server_exceptions=False, base_url="http://testserver.local" ) - if span_streaming: - items = capture_items("span") - - client.get("/message") - - sentry_sdk.flush() - spans = [item.payload for item in items] - - for span in spans: - if span["attributes"]["sentry.origin"] == "auto.http.httpx": - continue - assert span["attributes"]["sentry.origin"] == "auto.http.litestar" - else: - events = capture_events() + items = capture_items("span") - client.get("/message") + client.get("/message") - (_, event) = events + sentry_sdk.flush() + spans = [item.payload for item in items] - assert event["contexts"]["trace"]["origin"] == "auto.http.litestar" - for span in event["spans"]: - assert span["origin"] == "auto.http.litestar" + for span in spans: + if span["attributes"]["sentry.origin"] == "auto.http.httpx": + continue + assert span["attributes"]["sentry.origin"] == "auto.http.litestar" @pytest.mark.parametrize("init_kwargs, expect_user", DATA_COLLECTION_USER_INFO_CASES) -@pytest.mark.parametrize("span_streaming", [True, False]) def test_litestar_scope_user_on_exception_event( sentry_init, capture_exceptions, - capture_events, capture_items, init_kwargs, expect_user, - span_streaming, ): class TestUserMiddleware(AbstractMiddleware): async def __call__(self, scope, receive, send): @@ -622,36 +474,23 @@ async def __call__(self, scope, receive, send): sentry_init( integrations=[LitestarIntegration()], - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", **init_kwargs, ) litestar_app = litestar_app_factory(middleware=[TestUserMiddleware]) client = TestClient(litestar_app) exceptions = capture_exceptions() - if span_streaming: - items = capture_items("event") - - # This request intentionally raises an exception - try: - client.get("/some_url") - except Exception: - pass - - assert len(exceptions) == 1 - (event,) = (item.payload for item in items) - else: - events = capture_events() + items = capture_items("event") - # This request intentionally raises an exception - try: - client.get("/some_url") - except Exception: - pass + # This request intentionally raises an exception + try: + client.get("/some_url") + except Exception: + pass - assert len(exceptions) == 1 - assert len(events) == 1 - (event,) = events + assert len(exceptions) == 1 + (event,) = (item.payload for item in items) if expect_user: assert "user" in event @@ -860,15 +699,12 @@ def test_cookie_data_collection( @parametrize_test_configurable_status_codes -@pytest.mark.parametrize("span_streaming", [True, False]) def test_configurable_status_codes_handler( sentry_init, - capture_events, capture_items, failed_request_status_codes, status_code, expected_error, - span_streaming, ): integration_kwargs = ( {"failed_request_status_codes": failed_request_status_codes} @@ -877,7 +713,7 @@ def test_configurable_status_codes_handler( ) sentry_init( integrations=[LitestarIntegration(**integration_kwargs)], - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", ) @get("/error") @@ -886,31 +722,22 @@ async def error() -> None: app = Litestar([error]) client = TestClient(app) + items = capture_items("event") - if span_streaming: - items = capture_items("event") + client.get("/error") - client.get("/error") - - events = [item.payload for item in items] - else: - events = capture_events() - - client.get("/error") + events = [item.payload for item in items] assert len(events) == int(expected_error) @parametrize_test_configurable_status_codes -@pytest.mark.parametrize("span_streaming", [True, False]) def test_configurable_status_codes_middleware( sentry_init, - capture_events, capture_items, failed_request_status_codes, status_code, expected_error, - span_streaming, ): integration_kwargs = ( {"failed_request_status_codes": failed_request_status_codes} @@ -920,7 +747,7 @@ def test_configurable_status_codes_middleware( sentry_init( integrations=[LitestarIntegration(**integration_kwargs)], - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", ) def create_raising_middleware(app): @@ -934,31 +761,22 @@ async def error() -> None: ... app = Litestar([error], middleware=[create_raising_middleware]) client = TestClient(app) + items = capture_items("event") - if span_streaming: - items = capture_items("event") - - client.get("/error") - - events = [item.payload for item in items] - else: - events = capture_events() + client.get("/error") - client.get("/error") + events = [item.payload for item in items] assert len(events) == int(expected_error) -@pytest.mark.parametrize("span_streaming", [True, False]) def test_catch_non_http_exceptions_in_middleware( sentry_init, - capture_events, capture_items, - span_streaming, ): sentry_init( integrations=[LitestarIntegration()], - trace_lifecycle="stream" if span_streaming else "static", + trace_lifecycle="stream", ) def create_raising_middleware(app): @@ -972,23 +790,14 @@ async def error() -> None: ... app = Litestar([error], middleware=[create_raising_middleware]) client = TestClient(app) + items = capture_items("event") - if span_streaming: - items = capture_items("event") - - try: - client.get("/error") - except RuntimeError: - pass - - events = [item.payload for item in items] - else: - events = capture_events() + try: + client.get("/error") + except RuntimeError: + pass - try: - client.get("/error") - except RuntimeError: - pass + events = [item.payload for item in items] assert len(events) == 1 event_exception = events[0]["exception"]["values"][0] From d38d589895874b1053c22b9ec67a5882902cc09c Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Mon, 31 Aug 2026 10:32:44 +0200 Subject: [PATCH 2/2] remove transaction references in tests --- tests/integrations/litestar/test_litestar.py | 195 +------------------ 1 file changed, 1 insertion(+), 194 deletions(-) diff --git a/tests/integrations/litestar/test_litestar.py b/tests/integrations/litestar/test_litestar.py index a8f025aaf8..1c0fc83582 100644 --- a/tests/integrations/litestar/test_litestar.py +++ b/tests/integrations/litestar/test_litestar.py @@ -15,7 +15,6 @@ import sentry_sdk from sentry_sdk import capture_message -from sentry_sdk._types import SENSITIVE_DATA_SUBSTITUTE from sentry_sdk.integrations.litestar import LitestarIntegration from tests.conftest import ApproxDict from tests.integrations.conftest import parametrize_test_configurable_status_codes @@ -146,7 +145,7 @@ def test_catch_exceptions( ), ], ) -def test_transaction_name_and_source( +def test_segment_name_and_source( sentry_init, test_url, expected_tx_name, @@ -506,198 +505,6 @@ async def __call__(self, scope, receive, send): COOKIE_HEADER = "jwt=tokenval; theme=dark; lang=en; identity=alice" -@pytest.mark.parametrize( - "data_collection, expect_body", - [ - pytest.param(None, True, id="no_data_collection_experiment"), - pytest.param({}, True, id="data_collection_http_bodies_default"), - pytest.param( - {"http_bodies": ["incoming_request"]}, - True, - id="data_collection_http_bodies_incoming_request", - ), - pytest.param( - {"http_bodies": []}, False, id="data_collection_http_bodies_empty" - ), - ], -) -def test_request_body_data_collection( - sentry_init, capture_events, data_collection, expect_body -): - sentry_init( - traces_sample_rate=1.0, - integrations=[LitestarIntegration()], - _experiments=( - {} if data_collection is None else {"data_collection": data_collection} - ), - ) - - litestar_app = litestar_app_factory() - events = capture_events() - - body = {"foo": {"bar": "baz", "qux": ["1", "2", "3"]}} - - client = TestClient(litestar_app) - client.post("/body/json", json=body) - - (event, transaction_event) = events - - if expect_body: - assert event["request"]["data"] == body - assert transaction_event["request"]["data"] == body - else: - assert "data" not in event["request"] - assert "data" not in transaction_event["request"] - - -def test_request_body_data_collection_wins_over_send_default_pii( - sentry_init, capture_events -): - sentry_init( - traces_sample_rate=1.0, - integrations=[LitestarIntegration()], - send_default_pii=True, - _experiments={"data_collection": {"http_bodies": []}}, - ) - - litestar_app = litestar_app_factory() - events = capture_events() - - client = TestClient(litestar_app) - client.post("/body/json", json={"foo": {"bar": "baz", "qux": ["1", "2", "3"]}}) - - (event, transaction_event) = events - - assert "data" not in event["request"] - assert "data" not in transaction_event["request"] - - -@pytest.mark.parametrize( - "init_kwargs, expected_cookies", - [ - pytest.param( - {"send_default_pii": True}, - { - "jwt": "tokenval", - "theme": "dark", - "lang": "en", - "identity": "alice", - }, - id="send_default_pii_true", - ), - pytest.param( - {"send_default_pii": False}, - None, - id="send_default_pii_false", - ), - pytest.param( - {}, - None, - id="defaults", - ), - pytest.param( - {"_experiments": {"data_collection": {"cookies": {"mode": "off"}}}}, - None, - id="data_collection_off", - ), - pytest.param( - {"_experiments": {"data_collection": {"cookies": {"mode": "denylist"}}}}, - { - "jwt": SENSITIVE_DATA_SUBSTITUTE, - "theme": "dark", - "lang": "en", - "identity": SENSITIVE_DATA_SUBSTITUTE, - }, - id="data_collection_denylist_default", - ), - pytest.param( - { - "_experiments": { - "data_collection": { - "cookies": {"mode": "denylist", "terms": ["theme"]} - } - } - }, - { - "jwt": SENSITIVE_DATA_SUBSTITUTE, - "theme": SENSITIVE_DATA_SUBSTITUTE, - "lang": "en", - "identity": SENSITIVE_DATA_SUBSTITUTE, - }, - id="data_collection_denylist_custom_terms", - ), - pytest.param( - { - "_experiments": { - "data_collection": { - "cookies": {"mode": "allowlist", "terms": ["theme"]} - } - } - }, - { - "jwt": SENSITIVE_DATA_SUBSTITUTE, - "theme": "dark", - "lang": SENSITIVE_DATA_SUBSTITUTE, - "identity": SENSITIVE_DATA_SUBSTITUTE, - }, - id="data_collection_allowlist", - ), - pytest.param( - { - "_experiments": { - "data_collection": { - "cookies": {"mode": "allowlist", "terms": ["identity"]} - } - } - }, - { - "jwt": SENSITIVE_DATA_SUBSTITUTE, - "theme": SENSITIVE_DATA_SUBSTITUTE, - "lang": SENSITIVE_DATA_SUBSTITUTE, - "identity": SENSITIVE_DATA_SUBSTITUTE, - }, - id="data_collection_allowlist_sensitive_term", - ), - pytest.param( - { - "send_default_pii": False, - "_experiments": {"data_collection": {"cookies": {"mode": "denylist"}}}, - }, - { - "jwt": SENSITIVE_DATA_SUBSTITUTE, - "theme": "dark", - "lang": "en", - "identity": SENSITIVE_DATA_SUBSTITUTE, - }, - id="data_collection_wins_over_send_default_pii", - ), - ], -) -def test_cookie_data_collection( - sentry_init, capture_events, init_kwargs, expected_cookies -): - sentry_init( - traces_sample_rate=1.0, - integrations=[LitestarIntegration()], - **init_kwargs, - ) - - litestar_app = litestar_app_factory() - events = capture_events() - - client = TestClient(litestar_app) - client.get("/message", headers={"cookie": COOKIE_HEADER}) - - (event, transaction_event) = events - - if expected_cookies is None: - assert "cookies" not in event["request"] - assert "cookies" not in transaction_event["request"] - else: - assert event["request"]["cookies"] == expected_cookies - assert transaction_event["request"]["cookies"] == expected_cookies - - @parametrize_test_configurable_status_codes def test_configurable_status_codes_handler( sentry_init,