File: test_custom_schema_fields.py

package info (click to toggle)
fastapi 0.118.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 34,212 kB
  • sloc: python: 69,848; javascript: 369; sh: 18; makefile: 17
file content (75 lines) | stat: -rw-r--r-- 1,725 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from typing import Optional

from fastapi import FastAPI
from fastapi._compat import PYDANTIC_V2
from fastapi.testclient import TestClient
from pydantic import BaseModel
from typing_extensions import Annotated

if PYDANTIC_V2:
    from pydantic import WithJsonSchema

app = FastAPI()


class Item(BaseModel):
    name: str

    if PYDANTIC_V2:
        description: Annotated[
            Optional[str], WithJsonSchema({"type": ["string", "null"]})
        ] = None

        model_config = {
            "json_schema_extra": {
                "x-something-internal": {"level": 4},
            }
        }
    else:
        description: Optional[str] = None  # type: ignore[no-redef]

        class Config:
            schema_extra = {
                "x-something-internal": {"level": 4},
            }


@app.get("/foo", response_model=Item)
def foo():
    return {"name": "Foo item"}


client = TestClient(app)


item_schema = {
    "title": "Item",
    "required": ["name"],
    "type": "object",
    "x-something-internal": {
        "level": 4,
    },
    "properties": {
        "name": {
            "title": "Name",
            "type": "string",
        },
        "description": {
            "title": "Description",
            "type": ["string", "null"] if PYDANTIC_V2 else "string",
        },
    },
}


def test_custom_response_schema():
    response = client.get("/openapi.json")
    assert response.status_code == 200, response.text
    assert response.json()["components"]["schemas"]["Item"] == item_schema


def test_response():
    # For coverage
    response = client.get("/foo")
    assert response.status_code == 200, response.text
    assert response.json() == {"name": "Foo item", "description": None}