示例工程 35-asgi-fastapi
35-asgi-fastapi/02-fastapi-crud/test_fastapi_crud.py
"""test_fastapi_crud.py"""
from __future__ import annotations
import pytest
pytest.importorskip("fastapi")
from fastapi.testclient import TestClient
from fastapi_crud import create_app, main
def test_crud() -> None:
client = TestClient(create_app())
created = client.post("/items", json={"name": "apple", "qty": 3})
assert created.status_code == 201
assert created.json() == {"name": "apple", "qty": 3, "id": 1}
fetched = client.get("/items/1")
assert fetched.status_code == 200
assert fetched.json()["name"] == "apple"
listed = client.get("/items")
assert listed.status_code == 200
assert len(listed.json()) == 1
missing = client.get("/items/99")
assert missing.status_code == 404
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
main()
out = capsys.readouterr().out
assert "create: 201" in out
assert "missing: 404" in out