読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
check_permissions.py を作ります。
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def token(username: str) -> dict:
response = client.post("/auth/token", data={"username": username, "password": f"{username}-renshu"})
return {"Authorization": f"Bearer {response.json()['access_token']}"}
tanaka = token("tanaka")
suzuki = token("suzuki")
haru = token("haru")
cases = [
("未ログインで自分の予約一覧", "GET", "/reservations", {}, 401),
("田中が田中の予約を見る", "GET", "/reservations/R-0001", tanaka, 200),
("田中が鈴木の予約を見る", "GET", "/reservations/R-0002", tanaka, 404),
("田中が鈴木の予約をキャンセル", "POST", "/reservations/R-0002/cancel", tanaka, 404),
("鈴木が店員の一覧を見る", "GET", "/staff/reservations?pickupDate=2026-11-02", suzuki, 403),
("晴が店員の一覧を見る", "GET", "/staff/reservations?pickupDate=2026-11-02", haru, 200),
("晴が受け取り済みのR-0002を受け取り済みに", "POST", "/staff/reservations/R-0002/pickup", haru, 409),
]
for label, method, path, headers, expected in cases:
status = client.request(method, path, headers=headers).status_code
mark = "OK" if status == expected else "NG"
print(f"{mark} {status}(期待 {expected}) {label}")
TestClient は、サーバーを起動せずに、APIに要求を送れる部品です。client.request(メソッド, パス, headers=…) で要求を送り、status_code で状態コードを読みます。
18 / 20