python-testinglisted
Install: claude install-skill adomot/claude-settings
# Pythonテストパターン
pytest、TDD方法論、ベストプラクティスを使用したPythonアプリケーションの包括的なテスト戦略。
## 起動条件
- 新しいPythonコードの記述(TDDに従う: red、green、refactor)
- Pythonプロジェクトのテストスイート設計
- Pythonテストカバレッジのレビュー
- テストインフラの構築
## テストの基本哲学
### テスト駆動開発(TDD)
常にTDDサイクルに従う:
1. **RED**: 期待する振る舞いの失敗テストを書く
2. **GREEN**: テストをパスする最小限のコードを書く
3. **REFACTOR**: テストをグリーンに保ちながらコードを改善
```python
# ステップ1: 失敗テストを書く(RED)
def test_add_numbers():
result = add(2, 3)
assert result == 5
# ステップ2: 最小限の実装を書く(GREEN)
def add(a, b):
return a + b
# ステップ3: 必要に応じてリファクタリング(REFACTOR)
```
### カバレッジ要件
- **目標**: 80%以上のコードカバレッジ
- **クリティカルパス**: 100%のカバレッジが必要
- `pytest --cov` でカバレッジを計測
```bash
pytest --cov=mypackage --cov-report=term-missing --cov-report=html
```
## pytest基礎
### 基本的なテスト構造
```python
import pytest
def test_addition():
"""基本的な足し算のテスト。"""
assert 2 + 2 == 4
def test_string_uppercase():
"""文字列の大文字化のテスト。"""
text = "hello"
assert text.upper() == "HELLO"
def test_list_append():
"""リストのappendのテスト。"""
items = [1, 2, 3]
items.append(4)
assert 4 in items
assert len(items) == 4
```
### アサーション
```python
# 等値
assert result == expected
# 非等値
assert result != unexpected
# 真偽値
assert result # Truthy
assert not result # Falsy
assert result is True # 厳密にTrue
assert result is False # 厳密にFalse
assert result is None # 厳密にNone
# 所属
assert item in collection
assert item not in collection
# 比較
assert result > 0
assert 0 <= result <= 100
# 型チェック
assert isinstance(result, str)
# 例外テスト(推奨アプ