mcpField
P
python-testing

python-testing

github.com/autumnsgroveテスト・品質672 回インストール6 日前に更新
リポジトリ

python-testing について

python-testingは、テストを作成・実行するPython開発者やコーディングエージェント向けのスキルです。pytestの構成、フィクスチャ、モック、カバレッジ設定を扱います。

主な機能

  1. 01pytestの設定と実行
  2. 02Arrange-Act-Assert形式のテスト
  3. 03フィクスチャとパラメータ化テスト
  4. 04モック、例外、一時ファイルのテスト
  5. 05カバレッジ設定と命名規則

活用シーン

  1. 01Pythonコードの単体テスト作成
  2. 02pytestと共有フィクスチャの設定
  3. 03API呼び出しのモックとエラー検証
  4. 04テスト実行とカバレッジ確認

インストール

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

$npx skills add https://github.com/autumnsgrove/lattice --skill python-testing

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

詳細

Python テストスキル

有効化するタイミング

次の場合にこのスキルを有効にします:

  • Python のユニットテストを作成するとき
  • テストファイルやテストディレクトリを作成するとき
  • pytest の設定を行うとき
  • テストフィクスチャやモックを扱うとき
  • テストを実行したり、カバレッジを確認したりするとき

クイックコマンド

# Run all tests
uv run pytest

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

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

# Run verbose with output
uv run pytest -v -s

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

# Run last failed
uv run pytest --lf

テスト構造:AAA パターン

明確で保守しやすいテストにするため、Arrange-Act-Assert に従います:

def test_user_registration():
    # Arrange - set up test data
    email = "[email protected]"
    password = "secure_pass123"
    user_service = UserService()

    # Act - execute the function
    result = user_service.register(email, password)

    # Assert - verify the outcome
    assert result.success is True
    assert result.user.email == email

ディレクトリ構造

project/
├── src/
│   └── myapp/
├── tests/
│   ├── conftest.py      # Shared fixtures
│   ├── unit/
│   │   └── test_utils.py
│   ├── integration/
│   │   └── test_api.py
│   └── e2e/
│       └── test_workflows.py
└── pyproject.toml

フィクスチャ(conftest.py)

import pytest
from myapp import create_app

@pytest.fixture
def app():
    """Create application for testing."""
    app = create_app("testing")
    yield app

@pytest.fixture
def client(app):
    """Create test client."""
    return app.test_client()

@pytest.fixture
def sample_user():
    """Create a sample user for testing."""
    return User(email="[email protected]", username="testuser")

パラメーター化テスト

@pytest.mark.parametrize("email,expected", [
    ("[email protected]", True),
    ("invalid.email", False),
    ("[email protected]", True),
])
def test_email_validation(email, expected):
    assert is_valid_email(email) == expected

モック

from unittest.mock import Mock, patch

def test_api_call():
    mock_response = Mock()
    mock_response.json.return_value = {"data": "success"}

    with patch("requests.get", return_value=mock_response):
        result = fetch_data("https://api.example.com")
        assert result == {"data": "success"}

よく使われるパターン

例外のテスト
def test_division_by_zero():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(10, 0)
一時ファイルを使ったテスト
def test_file_processing(tmp_path):
    test_file = tmp_path / "test.txt"
    test_file.write_text("Hello World")
    result = process_file(str(test_file))
    assert result.word_count == 2
環境変数のテスト
def test_config_from_env(monkeypatch):
    monkeypatch.setenv("API_KEY", "test_key_123")
    assert load_config().api_key == "test_key_123"

カバレッジの設定

# pyproject.toml
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --cov=src --cov-report=term-missing"

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

命名規則

  • テストファイル:test_*.py
  • テスト関数:test_*
  • テストクラス:Test*

関連リソース

詳しいドキュメントについては、以下を含む AgentUsage/testing_python.md を参照してください:

  • 非同期テストのパターン
  • 統合テストの例
  • CI/CD との統合
  • テストの優先度に関するガイドライン

コメント