使用自訂目錄收集器¶
預設情況下,pytest 使用 pytest.Package
收集目錄,針對包含 __init__.py
檔案的目錄,以及 pytest.Dir
針對其他目錄。如果您想要自訂目錄的收集方式,您可以撰寫自己的 pytest.Directory
收集器,並使用 pytest_collect_directory
進行連結。
目錄清單檔案的基本範例¶
假設您想要自訂每個目錄的收集方式。以下是 conftest.py
外掛程式範例,允許目錄包含 manifest.json
檔案,定義如何針對目錄進行收集。在此範例中,僅支援檔案的簡單清單,但您可以想像新增其他金鑰,例如排除和 glob。
# content of conftest.py
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 `mainfest.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
def test_1():
pass
# content of test_second.py
def test_2():
pass
# content of test_third.py
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 ========================