読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
pytestを入れます。
pip install pytest
tests フォルダを作り、tests/test_rules.py に書きます。
from datetime import datetime
import pytest
from rules import JST, RuleError, check_reservation
PRODUCTS = {
"p001": {"name": "食パン(1斤)", "price": 380, "reservable": True},
"p002": {"name": "クロワッサン", "price": 220, "reservable": True},
"p006": {"name": "季節のタルト", "price": 460, "reservable": False},
}
PICKUP = datetime(2026, 11, 2, 8, 0, tzinfo=JST)
ITEMS = [{"product_id": "p001", "quantity": 1}, {"product_id": "p002", "quantity": 2}]
def test_accepts_at_1959():
check_reservation(PICKUP, ITEMS, PRODUCTS, datetime(2026, 11, 1, 19, 59, tzinfo=JST))
def test_rejects_at_2000():
with pytest.raises(RuleError) as error:
check_reservation(PICKUP, ITEMS, PRODUCTS, datetime(2026, 11, 1, 20, 0, tzinfo=JST))
assert error.value.code == "deadline_passed"
| 書き方 | 意味 |
|---|---|
test_ で始まる関数 | pytestが、テストとして実行する |
assert 式 | 式が真でなければ、テストを失敗にする |
with pytest.raises(RuleError) as error: | 中で RuleError が起きることを確かめる。起きなければ失敗 |
test_accepts_at_1959 には assert がありません。check_reservation が例外を起こさずに終われば、テストは成功です。
tests/conftest.py には、tests フォルダの外の rules.py などを読み込めるようにする設定を書きます(教材のファイルに入っています)。
6 / 20