Debian Codegraph @

doc/en/example/customdirectory.rst

raw
1 .. _`custom directory collectors`:
2
3 Using a custom directory collector
4 ====================================================
5
6 By default, pytest collects directories using :class:`pytest.Package`, for directories with ``__init__.py`` files,
7 and :class:`pytest.Dir` for other directories.
8 If you want to customize how a directory is collected, you can write your own :class:`pytest.Directory` collector,
9 and use :hook:`pytest_collect_directory` to hook it up.
10
11 .. _`directory manifest plugin`:
12
13 A basic example for a directory manifest file
14 --------------------------------------------------------------
15
16 Suppose you want to customize how collection is done on a per-directory basis.
17 Here is an example ``conftest.py`` plugin that allows directories to contain a ``manifest.json`` file,
18 which defines how the collection should be done for the directory.
19 In this example, only a simple list of files is supported,
20 however you can imagine adding other keys, such as exclusions and globs.
21
22 .. include:: customdirectory/conftest.py
23 :literal:
24
25 You can create a ``manifest.json`` file and some test files:
26
27 .. include:: customdirectory/tests/manifest.json
28 :literal:
29
30 .. include:: customdirectory/tests/test_first.py
31 :literal:
32
33 .. include:: customdirectory/tests/test_second.py
34 :literal:
35
36 .. include:: customdirectory/tests/test_third.py
37 :literal:
38
39 And you can now execute the test specification:
40
41 .. code-block:: pytest
42
43 customdirectory $ pytest
44 =========================== test session starts ============================
45 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
46 rootdir: /home/sweet/project/customdirectory
47 configfile: pytest.ini
48 collected 2 items
49
50 tests/test_first.py . [ 50%]
51 tests/test_second.py . [100%]
52
53 ============================ 2 passed in 0.12s =============================
54
55 .. regendoc:wipe
56
57 Notice how ``test_three.py`` was not executed, because it is not listed in the manifest.
58
59 You can verify that your custom collector appears in the collection tree:
60
61 .. code-block:: pytest
62
63 customdirectory $ pytest --collect-only
64 =========================== test session starts ============================
65 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
66 rootdir: /home/sweet/project/customdirectory
67 configfile: pytest.ini
68 collected 2 items
69
70 <Dir customdirectory>
71 <ManifestDirectory tests>
72 <Module test_first.py>
73 <Function test_1>
74 <Module test_second.py>
75 <Function test_2>
76
77 ======================== 2 tests collected in 0.12s ========================