88from sentry_sdk import capture_message , configure_scope
99from sentry_sdk .integrations .sanic import SanicIntegration
1010
11- from sanic import Sanic , request , response
11+ from sanic import Sanic , request , response , __version__ as SANIC_VERSION_RAW
1212from sanic .exceptions import abort
1313
14+ SANIC_VERSION = tuple (map (int , SANIC_VERSION_RAW .split ("." )))
15+
1416
1517@pytest .fixture
1618def app ():
@@ -34,7 +36,7 @@ def test_request_data(sentry_init, app, capture_events):
3436 event , = events
3537 assert event ["transaction" ] == "hi"
3638 assert event ["request" ]["env" ] == {"REMOTE_ADDR" : "" }
37- assert set (event ["request" ]["headers" ]) = = {
39+ assert set (event ["request" ]["headers" ]) > = {
3840 "accept" ,
3941 "accept-encoding" ,
4042 "host" ,
@@ -123,6 +125,17 @@ def myhandler(request, exception):
123125
124126
125127def test_concurrency (sentry_init , app ):
128+ """
129+ Make sure we instrument Sanic in a way where request data does not leak
130+ between request handlers. This test also implicitly tests our concept of
131+ how async code should be instrumented, so if it breaks it likely has
132+ ramifications for other async integrations and async usercode.
133+
134+ We directly call the request handler instead of using Sanic's test client
135+ because that's the only way we could reproduce leakage with such a low
136+ amount of concurrent tasks.
137+ """
138+
126139 sentry_init (integrations = [SanicIntegration ()])
127140
128141 @app .route ("/context-check/<i>" )
@@ -140,16 +153,21 @@ async def context_check(request, i):
140153 async def task (i ):
141154 responses = []
142155
143- await app .handle_request (
144- request .Request (
145- url_bytes = "http://localhost/context-check/{i}" .format (i = i ).encode (
146- "ascii"
147- ),
148- headers = {},
149- version = "1.1" ,
150- method = "GET" ,
151- transport = None ,
156+ kwargs = {
157+ "url_bytes" : "http://localhost/context-check/{i}" .format (i = i ).encode (
158+ "ascii"
152159 ),
160+ "headers" : {},
161+ "version" : "1.1" ,
162+ "method" : "GET" ,
163+ "transport" : None ,
164+ }
165+
166+ if SANIC_VERSION >= (19 ,):
167+ kwargs ["app" ] = app
168+
169+ await app .handle_request (
170+ request .Request (** kwargs ),
153171 write_callback = responses .append ,
154172 stream_callback = responses .append ,
155173 )
0 commit comments