55import pytest
66import asynctest
77import asyncio
8+ from typing import List
89from httpx import AsyncClient
910from fastapi import FastAPI , APIRouter , Request
1011from fastapi .responses import JSONResponse
2223MULTIPLE_THREADS_ROUTE = f'/{ MULTIPLE_THREADS_KEY } '
2324MULTIPLE_THREADS_RETURN_VALUE = MULTIPLE_THREADS_KEY
2425TEST_POST_DATA = {'post_test' : '123' }
26+ CUSTOM_RESPONSE = ["A" ]
27+ CUSTOM_RESPONSE_PATH = "/custom_response"
2528
2629def _get_response_data (key ):
2730 return {key : key }
@@ -33,6 +36,9 @@ def _get_response(key):
3336def handle ():
3437 return _get_response (RETURN_VALUE )
3538
39+ def handle_custom_response (response_model = List [str ]):
40+ return CUSTOM_RESPONSE
41+
3642def handle_given_request (request : Request ):
3743 assert request .method == 'POST'
3844 loop = None
@@ -70,6 +76,7 @@ def handle_error():
7076def fastapi_app ():
7177 app = FastAPI ()
7278 app .add_api_route ("/" , handle , methods = ["GET" ])
79+ app .add_api_route (CUSTOM_RESPONSE_PATH , handle_custom_response , methods = ["GET" ])
7380 app .add_api_route (REQUEST_OBJ_PATH , handle_given_request , methods = ["POST" ])
7481 app .add_api_route ("/a" , handle_a , methods = ["GET" ])
7582 app .add_api_route ("/b" , handle_b , methods = ["GET" ])
@@ -100,6 +107,23 @@ async def test_fastapi_sanity(trace_transport, fastapi_app):
100107 assert not trace_factory .traces
101108
102109
110+ @pytest .mark .asyncio
111+ async def test_fastapi_custom_response (trace_transport , fastapi_app ):
112+ """Sanity test."""
113+ request_path = f'{ CUSTOM_RESPONSE_PATH } ?x=testval'
114+ async with AsyncClient (app = fastapi_app , base_url = "http://test" ) as ac :
115+ response = await ac .get (request_path )
116+ response_data = response .json ()
117+ runner = trace_transport .last_trace .events [0 ]
118+ assert isinstance (runner , FastapiRunner )
119+ assert runner .resource ['name' ].startswith ('127.0.0.1' )
120+ assert runner .resource ['metadata' ]['Path' ] == CUSTOM_RESPONSE_PATH
121+ assert runner .resource ['metadata' ]['Query Params' ] == { 'x' : 'testval' }
122+ assert response_data == CUSTOM_RESPONSE
123+ # validating no `zombie` traces exist
124+ assert not trace_factory .traces
125+
126+
103127@pytest .mark .asyncio
104128async def test_fastapi_given_request (trace_transport , fastapi_app ):
105129 """Sanity test."""
0 commit comments