@@ -51,6 +51,20 @@ def application(tracer):
5151 yield application
5252
5353
54+ @pytest .fixture
55+ def app_with_middleware (application , tracer ):
56+ @application .middleware ("http" )
57+ async def traced_middlware (request , call_next ):
58+ response = await call_next (request )
59+ response .headers ["MIDDLEWARE-CALLED" ] = "true"
60+ span = tracer .current_span ()
61+ if span is not None :
62+ response .headers ["DD-TRACE-CURRENT-SPAN" ] = span .name
63+ return response
64+
65+ yield application
66+
67+
5468@pytest .fixture
5569def client (tracer ):
5670 with TestClient (app .get_app ()) as test_client :
@@ -589,3 +603,20 @@ def test_host_header(client, tracer, test_spans, host):
589603 assert test_spans .spans
590604 request_span = test_spans .spans [0 ]
591605 assert request_span .get_tag ("http.url" ) == "http://%s/asynctask" % (host ,)
606+
607+
608+ def test_tracing_in_middleware (app_with_middleware , test_spans ):
609+ """Test if fastapi middlewares are traced"""
610+
611+ with TestClient (app_with_middleware ) as client :
612+ r = client .get ("/" , headers = {"sleep" : "False" })
613+ assert r .status_code == 200
614+
615+ spans = test_spans .pop_traces ()
616+ assert len (spans ) == 1
617+ assert len (spans [0 ]) == 2
618+ request_span , _ = spans [0 ]
619+
620+ assert r .headers ["MIDDLEWARE-CALLED" ] == "true"
621+ assert "DD-TRACE-CURRENT-SPAN" in r .headers
622+ assert r .headers ["DD-TRACE-CURRENT-SPAN" ] == request_span .name
0 commit comments