|
| 1 | +--- |
| 2 | +description: テストファイルでの pytest 規約 |
| 3 | +applyTo: "samples/**/test_*.py,samples/**/tests/**/*.py" |
| 4 | +--- |
| 5 | + |
| 6 | +# テスト規約(pytest) |
| 7 | + |
| 8 | +このプロジェクトのテストコードは以下の pytest 規約に従ってください。 |
| 9 | + |
| 10 | +## ファイル・関数の命名 |
| 11 | + |
| 12 | +- テストファイル: `test_<module>.py` |
| 13 | +- テスト関数: `test_<feature>_<scenario>`(例: `test_add_book_empty_title`) |
| 14 | +- テストクラス: `Test<Feature><Scenario>`(関連シナリオのグループ化用) |
| 15 | + |
| 16 | +```python |
| 17 | +class TestFindByAuthorPartialMatch: |
| 18 | + """Substring of the author name should still find matching books.""" |
| 19 | +``` |
| 20 | + |
| 21 | +## フィクスチャ |
| 22 | + |
| 23 | +- `@pytest.fixture()` を使用し、説明的な名前をつける |
| 24 | +- テストファイルの分離には `tmp_path` を使用する |
| 25 | +- フィクスチャの連鎖で複雑なセットアップを構築する |
| 26 | + |
| 27 | +```python |
| 28 | +@pytest.fixture() |
| 29 | +def collection(tmp_path): |
| 30 | + """Create a BookCollection with temporary storage.""" |
| 31 | + temp_file = tmp_path / "data.json" |
| 32 | + temp_file.write_text("[]") |
| 33 | + return BookCollection(data_file=str(temp_file)) |
| 34 | + |
| 35 | +@pytest.fixture() |
| 36 | +def orwell_collection(collection): |
| 37 | + """Collection pre-loaded with two George Orwell books.""" |
| 38 | + collection.add_book("1984", "George Orwell", 1949) |
| 39 | + collection.add_book("Animal Farm", "George Orwell", 1945) |
| 40 | + return collection |
| 41 | +``` |
| 42 | + |
| 43 | +## アサーション |
| 44 | + |
| 45 | +- シンプルな `assert` 文を使用する(`self.assertEqual` ではなく) |
| 46 | +- 例外テストには `pytest.raises` を `match` パラメータ付きで使用する |
| 47 | +- 出力キャプチャには `capsys` フィクスチャを使用する |
| 48 | + |
| 49 | +```python |
| 50 | +def test_add_book_empty_title(collection): |
| 51 | + with pytest.raises(BookValidationError, match="Title cannot be empty"): |
| 52 | + collection.add_book("", "Author", 2020) |
| 53 | +``` |
| 54 | + |
| 55 | +```python |
| 56 | +def test_handle_add_output(mock_input, mock_collection, capsys): |
| 57 | + book_app.handle_add() |
| 58 | + output = capsys.readouterr().out |
| 59 | + assert "Book added successfully" in output |
| 60 | +``` |
| 61 | + |
| 62 | +## モック |
| 63 | + |
| 64 | +- `@patch()` デコレータで外部依存をモックする |
| 65 | +- `side_effect` でユーザー入力をシミュレーションする |
| 66 | +- `assert_called_once_with` で呼び出しを検証する |
| 67 | + |
| 68 | +```python |
| 69 | +@patch("book_app.collection") |
| 70 | +@patch("builtins.input", side_effect=["The Hobbit", "Tolkien", "1937"]) |
| 71 | +def test_handle_add_valid_input(mock_input, mock_collection, capsys): |
| 72 | + book_app.handle_add() |
| 73 | + mock_collection.add_book.assert_called_once_with("The Hobbit", "Tolkien", 1937) |
| 74 | +``` |
| 75 | + |
| 76 | +## テスト構成 |
| 77 | + |
| 78 | +- 論理セクションをコメントで区切る: `# --- Adding Books ---` |
| 79 | +- 1テスト1アサーション(関連する検証はまとめてよい) |
| 80 | +- テスト間の状態汚染を防ぐため `tmp_path` で分離する |
0 commit comments