Coverage for tests/test_custom_schema_fields.py: 100%
30 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-09-22 00:03 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-09-22 00:03 +0000
1from typing import Optional 1abcdef
3from fastapi import FastAPI 1abcdef
4from fastapi._compat import PYDANTIC_V2 1abcdef
5from fastapi.testclient import TestClient 1abcdef
6from pydantic import BaseModel 1abcdef
7from typing_extensions import Annotated 1abcdef
9if PYDANTIC_V2: 1abcdef
10 from pydantic import WithJsonSchema 1abcdef
12app = FastAPI() 1abcdef
15class Item(BaseModel): 1abcdef
16 name: str 1abcdef
18 if PYDANTIC_V2: 1abcdef
19 description: Annotated[ 1abcdef
20 Optional[str], WithJsonSchema({"type": ["string", "null"]})
21 ] = None
23 model_config = { 1abcdef
24 "json_schema_extra": {
25 "x-something-internal": {"level": 4},
26 }
27 }
28 else:
29 description: Optional[str] = None # type: ignore[no-redef] 1abcdef
31 class Config: 1abcdef
32 schema_extra = { 1abcdef
33 "x-something-internal": {"level": 4},
34 }
37@app.get("/foo", response_model=Item) 1abcdef
38def foo(): 1abcdef
39 return {"name": "Foo item"} 1ghijkl
42client = TestClient(app) 1abcdef
45item_schema = { 1abcdef
46 "title": "Item",
47 "required": ["name"],
48 "type": "object",
49 "x-something-internal": {
50 "level": 4,
51 },
52 "properties": {
53 "name": {
54 "title": "Name",
55 "type": "string",
56 },
57 "description": {
58 "title": "Description",
59 "type": ["string", "null"] if PYDANTIC_V2 else "string",
60 },
61 },
62}
65def test_custom_response_schema(): 1abcdef
66 response = client.get("/openapi.json") 1mnopqr
67 assert response.status_code == 200, response.text 1mnopqr
68 assert response.json()["components"]["schemas"]["Item"] == item_schema 1mnopqr
71def test_response(): 1abcdef
72 # For coverage
73 response = client.get("/foo") 1ghijkl
74 assert response.status_code == 200, response.text 1ghijkl
75 assert response.json() == {"name": "Foo item", "description": None} 1ghijkl