Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/doc/en/how-to/skipping.rst

raw
1 .. _`skip and xfail`:
2
3 .. _skipping:
4
5 How to use skip and xfail to deal with tests that cannot succeed
6 =================================================================
7
8 You can mark test functions that cannot be run on certain platforms
9 or that you expect to fail so pytest can deal with them accordingly and
10 present a summary of the test session, while keeping the test suite *green*.
11
12 A **skip** means that you expect your test to pass only if some conditions are met,
13 otherwise pytest should skip running the test altogether. Common examples are skipping
14 windows-only tests on non-windows platforms, or skipping tests that depend on an external
15 resource which is not available at the moment (for example a database).
16
17 An **xfail** means that you expect a test to fail for some reason.
18 A common example is a test for a feature not yet implemented, or a bug not yet fixed.
19 When a test passes despite being expected to fail (marked with ``pytest.mark.xfail``),
20 it's an **xpass** and will be reported in the test summary.
21
22 ``pytest`` counts and lists *skip* and *xfail* tests separately. Detailed
23 information about skipped/xfailed tests is not shown by default to avoid
24 cluttering the output. You can use the ``-r`` option to see details
25 corresponding to the "short" letters shown in the test progress:
26
27 .. code-block:: bash
28
29 pytest -rxXs # show extra info on xfailed, xpassed, and skipped tests
30
31 More details on the ``-r`` option can be found by running ``pytest -h``.
32
33 (See :ref:`how to change command line options defaults`)
34
35 .. _skipif:
36 .. _skip:
37 .. _`condition booleans`:
38
39 Skipping test functions
40 -----------------------
41
42
43
44 The simplest way to skip a test function is to mark it with the ``skip`` decorator
45 which may be passed an optional ``reason``:
46
47 .. code-block:: python
48
49 @pytest.mark.skip(reason="no way of currently testing this")
50 def test_the_unknown(): ...
51
52
53 Alternatively, it is also possible to skip imperatively during test execution or setup
54 by calling the ``pytest.skip(reason)`` function:
55
56 .. code-block:: python
57
58 def test_function():
59 if not valid_config():
60 pytest.skip("unsupported configuration")
61
62 The imperative method is useful when it is not possible to evaluate the skip condition
63 during import time.
64
65 It is also possible to skip the whole module using
66 ``pytest.skip(reason, allow_module_level=True)`` at the module level:
67
68 .. code-block:: python
69
70 import sys
71
72 import pytest
73
74 if not sys.platform.startswith("win"):
75 pytest.skip("skipping windows-only tests", allow_module_level=True)
76
77
78 **Reference**: :ref:`pytest.mark.skip ref`
79
80 ``skipif``
81 ~~~~~~~~~~
82
83
84
85 If you wish to skip something conditionally then you can use ``skipif`` instead.
86 Here is an example of marking a test function to be skipped
87 when run on an interpreter earlier than Python3.10:
88
89 .. code-block:: python
90
91 import sys
92
93
94 @pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python3.10 or higher")
95 def test_function(): ...
96
97 If the condition evaluates to ``True`` during collection, the test function will be skipped,
98 with the specified reason appearing in the summary when using ``-rs``.
99
100 You can share ``skipif`` markers between modules. Consider this test module:
101
102 .. code-block:: python
103
104 # content of test_mymodule.py
105 import mymodule
106
107 minversion = pytest.mark.skipif(
108 mymodule.__versioninfo__ < (1, 1), reason="at least mymodule-1.1 required"
109 )
110
111
112 @minversion
113 def test_function(): ...
114
115 You can import the marker and reuse it in another test module:
116
117 .. code-block:: python
118
119 # test_myothermodule.py
120 from test_mymodule import minversion
121
122
123 @minversion
124 def test_anotherfunction(): ...
125
126 For larger test suites it's usually a good idea to have one file
127 where you define the markers which you then consistently apply
128 throughout your test suite.
129
130 Alternatively, you can use :ref:`condition strings
131 <string conditions>` instead of booleans, but they can't be shared between modules easily
132 so they are supported mainly for backward compatibility reasons.
133
134 **Reference**: :ref:`pytest.mark.skipif ref`
135
136
137 Skip all test functions of a class or module
138 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
139
140 You can use the ``skipif`` marker (as any other marker) on classes:
141
142 .. code-block:: python
143
144 @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows")
145 class TestPosixCalls:
146 def test_function(self):
147 "will not be setup or run under 'win32' platform"
148
149 If the condition is ``True``, this marker will produce a skip result for
150 each of the test methods of that class.
151
152 If you want to skip all test functions of a module, you may use the
153 :globalvar:`pytestmark` global:
154
155 .. code-block:: python
156
157 # test_module.py
158 pytestmark = pytest.mark.skipif(...)
159
160 If multiple ``skipif`` decorators are applied to a test function, it
161 will be skipped if any of the skip conditions is true.
162
163 .. _`whole class- or module level`: mark.html#scoped-marking
164
165
166 Skipping files or directories
167 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
168
169 Sometimes you may need to skip an entire file or directory, for example if the
170 tests rely on Python version-specific features or contain code that you do not
171 wish pytest to run. In this case, you must exclude the files and directories
172 from collection. Refer to :ref:`customizing-test-collection` for more
173 information.
174
175
176 Skipping on a missing import dependency
177 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178
179 You can skip tests on a missing import by using :ref:`pytest.importorskip ref`
180 at module level, within a test, or test setup function.
181
182 .. code-block:: python
183
184 docutils = pytest.importorskip("docutils")
185
186 If ``docutils`` cannot be imported here, this will lead to a skip outcome of
187 the test. You can also skip based on the version number of a library:
188
189 .. code-block:: python
190
191 docutils = pytest.importorskip("docutils", minversion="0.3")
192
193 The version will be read from the specified
194 module's ``__version__`` attribute.
195
196 Summary
197 ~~~~~~~
198
199 Here's a quick guide on how to skip tests in a module in different situations:
200
201 1. Skip all tests in a module unconditionally:
202
203 .. code-block:: python
204
205 pytestmark = pytest.mark.skip("all tests still WIP")
206
207 2. Skip all tests in a module based on some condition:
208
209 .. code-block:: python
210
211 pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="tests for linux only")
212
213 3. Skip all tests in a module if some import is missing:
214
215 .. code-block:: python
216
217 pexpect = pytest.importorskip("pexpect")
218
219
220 .. _xfail:
221
222 XFail: mark test functions as expected to fail
223 ----------------------------------------------
224
225 You can use the ``xfail`` marker to indicate that you
226 expect a test to fail:
227
228 .. code-block:: python
229
230 @pytest.mark.xfail
231 def test_function(): ...
232
233 This test will run but no traceback will be reported when it fails. Instead, terminal
234 reporting will list it in the "expected to fail" (``XFAIL``) or "unexpectedly
235 passing" (``XPASS``) sections.
236
237 Alternatively, you can also mark a test as ``XFAIL`` from within the test or its setup function
238 imperatively:
239
240 .. code-block:: python
241
242 def test_function():
243 if not valid_config():
244 pytest.xfail("failing configuration (but should work)")
245
246 .. code-block:: python
247
248 def test_function2():
249 import slow_module
250
251 if slow_module.slow_function():
252 pytest.xfail("slow_module taking too long")
253
254 These two examples illustrate situations where you don't want to check for a condition
255 at the module level, which is when a condition would otherwise be evaluated for marks.
256
257 This will make ``test_function`` ``XFAIL``. Note that no other code is executed after
258 the :func:`pytest.xfail` call, differently from the marker. That's because it is implemented
259 internally by raising a known exception.
260
261 **Reference**: :ref:`pytest.mark.xfail ref`
262
263
264 ``condition`` parameter
265 ~~~~~~~~~~~~~~~~~~~~~~~
266
267 If a test is only expected to fail under a certain condition, you can pass
268 that condition as the first parameter:
269
270 .. code-block:: python
271
272 @pytest.mark.xfail(sys.platform == "win32", reason="bug in a 3rd party library")
273 def test_function(): ...
274
275 Note that you have to pass a reason as well (see the parameter description at
276 :ref:`pytest.mark.xfail ref`).
277
278 ``reason`` parameter
279 ~~~~~~~~~~~~~~~~~~~~
280
281 You can specify the motive of an expected failure with the ``reason`` parameter:
282
283 .. code-block:: python
284
285 @pytest.mark.xfail(reason="known parser issue")
286 def test_function(): ...
287
288
289 ``raises`` parameter
290 ~~~~~~~~~~~~~~~~~~~~
291
292 If you want to be more specific as to why the test is failing, you can specify
293 a single exception, or a tuple of exceptions, in the ``raises`` argument.
294
295 .. code-block:: python
296
297 @pytest.mark.xfail(raises=RuntimeError)
298 def test_function(): ...
299
300 Then the test will be reported as a regular failure if it fails with an
301 exception not mentioned in ``raises``.
302
303 ``run`` parameter
304 ~~~~~~~~~~~~~~~~~
305
306 If a test should be marked as xfail and reported as such but should not be
307 even executed, use the ``run`` parameter as ``False``:
308
309 .. code-block:: python
310
311 @pytest.mark.xfail(run=False)
312 def test_function(): ...
313
314 This is specially useful for xfailing tests that are crashing the interpreter and should be
315 investigated later.
316
317 .. _`xfail strict tutorial`:
318
319 ``strict`` parameter
320 ~~~~~~~~~~~~~~~~~~~~
321
322 Both ``XFAIL`` and ``XPASS`` don't fail the test suite by default.
323 You can change this by setting the ``strict`` keyword-only parameter to ``True``:
324
325 .. code-block:: python
326
327 @pytest.mark.xfail(strict=True)
328 def test_function(): ...
329
330
331 This will make ``XPASS`` ("unexpectedly passing") results from this test to fail the test suite.
332
333 You can change the default value of the ``strict`` parameter using the
334 ``xfail_strict`` ini option:
335
336 .. code-block:: ini
337
338 [pytest]
339 xfail_strict=true
340
341
342 Ignoring xfail
343 ~~~~~~~~~~~~~~
344
345 By specifying on the commandline:
346
347 .. code-block:: bash
348
349 pytest --runxfail
350
351 you can force the running and reporting of an ``xfail`` marked test
352 as if it weren't marked at all. This also causes :func:`pytest.xfail` to produce no effect.
353
354 Examples
355 ~~~~~~~~
356
357 Here is a simple test file with the several usages:
358
359 .. literalinclude:: /example/xfail_demo.py
360
361 Running it with the report-on-xfail option gives this output:
362
363 .. FIXME: Use $ instead of ! again to re-enable regendoc once it's fixed:
364 https://github.com/pytest-dev/pytest/issues/8807
365
366 .. code-block:: pytest
367
368 ! pytest -rx xfail_demo.py
369 =========================== test session starts ============================
370 platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-1.x.y
371 cachedir: $PYTHON_PREFIX/.pytest_cache
372 rootdir: $REGENDOC_TMPDIR/example
373 collected 7 items
374
375 xfail_demo.py xxxxxxx [100%]
376
377 ========================= short test summary info ==========================
378 XFAIL xfail_demo.py::test_hello
379 XFAIL xfail_demo.py::test_hello2
380 reason: [NOTRUN]
381 XFAIL xfail_demo.py::test_hello3
382 condition: hasattr(os, 'sep')
383 XFAIL xfail_demo.py::test_hello4
384 bug 110
385 XFAIL xfail_demo.py::test_hello5
386 condition: pytest.__version__[0] != "17"
387 XFAIL xfail_demo.py::test_hello6
388 reason: reason
389 XFAIL xfail_demo.py::test_hello7
390 ============================ 7 xfailed in 0.12s ============================
391
392 .. _`skip/xfail with parametrize`:
393
394 Skip/xfail with parametrize
395 ---------------------------
396
397 It is possible to apply markers like skip and xfail to individual
398 test instances when using parametrize:
399
400 .. code-block:: python
401
402 import sys
403
404 import pytest
405
406
407 @pytest.mark.parametrize(
408 ("n", "expected"),
409 [
410 (1, 2),
411 pytest.param(1, 0, marks=pytest.mark.xfail),
412 pytest.param(1, 3, marks=pytest.mark.xfail(reason="some bug")),
413 (2, 3),
414 (3, 4),
415 (4, 5),
416 pytest.param(
417 10, 11, marks=pytest.mark.skipif(sys.version_info >= (3, 0), reason="py2k")
418 ),
419 ],
420 )
421 def test_increment(n, expected):
422 assert n + 1 == expected