python-testing-patterns について
python-testing-patternsは、テストスイートを設計・保守するPython開発者向けのスキルです。pytestを用いたフィクスチャ、モック、テスト構成、カバレッジ、テストの進め方を紹介し、関連ドキュメントで追加パターンを案内します。
主な機能
- 01pytestによるテスト構成
- 02フィクスチャとテスト分離
- 03外部依存のモック
- 04AAAテスト構成
- 05カバレッジレポートの指針
- 06TDDと統合テストの指針
活用シーン
- 01Pythonテストスイートの作成
- 02リトライや時刻依存動作のテスト
- 03APIやサービス連携の確認
- 04失敗したテストの調査
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ full-stack-skills/ python-skills --skill python-testing-patternsインストール後、Claude Code で/python-testing-patternsを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
LICENSE.txtagents/openai.yamlexamples/advanced-usage.mdbasic-usage.mdintegration.mdreferences/advanced-patterns.mddetails.md詳細
出典の表記:wshobson/agents を基にしています (MIT License, Copyright (c) 2024 Seth Hobson;ライセンス全文は同じディレクトリの
LICENSE.txtをご覧ください)。 使用、変更、再配布にあたっては、当該 MIT ライセンスの条項に従い、著作権表示を保持する必要があります。
日本語の説明
このスキルでは、フルスタック開発に関するベストプラクティスとパターンを案内します。
name: python-testing-patterns description: pytest、フィクスチャ、モック、テスト駆動開発を活用した包括的なテスト戦略を実装します。Python のテスト作成、テストスイートの設定、テストのベストプラクティスの実装時に使用します。
Python テストパターン
pytest、フィクスチャ、モック、パラメーター化、テスト駆動開発の手法を使用して、Python で堅牢なテスト戦略を実装するための包括的なガイドです。
このスキルを使用する場面
- Python コードの単体テストを作成する
- テストスイートとテストインフラストラクチャを設定する
- テスト駆動開発(TDD)を実装する
- API やサービスの統合テストを作成する
- 外部の依存関係やサービスをモックする
- 非同期コードや並行処理をテストする
- CI/CD で継続的なテストを設定する
- プロパティベーステストを実装する
- データベース操作をテストする
- 失敗するテストをデバッグする
基本概念
1. テストの種類
- 単体テスト:個々の関数やクラスを分離してテストします
- 統合テスト:コンポーネント間の連携をテストします
- 機能テスト:機能全体をエンドツーエンドでテストします
- パフォーマンステスト:速度とリソース使用量を測定します
2. テスト構造(AAA パターン)
- 準備(Arrange):テストデータと事前条件を設定します
- 実行(Act):テスト対象のコードを実行します
- 検証(Assert):結果を検証します
3. テストカバレッジ
- テストによって実行されたコードを測定します
- テストされていないコードパスを特定します
- ただ高い数値を目指すのではなく、意味のあるカバレッジを目指します
4. テストの分離
- テストは互いに独立している必要があります
- テスト間で状態を共有しないようにします
- 各テストは自身で後処理を行う必要があります
クイックスタート
# test_example.py
def add(a, b):
return a + b
def test_add():
"""Basic test example."""
result = add(2, 3)
assert result == 5
def test_add_negative():
"""Test with negative numbers."""
assert add(-1, 1) == 0
# Run with: pytest test_example.py
詳細なパターンと実例
詳細なパターンのドキュメントは references/details.md にあります。上記のナビゲーションだけでは不十分な場合は、このファイルを読んでください。
テストのベストプラクティス
テストの整理
# tests/
# __init__.py
# conftest.py # Shared fixtures
# test_unit/ # Unit tests
# test_models.py
# test_utils.py
# test_integration/ # Integration tests
# test_api.py
# test_database.py
# test_e2e/ # End-to-end tests
# test_workflows.py
テストの命名規則
一般的なパターンは test_<unit>_<scenario>_<expected_outcome> です。チームの好みに合わせて調整してください。
# Pattern: test_<unit>_<scenario>_<expected>
def test_create_user_with_valid_data_returns_user():
...
def test_create_user_with_duplicate_email_raises_conflict():
...
def test_get_user_with_unknown_id_returns_none():
...
# Good test names - clear and descriptive
def test_user_creation_with_valid_data():
"""Clear name describes what is being tested."""
pass
def test_login_fails_with_invalid_password():
"""Name describes expected behavior."""
pass
def test_api_returns_404_for_missing_resource():
"""Specific about inputs and expected outcomes."""
pass
# Bad test names - avoid these
def test_1(): # Not descriptive
pass
def test_user(): # Too vague
pass
def test_function(): # Doesn't explain what's tested
pass
リトライ動作のテスト
モックの副作用を使って、リトライロジックが正しく動作することを検証します。
from unittest.mock import Mock
def test_retries_on_transient_error():
"""Test that service retries on transient failures."""
client = Mock()
# Fail twice, then succeed
client.request.side_effect = [
ConnectionError("Failed"),
ConnectionError("Failed"),
{"status": "ok"},
]
service = ServiceWithRetry(client, max_retries=3)
result = service.fetch()
assert result == {"status": "ok"}
assert client.request.call_count == 3
def test_gives_up_after_max_retries():
"""Test that service stops retrying after max attempts."""
client = Mock()
client.request.side_effect = ConnectionError("Failed")
service = ServiceWithRetry(client, max_retries=3)
with pytest.raises(ConnectionError):
service.fetch()
assert client.request.call_count == 3
def test_does_not_retry_on_permanent_error():
"""Test that permanent errors are not retried."""
client = Mock()
client.request.side_effect = ValueError("Invalid input")
service = ServiceWithRetry(client, max_retries=3)
with pytest.raises(ValueError):
service.fetch()
# Only called once - no retry for ValueError
assert client.request.call_count == 1
Freezegun による時間のモック
freezegun を使用してテスト内の時間を制御し、時間に依存する動作を予測可能にします。
from freezegun import freeze_time
from datetime import datetime, timedelta
@freeze_time("2026-01-15 10:00:00")
def test_token_expiry():
"""Test token expires at correct time."""
token = create_token(expires_in_seconds=3600)
assert token.expires_at == datetime(2026, 1, 15, 11, 0, 0)
@freeze_time("2026-01-15 10:00:00")
def test_is_expired_returns_false_before_expiry():
"""Test token is not expired when within validity period."""
token = create_token(expires_in_seconds=3600)
assert not token.is_expired()
@freeze_time("2026-01-15 12:00:00")
def test_is_expired_returns_true_after_expiry():
"""Test token is expired after validity period."""
token = Token(expires_at=datetime(2026, 1, 15, 11, 30, 0))
assert token.is_expired()
def test_with_time_travel():
"""Test behavior across time using freeze_time context."""
with freeze_time("2026-01-01") as frozen_time:
item = create_item()
assert item.created_at == datetime(2026, 1, 1)
# Move forward in time
frozen_time.move_to("2026-01-15")
assert item.age_days == 14
テストマーカー
# test_markers.py
import pytest
@pytest.mark.slow
def test_slow_operation():
"""Mark slow tests."""
import time
time.sleep(2)
@pytest.mark.integration
def test_database_integration():
"""Mark integration tests."""
pass
@pytest.mark.skip(reason="Feature not implemented yet")
def test_future_feature():
"""Skip tests temporarily."""
pass
@pytest.mark.skipif(os.name == "nt", reason="Unix only test")
def test_unix_specific():
"""Conditional skip."""
pass
@pytest.mark.xfail(reason="Known bug #123")
def test_known_bug():
"""Mark expected failures."""
assert False
# Run with:
# pytest -m slow # Run only slow tests
# pytest -m "not slow" # Skip slow tests
# pytest -m integration # Run integration tests
カバレッジレポート
# Install coverage
pip install pytest-cov
# Run tests with coverage
pytest --cov=myapp tests/
# Generate HTML report
pytest --cov=myapp --cov-report=html tests/
# Fail if coverage below threshold
pytest --cov=myapp --cov-fail-under=80 tests/
# Show missing lines
pytest --cov=myapp --cov-report=term-missing tests/
高度なパターン(非同期テスト、monkeypatching、プロパティベーステスト、データベーステスト、CI/CD 連携、設定)については、references/advanced-patterns.md をご覧ください。
能力の範囲
✅ 得意なこと
- フルスタック開発に関するベストプラクティス
- コードアーキテクチャ設計のガイダンス
- パフォーマンス最適化の提案
⚠️ 必要な情報
- 具体的なプロジェクトのコンテキスト
- 技術スタックの情報
❌ 対応範囲外
- 技術以外の分野におけるビジネス上の意思決定
- 具体的なコードの実装(ガイダンスのみを提供)
注意点
1. 過剰設計
単純なケースで複雑なデザインパターンを使用しないでください
2. パフォーマンスの軽視
特に本番環境では、パフォーマンスの最適化を軽視しないでください
3. セキュリティへの配慮
常にセキュリティとデータ保護を考慮してください
4. テストカバレッジ
特に境界ケースについて、十分なテストカバレッジを確保してください
5. ドキュメントのメンテナンス
ドキュメントをコードと同期して更新してください