Add variants for `dataclasses/tutorial001`

This commit is contained in:
Yurii Motov 2025-11-26 22:03:56 +01:00
parent 42e30173d3
commit b841e9f807
3 changed files with 42 additions and 7 deletions

View File

@ -4,7 +4,7 @@ FastAPI is built on top of **Pydantic**, and I have been showing you how to use
But FastAPI also supports using <a href="https://docs.python.org/3/library/dataclasses.html" class="external-link" target="_blank">`dataclasses`</a> the same way:
{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *}
{* ../../docs_src/dataclasses/tutorial001_py310.py hl[1,6:11,18:19] *}
This is still supported thanks to **Pydantic**, as it has <a href="https://docs.pydantic.dev/latest/concepts/dataclasses/#use-of-stdlib-dataclasses-with-basemodel" class="external-link" target="_blank">internal support for `dataclasses`</a>.

View File

@ -0,0 +1,19 @@
from dataclasses import dataclass
from fastapi import FastAPI
@dataclass
class Item:
name: str
price: float
description: str | None = None
tax: float | None = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item

View File

@ -1,12 +1,28 @@
import importlib
import pytest
from dirty_equals import IsDict
from fastapi.testclient import TestClient
from docs_src.dataclasses.tutorial001 import app
client = TestClient(app)
from tests.utils import needs_py310
def test_post_item():
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial001"),
pytest.param("tutorial001_py310", marks=needs_py310),
],
)
def get_client(request: pytest.FixtureRequest):
mod = importlib.import_module(f"docs_src.dataclasses.{request.param}")
client = TestClient(mod.app)
client.headers.clear()
return client
def test_post_item(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": 3})
assert response.status_code == 200
assert response.json() == {
@ -17,7 +33,7 @@ def test_post_item():
}
def test_post_invalid_item():
def test_post_invalid_item(client: TestClient):
response = client.post("/items/", json={"name": "Foo", "price": "invalid price"})
assert response.status_code == 422
assert response.json() == IsDict(
@ -45,7 +61,7 @@ def test_post_invalid_item():
)
def test_openapi_schema():
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == {