mcpField
P
python-testing-patterns

python-testing-patterns

github.com/nickcrewテスト・品質6287 回インストール18 週間前に更新
リポジトリ

python-testing-patterns について

python-testing-patternsは、Pythonのテストスイートを構築・保守する開発者向けのガイドスキルです。pytestの基本からフィクスチャ、モック、非同期、統合、プロパティベーステストまで、テーマ別に解説します。

主な機能

  1. 01pytestのテスト構成と検出
  2. 02フィクスチャの設定・スコープ・後処理
  3. 03パラメーター化テストとモック
  4. 04非同期テストとプロパティベーステスト
  5. 05統合テストとカバレッジのガイド

活用シーン

  1. 01Pythonプロジェクトでpytestを導入
  2. 02API、データベース、外部サービスのテスト
  3. 03非同期コードと境界条件の確認
  4. 04カバレッジ測定とテスト実行の整理

インストール

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

$npx skills add https://github.com/nickcrew/claude-cortex --skill python-testing-patterns

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

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
async-testing.md
best-practices.md
coverage.md
fixtures.md
integration-testing.md
mocking.md
monkeypatch.md
parametrized-tests.md
property-based-testing.md
pytest-fundamentals.md
test-organization.md
validation/
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.pyskills/python-testing-patterns/references/fixtures.md
パラメーター化、複数のテストケースskills/python-testing-patterns/references/parametrized-tests.md
モック、パッチ、unittest.mock、pytest-mockskills/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

よくある間違い

  1. フィクスチャを使わない:テスト間でセットアップコードを繰り返す

    • 解決策:conftest.py にフィクスチャを作成する
  2. テストが実行順に依存する:グローバル状態が汚染される

    • 解決策:適切なフィクスチャを使い、テストの独立性を確保する
  3. モックの使いすぎ:内部実装をモックする

    • 解決策:外部との境界(API、データベース)のみをモックする
  4. エッジケースの見落とし:正常系のみをテストする

    • 解決策:境界条件、エラー、無効な入力をテストする
  5. テストが遅い:統合テスト一式を頻繁に実行する

    • 解決策:ユニットテストと統合テストを分け、マーカーを使い、フィクスチャを最適化する
  6. カバレッジの不足を無視する:テストカバレッジを測定しない

    • 解決策:pytest-cov を使用してメトリクスを追跡する
  7. テスト名が不適切:test_1() のような汎用的な名前を使う

    • 解決策:test_<behavior>_<condition>_<expected> のような説明的な名前を使う
  8. クリーンアップを行わない:リソースが解放されない

    • 解決策:適切なティアダウンを行うフィクスチャを使う(yield パターン)

リソース

コメント