Browse Source

Add test for schema, run tests on pydantic 1

pull/12942/head
Patrick Arminio 10 months ago
parent
commit
891ac6e21c
Failed to extract signature
  1. 82
      tests/test_union_body_discriminator.py

82
tests/test_union_body_discriminator.py

@ -1,57 +1,75 @@
from typing import Any, Dict, Union
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inline_snapshot import snapshot
from pydantic import BaseModel, Discriminator, Tag
from typing_extensions import Annotated
from .utils import needs_pydanticv2
app = FastAPI()
@pytest.fixture(name="client")
def get_client() -> TestClient:
from pydantic import BaseModel, Discriminator, Tag
class FirstItem(BaseModel):
value: str
price: int
app = FastAPI()
class FirstItem(BaseModel):
value: str
price: int
class OtherItem(BaseModel):
value: str
price: float
class OtherItem(BaseModel):
value: str
price: float
def get_discriminator_value(v: Any) -> str:
return v.get("value")
def get_discriminator_value(v: Any) -> str:
return v.get("value")
Item = Annotated[
Union[
Annotated[FirstItem, Tag("first")],
Annotated[OtherItem, Tag("other")],
],
Discriminator(get_discriminator_value),
]
@app.post("/items/")
def save_union_body_discriminator(
item: Item, q: Annotated[str, Tag("query")]
) -> Dict[str, Any]:
return {"item": item}
Item = Annotated[
Union[
Annotated[FirstItem, Tag("first")],
Annotated[OtherItem, Tag("other")],
],
Discriminator(get_discriminator_value),
]
client = TestClient(app)
return client
@app.post("/items/")
def save_union_body_discriminator(
item: Item, q: Annotated[str, Tag("query")]
) -> Dict[str, Any]:
return {"item": item}
@needs_pydanticv2
def test_post_item(client: TestClient) -> None:
client = TestClient(app)
def test_openapi_schema() -> None:
openapi = app.openapi()
assert openapi["paths"]["/items/"]["post"]["requestBody"] == snapshot(
{
"required": True,
"content": {
"application/json": {
"schema": {
"oneOf": [
{"$ref": "#/components/schemas/FirstItem"},
{"$ref": "#/components/schemas/OtherItem"},
],
"title": "Item",
}
}
},
}
)
def test_post_item() -> None:
response = client.post("/items/?q=first", json={"value": "first", "price": 100})
assert response.status_code == 200, response.text
assert response.json() == {"item": {"value": "first", "price": 100}}
@needs_pydanticv2
def test_post_other_item(client: TestClient) -> None:
def test_post_other_item() -> None:
response = client.post("/items/?q=other", json={"value": "other", "price": 100.5})
assert response.status_code == 200, response.text
assert response.json() == {"item": {"value": "other", "price": 100.5}}

Loading…
Cancel
Save