カスタムディレクトリコレクタの使用¶
デフォルトでは、pytest は __init__.py ファイルを持つディレクトリに対して pytest.Package、その他のディレクトリに対して pytest.Dir を使用してディレクトリを収集します。 ディレクトリの収集方法をカスタマイズする場合は、独自の pytest.Directory コレクタを記述し、pytest_collect_directory を使用してそれをフックアップできます。
ディレクトリマニフェストファイルの基本的な例¶
ディレクトリごとに収集方法をカスタマイズしたいとします。 ディレクトリに manifest.json ファイルを含めることで、ディレクトリの収集方法を定義できる conftest.py プラグインの例があります。 この例では、ファイルの単純なリストのみがサポートされていますが、他のキー (除外やグロブなど) を追加することもできます。
# content of conftest.py
from __future__ import annotations
import json
import pytest
class ManifestDirectory(pytest.Directory):
def collect(self):
# The standard pytest behavior is to loop over all `test_*.py` files and
# call `pytest_collect_file` on each file. This collector instead reads
# the `manifest.json` file and only calls `pytest_collect_file` for the
# files defined there.
manifest_path = self.path / "manifest.json"
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
ihook = self.ihook
for file in manifest["files"]:
yield from ihook.pytest_collect_file(
file_path=self.path / file, parent=self
)
@pytest.hookimpl
def pytest_collect_directory(path, parent):
# Use our custom collector for directories containing a `manifest.json` file.
if path.joinpath("manifest.json").is_file():
return ManifestDirectory.from_parent(parent=parent, path=path)
# Otherwise fallback to the standard behavior.
return None
manifest.json ファイルといくつかのテストファイルを作成できます:
{
"files": [
"test_first.py",
"test_second.py"
]
}
# content of test_first.py
from __future__ import annotations
def test_1():
pass
# content of test_second.py
from __future__ import annotations
def test_2():
pass
# content of test_third.py
from __future__ import annotations
def test_3():
pass
テスト仕様を実行できます:
customdirectory $ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project/customdirectory
configfile: pytest.ini
collected 2 items
tests/test_first.py . [ 50%]
tests/test_second.py . [100%]
============================ 2 passed in 0.12s =============================
test_three.py が実行されなかったことに注意してください。 これはマニフェストに記載されていないためです。
カスタムコレクタがコレクションツリーに表示されることを確認できます:
customdirectory $ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project/customdirectory
configfile: pytest.ini
collected 2 items
<Dir customdirectory>
<ManifestDirectory tests>
<Module test_first.py>
<Function test_1>
<Module test_second.py>
<Function test_2>
======================== 2 tests collected in 0.12s ========================