jpskill.com
🛠️ 開発・MCP コミュニティ

python-pytest-ops

Pythonのpytestテストパターンを網羅し、フィクスチャ、マーク、パラメタライズ、モック、conftest、テストカバレッジ、ユニットテスト、結合テスト、pytest.raisesといった幅広いテストシナリオに対応するSkill。

📜 元の英語説明(参考)

pytest testing patterns for Python. Triggers on: pytest, fixture, mark, parametrize, mock, conftest, test coverage, unit test, integration test, pytest.raises.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Pythonのpytestテストパターンを網羅し、フィクスチャ、マーク、パラメタライズ、モック、conftest、テストカバレッジ、ユニットテスト、結合テスト、pytest.raisesといった幅広いテストシナリオに対応するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o python-pytest-ops.zip https://jpskill.com/download/5928.zip && unzip -o python-pytest-ops.zip && rm python-pytest-ops.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/5928.zip -OutFile "$d\python-pytest-ops.zip"; Expand-Archive "$d\python-pytest-ops.zip" -DestinationPath $d -Force; ri "$d\python-pytest-ops.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して python-pytest-ops.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → python-pytest-ops フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-17
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Python pytest パターン

効果的なテストのための最新の pytest パターンです。

基本的なテスト構造

import pytest

def test_basic():
    """シンプルなアサーションテストです。"""
    assert 1 + 1 == 2

def test_with_description():
    """記述的な名前とdocstringです。"""
    result = calculate_total([1, 2, 3])
    assert result == 6, "Sum should equal 6"

フィクスチャ

import pytest

@pytest.fixture
def sample_user():
    """テストユーザーを作成します。"""
    return {"id": 1, "name": "Test User"}

@pytest.fixture
def db_connection():
    """セットアップとティアダウンを持つフィクスチャです。"""
    conn = create_connection()
    yield conn
    conn.close()

def test_user(sample_user):
    """名前でインジェクトされるフィクスチャです。"""
    assert sample_user["name"] == "Test User"

フィクスチャのスコープ

@pytest.fixture(scope="function")  # デフォルト - テストごと
@pytest.fixture(scope="class")     # テストクラスごと
@pytest.fixture(scope="module")    # テストファイルごと
@pytest.fixture(scope="session")   # テスト実行全体

パラメータ化 (Parametrize)

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

# 複数のパラメータ
@pytest.mark.parametrize("x", [1, 2])
@pytest.mark.parametrize("y", [10, 20])
def test_multiply(x, y):  # 4つのテストの組み合わせ
    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():
    """カスタムマーカー - 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 - 共有フィクスチャ

import pytest

@pytest.fixture(scope="session")
def app():
    """すべてのテストで利用可能なアプリケーションフィクスチャです。"""
    return create_app(testing=True)

@pytest.fixture
def client(app):
    """テストクライアントフィクスチャです。"""
    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-ops - 型安全なテストコード
  • python-async-ops - 非同期テストパターン (pytest-asyncio)

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

  • python-fastapi-ops - TestClient、APIテスト
  • python-database-ops - データベースフィクスチャ、トランザクション
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Python pytest Patterns

Modern pytest patterns for effective testing.

Basic Test Structure

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"

Fixtures

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"

Fixture Scopes

@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

Parametrize

@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

Exception Testing

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")

Markers

@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

Mocking

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 (Recommended)

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()

Quick Reference

Command Description
pytest Run all tests
pytest -v Verbose output
pytest -x Stop on first failure
pytest -k "test_name" Run matching tests
pytest -m slow Run marked tests
pytest --lf Rerun last failed
pytest --cov=src Coverage report
pytest -n auto Parallel (pytest-xdist)

Additional Resources

  • ./references/fixtures-advanced.md - Factory fixtures, autouse, conftest patterns
  • ./references/mocking-patterns.md - Mock, patch, MagicMock, side_effect
  • ./references/async-testing.md - pytest-asyncio patterns
  • ./references/coverage-strategies.md - pytest-cov, branch coverage, reports
  • ./references/integration-testing.md - Database fixtures, API testing, testcontainers
  • ./references/property-testing.md - Hypothesis framework, strategies, shrinking
  • ./references/test-architecture.md - Test pyramid, organization, isolation strategies

Scripts

  • ./scripts/run-tests.sh - Run tests with recommended options
  • ./scripts/generate-conftest.sh - Generate conftest.py boilerplate

Assets

  • ./assets/pytest.ini.template - Recommended pytest configuration
  • ./assets/conftest.py.template - Common fixture patterns

See Also

Related Skills:

  • python-typing-ops - Type-safe test code
  • python-async-ops - Async test patterns (pytest-asyncio)

Testing specific frameworks:

  • python-fastapi-ops - TestClient, API testing
  • python-database-ops - Database fixtures, transactions