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

pytest-mastery

pytestを使ってPythonのテスト実行、テストコード作成、フィクスチャ設定、パラメータ化、カバレッジレポート生成、FastAPIアプリのテスト、デバッグ、設定を行うなど、様々なテスト作業を効率的に進めるSkill。

📜 元の英語説明(参考)

Python testing with pytest using uv package manager. Use when: (1) Running Python tests, (2) Writing test files or test functions, (3) Setting up fixtures, (4) Parametrizing tests, (5) Generating coverage reports, (6) Testing FastAPI applications, (7) Debugging test failures, (8) Configuring pytest options. Triggers: "run tests", "write tests", "test coverage", "pytest", "unit test", "integration test", "test FastAPI".

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

一言でいうと

pytestを使ってPythonのテスト実行、テストコード作成、フィクスチャ設定、パラメータ化、カバレッジレポート生成、FastAPIアプリのテスト、デバッグ、設定を行うなど、様々なテスト作業を効率的に進めるSkill。

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

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

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

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

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

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

📖 Skill本文(日本語訳)

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

pytest と uv を用いたテスト

クイックリファレンス

# 全てのテストを実行
uv run pytest

# 詳細な出力で実行
uv run pytest -v

# 特定のファイルを実行
uv run pytest tests/test_example.py

# 特定のテスト関数を実行
uv run pytest tests/test_example.py::test_function_name

# パターンに一致するテストを実行
uv run pytest -k "pattern"

# カバレッジ付きで実行
uv run pytest --cov=src --cov-report=html

インストール

# pytest を開発依存関係として追加
uv add --dev pytest

# カバレッジサポートを追加
uv add --dev pytest-cov

# async サポートを追加 (FastAPI 用)
uv add --dev pytest-asyncio httpx

テストの検出

pytest は、以下の規約に従ってテストを自動的に検出します。

  • ファイル: test_*.py または *_test.py
  • 関数: test_*
  • クラス: Test* (__init__ メソッドを持たない)
  • メソッド: Test* クラス内の test_*

標準的なプロジェクト構造:

project/
├── src/
│   └── myapp/
├── tests/
│   ├── __init__.py
│   ├── conftest.py      # 共有フィクスチャ
│   ├── test_unit.py
│   └── integration/
│       └── test_api.py
└── pyproject.toml

フィクスチャ

フィクスチャは、再利用可能なテストのセットアップ/ティアダウンを提供します。

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_name(sample_user):
    assert sample_user["name"] == "Test User"

フィクスチャのスコープ

@pytest.fixture(scope="function")  # デフォルト: テストごとに新しいインスタンス
@pytest.fixture(scope="class")     # テストクラスごとに1回
@pytest.fixture(scope="module")    # モジュールごとに1回
@pytest.fixture(scope="session")   # テストセッションごとに1回

共有フィクスチャ (conftest.py)

自動的に利用できるようにするには、tests/conftest.py に配置します。

# tests/conftest.py
import pytest

@pytest.fixture
def api_client():
    return TestClient(app)

パラメータ化

複数の入力で同じテストを実行します。

import pytest

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

@pytest.mark.parametrize("value", [None, "", [], {}])
def test_falsy_values(value):
    assert not value

一般的なオプション

オプション 説明
-v 詳細な出力
-vv より詳細な出力
-q 静音モード
-x 最初の失敗で停止
--lf 最後に失敗したテストのみを実行
--ff 失敗したテストを最初に実行
-k "expr" 名前式でフィルタ
-m "mark" マークされたテストのみを実行
--tb=short 短いトレースバック
--tb=no トレースバックなし
-s print 文を表示
--durations=10 最も遅いテストを10個表示
-n auto 並列実行 (pytest-xdist)

カバレッジレポート

# ターミナルレポート
uv run pytest --cov=src

# HTML レポート (htmlcov/ を作成)
uv run pytest --cov=src --cov-report=html

# 最小閾値付き (下回ると失敗)
uv run pytest --cov=src --cov-fail-under=80

# 複数のレポート形式
uv run pytest --cov=src --cov-report=term --cov-report=xml

マーカー

import pytest

@pytest.mark.slow
def test_slow_operation():
    ...

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

@pytest.mark.skipif(condition, reason="...")
def test_conditional():
    ...

@pytest.mark.xfail(reason="Known bug")
def test_known_failure():
    ...

マーカーで実行:

uv run pytest -m "not slow"
uv run pytest -m "integration"

pyproject.toml の設定

