Coverage for tests/test_custom_schema_fields.py: 100%
30 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
1from typing import Optional 1abcdefg
3from fastapi import FastAPI 1abcdefg
4from fastapi._compat import PYDANTIC_V2 1abcdefg
5from fastapi.testclient import TestClient 1abcdefg
6from pydantic import BaseModel 1abcdefg
7from typing_extensions import Annotated 1abcdefg
9if PYDANTIC_V2: 1abcdefg
10 from pydantic import WithJsonSchema 1abcdefg
12app = FastAPI() 1abcdefg
15class Item(BaseModel): 1abcdefg
16 name: str 1abcdefg
18 if PYDANTIC_V2: 1abcdefg
19 description: Annotated[ 1abcdefg
20 Optional[str], WithJsonSchema({"type": ["string", "null"]})
21 ] = None
23 model_config = { 1abcdefg
24 "json_schema_extra": {
25 "x-something-internal": {"level": 4},
26 }
27 }
28 else:
29 description: Optional[str] = None # type: ignore[no-redef] 1abcdefg
31 class Config: 1abcdef
32 schema_extra = { 1abcdef
33 "x-something-internal": {"level": 4},
34 }
37@app.get("/foo", response_model=Item) 1abcdefg
38def foo(): 1abcdefg
39 return {"name": "Foo item"} 1hijklmn
42client = TestClient(app) 1abcdefg
45item_schema = { 1abcdefg
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(): 1abcdefg
66 response = client.get("/openapi.json") 1opqrstu
67 assert response.status_code == 200, response.text 1opqrstu
68 assert response.json()["components"]["schemas"]["Item"] == item_schema 1opqrstu
71def test_response(): 1abcdefg
72 # For coverage
73 response = client.get("/foo") 1hijklmn
74 assert response.status_code == 200, response.text 1hijklmn
75 assert response.json() == {"name": "Foo item", "description": None} 1hijklmn