Debian Codegraph @

doc/en/example/pythoncollection.rst

raw
1 Changing standard (Python) test discovery
2 ===============================================
3
4 Ignore paths during test collection
5 -----------------------------------
6
7 You can easily ignore certain test directories and modules during collection
8 by passing the :option:`--ignore=path` option on the cli. ``pytest`` allows multiple
9 ``--ignore`` options. Example:
10
11 .. code-block:: text
12
13 tests/
14 |-- example
15 | |-- test_example_01.py
16 | |-- test_example_02.py
17 | '-- test_example_03.py
18 |-- foobar
19 | |-- test_foobar_01.py
20 | |-- test_foobar_02.py
21 | '-- test_foobar_03.py
22 '-- hello
23 '-- world
24 |-- test_world_01.py
25 |-- test_world_02.py
26 '-- test_world_03.py
27
28 Now if you invoke ``pytest`` with ``--ignore=tests/foobar/test_foobar_03.py --ignore=tests/hello/``,
29 you will see that ``pytest`` only collects test-modules, which do not match the patterns specified:
30
31 .. code-block:: pytest
32
33 =========================== test session starts ============================
34 platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
35 rootdir: $REGENDOC_TMPDIR, inifile:
36 collected 5 items
37
38 tests/example/test_example_01.py . [ 20%]
39 tests/example/test_example_02.py . [ 40%]
40 tests/example/test_example_03.py . [ 60%]
41 tests/foobar/test_foobar_01.py . [ 80%]
42 tests/foobar/test_foobar_02.py . [100%]
43
44 ========================= 5 passed in 0.02 seconds =========================
45
46 The :option:`--ignore-glob` option allows to ignore test file paths based on Unix shell-style wildcards.
47 If you want to exclude test-modules that end with ``_01.py``, execute ``pytest`` with :option:`--ignore-glob='*_01.py'`.
48
49 Deselect tests during test collection
50 -------------------------------------
51
52 Tests can individually be deselected during collection by passing the :option:`--deselect=item` option.
53 For example, say ``tests/foobar/test_foobar_01.py`` contains ``test_a`` and ``test_b``.
54 You can run all of the tests within ``tests/`` *except* for ``tests/foobar/test_foobar_01.py::test_a``
55 by invoking ``pytest`` with ``--deselect=tests/foobar/test_foobar_01.py::test_a``.
56 ``pytest`` allows multiple ``--deselect`` options.
57
58 .. _duplicate-paths:
59
60 Keeping duplicate paths specified from command line
61 ----------------------------------------------------
62
63 Default behavior of ``pytest`` is to ignore duplicate paths specified from the command line.
64 Example:
65
66 .. code-block:: pytest
67
68 pytest path_a path_a
69
70 ...
71 collected 1 item
72 ...
73
74 Just collect tests once.
75
76 To collect duplicate tests, use the :option:`--keep-duplicates` option on the cli.
77 Example:
78
79 .. code-block:: pytest
80
81 pytest --keep-duplicates path_a path_a
82
83 ...
84 collected 2 items
85 ...
86
87
88 Changing directory recursion
89 -----------------------------------------------------
90
91 You can set the :confval:`norecursedirs` option in a configuration file:
92
93 .. code-block:: toml
94
95 # content of pytest.toml
96 [pytest]
97 norecursedirs = [".svn", "_build", "tmp*"]
98
99 This would tell ``pytest`` to not recurse into typical subversion or sphinx-build directories or into any ``tmp`` prefixed directory.
100
101 .. _`change naming conventions`:
102
103 Changing naming conventions
104 -----------------------------------------------------
105
106 You can configure different naming conventions by setting
107 the :confval:`python_files`, :confval:`python_classes` and
108 :confval:`python_functions` in your :ref:`configuration file <config file formats>`.
109 Here is an example:
110
111 .. code-block:: toml
112
113 # content of pytest.toml
114 # Example 1: have pytest look for "check" instead of "test"
115 [pytest]
116 python_files = ["check_*.py"]
117 python_classes = ["Check"]
118 python_functions = ["*_check"]
119
120 This would make ``pytest`` look for tests in files that match the ``check_*
121 .py`` glob-pattern, ``Check`` prefixes in classes, and functions and methods
122 that match ``*_check``. For example, if we have:
123
124 .. code-block:: python
125
126 # content of check_myapp.py
127 class CheckMyApp:
128 def simple_check(self):
129 pass
130
131 def complex_check(self):
132 pass
133
134 The test collection would look like this:
135
136 .. code-block:: pytest
137
138 $ pytest --collect-only
139 =========================== test session starts ============================
140 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
141 rootdir: /home/sweet/project
142 configfile: pytest.toml
143 collected 2 items
144
145 <Dir pythoncollection.rst-216>
146 <Module check_myapp.py>
147 <Class CheckMyApp>
148 <Function simple_check>
149 <Function complex_check>
150
151 ======================== 2 tests collected in 0.12s ========================
152
153 You can check for multiple glob patterns by adding a space between the patterns:
154
155 .. code-block:: toml
156
157 # content of pytest.toml
158 # Example 2: have pytest look for files with "test" and "example"
159 [pytest]
160 python_files = ["test_*.py", "example_*.py"]
161
162 .. note::
163
164 the ``python_functions`` and ``python_classes`` options have no effect
165 for ``unittest.TestCase`` test discovery because pytest delegates
166 discovery of test case methods to unittest code.
167
168 Interpreting cmdline arguments as Python packages
169 -----------------------------------------------------
170
171 You can use the :option:`--pyargs` option to make ``pytest`` try
172 interpreting arguments as python package names, deriving
173 their file system path and then running the test. For
174 example if you have unittest2 installed you can type:
175
176 .. code-block:: bash
177
178 pytest --pyargs unittest2.test.test_skipping -q
179
180 which would run the respective test module. Like with
181 other options, through a configuration file and the :confval:`addopts` option you
182 can make this change more permanently:
183
184 .. code-block:: toml
185
186 # content of pytest.toml
187 [pytest]
188 addopts = ["--pyargs"]
189
190 Now a simple invocation of ``pytest NAME`` will check
191 if NAME exists as an importable package/module and otherwise
192 treat it as a filesystem path.
193
194 Finding out what is collected
195 -----------------------------------------------
196
197 You can always peek at the collection tree without running tests like this:
198
199 .. code-block:: pytest
200
201 . $ pytest --collect-only pythoncollection.py
202 =========================== test session starts ============================
203 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
204 rootdir: /home/sweet/project
205 configfile: pytest.toml
206 collected 3 items
207
208 <Dir pythoncollection.rst-216>
209 <Dir CWD>
210 <Module pythoncollection.py>
211 <Function test_function>
212 <Class TestClass>
213 <Function test_method>
214 <Function test_anothermethod>
215
216 ======================== 3 tests collected in 0.12s ========================
217
218 .. _customizing-test-collection:
219
220 Customizing test collection
221 ---------------------------
222
223 .. regendoc:wipe
224
225 You can easily instruct ``pytest`` to discover tests from every Python file:
226
227 .. code-block:: toml
228
229 # content of pytest.toml
230 [pytest]
231 python_files = ["*.py"]
232
233 However, many projects will have a ``setup.py`` which they don't want to be
234 imported. Moreover, there may be files only importable by a specific python
235 version. For such cases you can dynamically define files to be ignored by
236 listing them in a ``conftest.py`` file:
237
238 .. code-block:: python
239
240 # content of conftest.py
241 import sys
242
243 collect_ignore = ["setup.py"]
244 if sys.version_info[0] > 2:
245 collect_ignore.append("pkg/module_py2.py")
246
247 and then if you have a module file like this:
248
249 .. code-block:: python
250
251 # content of pkg/module_py2.py
252 def test_only_on_python2():
253 try:
254 assert 0
255 except Exception, e:
256 pass
257
258 and a ``setup.py`` dummy file like this:
259
260 .. code-block:: python
261
262 # content of setup.py
263 0 / 0 # will raise exception if imported
264
265 If you run with a Python 2 interpreter then you will find the one test and will
266 leave out the ``setup.py`` file:
267
268 .. code-block:: pytest
269
270 #$ pytest --collect-only
271 ====== test session starts ======
272 platform linux2 -- Python 2.7.10, pytest-2.9.1, py-1.4.31, pluggy-0.3.1
273 rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini
274 collected 1 items
275 <Module 'pkg/module_py2.py'>
276 <Function 'test_only_on_python2'>
277
278 ====== 1 tests found in 0.04 seconds ======
279
280 If you run with a Python 3 interpreter both the one test and the ``setup.py``
281 file will be left out:
282
283 .. code-block:: pytest
284
285 $ pytest --collect-only
286 =========================== test session starts ============================
287 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
288 rootdir: /home/sweet/project
289 configfile: pytest.toml
290 collected 0 items
291
292 ======================= no tests collected in 0.12s ========================
293
294 It's also possible to ignore files based on Unix shell-style wildcards by adding
295 patterns to :globalvar:`collect_ignore_glob`.
296
297 The following example ``conftest.py`` ignores the file ``setup.py`` and in
298 addition all files that end with ``*_py2.py`` when executed with a Python 3
299 interpreter:
300
301 .. code-block:: python
302
303 # content of conftest.py
304 import sys
305
306 collect_ignore = ["setup.py"]
307 if sys.version_info[0] > 2:
308 collect_ignore_glob = ["*_py2.py"]
309
310 Since Pytest 2.6, users can prevent pytest from discovering classes that start
311 with ``Test`` by setting a boolean ``__test__`` attribute to ``False``.
312
313 .. code-block:: python
314
315 # Will not be discovered as a test
316 class TestClass:
317 __test__ = False
318
319 .. note::
320
321 If you are working with abstract test classes and want to avoid manually setting
322 the ``__test__`` attribute for subclasses, you can use a mixin class to handle
323 this automatically. For example:
324
325 .. code-block:: python
326
327 # Mixin to handle abstract test classes
328 class NotATest:
329 def __init_subclass__(cls):
330 cls.__test__ = NotATest not in cls.__bases__
331
332
333 # Abstract test class
334 class AbstractTest(NotATest):
335 pass
336
337
338 # Subclass that will be collected as a test
339 class RealTest(AbstractTest):
340 def test_example(self):
341 assert 1 + 1 == 2
342
343 This approach ensures that subclasses of abstract test classes are automatically
344 collected without needing to explicitly set the ``__test__`` attribute.