コンテンツにスキップ

アプリをテストする

このページでは、アプリを拡張するで作成した layered レベルの shop プロジェクトのテストを実行し、その作りを読み、自分でもテストを 1 つ書きます。FastAPI の TestClient がサーバーなしでアプリケーションを呼び出す仕組み、pytest のフィクスチャが各テストの準備をする仕組み、app.dependency_overrides で依存関係をテスト用のものに差し替える方法、そして検証とエラーレスポンスを確認する方法を学びます。また、fastkit にどのようなテストが含まれているのか、Coverage のテストオプションでそれらのカバレッジをどう計測するのかも紹介します。

テストを実行する

fastkit のどのレベルにもテストが含まれており、fastkit addroute も追加するリソースごとにテストを書きます。shop で、pytest を使ってテストを実行します。

$ uv run pytest -q
...
tests/test_config.py ......................................              [ 41%]
tests/test_item_store.py .....                                           [ 47%]
tests/test_items.py .........................                            [ 74%]
tests/test_main.py ......                                                [ 81%]
tests/test_users.py .................                                    [100%]

============================= 91 passed in 10.42s ==============================

pytest は tests/ の下にあるすべての test_*.py ファイルを集め、名前が test_ で始まる関数をそれぞれ実行します。ドット 1 つが、成功したテスト 1 つを表します。test_config.py は設定のルール(たとえば開発環境以外での SECRET_KEY のチェック)を、test_item_store.py はファイルベースのアイテムストアを、test_items.py と test_main.py は HTTP エンドポイントを確認します。test_users.py は fastkit addroute users が書いたファイルです。

テストクライアントの作り

TestClient は、uvicorn を起動せずに、リクエストをアプリケーションオブジェクトに直接送ります。client.get(...) や client.post(..., json=...) を呼び出すと、status_code、headers、json() を持つレスポンスが返ります。pytest のフィクスチャは、@pytest.fixture を付けた関数です。フィクスチャの名前を引数に書いたテストは、そのフィクスチャの値を受け取ります。フィクスチャが yield を使っている場合、yield の後のコードはテストが終わってから実行されます。tests/conftest.py には、すべてのテストファイルで共有するフィクスチャが入っています。

tests/conftest.py
@pytest.fixture
def store(tmp_path: Path) -> ItemStore:
    """Item store on a temporary file, so tests never touch src/mocks."""
    path = tmp_path / "items.json"
    path.write_text(json.dumps(SEED_ITEMS), encoding="utf-8")
    return ItemStore(path)


@pytest.fixture
def client(store: ItemStore) -> Generator[TestClient, None, None]:
    app.dependency_overrides[get_item_store] = lambda: store
    # TestClient sends requests straight to the app, without starting a server.
    # https://fastapi.tiangolo.com/tutorial/testing/
    with TestClient(app) as c:
        yield c
    app.dependency_overrides.clear()

エンドポイントは、依存関係 get_item_store からアイテムストアを受け取ります(アプリを拡張するを参照)。app.dependency_overrides はアプリケーションが持つ辞書で、キーは依存関係の関数、値は FastAPI がその代わりに呼び出す関数です。ここでは、テスト中のすべてのリクエストが、初期データとして 2 つのアイテムを入れ、一時ファイルにデータを保存するストアを受け取ります。そのため、テストが src/mocks/mock_items.json を変更することはありません。tmp_path は pytest に組み込まれたフィクスチャで、テストごとに新しい一時ディレクトリを用意します。テストの後、clear() がオーバーライドを解除します。この手法は、FastAPI のガイド Testing dependencies with overrides で説明されています。

テストを 1 つ読む

テストは 1 つのリクエストを送り、レスポンスを assert で確認します。tests/test_items.py にある次のテストは、存在しない ID に対して 404 が返ることを確認します。

tests/test_items.py
def test_get_item_not_found(client: TestClient) -> None:
    response = client.get(f"{ITEMS_URL}/999")

    assert response.status_code == 404
    assert response.json() == {"detail": "Item not found"}

ITEMS_URL は /api/v1/items で、conftest.py の中で設定から組み立てられています。ほかのテストも同じパターンに従います。test_create_item_returns_201_and_location は、ステータスが 201 であることと、Location ヘッダーが新しいアイテムを指していることを確認します。test_create_item_validates_input は不正なボディ(空の名前、負の価格、価格なし)を送り、422 が返ることを期待します。ボディが ItemCreate モデルに合わないため、FastAPI はエンドポイントを実行する前に 422 を返します。

テストを書く

fastkit addroute が追加した users リソースは、レコードをメモリ上の UserRepository に保持します。エンドポイントはこのリポジトリを依存関係 get_user_repository から受け取ります(src/crud/users.py にあり、src/api/deps.py がこれを UserRepositoryDep として包んでいます)。tests/test_users_override.py を作成してください。このファイルのフィクスチャは、すでにユーザーが 1 人入っているリポジトリをエンドポイントに渡します。

tests/test_users_override.py
from collections.abc import Iterator

import pytest
from fastapi.testclient import TestClient

from src.crud.users import UserRepository, get_user_repository
from src.main import app

USERS_URL = app.url_path_for("list_users")


@pytest.fixture
def client() -> Iterator[TestClient]:
    repository = UserRepository()
    repository.add({"name": "Ada"})
    app.dependency_overrides[get_user_repository] = lambda: repository
    with TestClient(app) as c:
        yield c
    app.dependency_overrides.clear()


def test_lists_the_users_of_the_test_repository(client: TestClient) -> None:
    response = client.get(USERS_URL)

    assert response.status_code == 200
    assert response.json()["items"] == [{"id": 1, "name": "Ada", "description": None}]


def test_rejects_an_empty_name(client: TestClient) -> None:
    response = client.post(USERS_URL, json={"name": ""})

    assert response.status_code == 422
    assert response.json()["detail"][0]["loc"] == ["body", "name"]

app.url_path_for("list_users") はエンドポイント関数 list_users のパスを調べるので、プレフィックスが変わってもテストはそのまま動きます。2 つ目のテストは 422 レスポンスのボディを読みます。detail はエラーのリストで、loc は不正な値の場所(リクエストボディの name フィールド)を示します。もう一度テストを実行すると、新しい 2 つのテストが加わって合計 93 個になります。

$ uv run pytest -q
...
============================== 93 passed in 0.90s ==============================

カバレッジを計測する

カバレッジは、テストがコードのどの行を実行したかを示します。hello より後のすべてのレベルには pytest-cov が含まれており、何を計測するかは pyproject.toml で設定されています([tool.coverage.run]、source = ["src"])。shop で次のように実行します。

$ uv run pytest --cov
...
Name                         Stmts   Miss  Cover   Missing
----------------------------------------------------------
...
src/api/deps.py                  8      1    88%   14
...
src/main.py                     11      1    91%   24
...
----------------------------------------------------------
TOTAL                          350      4    99%
============================== 93 passed in 1.25s ==============================

Miss はどのテストも実行しなかった行の数で、Missing はその行番号です。src/api/deps.py の 14 行目は get_item_store の本体で、テストでは常にオーバーライドで置き換えられています。

FastAPI のドキュメント

次へ

ドメイン構成とデータベースへ移行するでは、shop を domain レベルに移します。このレベルでは、アイテムは SQL データベースに保存されます。