Skip to content

Commit eef946a

Browse files
committed
Python: FastAPI: Add test for custom response annotation
It really is rather contrived, but it also _does_ work.
1 parent c9895b5 commit eef946a

1 file changed

Lines changed: 19 additions & 5 deletions

File tree

python/ql/test/library-tests/frameworks/fastapi/response_test.py

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# see https://fastapi.tiangolo.com/advanced/response-cookies/
22

33
from fastapi import FastAPI, Response
4+
import fastapi.responses
45
import asyncio
56

67
app = FastAPI()
@@ -31,12 +32,29 @@ async def response_parameter_no_type(response): # $ requestHandler routedParamet
3132
return {"message": "response as parameter"} # $ HttpResponse mimetype=application/json responseBody=Dict
3233

3334

35+
class MyXmlResponse(fastapi.responses.Response):
36+
media_type = "application/xml"
37+
38+
39+
@app.get("/response_parameter_custom_type", response_class=MyXmlResponse) # $ routeSetup="/response_parameter_custom_type"
40+
async def response_parameter_custom_type(response: MyXmlResponse): # $ requestHandler SPURIOUS: routedParameter=response
41+
# NOTE: This is a contrived example of using a wrong annotation for the response
42+
# parameter. It will be passed a `fastapi.responses.Response` value when handling an
43+
# incoming request, so NOT a `MyXmlResponse` value. Cookies/Headers are still
44+
# propagated to the final response though.
45+
print(type(response))
46+
assert type(response) == fastapi.responses.Response
47+
response.set_cookie("key", "value") # $ MISSING: CookieWrite CookieName="key" CookieValue="value"
48+
response.headers["Custom-Response-Type"] = "yes, but only after function has run"
49+
xml_data = "<foo>FOO</foo>"
50+
return xml_data # $ HttpResponse responseBody=xml_data SPURIOUS: mimetype=application/json MISSING: mimetype=application/xml
51+
52+
3453
# Direct response construction
3554

3655
# see https://fastapi.tiangolo.com/advanced/response-directly/
3756
# see https://fastapi.tiangolo.com/advanced/custom-response/
3857

39-
import fastapi.responses
4058

4159

4260
@app.get("/direct_response") # $ routeSetup="/direct_response"
@@ -53,10 +71,6 @@ async def direct_response2(): # $ requestHandler
5371
return xml_data # $ HttpResponse responseBody=xml_data SPURIOUS: mimetype=application/json
5472

5573

56-
class MyXmlResponse(fastapi.responses.Response):
57-
media_type = "application/xml"
58-
59-
6074
@app.get("/my_xml_response") # $ routeSetup="/my_xml_response"
6175
async def my_xml_response(): # $ requestHandler
6276
xml_data = "<foo>FOO</foo>"

0 commit comments

Comments
 (0)