mcpField
P
python-testing-patterns

python-testing-patterns

github.com/wshobsonテスト・品質41.9k37.5k 回インストール2 週間前に更新
リポジトリ

python-testing-patterns について

pytest、フィクスチャ、モック、パラメーター化などを扱う Python 開発者向けのテストパターンガイドです。単体テストから非同期・データベース・CI/CD のテストまで、設計や問題調査に役立ちます。

主な機能

  1. 01単体、統合、エンドツーエンドテスト
  2. 02pytest のフィクスチャとテスト構成
  3. 03モックとパラメーター化テスト
  4. 04非同期・データベーステストの指針
  5. 05カバレッジと CI/CD の実践

活用シーン

  1. 01Python プロジェクトのテストスイート構築
  2. 02API やサービスの統合テスト作成
  3. 03依存先のモック化とテスト失敗の調査
  4. 04CI/CD での継続的テストの計画

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/wshobson/agents --skill python-testing-patterns

インストール後、Claude Code で/python-testing-patternsを入力して読み込まれたか確認します。

同梱ファイルreferences/advanced-patterns.mdreferences/details.md

詳細

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 を参照してください

コメント