Coverage for tests/test_skip_defaults.py: 100%
50 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
1from typing import Optional 1abcde
3from fastapi import FastAPI 1abcde
4from fastapi.testclient import TestClient 1abcde
5from pydantic import BaseModel 1abcde
7app = FastAPI() 1abcde
10class SubModel(BaseModel): 1abcde
11 a: Optional[str] = "foo" 1abcde
14class Model(BaseModel): 1abcde
15 x: Optional[int] = None 1abcde
16 sub: SubModel 1abcde
19class ModelSubclass(Model): 1abcde
20 y: int 1abcde
21 z: int = 0 1abcde
22 w: Optional[int] = None 1abcde
25class ModelDefaults(BaseModel): 1abcde
26 w: Optional[str] = None 1abcde
27 x: Optional[str] = None 1abcde
28 y: str = "y" 1abcde
29 z: str = "z" 1abcde
32@app.get("/", response_model=Model, response_model_exclude_unset=True) 1abcde
33def get_root() -> ModelSubclass: 1abcde
34 return ModelSubclass(sub={}, y=1, z=0) 1abcde
37@app.get( 1abcde
38 "/exclude_unset", response_model=ModelDefaults, response_model_exclude_unset=True
39)
40def get_exclude_unset() -> ModelDefaults: 1abcde
41 return ModelDefaults(x=None, y="y") 1abcde
44@app.get( 1abcde
45 "/exclude_defaults",
46 response_model=ModelDefaults,
47 response_model_exclude_defaults=True,
48)
49def get_exclude_defaults() -> ModelDefaults: 1abcde
50 return ModelDefaults(x=None, y="y") 1abcde
53@app.get( 1abcde
54 "/exclude_none", response_model=ModelDefaults, response_model_exclude_none=True
55)
56def get_exclude_none() -> ModelDefaults: 1abcde
57 return ModelDefaults(x=None, y="y") 1abcde
60@app.get( 1abcde
61 "/exclude_unset_none",
62 response_model=ModelDefaults,
63 response_model_exclude_unset=True,
64 response_model_exclude_none=True,
65)
66def get_exclude_unset_none() -> ModelDefaults: 1abcde
67 return ModelDefaults(x=None, y="y") 1abcde
70client = TestClient(app) 1abcde
73def test_return_defaults(): 1abcde
74 response = client.get("/") 1abcde
75 assert response.json() == {"sub": {}} 1abcde
78def test_return_exclude_unset(): 1abcde
79 response = client.get("/exclude_unset") 1abcde
80 assert response.json() == {"x": None, "y": "y"} 1abcde
83def test_return_exclude_defaults(): 1abcde
84 response = client.get("/exclude_defaults") 1abcde
85 assert response.json() == {} 1abcde
88def test_return_exclude_none(): 1abcde
89 response = client.get("/exclude_none") 1abcde
90 assert response.json() == {"y": "y", "z": "z"} 1abcde
93def test_return_exclude_unset_none(): 1abcde
94 response = client.get("/exclude_unset_none") 1abcde
95 assert response.json() == {"y": "y"} 1abcde