Browse Source

Add variants for `dataclasses/tutorial002`

pull/14413/head
Yurii Motov 8 months ago
parent
commit
ee37c69379
  1. 2
      docs/en/docs/advanced/dataclasses.md
  2. 25
      docs_src/dataclasses/tutorial002_py310.py
  3. 26
      docs_src/dataclasses/tutorial002_py39.py
  4. 25
      tests/test_tutorial/test_dataclasses/test_tutorial002.py

2
docs/en/docs/advanced/dataclasses.md

@ -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.

25
docs_src/dataclasses/tutorial002_py310.py

@ -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"],
}

26
docs_src/dataclasses/tutorial002_py39.py

@ -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"],
}

25
tests/test_tutorial/test_dataclasses/test_tutorial002.py

@ -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
from tests.utils import needs_py39, needs_py310
@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(app)
client = TestClient(mod.app)
client.headers.clear()
return client
def test_get_item():
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() == {

Loading…
Cancel
Save