FastAPI+jinja2をユニットテストする機会があった。Claudeにサンプルコードを出してもらった。以下はそのコードである。割と愚直にチェックするのがスタンダードなのだろう、と感じた。
# app.py
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse(
"index.html",
{"request": request, "title": "Home", "items": ["A", "B", "C"]}
)
# test_app.py
import pytest
from fastapi.testclient import TestClient
from app import app
client = TestClient(app)
def test_render_template():
"""HTMLレンダリングの基本テスト"""
response = client.get("/")
# ステータスコード確認
assert response.status_code == 200
# Content-Type確認
assert "text/html" in response.headers["content-type"]
# HTMLコンテンツの確認
html = response.text
assert "<title>Home</title>" in html
assert "A" in html
assert "B" in html
def test_template_context():
"""テンプレートコンテキストの検証"""
response = client.get("/")
# 特定の要素が含まれているか
assert "Home" in response.text
# リストアイテムの確認
for item in ["A", "B", "C"]:
assert item in response.text