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 ExtendedItem(Item):
20
def save_union_different_body(item: Union[ExtendedItem, Item]):
24
client = TestClient(app)
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}}
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 Different Body",
65
"operationId": "save_union_different_body_items__post",
72
{"$ref": "#/components/schemas/ExtendedItem"},
73
{"$ref": "#/components/schemas/Item"},
92
"anyOf": [{"type": "string"}, {"type": "null"}],
96
# TODO: remove when deprecating Pydantic v1
97
{"title": "Name", "type": "string"}
102
"title": "ExtendedItem",
109
"anyOf": [{"type": "string"}, {"type": "null"}],
113
# TODO: remove when deprecating Pydantic v1
114
{"title": "Name", "type": "string"}
116
"age": {"title": "Age", "type": "integer"},
120
"title": "ValidationError",
121
"required": ["loc", "msg", "type"],
128
"anyOf": [{"type": "string"}, {"type": "integer"}]
131
"msg": {"title": "Message", "type": "string"},
132
"type": {"title": "Error Type", "type": "string"},
135
"HTTPValidationError": {
136
"title": "HTTPValidationError",
142
"items": {"$ref": "#/components/schemas/ValidationError"},