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

tdd-pytest

Pythonのpytestを使ったテスト駆動開発を支援し、テスト作成、品質監査、実行、レポート生成を効率化、uvやpyproject.tomlとの連携で開発環境を最適化するSkill。

📜 元の英語説明(参考)

Python/pytest TDD specialist for test-driven development workflows. Use when writing tests, auditing test quality, running pytest, or generating test reports. Integrates with uv and pyproject.toml configuration.

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

一言でいうと

Pythonのpytestを使ったテスト駆動開発を支援し、テスト作成、品質監査、実行、レポート生成を効率化、uvやpyproject.tomlとの連携で開発環境を最適化するSkill。

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

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

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

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

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

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して tdd-pytest.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → tdd-pytest フォルダができる
  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-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

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

TDD-Pytest Skill

このスキルは、ユーザーが以下の点で助けを必要としている場合に有効化してください。

  • TDD(Red-Green-Refactor)手法を用いたテストの作成
  • 既存の pytest テストファイルの品質監査
  • カバレッジ付きのテスト実行
  • TESTING_REPORT.local.md へのテストレポートの生成
  • pyproject.toml での pytest 設定

TDD ワークフロー

Red-Green-Refactor サイクル

  1. RED - まず失敗するテストを書く

    • テストは正しい理由で失敗するべき(import エラーではない)
    • テストは最小限で焦点を絞るべき
    • 失敗するテストの出力を表示する
  2. GREEN - テストをパスさせるための最小限のコードを書く

    • テストをパスさせるために必要なことだけを実装する
    • 早すぎる最適化はしない
    • パスするテストの出力を表示する
  3. REFACTOR - テストをパスさせながらコードを改善する

    • 重複を解消する
    • 命名を改善する
    • 必要に応じて関数/クラスを抽出する
    • 各変更後にテストを実行する

テストの構成

ファイル構造

project/
  src/
    module.py
  tests/
    conftest.py          # 共有フィクスチャ
    test_module.py       # module.py のテスト
  pyproject.toml         # Pytest 設定

命名規則

  • テストファイル: test_*.py または *_test.py
  • テスト関数: test_*
  • テストクラス: Test*
  • フィクスチャ: 説明的な名前 (mock_database, sample_user)

Pytest のベストプラクティス

フィクスチャ

import pytest

@pytest.fixture
def sample_config():
    return {"key": "value"}

@pytest.fixture
def mock_client(mocker):
    return mocker.MagicMock()

パラメータ化

@pytest.mark.parametrize("input,expected", [
    ("hello", "HELLO"),
    ("world", "WORLD"),
    ("", ""),
])
def test_uppercase(input, expected):
    assert input.upper() == expected

Async テスト

import pytest

@pytest.mark.asyncio
async def test_async_function():
    result = await async_operation()
    assert result == expected

例外テスト

def test_raises_value_error():
    with pytest.raises(ValueError, match="invalid input"):
        process_input(None)

テストの実行

With uv

uv run pytest                              # すべてのテストを実行
uv run pytest tests/test_module.py         # 特定のファイルを実行
uv run pytest -k "test_name"               # 名前パターンで実行
uv run pytest -v --tb=short                # 詳細な出力と短いトレースバック
uv run pytest --cov=src --cov-report=term  # カバレッジ付き

一般的なフラグ

  • -v / --verbose - 詳細な出力
  • -x / --exitfirst - 最初の失敗で停止
  • --tb=short - 短いトレースバック
  • --tb=no - トレースバックなし
  • -k EXPR - 式に一致するテストを実行
  • -m MARKER - マーカー付きのテストを実行
  • --cov=PATH - パスのカバレッジ
  • --cov-report=term-missing - 不足している行を表示

pyproject.toml 設定

最小限の設定

[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]

完全な設定

