Debian Codegraph @

tests/test_custom_schema_fields.py

raw
1 from typing import Annotated
2
3 from fastapi import FastAPI
4 from fastapi.testclient import TestClient
5 from pydantic import BaseModel, WithJsonSchema
6
7 app = FastAPI()
8
9
10 class Item(BaseModel):
11 name: str
12
13 description: Annotated[str | None, WithJsonSchema({"type": ["string", "null"]})] = (
14 None
15 )
16
17 model_config = {
18 "json_schema_extra": {
19 "x-something-internal": {"level": 4},
20 }
21 }
22
23
24 @app.get("/foo", response_model=Item)
25 def foo():
26 return {"name": "Foo item"}
27
28
29 client = TestClient(app)
30
31
32 item_schema = {
33 "title": "Item",
34 "required": ["name"],
35 "type": "object",
36 "x-something-internal": {
37 "level": 4,
38 },
39 "properties": {
40 "name": {
41 "title": "Name",
42 "type": "string",
43 },
44 "description": {
45 "title": "Description",
46 "type": ["string", "null"],
47 },
48 },
49 }
50
51
52 def test_custom_response_schema():
53 response = client.get("/openapi.json")
54 assert response.status_code == 200, response.text
55 assert response.json()["components"]["schemas"]["Item"] == item_schema
56
57
58 def test_response():
59 # For coverage
60 response = client.get("/foo")
61 assert response.status_code == 200, response.text
62 assert response.json() == {"name": "Foo item", "description": None}