fastapi

Форк
0
/
test_union_inherited_body.py 
148 строк · 5.2 Кб
1
from typing import Optional, Union
2

3
from dirty_equals import IsDict
4
from fastapi import FastAPI
5
from fastapi.testclient import TestClient
6
from pydantic import BaseModel
7

8
app = FastAPI()
9

10

11
class Item(BaseModel):
12
    name: Optional[str] = None
13

14

15
class ExtendedItem(Item):
16
    age: int
17

18

19
@app.post("/items/")
20
def save_union_different_body(item: Union[ExtendedItem, Item]):
21
    return {"item": item}
22

23

24
client = TestClient(app)
25

26

27
def test_post_extended_item():
28
    response = client.post("/items/", json={"name": "Foo", "age": 5})
29
    assert response.status_code == 200, response.text
30
    assert response.json() == {"item": {"name": "Foo", "age": 5}}
31

32

33
def test_post_item():
34
    response = client.post("/items/", json={"name": "Foo"})
35
    assert response.status_code == 200, response.text
36
    assert response.json() == {"item": {"name": "Foo"}}
37

38

39
def test_openapi_schema():
40
    response = client.get("/openapi.json")
41
    assert response.status_code == 200, response.text
42
    assert response.json() == {
43
        "openapi": "3.1.0",
44
        "info": {"title": "FastAPI", "version": "0.1.0"},
45
        "paths": {
46
            "/items/": {
47
                "post": {
48
                    "responses": {
49
                        "200": {
50
                            "description": "Successful Response",
51
                            "content": {"application/json": {"schema": {}}},
52
                        },
53
                        "422": {
54
                            "description": "Validation Error",
55
                            "content": {
56
                                "application/json": {
57
                                    "schema": {
58
                                        "$ref": "#/components/schemas/HTTPValidationError"
59
                                    }
60
                                }
61
                            },
62
                        },
63
                    },
64
                    "summary": "Save Union Different Body",
65
                    "operationId": "save_union_different_body_items__post",
66
                    "requestBody": {
67
                        "content": {
68
                            "application/json": {
69
                                "schema": {
70
                                    "title": "Item",
71
                                    "anyOf": [
72
                                        {"$ref": "#/components/schemas/ExtendedItem"},
73
                                        {"$ref": "#/components/schemas/Item"},
74
                                    ],
75
                                }
76
                            }
77
                        },
78
                        "required": True,
79
                    },
80
                }
81
            }
82
        },
83
        "components": {
84
            "schemas": {
85
                "Item": {
86
                    "title": "Item",
87
                    "type": "object",
88
                    "properties": {
89
                        "name": IsDict(
90
                            {
91
                                "title": "Name",
92
                                "anyOf": [{"type": "string"}, {"type": "null"}],
93
                            }
94
                        )
95
                        | IsDict(
96
                            # TODO: remove when deprecating Pydantic v1
97
                            {"title": "Name", "type": "string"}
98
                        )
99
                    },
100
                },
101
                "ExtendedItem": {
102
                    "title": "ExtendedItem",
103
                    "required": ["age"],
104
                    "type": "object",
105
                    "properties": {
106
                        "name": IsDict(
107
                            {
108
                                "title": "Name",
109
                                "anyOf": [{"type": "string"}, {"type": "null"}],
110
                            }
111
                        )
112
                        | IsDict(
113
                            # TODO: remove when deprecating Pydantic v1
114
                            {"title": "Name", "type": "string"}
115
                        ),
116
                        "age": {"title": "Age", "type": "integer"},
117
                    },
118
                },
119
                "ValidationError": {
120
                    "title": "ValidationError",
121
                    "required": ["loc", "msg", "type"],
122
                    "type": "object",
123
                    "properties": {
124
                        "loc": {
125
                            "title": "Location",
126
                            "type": "array",
127
                            "items": {
128
                                "anyOf": [{"type": "string"}, {"type": "integer"}]
129
                            },
130
                        },
131
                        "msg": {"title": "Message", "type": "string"},
132
                        "type": {"title": "Error Type", "type": "string"},
133
                    },
134
                },
135
                "HTTPValidationError": {
136
                    "title": "HTTPValidationError",
137
                    "type": "object",
138
                    "properties": {
139
                        "detail": {
140
                            "title": "Detail",
141
                            "type": "array",
142
                            "items": {"$ref": "#/components/schemas/ValidationError"},
143
                        }
144
                    },
145
                },
146
            }
147
        },
148
    }
149

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.