python-testing-patterns について
python-testing-patternsは、Pythonのテストスイートを構築・保守する開発者向けのガイドスキルです。pytestの基本からフィクスチャ、モック、非同期、統合、プロパティベーステストまで、テーマ別に解説します。
主な機能
- 01pytestのテスト構成と検出
- 02フィクスチャの設定・スコープ・後処理
- 03パラメーター化テストとモック
- 04非同期テストとプロパティベーステスト
- 05統合テストとカバレッジのガイド
活用シーン
- 01Pythonプロジェクトでpytestを導入
- 02API、データベース、外部サービスのテスト
- 03非同期コードと境界条件の確認
- 04カバレッジ測定とテスト実行の整理
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ nickcrew/ claude-cortex --skill python-testing-patternsインストール後、Claude Code で/python-testing-patternsを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/async-testing.mdbest-practices.mdcoverage.mdfixtures.mdintegration-testing.mdmocking.mdmonkeypatch.mdparametrized-tests.mdproperty-based-testing.mdpytest-fundamentals.mdtest-organization.mdvalidation/rubric.yaml詳細
Python のテストパターン
pytest、フィクスチャ、モック、パラメーター化、プロパティベーステストを使用して、堅牢なテスト戦略を Python に実装するための包括的なガイドです。
このスキルを使用する場面
- Python の関数やクラスのユニットテストを作成する
- 包括的なテストスイートとインフラストラクチャを構築する
- テスト駆動開発(TDD)のワークフローを実装する
- API、データベース、サービスの統合テストを作成する
- 外部依存関係やサードパーティーサービスをモックする
- 非同期コードや並行処理をテストする
- Hypothesis を使用してプロパティベーステストを実装する
- CI/CD のテスト自動化を構築する
- 失敗するテストをデバッグし、テストカバレッジを向上させる
コアコンセプト
テストの検出:test_*.py または *_test.py に一致するファイル、および test_ で始まる関数
フィクスチャ:セットアップとティアダウンを備えた再利用可能なテストリソース
- スコープ:
function(デフォルト)、class、module、session - 合成:単純なフィクスチャから複雑なフィクスチャを構築する
conftest.pyで共有し、プロジェクト全体で利用可能にする
アサーション:assert 文と、例外のテストに使う pytest.raises()
構成:unit/、integration/、e2e/ ディレクトリを分ける
クイックリファレンス
特定のトピックについて、詳細なリファレンスを読み込みます。
| タスク | リファレンスファイル |
|---|---|
| Pytest の基礎、テスト構造、AAA パターン | skills/python-testing-patterns/references/pytest-fundamentals.md |
| フィクスチャ、スコープ、セットアップ/ティアダウン、conftest.py | skills/python-testing-patterns/references/fixtures.md |
| パラメーター化、複数のテストケース | skills/python-testing-patterns/references/parametrized-tests.md |
| モック、パッチ、unittest.mock、pytest-mock | skills/python-testing-patterns/references/mocking.md |
| 非同期テスト、pytest-asyncio、イベントループ | skills/python-testing-patterns/references/async-testing.md |
| プロパティベーステスト、Hypothesis、ストラテジー | skills/python-testing-patterns/references/property-based-testing.md |
| Monkeypatch、環境変数、属性 | skills/python-testing-patterns/references/monkeypatch.md |
| テスト構造、マーカー、conftest.py のパターン | skills/python-testing-patterns/references/test-organization.md |
| カバレッジの測定、レポート、しきい値 | skills/python-testing-patterns/references/coverage.md |
| データベース、API、Redis、メッセージキューのテスト | skills/python-testing-patterns/references/integration-testing.md |
| ベストプラクティス、テスト品質、フィクスチャの設計 | skills/python-testing-patterns/references/best-practices.md |
ワークフロー
1. 基本的なテストのセットアップ
# test_example.py
import pytest
def test_something():
"""Descriptive test name."""
# Arrange
expected = 5
# Act
result = 2 + 3
# Assert
assert result == expected
テストを実行する:
pytest # Run all tests
pytest -v # Verbose output
pytest tests/unit/ # Specific directory
pytest -k "test_user" # Match pattern
pytest -m unit # Run marked tests
2. フィクスチャの使用
@pytest.fixture
def sample_data():
"""Provide test data."""
data = {"key": "value"}
yield data
# Cleanup if needed
def test_with_fixture(sample_data):
assert sample_data["key"] == "value"
3. パラメーター化されたテスト
@pytest.mark.parametrize("input,expected", [
(2, 4),
(3, 9),
(4, 16),
])
def test_square(input, expected):
assert input ** 2 == expected
4. 外部依存関係のモック
from unittest.mock import patch
@patch("module.external_api_call")
def test_with_mock(mock_api):
mock_api.return_value = {"status": "ok"}
result = my_function()
assert result["status"] == "ok"
mock_api.assert_called_once()
5. カバレッジの測定
pytest --cov=src --cov-report=term-missing
pytest --cov=src --cov-report=html
pytest --cov=src --cov-fail-under=80
6. テストの設定
pytest.ini:
[pytest]
testpaths = tests
python_files = test_*.py
addopts = -v --strict-markers --cov=src
markers =
unit: Unit tests
integration: Integration tests
slow: Slow tests
よく使われるパターン
例外のテスト:
with pytest.raises(ValueError, match="error message"):
function_that_raises()
非同期テスト:
@pytest.mark.asyncio
async def test_async_function():
result = await async_operation()
assert result is not None
一時ファイル:
def test_file_operation(tmp_path):
test_file = tmp_path / "test.txt"
test_file.write_text("content")
assert test_file.read_text() == "content"
テスト選択用のマーカー:
@pytest.mark.slow
@pytest.mark.integration
def test_database_operation():
pass
よくある間違い
-
フィクスチャを使わない:テスト間でセットアップコードを繰り返す
- 解決策:conftest.py にフィクスチャを作成する
-
テストが実行順に依存する:グローバル状態が汚染される
- 解決策:適切なフィクスチャを使い、テストの独立性を確保する
-
モックの使いすぎ:内部実装をモックする
- 解決策:外部との境界(API、データベース)のみをモックする
-
エッジケースの見落とし:正常系のみをテストする
- 解決策:境界条件、エラー、無効な入力をテストする
-
テストが遅い:統合テスト一式を頻繁に実行する
- 解決策:ユニットテストと統合テストを分け、マーカーを使い、フィクスチャを最適化する
-
カバレッジの不足を無視する:テストカバレッジを測定しない
- 解決策:pytest-cov を使用してメトリクスを追跡する
-
テスト名が不適切:
test_1()のような汎用的な名前を使う- 解決策:
test_<behavior>_<condition>_<expected>のような説明的な名前を使う
- 解決策:
-
クリーンアップを行わない:リソースが解放されない
- 解決策:適切なティアダウンを行うフィクスチャを使う(yield パターン)
リソース
- pytest: https://docs.pytest.org/
- unittest.mock: https://docs.python.org/3/library/unittest.mock.html
- pytest-asyncio: 非同期コードのテスト
- pytest-cov: カバレッジレポート
- pytest-mock: mock 用の pytest ラッパー
- Hypothesis: https://hypothesis.readthedocs.io/
- pytest-xdist: テストの並列実行
- testcontainers: テスト用の Docker コンテナ