mcpField
P
python-pytest-patterns

python-pytest-patterns

github.com/0xdarkmatterテスト・品質7859 回インストール2 週間前に更新
リポジトリ

python-pytest-patterns について

pytestを使うPython開発者向けのパターン集です。テスト構成、フィクスチャ、パラメーター化、例外、マーカー、モックに加え、スクリプトと設定テンプレートも扱います。

主な機能

  1. 01テスト構成とアサーション
  2. 02フィクスチャのスコープと共有
  3. 03パラメーター化と例外テスト
  4. 04マーカーとモックのパターン
  5. 05コマンド、スクリプト、設定テンプレート

活用シーン

  1. 01テストスイートに再利用可能なフィクスチャを追加
  2. 02複数の入力を扱うパラメーター化テストを作成
  3. 03API呼び出しをモックし例外を検証
  4. 04名前やマーカーでpytestテストを実行

インストール

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

$npx skills add https://github.com/0xdarkmatter/claude-mods --skill python-pytest-patterns

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

同梱ファイル

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

assets/
conftest.py.template
pytest.ini.template
references/
async-testing.md
coverage-strategies.md
fixtures-advanced.md
integration-testing.md
mocking-patterns.md
property-testing.md
test-architecture.md
scripts/
generate-conftest.sh
run-tests.sh

詳細

Python pytest パターン

効果的なテストに役立つ、最新の pytest パターンです。

基本的なテスト構造

import pytest

def test_basic():
    """Simple assertion test."""
    assert 1 + 1 == 2

def test_with_description():
    """Descriptive name and docstring."""
    result = calculate_total([1, 2, 3])
    assert result == 6, "Sum should equal 6"

フィクスチャ

import pytest

@pytest.fixture
def sample_user():
    """Create test user."""
    return {"id": 1, "name": "Test User"}

@pytest.fixture
def db_connection():
    """Fixture with setup and teardown."""
    conn = create_connection()
    yield conn
    conn.close()

def test_user(sample_user):
    """Fixtures injected by name."""
    assert sample_user["name"] == "Test User"
フィクスチャのスコープ
@pytest.fixture(scope="function")  # Default - per test
@pytest.fixture(scope="class")     # Per test class
@pytest.fixture(scope="module")    # Per test file
@pytest.fixture(scope="session")   # Entire test run

パラメーター化

@pytest.mark.parametrize("input,expected", [
    (1, 2),
    (2, 4),
    (3, 6),
])
def test_double(input, expected):
    assert double(input) == expected

# Multiple parameters
@pytest.mark.parametrize("x", [1, 2])
@pytest.mark.parametrize("y", [10, 20])
def test_multiply(x, y):  # 4 test combinations
    assert x * y > 0

例外のテスト

def test_raises():
    with pytest.raises(ValueError) as exc_info:
        raise ValueError("Invalid input")
    assert "Invalid" in str(exc_info.value)

def test_raises_match():
    with pytest.raises(ValueError, match=r".*[Ii]nvalid.*"):
        raise ValueError("Invalid input")

マーカー

@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
    pass

@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_feature():
    pass

@pytest.mark.xfail(reason="Known bug")
def test_buggy():
    assert broken_function() == expected

@pytest.mark.slow
def test_performance():
    """Custom marker - register in pytest.ini."""
    pass

モック

from unittest.mock import Mock, patch, MagicMock

def test_with_mock():
    mock_api = Mock()
    mock_api.get.return_value = {"status": "ok"}
    result = mock_api.get("/endpoint")
    assert result["status"] == "ok"

@patch("module.external_api")
def test_with_patch(mock_api):
    mock_api.return_value = {"data": []}
    result = function_using_api()
    mock_api.assert_called_once()
pytest-mock(推奨)
def test_with_mocker(mocker):
    mock_api = mocker.patch("module.api_call")
    mock_api.return_value = {"success": True}
    result = process_data()
    assert result["success"]

conftest.py

# tests/conftest.py - Shared fixtures

import pytest

@pytest.fixture(scope="session")
def app():
    """Application fixture available to all tests."""
    return create_app(testing=True)

@pytest.fixture
def client(app):
    """Test client fixture."""
    return app.test_client()

クイックリファレンス

コマンド説明
pytestすべてのテストを実行
pytest -v詳細な出力
pytest -x最初の失敗で停止
pytest -k "test_name"条件に一致するテストを実行
pytest -m slowマークされたテストを実行
pytest --lf前回失敗したテストを再実行
pytest --cov=srcカバレッジレポート
pytest -n auto並列実行(pytest-xdist)

追加リソース

  • ./references/fixtures-advanced.md - ファクトリーフィクスチャ、autouse、conftest のパターン
  • ./references/mocking-patterns.md - Mock、patch、MagicMock、side_effect
  • ./references/async-testing.md - pytest-asyncio のパターン
  • ./references/coverage-strategies.md - pytest-cov、ブランチカバレッジ、レポート
  • ./references/integration-testing.md - データベースフィクスチャ、API テスト、testcontainers
  • ./references/property-testing.md - Hypothesis フレームワーク、ストラテジー、縮小
  • ./references/test-architecture.md - テストピラミッド、構成、分離戦略

スクリプト

  • ./scripts/run-tests.sh - 推奨オプションでテストを実行
  • ./scripts/generate-conftest.sh - conftest.py のひな形を生成

アセット

  • ./assets/pytest.ini.template - 推奨する pytest 設定
  • ./assets/conftest.py.template - 一般的なフィクスチャのパターン

関連項目

関連スキル:

  • python-typing-patterns - 型安全なテストコード
  • python-async-patterns - 非同期テストのパターン(pytest-asyncio)

特定のフレームワークのテスト:

  • python-fastapi-patterns - TestClient、API テスト
  • python-database-patterns - データベースフィクスチャ、トランザクション

コメント