Skip to content
This repository was archived by the owner on Sep 27, 2019. It is now read-only.

Commit f4ea208

Browse files
committed
Add the sentry hub into the asgi_scope so other middlewares can access it
1 parent c6a42d4 commit f4ea208

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

sentry_asgi/middleware.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ def __init__(self, app):
1212
async def __call__(self, scope, receive, send):
1313
hub = sentry_sdk.Hub.current
1414
with sentry_sdk.Hub(hub) as hub:
15+
scope["sentry_hub"] = hub
1516
with hub.configure_scope() as sentry_scope:
1617
processor = functools.partial(self.event_processor, asgi_scope=scope)
1718
sentry_scope.add_event_processor(processor)

tests/test_middleware.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
import sys
44

55
import pytest
6-
from sentry_sdk import capture_message
6+
from sentry_sdk import capture_message, Hub
77
from starlette.applications import Starlette
8+
from starlette.middleware.base import BaseHTTPMiddleware
89
from starlette.responses import PlainTextResponse
910
from starlette.testclient import TestClient
1011

@@ -30,6 +31,24 @@ async def hi(request):
3031
return app
3132

3233

34+
@pytest.fixture
35+
def app_with_extra_middleware():
36+
class _ExtraMiddleware(BaseHTTPMiddleware):
37+
async def dispatch(self, request, call_next):
38+
sentry_hub: Hub = request.get("sentry_hub")
39+
if sentry_hub:
40+
with sentry_hub.configure_scope() as scope:
41+
scope.user = {"id": "expected_user_id"}
42+
return await call_next(request)
43+
44+
app = Starlette()
45+
46+
app.add_middleware(_ExtraMiddleware)
47+
app.add_middleware(SentryMiddleware)
48+
49+
return app
50+
51+
3352
@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires python3.7 or higher")
3453
def test_sync_request_data(sentry_init, app, capture_events):
3554
sentry_init()
@@ -118,3 +137,21 @@ def myerror(request):
118137
frame["filename"].endswith("test_middleware.py")
119138
for frame in exception["stacktrace"]["frames"]
120139
)
140+
141+
142+
def test_sentry_hub_is_set_in_context(
143+
sentry_init, app_with_extra_middleware, capture_events
144+
):
145+
sentry_init()
146+
events = capture_events()
147+
148+
@app_with_extra_middleware.route("/error")
149+
def myerror(request):
150+
raise ValueError("oh no")
151+
152+
client = TestClient(app_with_extra_middleware, raise_server_exceptions=False)
153+
client.get("/error")
154+
155+
event, = events
156+
157+
assert event["user"]["id"] == "expected_user_id"

0 commit comments

Comments
 (0)