Flask テスト
テストはコード品質を保証する基盤です。
Flask には組み込みのテストクライアントがあり、pytest と組み合わせることで効率的にテストを作成・実行できます。
テストクライアント——test_client
Flask のtest_client()メソッドは、サーバーを起動せずにリクエストを送信できるモック HTTP クライアントを作成します:
例
# ファイルパス: test_demo.py(Python 対話環境でのテスト)
from app import create_app
# テスト用の app インスタンスを作成
app = create_app()
# テストクライアントを作成
with app.test_client() as client:
# GET リクエストを送信
response = client.get("/")
print(response.status_code) # 200
print(response.data[:100]) # レスポンスボディの先頭100バイト
# POST リクエストを送信し、データを JSON で送信
response = client.post("/api/posts",
json={"title": "サンプル 教程", "body": "内容", "author_id": 1})
print(response.status_code) # 201
print(response.get_json()) # JSON レスポンスを解析
from app import create_app
# テスト用の app インスタンスを作成
app = create_app()
# テストクライアントを作成
with app.test_client() as client:
# GET リクエストを送信
response = client.get("/")
print(response.status_code) # 200
print(response.data[:100]) # レスポンスボディの先頭100バイト
# POST リクエストを送信し、データを JSON で送信
response = client.post("/api/posts",
json={"title": "サンプル 教程", "body": "内容", "author_id": 1})
print(response.status_code) # 201
print(response.get_json()) # JSON レスポンスを解析
pytest 統合
pytest は Python コミュニティの標準テストフレームワークであり、Flask と組み合わせて使うと非常に便利です。
pytest のインストール
(.venv) $ pip install pytest
テストの作成——conftest.py(共有フィクスチャ)
使用conftest.pyファイルは再利用可能なテストフィクスチャ(fixture)を作成します:
例
# ファイルパス: tests/conftest.py
import os
import tempfile
import pytest
from app import create_app
from db import init_db, get_db
@pytest.fixture
def app():
"""テスト用の app インスタンスを作成し、一時データベースを使用する"""
# テストデータベースとして一時ファイルを作成
db_fd, db_path = tempfile.mkstemp()
# app を作成し、データベースパスを一時ファイルに変更
app = create_app()
app.config["DATABASE"] = db_path
app.config["TESTING"] = True # テストモードを有効にする
# テストデータベースのテーブル構造を初期化
with app.app_context():
init_db()
yield app
# テスト後のクリーンアップ: 一時データベースファイルを閉じて削除
os.close(db_fd)
os.unlink(db_path)
@pytest.fixture
def client(app):
"""テストクライアントを作成"""
return app.test_client()
@pytest.fixture
def runner(app):
"""CLI テストランナーを作成"""
return app.test_cli_runner()
import os
import tempfile
import pytest
from app import create_app
from db import init_db, get_db
@pytest.fixture
def app():
"""テスト用の app インスタンスを作成し、一時データベースを使用する"""
# テストデータベースとして一時ファイルを作成
db_fd, db_path = tempfile.mkstemp()
# app を作成し、データベースパスを一時ファイルに変更
app = create_app()
app.config["DATABASE"] = db_path
app.config["TESTING"] = True # テストモードを有効にする
# テストデータベースのテーブル構造を初期化
with app.app_context():
init_db()
yield app
# テスト後のクリーンアップ: 一時データベースファイルを閉じて削除
os.close(db_fd)
os.unlink(db_path)
@pytest.fixture
def client(app):
"""テストクライアントを作成"""
return app.test_client()
@pytest.fixture
def runner(app):
"""CLI テストランナーを作成"""
return app.test_cli_runner()
ルートのテスト
例
# ファイルパス: tests/test_app.py
def test_home_page(client):
"""ホームページが正常に返ることをテスト"""
response = client.get("/")
assert response.status_code == 200
# ページに期待するキーワードが含まれているか確認
assert b"サンプル" in response.data
def test_404_page(client):
"""存在しないページへのアクセスをテスト"""
response = client.get("/this-page-does-not-exist")
assert response.status_code == 404
def test_home_page(client):
"""ホームページが正常に返ることをテスト"""
response = client.get("/")
assert response.status_code == 200
# ページに期待するキーワードが含まれているか確認
assert b"サンプル" in response.data
def test_404_page(client):
"""存在しないページへのアクセスをテスト"""
response = client.get("/this-page-does-not-exist")
assert response.status_code == 404
テストを実行:
(.venv) $ pytest tests/test_app.py -v ==================================== tests/test_app.py::test_home_page PASSED tests/test_app.py::test_404_page PASSED ====================================
JSON API のテスト
例
# ファイルパス: tests/test_api.py
def test_create_post(client):
"""記事作成 API をテスト"""
response = client.post("/api/posts", json={
"title": "サンプル 测试文章",
"body": "これはテスト内容です",
"author_id": 1
})
# 作成成功時は 201 を返す
assert response.status_code == 201
data = response.get_json()
assert data["title"] == "サンプル 测试文章"
assert "id" in data
def test_create_post_without_title(client):
"""タイトルが空の場合に 400 エラーを返すことをテスト"""
response = client.post("/api/posts", json={
"title": "",
"body": "内容",
"author_id": 1
})
assert response.status_code == 400
assert b"error" in response.data
def test_get_posts(client):
"""記事一覧の取得をテスト"""
# まず記事を1件作成
client.post("/api/posts", json={
"title": "文章 A", "body": "内容 A", "author_id": 1
})
# 一覧を取得
response = client.get("/api/posts")
assert response.status_code == 200
data = response.get_json()
assert len(data) >= 1
def test_delete_post(client):
"""記事削除をテスト"""
# まず作成
rv = client.post("/api/posts", json={
"title": "待删除", "body": "内容", "author_id": 1
})
post_id = rv.get_json()["id"]
# 次に削除
rv = client.delete(f"/api/posts/{post_id}")
assert rv.status_code == 200
# 削除されたことを確認
rv = client.get(f"/api/posts/{post_id}")
assert rv.status_code == 404
def test_create_post(client):
"""記事作成 API をテスト"""
response = client.post("/api/posts", json={
"title": "サンプル 测试文章",
"body": "これはテスト内容です",
"author_id": 1
})
# 作成成功時は 201 を返す
assert response.status_code == 201
data = response.get_json()
assert data["title"] == "サンプル 测试文章"
assert "id" in data
def test_create_post_without_title(client):
"""タイトルが空の場合に 400 エラーを返すことをテスト"""
response = client.post("/api/posts", json={
"title": "",
"body": "内容",
"author_id": 1
})
assert response.status_code == 400
assert b"error" in response.data
def test_get_posts(client):
"""記事一覧の取得をテスト"""
# まず記事を1件作成
client.post("/api/posts", json={
"title": "文章 A", "body": "内容 A", "author_id": 1
})
# 一覧を取得
response = client.get("/api/posts")
assert response.status_code == 200
data = response.get_json()
assert len(data) >= 1
def test_delete_post(client):
"""記事削除をテスト"""
# まず作成
rv = client.post("/api/posts", json={
"title": "待删除", "body": "内容", "author_id": 1
})
post_id = rv.get_json()["id"]
# 次に削除
rv = client.delete(f"/api/posts/{post_id}")
assert rv.status_code == 200
# 削除されたことを確認
rv = client.get(f"/api/posts/{post_id}")
assert rv.status_code == 404
セッションのテスト
ログインなど Session が必要な機能をテスト:
例
# ファイルパス: tests/test_auth.py
def test_login(client):
"""ログインフローをテスト"""
# ログインリクエストを送信
response = client.post("/auth/login", data={
"username": "testuser",
"password": "testpass"
}, follow_redirects=True) # follow_redirects でリダイレクトを自動追従
assert response.status_code == 200
def test_session_transaction(client):
"""session を直接操作してテスト"""
with client.session_transaction() as session:
# session に直接値を設定し、ログイン済み状態をシミュレート
session["username"] = "サンプル"
# ホームページにアクセスすると、ログイン済み状態が表示されるはず
response = client.get("/")
assert b"サンプル" in response.data
def test_login(client):
"""ログインフローをテスト"""
# ログインリクエストを送信
response = client.post("/auth/login", data={
"username": "testuser",
"password": "testpass"
}, follow_redirects=True) # follow_redirects でリダイレクトを自動追従
assert response.status_code == 200
def test_session_transaction(client):
"""session を直接操作してテスト"""
with client.session_transaction() as session:
# session に直接値を設定し、ログイン済み状態をシミュレート
session["username"] = "サンプル"
# ホームページにアクセスすると、ログイン済み状態が表示されるはず
response = client.get("/")
assert b"サンプル" in response.data
client.session_transaction()これは非常に実用的なテストツールです——完全なログインフローを経由せずに Session の内容を直接変更できます。
CLI コマンドのテスト
例
# ファイルパス: tests/test_cli.py
def test_init_db(runner):
"""データベース初期化コマンドをテスト"""
result = runner.invoke(args=["init-db"])
# コマンド実行が成功した場合、exit_code は 0 になるはず
assert result.exit_code == 0
def test_flask_routes(runner):
"""flask routes コマンドをテスト"""
result = runner.invoke(args=["routes"])
assert result.exit_code == 0
# 出力に登録済みルートが含まれているか確認
assert "/api/posts" in result.output
def test_init_db(runner):
"""データベース初期化コマンドをテスト"""
result = runner.invoke(args=["init-db"])
# コマンド実行が成功した場合、exit_code は 0 になるはず
assert result.exit_code == 0
def test_flask_routes(runner):
"""flask routes コマンドをテスト"""
result = runner.invoke(args=["routes"])
assert result.exit_code == 0
# 出力に登録済みルートが含まれているか確認
assert "/api/posts" in result.output
テストのベストプラクティス
| 実践 | 説明 |
|---|---|
| 一時データベースを使用 | 各テストで独立したデータベースを使用し、互いに干渉しない(例: conftest.py 内の tempfile) |
| TESTING モードを有効にする | app.config["TESTING"] = True例外がエラーハンドラに飲み込まれず、正常に伝播させる |
| 1つのテストは1つのことだけ検証する | 各 test 関数は1つの動作だけを検証し、問題の特定を容易にする |
| 命名を明確にする | 関数名の形式はtest_どんなシナリオ_どんな結果を期待 |
| follow_redirects を活用する | POST 後のリダイレクトフローをテストする場合に便利 |
すべてのテストを実行
(.venv) $ pytest tests/ -v tests/test_app.py::test_home_page PASSED tests/test_app.py::test_404_page PASSED tests/test_api.py::test_create_post PASSED tests/test_api.py::test_create_post_without_title PASSED tests/test_api.py::test_get_posts PASSED tests/test_api.py::test_delete_post PASSED tests/test_auth.py::test_login PASSED tests/test_auth.py::test_session_transaction PASSED tests/test_cli.py::test_init_db PASSED tests/test_cli.py::test_flask_routes PASSED ==================== 10 passed in 0.45s ====================その他の拡張