mcpField
P
pytest-skill

pytest-skill

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

pytest-skill について

pytest-skillは、pytestでPythonテストを作成・実行するためのスキルです。基本パターンに加え、詳しい実践手法をまとめたプレイブックを案内します。

主な機能

  1. 01フィクスチャと後処理
  2. 02パラメーター化テストとマーカー
  3. 03モックとアサーションのパターン
  4. 04テスト選択とカバレッジ計測のコマンド
  5. 05reference/playbook.mdの応用パターン

活用シーン

  1. 01テスト環境の設定と後片付けの再利用
  2. 02複数の入力と期待値をまとめて検証
  3. 03外部呼び出しをモックして例外を確認
  4. 04特定のテストの実行やカバレッジ計測

インストール

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

$npx skills add https://github.com/lambdatest/agent-skills --skill pytest-skill

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

同梱ファイルreference/advanced-patterns.mdreference/playbook.md

詳細

Pytest テストスキル

基本パターン

基本的なテスト
import pytest

def test_addition():
    assert 2 + 3 == 5

def test_exception():
    with pytest.raises(ValueError, match="invalid"):
        int("not_a_number")

class TestCalculator:
    def test_add(self):
        calc = Calculator()
        assert calc.add(2, 3) == 5

    def test_divide_by_zero(self):
        with pytest.raises(ZeroDivisionError):
            Calculator().divide(10, 0)
フィクスチャ
@pytest.fixture
def calculator():
    return Calculator()

@pytest.fixture
def db_connection():
    conn = Database.connect("test_db")
    yield conn  # teardown after yield
    conn.rollback()
    conn.close()

@pytest.fixture(scope="module")
def api_client():
    client = APIClient(base_url="http://localhost:8000")
    yield client
    client.logout()

# conftest.py - shared fixtures
@pytest.fixture(autouse=True)
def reset_state():
    State.reset()
    yield
    State.cleanup()

# Usage
def test_add(calculator):
    assert calculator.add(2, 3) == 5
パラメーター化
@pytest.mark.parametrize("input,expected", [
    ("hello", 5), ("", 0), ("pytest", 6),
])
def test_string_length(input, expected):
    assert len(input) == expected

@pytest.mark.parametrize("a,b,expected", [
    (2, 3, 5), (-1, 1, 0), (0, 0, 0),
])
def test_add(calculator, a, b, expected):
    assert calculator.add(a, b) == expected
マーカー
@pytest.mark.slow
def test_large_dataset(): ...

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

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

@pytest.mark.xfail(reason="Known bug #123")
def test_known_bug(): ...
モック
from unittest.mock import patch, MagicMock

def test_send_email(mocker):
    mock_smtp = mocker.patch("myapp.email.smtplib.SMTP")
    send_welcome_email("[email protected]")
    mock_smtp.return_value.sendmail.assert_called_once()

def test_api_call(mocker):
    mock_response = mocker.Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {"users": [{"name": "Alice"}]}
    mocker.patch("myapp.service.requests.get", return_value=mock_response)
    users = get_users()
    assert len(users) == 1

@patch("myapp.service.database")
def test_save_user(mock_db):
    mock_db.save.return_value = True
    assert save_user({"name": "Alice"}) is True
    mock_db.save.assert_called_once()
アサーション
assert x == y
assert x != y
assert x in collection
assert isinstance(obj, MyClass)
assert 0.1 + 0.2 == pytest.approx(0.3)

with pytest.raises(ValueError) as exc_info:
    raise ValueError("bad")
assert "bad" in str(exc_info.value)
アンチパターン
悪い例良い例理由
self.assertEqual()assert x == ypytest による書き換えで、より分かりやすい出力が得られます
__init__ でのセットアップ@pytest.fixtureライフサイクルを管理できます
グローバル状態yield を使ったフィクスチャ適切にクリーンアップできます
大きなテスト関数小さく、目的を絞ったテストデバッグが容易になります

クイックリファレンス

タスクコマンド
すべて実行pytest
ファイルを実行pytest tests/test_login.py
特定のテストを実行pytest tests/test_login.py::test_login_success
マーカーで指定pytest -m slow
キーワードで指定pytest -k "login and not invalid"
詳細表示pytest -v
最初の失敗で停止pytest -x
最後に失敗したテストpytest --lf
カバレッジpytest --cov=myapp --cov-report=html
並列実行pytest -n auto (pytest-xdist)

pyproject.toml

[tool.pytest.ini_options]
testpaths = ["tests"]
markers = ["slow: slow tests", "integration: integration tests"]
addopts = "-v --tb=short"

高度なパターン

本番環境向けのパターンについては、reference/playbook.md を参照してください。

セクション内容
§1 設定マーカーとカバレッジを含む pytest.ini と pyproject.toml
§2 フィクスチャスコープ、ファクトリー、ティアダウン、autouse、tmp_path
§3 パラメーター化基本、ID 付き、直積、間接
§4 モックpytest-mock、monkeypatch、スパイ、環境変数
§5 非同期処理pytest-asyncio、非同期フィクスチャ、非同期クライアント
§6 例外pytest.raises(match=)、警告
§7 マーカーとプラグインカスタムマーカー、収集フック
§8 クラスベースネストされたクラス、autouse によるセットアップ
§9 CI/CDGitHub Actions のマトリックス、カバレッジのゲート
§10 デバッグ表よくある問題10件と解決策
§11 ベストプラクティス本番環境向けチェックリスト15項目

コメント