fastapi

Форк
0
/
test_union_body.py 
136 строк · 4.6 Кб
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 OtherItem(BaseModel):
16
    price: int
17

18

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

23

24
client = TestClient(app)
25

26

27
def test_post_other_item():
28
    response = client.post("/items/", json={"price": 100})
29
    assert response.status_code == 200, response.text
30
    assert response.json() == {"item": {"price": 100}}
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 Body",
65
                    "operationId": "save_union_body_items__post",
66
                    "requestBody": {
67
                        "content": {
68
                            "application/json": {
69
                                "schema": {
70
                                    "title": "Item",
71
                                    "anyOf": [
72
                                        {"$ref": "#/components/schemas/OtherItem"},
73
                                        {"$ref": "#/components/schemas/Item"},
74
                                    ],
75
                                }
76
                            }
77
                        },
78
                        "required": True,
79
                    },
80
                }
81
            }
82
        },
83
        "components": {
84
            "schemas": {
85
                "OtherItem": {
86
                    "title": "OtherItem",
87
                    "required": ["price"],
88
                    "type": "object",
89
                    "properties": {"price": {"title": "Price", "type": "integer"}},
90
                },
91
                "Item": {
92
                    "title": "Item",
93
                    "type": "object",
94
                    "properties": IsDict(
95
                        {
96
                            "name": {
97
                                "title": "Name",
98
                                "anyOf": [{"type": "string"}, {"type": "null"}],
99
                            }
100
                        }
101
                    )
102
                    | IsDict(
103
                        # TODO: remove when deprecating Pydantic v1
104
                        {"name": {"title": "Name", "type": "string"}}
105
                    ),
106
                },
107
                "ValidationError": {
108
                    "title": "ValidationError",
109
                    "required": ["loc", "msg", "type"],
110
                    "type": "object",
111
                    "properties": {
112
                        "loc": {
113
                            "title": "Location",
114
                            "type": "array",
115
                            "items": {
116
                                "anyOf": [{"type": "string"}, {"type": "integer"}]
117
                            },
118
                        },
119
                        "msg": {"title": "Message", "type": "string"},
120
                        "type": {"title": "Error Type", "type": "string"},
121
                    },
122
                },
123
                "HTTPValidationError": {
124
                    "title": "HTTPValidationError",
125
                    "type": "object",
126
                    "properties": {
127
                        "detail": {
128
                            "title": "Detail",
129
                            "type": "array",
130
                            "items": {"$ref": "#/components/schemas/ValidationError"},
131
                        }
132
                    },
133
                },
134
            }
135
        },
136
    }
137

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

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

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

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