python-testing-patterns
できること
このガイドでは、Pythonコードを十分にテストする方法を学べます。pytestなどのツールの使い方、プログラムの各部分に対するテストの作成方法、そしてテストをより効果的にするための外部コンポーネントの模擬(シミュレート)方法を説明します。
使う場面
- ✓Pythonコードのテストを書くとき。
- ✓テストスイートや、テストを実行するための構成を整理するとき。
- ✓公開する前に、コードが期待どおりに動作することを確認したいとき。
スキルのリンク
https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-testing-patterns/SKILL.mdコピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。
使い方
いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。
貼り付け用メッセージ
Claude Code、Codex、Cursorの場合:プロジェクトのフォルダで実行するとスキルがインストールされます。
SKILL.mdをダウンロードして、エージェントのスキル用フォルダに入れてください。
AIへの頼み方の例
“Pythonで2つの数値を足し算する関数の、簡単なテストを書くにはどうすればよいですか?”
毎週5つの新しいスキル。1分で読めます。
仕組み
このガイドでは、さまざまな種類のテストと、その構成方法を解説しています。また、テストにわかりやすい名前を付ける方法や、外部の依存関係を模擬したり、時間を制御したりするツールの使い方の例も紹介しています。
技術的な内容(元のSKILL.md)
作者による元のテキスト(英語)をGitHubからそのまま表示しています。
Python Testing Patterns
Comprehensive guide to implementing robust testing strategies in Python using pytest, fixtures, mocking, parameterization, and test-driven development practices.
When to Use This Skill
- Writing unit tests for Python code
- Setting up test suites and test infrastructure
- Implementing test-driven development (TDD)
- Creating integration tests for APIs and services
- Mocking external dependencies and services
- Testing async code and concurrent operations
- Setting up continuous testing in CI/CD
- Implementing property-based testing
- Testing database operations
- Debugging failing tests
Core Concepts
1. Test Types
- Unit Tests: Test individual functions/classes in isolation
- Integration Tests: Test interaction between components
- Functional Tests: Test complete features end-to-end
- Performance Tests: Measure speed and resource usage
2. Test Structure (AAA Pattern)
- Arrange: Set up test data and preconditions
- Act: Execute the code under test
- Assert: Verify the results
3. Test Coverage
- Measure what code is exercised by tests
- Identify untested code paths
- Aim for meaningful coverage, not just high percentages
4. Test Isolation
- Tests should be independent
- No shared state between tests
- Each test should clean up after itself
Quick Start
# test_example.py
def add(a, b):
return a + b
def test_add():
"""Basic test example."""
result = add(2, 3)
assert result == 5
def test_add_negative():
"""Test with negative numbers."""
assert add(-1, 1) == 0
# Run with: pytest test_example.py
Detailed patterns and worked examples
Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.
Testing Best Practices
Test Organization
# tests/
# __init__.py
# conftest.py # Shared fixtures
# test_unit/ # Unit tests
# test_models.py
# test_utils.py
# test_integration/ # Integration tests
# test_api.py
# test_database.py
# test_e2e/ # End-to-end tests
# test_workflows.py
Test Naming Convention
A common pattern: test_<unit>_<scenario>_<expected_outcome>. Adapt to your team's preferences.
# Pattern: test_<unit>_<scenario>_<expected>
def test_create_user_with_valid_data_returns_user():
...
def test_create_user_with_duplicate_email_raises_conflict():
...
def test_get_user_with_unknown_id_returns_none():
...
# Good test names - clear and descriptive
def test_user_creation_with_valid_data():
"""Clear name describes what is being tested."""
pass
def test_login_fails_with_invalid_password():
"""Name describes expected behavior."""
pass
def test_api_returns_404_for_missing_resource():
"""Specific about inputs and expected outcomes."""
pass
# Bad test names - avoid these
def test_1(): # Not descriptive
pass
def test_user(): # Too vague
pass
def test_function(): # Doesn't explain what's tested
pass
Testing Retry Behavior
Verify that retry logic works correctly using mock side effects.
from unittest.mock import Mock
def test_retries_on_transient_error():
"""Test that service retries on transient failures."""
client = Mock()
# Fail twice, then succeed
client.request.side_effect = [
ConnectionError("Failed"),
ConnectionError("Failed"),
{"status": "ok"},
]
service = ServiceWithRetry(client, max_retries=3)
result = service.fetch()
assert result == {"status": "ok"}
assert client.request.call_count == 3
def test_gives_up_after_max_retries():
"""Test that service stops retrying after max attempts."""
client = Mock()
client.request.side_effect = ConnectionError("Failed")
service = ServiceWithRetry(client, max_retries=3)
with pytest.raises(ConnectionError):
service.fetch()
assert client.request.call_count == 3
def test_does_not_retry_on_permanent_error():
"""Test that permanent errors are not retried."""
client = Mock()
client.request.side_effect = ValueError("Invalid input")
service = ServiceWithRetry(client, max_retries=3)
with pytest.raises(ValueError):
service.fetch()
# Only called once - no retry for ValueError
assert client.request.call_count == 1
Mocking Time with Freezegun
…
よくある質問
単体テストと結合テストとは何ですか?
単体テストは、コードの小さな部分を単独で確認するテストです。一方、結合テストは、コードの異なる部分が連携して正しく動くかを確認するテストです。
「モッキング」とは何ですか?
ネットワーク通信やデータベースなどの一部を偽物に置き換えることです。これにより、外部の要素に頼らずに本体のコードをテストできます。
TDD(テスト駆動開発)とは何ですか?
実際のコードを書く前にテストを書き、そのテストで定められた要件をコードが満たすようにする開発手法です。
詳細
作者による元の説明
Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development. Use when writing Python tests, setting up test suites, or implementing testing best practices.
repo: wshobson/agents
人気
- GitHubのスター
- 41k
- ランキング
- #6768
- ライセンス
- MIT
- 更新日
- 2026/10/15
コメント
- …
このリポジトリの他のスキル
screen-reader-testing
41kエージェントにスクリーンリーダーを使ってWebサイトをテストさせ、アクセシビリティを確認します。
wcag-audit-patterns
41kエージェントがWebサイトのアクセシビリティを監査し、WCAGガイドラインに沿って問題を修正できるようにします。
multi-reviewer-patterns
41kエージェントが複数のコードレビューを並行して調整できるようにします。指摘事項の重複を排除し、レポートにまとめます。
parallel-debugging
41kエージェントが並行調査と根本原因分析を使って、複雑な問題をデバッグできるようにします。
似ているスキル
test-driven-development
311k機能や修正を作る前に、まず失敗するテストを書き、それが失敗するのを確認してから、合格させる最小のコードを書くようエージェントに教えます。
verification-before-completion
311kタスク、修正、ビルドが完了した、または合格したと主張する前に、実際のチェックを実行し、その出力を読むようエージェントに教えます。
migrate-to-shoehorn
310kテストファイル内の危険な型キャストを、shoehornライブラリに置き換え、テストが部分的なデータを使いつつ型チェックを通るようにします。