python-pytest-ops について
Python 開発者向けに、テストの作成と実行に役立つ pytest の実践パターンをまとめたスキルです。フィクスチャ、パラメーター化、例外、マーカー、モックに加え、補助スクリプトとテンプレートも扱います。
主な機能
- 01テスト構成とアサーション
- 02スコープ別フィクスチャの作成
- 03テストケースのパラメーター化
- 04例外テストとマーカーの利用
- 05依存先のモック化
- 06テスト実行と設定ファイル生成
活用シーン
- 01Python プロジェクトのテスト整理
- 02パラメーター化による複数入力の検証
- 03モックによる外部呼び出しの分離
- 04テストの絞り込み実行やカバレッジ確認
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ 0xdarkmatter/ claude-mods --skill python-pytest-opsインストール後、Claude Code で/python-pytest-opsを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
assets/conftest.py.templatepytest.ini.templatereferences/async-testing.mdcoverage-strategies.mdfixtures-advanced.mdintegration-testing.mdmocking-patterns.mdproperty-testing.mdtest-architecture.mdscripts/generate-conftest.shrun-tests.shtests/run.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()
クイックリファレンス
プロジェクト環境内で実行してください。uv run を先頭に付けます(例:uv run pytest -v)。
簡潔にするため、以下では pytest のみを記載しています。
| コマンド | 説明 |
|---|---|
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-ops- 型安全なテストコードpython-async-ops- 非同期テストのパターン(pytest-asyncio)
特定のフレームワークのテスト:
python-fastapi-ops- TestClient、API テストpython-database-ops- データベースフィクスチャ、トランザクション
コメント
Markdown 対応