Pytest による単体テストと結合テスト
概要#
Flask アプリケーションに対する Pytest を用いたテスト設計。テスト用データベース(インメモリ SQLite)のセットアップ、フィクスチャ設計、ORM モデルのテスト、Test Client を用いたルーティング・View の結合テストについてのまとめ。
参考ブログ記事#
1. Pytest フィクスチャ設計 (tests/conftest.py)#
1import pytest
2from app import create_app, db
3
4@pytest.fixture
5def app():
6 test_config = {
7 "TESTING": True,
8 "SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:",
9 "WTF_CSRF_ENABLED": False,
10 }
11 app = create_app(test_config)
12
13 with app.app_context():
14 db.create_all()
15 yield app
16 db.session.remove()
17 db.drop_all()
18
19@pytest.fixture
20def client(app):
21 return app.test_client()
22
23@pytest.fixture
24def runner(app):
25 return app.test_cli_runner()2. Model の単体テスト (tests/test_models.py)#
3. View / ルーティングのテスト (tests/test_views.py)#
1def test_login_page_get(client):
2 response = client.get("/auth/login")
3 assert response.status_code == 200
4 assert b"Login" in response.data
5
6def test_login_post_success(client, app):
7 # テストユーザー作成
8 with app.app_context():
9 user = User(username="admin")
10 user.set_password("secret123")
11 db.session.add(user)
12 db.session.commit()
13
14 response = client.post(
15 "/auth/login",
16 data={"username": "admin", "password": "secret123"},
17 follow_redirects=True,
18 )
19 assert response.status_code == 200
20 assert b"Welcome, admin" in response.dataここに掲載する記事はまだありません。
