L10 ch01 — pytest
テクノロジ系 / L10 test — テスト
L10 ch01 — pytest
Python 標準のテストフレームワーク
ゴール
- pytest でテスト関数を書く
- assert で期待値検証
- fixture で初期化を共通化
インストール
uv add --dev pytest
最小テスト
# tests/test_calc.py
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, 1) == 0uv run pytest # 2 passed in 0.05s
ルール
- ファイル名: **
test_*.py** または*_test.py - 関数名: **
test_*** で始まる - アサーション:
assertキーワード (フレームワーク独自構文不要)
fixture で共通初期化
import pytest
@pytest.fixture
def sample_tasks():
return [
{"id": 1, "title": "a"},
{"id": 2, "title": "b"},
]
def test_count(sample_tasks):
assert len(sample_tasks) == 2
def test_first(sample_tasks):
assert sample_tasks[0]["title"] == "a"parametrize で複数ケース
@pytest.mark.parametrize("a,b,expected", [
(2, 3, 5),
(0, 0, 0),
(-1, 1, 0),
])
def test_add(a, b, expected):
assert add(a, b) == expected→ 1 関数で 3 ケース検証
FastAPI TestClient
from fastapi.testclient import TestClient
from main import app
def test_root():
with TestClient(app) as client:
res = client.get("/")
assert res.status_code == 200drill
drill/ — add 関数のテストを書く
力試ししたい方は クイズ形式の演習(任意) もあります。読むだけでも十分です。