Debian Codegraph @

tests/test_deprecated_responses.py

raw
1 import warnings
2
3 import pytest
4 from fastapi import FastAPI
5 from fastapi.exceptions import FastAPIDeprecationWarning
6 from fastapi.responses import ORJSONResponse, UJSONResponse # ty: ignore[deprecated]
7 from fastapi.testclient import TestClient
8 from pydantic import BaseModel
9
10 from tests.utils import needs_orjson, needs_ujson
11
12
13 class Item(BaseModel):
14 name: str
15 price: float
16
17
18 # ORJSON
19
20
21 def _make_orjson_app() -> FastAPI:
22 with warnings.catch_warnings():
23 warnings.simplefilter("ignore", FastAPIDeprecationWarning)
24 app = FastAPI(default_response_class=ORJSONResponse) # ty: ignore[deprecated]
25
26 @app.get("/items")
27 def get_items() -> Item:
28 return Item(name="widget", price=9.99)
29
30 return app
31
32
33 @needs_orjson
34 def test_orjson_response_returns_correct_data():
35 app = _make_orjson_app()
36 client = TestClient(app)
37 with warnings.catch_warnings():
38 warnings.simplefilter("ignore", FastAPIDeprecationWarning)
39 response = client.get("/items")
40 assert response.status_code == 200
41 assert response.json() == {"name": "widget", "price": 9.99}
42
43
44 @needs_orjson
45 def test_orjson_response_emits_deprecation_warning():
46 with pytest.warns(FastAPIDeprecationWarning, match="ORJSONResponse is deprecated"):
47 ORJSONResponse(content={"hello": "world"}) # ty: ignore[deprecated]
48
49
50 # UJSON
51
52
53 def _make_ujson_app() -> FastAPI:
54 with warnings.catch_warnings():
55 warnings.simplefilter("ignore", FastAPIDeprecationWarning)
56 app = FastAPI(default_response_class=UJSONResponse) # ty: ignore[deprecated]
57
58 @app.get("/items")
59 def get_items() -> Item:
60 return Item(name="widget", price=9.99)
61
62 return app
63
64
65 @needs_ujson
66 def test_ujson_response_returns_correct_data():
67 app = _make_ujson_app()
68 client = TestClient(app)
69 with warnings.catch_warnings():
70 warnings.simplefilter("ignore", FastAPIDeprecationWarning)
71 response = client.get("/items")
72 assert response.status_code == 200
73 assert response.json() == {"name": "widget", "price": 9.99}
74
75
76 @needs_ujson
77 def test_ujson_response_emits_deprecation_warning():
78 with pytest.warns(FastAPIDeprecationWarning, match="UJSONResponse is deprecated"):
79 UJSONResponse(content={"hello": "world"}) # ty: ignore[deprecated]