[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_functions = ["test_*"]
addopts = "-v --tb=short"
markers = [
    "slow: marks tests as slow",
    "integration: integration tests",
]

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

[tool.coverage.report]
exclude_lines = [
    "pragma: no cover",
    "if TYPE_CHECKING:",
]

FastAPI のテスト

包括的な FastAPI テストパターンについては、references/fastapi-testing.md を参照してください。内容は以下の通りです。

  • TestClient のセットアップ
  • httpx を使用した Async テスト
  • データベースフィクスチャのパターン
  • 依存性のオーバーライド
  • 認証テスト

失敗したテストのデバッグ

# 完全なトレースバックで実行
uv run pytest --tb=long

# 失敗時にデバッガにドロップ
uv run pytest --pdb

# トレースバックにローカル変数を表示
uv run pytest -l

# 以前に失敗したテストのみを実行
uv run pytest --lf
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

pytest Testing with uv

Quick Reference

# Run all tests
uv run pytest

# Run with verbose output
uv run pytest -v

# Run specific file
uv run pytest tests/test_example.py

# Run specific test function
uv run pytest tests/test_example.py::test_function_name

# Run tests matching pattern
uv run pytest -k "pattern"

# Run with coverage
uv run pytest --cov=src --cov-report=html

Installation

# Add pytest as dev dependency
uv add --dev pytest

# Add coverage support
uv add --dev pytest-cov

# Add async support (for FastAPI)
uv add --dev pytest-asyncio httpx

Test Discovery

pytest automatically discovers tests following these conventions:

  • Files: test_*.py or *_test.py
  • Functions: test_*
  • Classes: Test* (no __init__ method)
  • Methods: test_* inside Test* classes

Standard project structure:

project/
├── src/
│   └── myapp/
├── tests/
│   ├── __init__.py
│   ├── conftest.py      # Shared fixtures
│   ├── test_unit.py
│   └── integration/
│       └── test_api.py
└── pyproject.toml

Fixtures

Fixtures provide reusable test setup/teardown:

import pytest

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

@pytest.fixture
def db_connection():
    conn = create_connection()
    yield conn  # Test runs here
    conn.close()  # Teardown

def test_user_name(sample_user):
    assert sample_user["name"] == "Test User"

Fixture Scopes

@pytest.fixture(scope="function")  # Default: new instance per test
@pytest.fixture(scope="class")     # Once per test class
@pytest.fixture(scope="module")    # Once per module
@pytest.fixture(scope="session")   # Once per test session

Shared Fixtures (conftest.py)

Place in tests/conftest.py for automatic availability:

# tests/conftest.py
import pytest

@pytest.fixture
def api_client():
    return TestClient(app)

Parametrization

Run same test with multiple inputs:

import pytest

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

@pytest.mark.parametrize("value", [None, "", [], {}])
def test_falsy_values(value):
    assert not value

Common Options

Option Description
-v Verbose output
-vv More verbose
-q Quiet mode
-x Stop on first failure
--lf Run last failed tests only
--ff Run failures first
-k "expr" Filter by name expression
-m "mark" Run marked tests only
--tb=short Shorter traceback
--tb=no No traceback
-s Show print statements
--durations=10 Show 10 slowest tests
-n auto Parallel execution (pytest-xdist)

Coverage Reports

# Terminal report
uv run pytest --cov=src

# HTML report (creates htmlcov/)
uv run pytest --cov=src --cov-report=html

# With minimum threshold (fails if below)
uv run pytest --cov=src --cov-fail-under=80

# Multiple report formats
uv run pytest --cov=src --cov-report=term --cov-report=xml

Markers

import pytest

@pytest.mark.slow
def test_slow_operation():
    ...

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

@pytest.mark.skipif(condition, reason="...")
def test_conditional():
    ...

@pytest.mark.xfail(reason="Known bug")
def test_known_failure():
    ...

Run by marker:

uv run pytest -m "not slow"
uv run pytest -m "integration"

pyproject.toml Configuration

[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_functions = ["test_*"]
addopts = "-v --tb=short"
markers = [
    "slow: marks tests as slow",
    "integration: integration tests",
]

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

[tool.coverage.report]
exclude_lines = [
    "pragma: no cover",
    "if TYPE_CHECKING:",
]

FastAPI Testing

See references/fastapi-testing.md for comprehensive FastAPI testing patterns including:

  • TestClient setup
  • Async testing with httpx
  • Database fixture patterns
  • Dependency overrides
  • Authentication testing

Debugging Failed Tests

# Run with full traceback
uv run pytest --tb=long

# Drop into debugger on failure
uv run pytest --pdb

# Show local variables in traceback
uv run pytest -l

# Run only previously failed
uv run pytest --lf

同梱ファイル

※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。