feat(asgi): Add support for setting transaction name to path in FastA… · gitcommit90/sentry-python@84015f9 · GitHub
Skip to content

Commit 84015f9

Browse files
authored
feat(asgi): Add support for setting transaction name to path in FastAPI (getsentry#1349)
1 parent de0bc50 commit 84015f9

3 files changed

Lines changed: 73 additions & 9 deletions

File tree

sentry_sdk/integrations/asgi.py

Lines changed: 26 additions & 9 deletions
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import sys
2+
3+
import pytest
4+
from fastapi import FastAPI
5+
from fastapi.testclient import TestClient
6+
from sentry_sdk import capture_message
7+
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
8+
9+
10+
@pytest.fixture
11+
def app():
12+
app = FastAPI()
13+
14+
@app.get("/users/{user_id}")
15+
async def get_user(user_id: str):
16+
capture_message("hi", level="error")
17+
return {"user_id": user_id}
18+
19+
app.add_middleware(SentryAsgiMiddleware, transaction_style="url")
20+
21+
return app
22+
23+
24+
@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires python3.7 or higher")
25+
def test_fastapi_transaction_style(sentry_init, app, capture_events):
26+
sentry_init(send_default_pii=True)
27+
events = capture_events()
28+
29+
client = TestClient(app)
30+
response = client.get("/users/rick")
31+
32+
assert response.status_code == 200
33+
34+
(event,) = events
35+
assert event["transaction"] == "/users/{user_id}"
36+
assert event["request"]["env"] == {"REMOTE_ADDR": "testclient"}
37+
assert event["request"]["url"].endswith("/users/rick")
38+
assert event["request"]["method"] == "GET"
39+
40+
# Assert that state is not leaked
41+
events.clear()
42+
capture_message("foo")
43+
(event,) = events
44+
45+
assert "request" not in event
46+
assert "transaction" not in event

tox.ini

Lines changed: 1 addition & 0 deletions

0 commit comments

Comments
 (0)