| 1 |
from unittest.mock import patch |
| 2 |
|
| 3 |
from fastapi import FastAPI |
| 4 |
from fastapi.responses import JSONResponse |
| 5 |
from fastapi.testclient import TestClient |
| 6 |
from pydantic import BaseModel |
| 7 |
|
| 8 |
|
| 9 |
class Item(BaseModel): |
| 10 |
name: str |
| 11 |
price: float |
| 12 |
|
| 13 |
|
| 14 |
app = FastAPI() |
| 15 |
|
| 16 |
|
| 17 |
@app.get("/default") |
| 18 |
def get_default() -> Item: |
| 19 |
return Item(name="widget", price=9.99) |
| 20 |
|
| 21 |
|
| 22 |
@app.get("/explicit", response_class=JSONResponse) |
| 23 |
def get_explicit() -> Item: |
| 24 |
return Item(name="widget", price=9.99) |
| 25 |
|
| 26 |
|
| 27 |
client = TestClient(app) |
| 28 |
|
| 29 |
|
| 30 |
def test_default_response_class_skips_json_dumps(): |
| 31 |
"""When no response_class is set, the fast path serializes directly to |
| 32 |
JSON bytes via Pydantic's dump_json and never calls json.dumps.""" |
| 33 |
with patch( |
| 34 |
"starlette.responses.json.dumps", wraps=__import__("json").dumps |
| 35 |
) as mock_dumps: |
| 36 |
response = client.get("/default") |
| 37 |
assert response.status_code == 200 |
| 38 |
assert response.json() == {"name": "widget", "price": 9.99} |
| 39 |
mock_dumps.assert_not_called() |
| 40 |
|
| 41 |
|
| 42 |
def test_explicit_response_class_uses_json_dumps(): |
| 43 |
"""When response_class is explicitly set to JSONResponse, the normal path |
| 44 |
is used and json.dumps is called via JSONResponse.render().""" |
| 45 |
with patch( |
| 46 |
"starlette.responses.json.dumps", wraps=__import__("json").dumps |
| 47 |
) as mock_dumps: |
| 48 |
response = client.get("/explicit") |
| 49 |
assert response.status_code == 200 |
| 50 |
assert response.json() == {"name": "widget", "price": 9.99} |
| 51 |
mock_dumps.assert_called_once() |