[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
python_functions = ["test_*"]
python_classes = ["Test*"]
addopts = "-v --tb=short"
markers = [
    "slow: marks tests as slow",
    "integration: marks integration tests",
]
filterwarnings = [
    "ignore::DeprecationWarning",
]

[tool.coverage.run]
source = ["src"]
branch = true
omit = ["tests/*", "*/__init__.py"]

[tool.coverage.report]
exclude_lines = [
    "pragma: no cover",
    "if TYPE_CHECKING:",
    "raise NotImplementedError",
]
fail_under = 80
show_missing = true

レポートの生成

TESTING_REPORT.local.md ファイルには以下が含まれる必要があります。

  1. テスト実行の概要 (成功/失敗/スキップ)
  2. モジュールごとのカバレッジメトリクス
  3. 重大度別の監査結果
  4. ファイル:行 参照付きの推奨事項
  5. 証拠 (コマンド出力)

会話との統合

ユーザーがテストの作成を依頼した場合:

  1. テスト対象に関するコンテキストについて、会話履歴を確認する
  2. 議論されているコード/機能を特定する
  3. 不明な場合は、明確にするための質問をする:
    • "具体的にどのような動作をテストすればよいですか?"
    • "X のエッジケースを含めるべきですか?"
    • "ユニットテスト、結合テスト、または両方が必要ですか?"
  4. TDD に従う: まず失敗するテストを書き、次に実装する

利用可能なコマンド

  • /tdd-pytest:init - pytest 設定を初期化
  • /tdd-pytest:test [path] - TDD を使用してテストを作成 (コンテキストを考慮)
  • /tdd-pytest:test-all - すべてのテストを実行
  • /tdd-pytest:report - TESTING_REPORT.local.md を生成/更新
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

TDD-Pytest Skill

Activate this skill when the user needs help with:

  • Writing tests using TDD methodology (Red-Green-Refactor)
  • Auditing existing pytest test files for quality
  • Running tests with coverage
  • Generating test reports to TESTING_REPORT.local.md
  • Setting up pytest configuration in pyproject.toml

TDD Workflow

Red-Green-Refactor Cycle

  1. RED - Write a failing test first

    • Test should fail for the right reason (not import errors)
    • Test should be minimal and focused
    • Show the failing test output
  2. GREEN - Write minimal code to pass

    • Only implement what's needed to pass the test
    • No premature optimization
    • Show the passing test output
  3. REFACTOR - Improve code while keeping tests green

    • Clean up duplication
    • Improve naming
    • Extract functions/classes if needed
    • Run tests after each change

Test Organization

File Structure

project/
  src/
    module.py
  tests/
    conftest.py          # Shared fixtures
    test_module.py       # Tests for module.py
  pyproject.toml         # Pytest configuration

Naming Conventions

  • Test files: test_*.py or *_test.py
  • Test functions: test_*
  • Test classes: Test*
  • Fixtures: Descriptive names (mock_database, sample_user)

Pytest Best Practices

Fixtures

import pytest

@pytest.fixture
def sample_config():
    return {"key": "value"}

@pytest.fixture
def mock_client(mocker):
    return mocker.MagicMock()

Parametrization

@pytest.mark.parametrize("input,expected", [
    ("hello", "HELLO"),
    ("world", "WORLD"),
    ("", ""),
])
def test_uppercase(input, expected):
    assert input.upper() == expected

Async Tests

import pytest

@pytest.mark.asyncio
async def test_async_function():
    result = await async_operation()
    assert result == expected

Exception Testing

def test_raises_value_error():
    with pytest.raises(ValueError, match="invalid input"):
        process_input(None)

Running Tests

With uv

uv run pytest                              # Run all tests
uv run pytest tests/test_module.py         # Run specific file
uv run pytest -k "test_name"               # Run by name pattern
uv run pytest -v --tb=short                # Verbose with short traceback
uv run pytest --cov=src --cov-report=term  # With coverage

Common Flags

  • -v / --verbose - Detailed output
  • -x / --exitfirst - Stop on first failure
  • --tb=short - Short tracebacks
  • --tb=no - No tracebacks
  • -k EXPR - Run tests matching expression
  • -m MARKER - Run tests with marker
  • --cov=PATH - Coverage for path
  • --cov-report=term-missing - Show missing lines

pyproject.toml Configuration

Minimal Setup

[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]

Full Configuration

[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
python_functions = ["test_*"]
python_classes = ["Test*"]
addopts = "-v --tb=short"
markers = [
    "slow: marks tests as slow",
    "integration: marks integration tests",
]
filterwarnings = [
    "ignore::DeprecationWarning",
]

[tool.coverage.run]
source = ["src"]
branch = true
omit = ["tests/*", "*/__init__.py"]

[tool.coverage.report]
exclude_lines = [
    "pragma: no cover",
    "if TYPE_CHECKING:",
    "raise NotImplementedError",
]
fail_under = 80
show_missing = true

Report Generation

The TESTING_REPORT.local.md file should contain:

  1. Test execution summary (passed/failed/skipped)
  2. Coverage metrics by module
  3. Audit findings by severity
  4. Recommendations with file:line references
  5. Evidence (command outputs)

Integration with Conversation

When the user asks to write tests:

  1. Check conversation history for context about what to test
  2. Identify the code/feature being discussed
  3. If unclear, ask clarifying questions:
    • "What specific behavior should I test?"
    • "Should I include edge cases for X?"
    • "Do you want unit tests, integration tests, or both?"
  4. Follow TDD: Write failing test first, then implement

Commands Available

  • /tdd-pytest:init - Initialize pytest configuration
  • /tdd-pytest:test [path] - Write tests using TDD (context-aware)
  • /tdd-pytest:test-all - Run all tests
  • /tdd-pytest:report - Generate/update TESTING_REPORT.local.md