python-testing
Pytestを使ったPythonテストのベストプラクティスを提供するスキルで、フィクスチャ・パラメータ化・モック・カバレッジ分析・非同期テスト・テスト構成などを網羅しています。Pythonのテストコードを新規作成または改善する際に活用してください。
description の原文を見る
> Python testing best practices using pytest including fixtures, parametrization, mocking, coverage analysis, async testing, and test organization. Use when writing or improving Python tests.
SKILL.md 本文
Python Testing
このスキルはテストフレームワークとして pytest を使用した包括的な Python テストパターンを提供します。
テストフレームワーク
テストフレームワークとして pytest を使用してください。強力な機能とクリーンな構文を備えています。
基本的なテスト構造
def test_user_creation():
"""Test that a user can be created with valid data"""
user = User(name="Alice", email="alice@example.com")
assert user.name == "Alice"
assert user.email == "alice@example.com"
assert user.is_active is True
テスト検出
pytest は次の規約に従ってテストを自動的に検出します:
- ファイル:
test_*.pyまたは*_test.py - 関数:
test_* - クラス:
Test*(__init__なし) - メソッド:
test_*
Fixtures
Fixtures はテストのセットアップとクリーンアップを再利用可能にします:
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
@pytest.fixture
def db_session():
"""Provide a database session for tests"""
engine = create_engine("sqlite:///:memory:")
Session = sessionmaker(bind=engine)
session = Session()
# Setup
Base.metadata.create_all(engine)
yield session
# Teardown
session.close()
def test_user_repository(db_session):
"""Test using the db_session fixture"""
repo = UserRepository(db_session)
user = repo.create(name="Alice", email="alice@example.com")
assert user.id is not None
Fixture スコープ
@pytest.fixture(scope="function") # Default: per test
def user():
return User(name="Alice")
@pytest.fixture(scope="class") # Per test class
def database():
db = Database()
db.connect()
yield db
db.disconnect()
@pytest.fixture(scope="module") # Per module
def app():
return create_app()
@pytest.fixture(scope="session") # Once per test session
def config():
return load_config()
Fixture 依存関係
@pytest.fixture
def database():
db = Database()
db.connect()
yield db
db.disconnect()
@pytest.fixture
def user_repository(database):
"""Fixture that depends on database fixture"""
return UserRepository(database)
def test_create_user(user_repository):
user = user_repository.create(name="Alice")
assert user.id is not None
パラメーター化
@pytest.mark.parametrize を使用して複数の入力をテストします:
import pytest
@pytest.mark.parametrize("email,expected", [
("user@example.com", True),
("invalid-email", False),
("", False),
("user@", False),
("@example.com", False),
])
def test_email_validation(email, expected):
result = validate_email(email)
assert result == expected
複数のパラメーター
@pytest.mark.parametrize("name,age,valid", [
("Alice", 25, True),
("Bob", 17, False),
("", 25, False),
("Charlie", -1, False),
])
def test_user_validation(name, age, valid):
result = validate_user(name, age)
assert result == valid
ID 付きパラメーター化
@pytest.mark.parametrize("input,expected", [
("hello", "HELLO"),
("world", "WORLD"),
], ids=["lowercase", "another_lowercase"])
def test_uppercase(input, expected):
assert input.upper() == expected
テストマーカー
テストの分類と選択的実行にマーカーを使用します:
import pytest
@pytest.mark.unit
def test_calculate_total():
"""Fast unit test"""
assert calculate_total([1, 2, 3]) == 6
@pytest.mark.integration
def test_database_connection():
"""Slower integration test"""
db = Database()
assert db.connect() is True
@pytest.mark.slow
def test_large_dataset():
"""Very slow test"""
process_million_records()
@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
pass
@pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires Python 3.10+")
def test_new_syntax():
pass
特定のマーカーを実行:
pytest -m unit # Run only unit tests
pytest -m "not slow" # Skip slow tests
pytest -m "unit or integration" # Run unit OR integration
モッキング
unittest.mock の使用
from unittest.mock import Mock, patch, MagicMock
def test_user_service_with_mock():
"""Test with mock repository"""
mock_repo = Mock()
mock_repo.find_by_id.return_value = User(id="1", name="Alice")
service = UserService(mock_repo)
user = service.get_user("1")
assert user.name == "Alice"
mock_repo.find_by_id.assert_called_once_with("1")
@patch('myapp.services.EmailService')
def test_send_notification(mock_email_service):
"""Test with patched dependency"""
service = NotificationService()
service.send("user@example.com", "Hello")
mock_email_service.send.assert_called_once()
pytest-mock プラグイン
def test_with_mocker(mocker):
"""Using pytest-mock plugin"""
mock_repo = mocker.Mock()
mock_repo.find_by_id.return_value = User(id="1", name="Alice")
service = UserService(mock_repo)
user = service.get_user("1")
assert user.name == "Alice"
カバレッジ分析
基本的なカバレッジ
pytest --cov=src --cov-report=term-missing
HTML カバレッジレポート
pytest --cov=src --cov-report=html
open htmlcov/index.html
カバレッジ設定
# pytest.ini or pyproject.toml
[tool.pytest.ini_options]
addopts = """
--cov=src
--cov-report=term-missing
--cov-report=html
--cov-fail-under=80
"""
ブランチカバレッジ
pytest --cov=src --cov-branch
非同期テスト
非同期関数のテスト
import pytest
@pytest.mark.asyncio
async def test_async_fetch_user():
"""Test async function"""
user = await fetch_user("1")
assert user.name == "Alice"
@pytest.fixture
async def async_client():
"""Async fixture"""
client = AsyncClient()
await client.connect()
yield client
await client.disconnect()
@pytest.mark.asyncio
async def test_with_async_fixture(async_client):
result = await async_client.get("/users/1")
assert result.status == 200
テスト構成
ディレクトリ構造
tests/
├── unit/
│ ├── test_models.py
│ ├── test_services.py
│ └── test_utils.py
├── integration/
│ ├── test_database.py
│ └── test_api.py
├── conftest.py # Shared fixtures
└── pytest.ini # Configuration
conftest.py
# tests/conftest.py
import pytest
@pytest.fixture(scope="session")
def app():
"""Application fixture available to all tests"""
return create_app()
@pytest.fixture
def client(app):
"""Test client fixture"""
return app.test_client()
def pytest_configure(config):
"""Register custom markers"""
config.addinivalue_line("markers", "unit: Unit tests")
config.addinivalue_line("markers", "integration: Integration tests")
config.addinivalue_line("markers", "slow: Slow tests")
アサーション
基本的なアサーション
def test_assertions():
assert value == expected
assert value != other
assert value > 0
assert value in collection
assert isinstance(value, str)
より良いエラーメッセージ付きの pytest アサーション
def test_with_context():
"""pytest provides detailed assertion introspection"""
result = calculate_total([1, 2, 3])
expected = 6
# pytest shows: assert 5 == 6
assert result == expected
カスタムアサーションメッセージ
def test_with_message():
result = process_data(input_data)
assert result.is_valid, f"Expected valid result, got errors: {result.errors}"
近似比較
import pytest
def test_float_comparison():
result = 0.1 + 0.2
assert result == pytest.approx(0.3)
# With tolerance
assert result == pytest.approx(0.3, abs=1e-9)
例外テスト
import pytest
def test_raises_exception():
"""Test that function raises expected exception"""
with pytest.raises(ValueError):
validate_age(-1)
def test_exception_message():
"""Test exception message"""
with pytest.raises(ValueError, match="Age must be positive"):
validate_age(-1)
def test_exception_details():
"""Capture and inspect exception"""
with pytest.raises(ValidationError) as exc_info:
validate_user(name="", age=-1)
assert "name" in exc_info.value.errors
assert "age" in exc_info.value.errors
テストヘルパー
# tests/helpers.py
def assert_user_equal(actual, expected):
"""Custom assertion helper"""
assert actual.id == expected.id
assert actual.name == expected.name
assert actual.email == expected.email
def create_test_user(**kwargs):
"""Test data factory"""
defaults = {
"name": "Test User",
"email": "test@example.com",
"age": 25,
}
defaults.update(kwargs)
return User(**defaults)
プロパティベーステスト
hypothesis を使用したプロパティベーステスト:
from hypothesis import given, strategies as st
@given(st.integers(), st.integers())
def test_addition_commutative(a, b):
"""Test that addition is commutative"""
assert a + b == b + a
@given(st.lists(st.integers()))
def test_sort_idempotent(lst):
"""Test that sorting twice gives same result"""
sorted_once = sorted(lst)
sorted_twice = sorted(sorted_once)
assert sorted_once == sorted_twice
ベストプラクティス
- テストごとに 1 つのアサーション (可能な限り)
- 説明的なテスト名を使用 - テスト対象を説明する
- Arrange-Act-Assert パターン - テスト構造を明確にする
- セットアップに fixture を使用 - 重複を避ける
- 外部依存関係をモック - テストを高速かつ分離させる
- エッジケースをテスト - 空の入力、None、境界値
- parametrize を使用 - 複数のシナリオを効率的にテスト
- テストを独立させる - テスト間で共有状態を持たない
テストの実行
# Run all tests
pytest
# Run specific file
pytest tests/test_user.py
# Run specific test
pytest tests/test_user.py::test_create_user
# Run with verbose output
pytest -v
# Run with output capture disabled
pytest -s
# Run in parallel (requires pytest-xdist)
pytest -n auto
# Run only failed tests from last run
pytest --lf
# Run failed tests first
pytest --ff
このスキルを使用するタイミング
- 新しい Python テストを書く
- テストカバレッジを改善する
- pytest インフラストラクチャをセットアップする
- 不安定なテストをデバッグする
- 統合テストを実装する
- 非同期 Python コードをテストする
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- affaan-m
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/affaan-m/everything-claude-code / ライセンス: MIT
関連スキル
doubt-driven-development
重要な判断はすべて、本番環境への展開前に新しい視点から対抗的レビューを実施します。速度より正確性が重要な場合、不慣れなコードを扱う場合、本番環境・セキュリティに関わるロジック・取り消し不可の操作など影響度が高い場合、または後でバグを修正するよりも今検証する方が効率的な場合に活用してください。
apprun-skills
TypeScriptを使用したAppRunアプリケーションのMVU設計に関する総合的なガイダンスが得られます。コンポーネントパターン、イベントハンドリング、状態管理(非同期ジェネレータを含む)、パラメータと保護機能を備えたルーティング・ナビゲーション、vistestを使用したテストに対応しています。AppRunコンポーネントの設計・レビュー、ルートの配線、状態フローの管理、AppRunテストの作成時に活用してください。
desloppify
コードベースのヘルスチェックと技術負債の追跡ツールです。コード品質、技術負債、デッドコード、大規模ファイル、ゴッドクラス、重複関数、コードスメル、命名規則の問題、インポートサイクル、結合度の問題についてユーザーが質問した場合に使用してください。また、ヘルススコアの確認、次の改善項目の提案、クリーンアップ計画の作成をリクエストされた際にも対応します。29言語に対応しています。
debugging-and-error-recovery
テストが失敗したり、ビルドが壊れたり、動作が期待と異なったり、予期しないエラーが発生したりした場合に、体系的な根本原因デバッグをガイドします。推測ではなく、根本原因を見つけて修正するための体系的なアプローチが必要な場合に使用してください。
test-driven-development
テスト駆動開発により実装を進めます。ロジックの実装、バグの修正、動作の変更など、あらゆる場面で活用できます。コードが正常に動作することを証明する必要がある場合、バグ報告を受けた場合、既存機能を修正する予定がある場合に使用してください。
incremental-implementation
変更を段階的に実施します。複数のファイルに影響する機能や変更を実装する場合に使用してください。大量のコードを一度に書こうとしている場合や、タスクが一度では完結できないほど大きい場合に活用します。