Add variants for `dataclasses/tutorial002`

This commit is contained in:
Yurii Motov 2025-11-26 22:16:07 +01:00
parent b841e9f807
commit ee37c69379
4 changed files with 74 additions and 6 deletions

View File

@ -32,7 +32,7 @@ But if you have a bunch of dataclasses laying around, this is a nice trick to us
You can also use `dataclasses` in the `response_model` parameter:
{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *}
{* ../../docs_src/dataclasses/tutorial002_py310.py hl[1,6:12,18] *}
The dataclass will be automatically converted to a Pydantic dataclass.

View File

@ -0,0 +1,25 @@
from dataclasses import dataclass, field
from fastapi import FastAPI
@dataclass
class Item:
name: str
price: float
tags: list[str] = field(default_factory=list)
description: str | None = None
tax: float | None = None
app = FastAPI()
@app.get("/items/next", response_model=Item)
async def read_next_item():
return {
"name": "Island In The Moon",
"price": 12.99,
"description": "A place to be playin' and havin' fun",
"tags": ["breater"],
}

View File

@ -0,0 +1,26 @@
from dataclasses import dataclass, field
from typing import Union
from fastapi import FastAPI
@dataclass
class Item:
name: str
price: float
tags: list[str] = field(default_factory=list)
description: Union[str, None] = None
tax: Union[float, None] = None
app = FastAPI()
@app.get("/items/next", response_model=Item)
async def read_next_item():
return {
"name": "Island In The Moon",
"price": 12.99,
"description": "A place to be playin' and havin' fun",
"tags": ["breater"],
}

View File

@ -1,12 +1,29 @@
import importlib
import pytest
from dirty_equals import IsDict, IsOneOf
from fastapi.testclient import TestClient
from docs_src.dataclasses.tutorial002 import app
client = TestClient(app)
from tests.utils import needs_py39, needs_py310
def test_get_item():
@pytest.fixture(
name="client",
params=[
pytest.param("tutorial002"),
pytest.param("tutorial002_py39", marks=needs_py39),
pytest.param("tutorial002_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_get_item(client: TestClient):
response = client.get("/items/next")
assert response.status_code == 200
assert response.json() == {
@ -18,7 +35,7 @@ def test_get_item():
}
def test_openapi_schema():
def test_openapi_schema(client: TestClient):
response = client.get("/openapi.json")
assert response.status_code == 200
assert response.json() == {