1
from typing import Optional, Union
3
from dirty_equals import IsDict
4
from fastapi import FastAPI
5
from fastapi.testclient import TestClient
6
from pydantic import BaseModel
12
name: Optional[str] = None
15
class OtherItem(BaseModel):
20
def save_union_body(item: Union[OtherItem, Item]):
24
client = TestClient(app)
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}}
34
response = client.post("/items/", json={"name": "Foo"})
35
assert response.status_code == 200, response.text
36
assert response.json() == {"item": {"name": "Foo"}}
39
def test_openapi_schema():
40
response = client.get("/openapi.json")
41
assert response.status_code == 200, response.text
42
assert response.json() == {
44
"info": {"title": "FastAPI", "version": "0.1.0"},
50
"description": "Successful Response",
51
"content": {"application/json": {"schema": {}}},
54
"description": "Validation Error",
58
"$ref": "#/components/schemas/HTTPValidationError"
64
"summary": "Save Union Body",
65
"operationId": "save_union_body_items__post",
72
{"$ref": "#/components/schemas/OtherItem"},
73
{"$ref": "#/components/schemas/Item"},
87
"required": ["price"],
89
"properties": {"price": {"title": "Price", "type": "integer"}},
98
"anyOf": [{"type": "string"}, {"type": "null"}],
103
# TODO: remove when deprecating Pydantic v1
104
{"name": {"title": "Name", "type": "string"}}
108
"title": "ValidationError",
109
"required": ["loc", "msg", "type"],
116
"anyOf": [{"type": "string"}, {"type": "integer"}]
119
"msg": {"title": "Message", "type": "string"},
120
"type": {"title": "Error Type", "type": "string"},
123
"HTTPValidationError": {
124
"title": "HTTPValidationError",
130
"items": {"$ref": "#/components/schemas/ValidationError"},