Debian Codegraph @

doc/en/how-to/capture-warnings.rst

raw
1 .. _`warnings`:
2
3 How to capture warnings
4 =======================
5
6
7
8 Starting from version ``3.1``, pytest now automatically catches warnings during test execution
9 and displays them at the end of the session:
10
11 .. code-block:: python
12
13 # content of test_show_warnings.py
14 import warnings
15
16
17 def api_v1():
18 warnings.warn(UserWarning("api v1, should use functions from v2"))
19 return 1
20
21
22 def test_one():
23 assert api_v1() == 1
24
25 Running pytest now produces this output:
26
27 .. code-block:: pytest
28
29 $ pytest test_show_warnings.py
30 =========================== test session starts ============================
31 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
32 rootdir: /home/sweet/project
33 collected 1 item
34
35 test_show_warnings.py . [100%]
36
37 ============================= warnings summary =============================
38 test_show_warnings.py::test_one
39 /home/sweet/project/test_show_warnings.py:5: UserWarning: api v1, should use functions from v2
40 warnings.warn(UserWarning("api v1, should use functions from v2"))
41
42 -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
43 ======================= 1 passed, 1 warning in 0.12s =======================
44
45 .. _`controlling-warnings`:
46
47 Controlling warnings
48 --------------------
49
50 Similar to Python's `warning filter`_ and :option:`-W option <python:-W>` flag, pytest provides
51 its own ``-W`` flag to control which warnings are ignored, displayed, or turned into
52 errors. See the `warning filter`_ documentation for more
53 advanced use-cases.
54
55 .. _`warning filter`: https://docs.python.org/3/library/warnings.html#warning-filter
56
57 This code sample shows how to treat any ``UserWarning`` category class of warning
58 as an error:
59
60 .. code-block:: pytest
61
62 $ pytest -q test_show_warnings.py -W error::UserWarning
63 F [100%]
64 ================================= FAILURES =================================
65 _________________________________ test_one _________________________________
66
67 def test_one():
68 > assert api_v1() == 1
69 ^^^^^^^^
70
71 test_show_warnings.py:10:
72 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
73
74 def api_v1():
75 > warnings.warn(UserWarning("api v1, should use functions from v2"))
76 E UserWarning: api v1, should use functions from v2
77
78 test_show_warnings.py:5: UserWarning
79 ========================= short test summary info ==========================
80 FAILED test_show_warnings.py::test_one - UserWarning: api v1, should use ...
81 1 failed in 0.12s
82
83 The same option can be set in the configuration file using the
84 :confval:`filterwarnings` configuration option. For example, the configuration below will ignore all
85 user warnings and specific deprecation warnings matching a regex, but will transform
86 all other warnings into errors.
87
88 .. tab:: toml
89
90 .. code-block:: toml
91
92 [pytest]
93 filterwarnings = [
94 'error',
95 'ignore::UserWarning',
96 # Note the use of single quote below to denote "raw" strings in TOML.
97 'ignore:function ham\(\) is deprecated:DeprecationWarning',
98 ]
99
100 .. tab:: ini
101
102 .. code-block:: ini
103
104 [pytest]
105 filterwarnings =
106 error
107 ignore::UserWarning
108 ignore:function ham\(\) is deprecated:DeprecationWarning
109
110
111 When a warning matches more than one option in the list, the action for the last matching option
112 is performed.
113
114
115 .. note::
116
117 The ``-W`` flag and the :confval:`filterwarnings` configuration option use warning filters that are
118 similar in structure, but each configuration option interprets its filter
119 differently. For example, *message* in ``filterwarnings`` is a string containing a
120 regular expression that the start of the warning message must match,
121 case-insensitively, while *message* in ``-W`` is a literal string that the start of
122 the warning message must contain (case-insensitively), ignoring any whitespace at
123 the start or end of message. Consult the `warning filter`_ documentation for more
124 details.
125
126
127 .. _`filterwarnings`:
128
129 ``@pytest.mark.filterwarnings``
130 -------------------------------
131
132
133
134 You can use the :ref:`@pytest.mark.filterwarnings <pytest.mark.filterwarnings ref>` mark to add warning filters to specific test items,
135 allowing you to have finer control of which warnings should be captured at test, class or
136 even module level:
137
138 .. code-block:: python
139
140 import warnings
141
142
143 def api_v1():
144 warnings.warn(UserWarning("api v1, should use functions from v2"))
145 return 1
146
147
148 @pytest.mark.filterwarnings("ignore:api v1")
149 def test_one():
150 assert api_v1() == 1
151
152
153 You can specify multiple filters with separate decorators:
154
155 .. code-block:: python
156
157 # Ignore "api v1" warnings, but fail on all other warnings
158 @pytest.mark.filterwarnings("ignore:api v1")
159 @pytest.mark.filterwarnings("error")
160 def test_one():
161 assert api_v1() == 1
162
163 You can also pass multiple filters to a single mark by providing multiple arguments:
164
165 .. code-block:: python
166
167 # Later arguments take precedence, matching warnings.filterwarnings behavior.
168 @pytest.mark.filterwarnings("error", "ignore:api v1")
169 def test_one():
170 assert api_v1() == 1
171
172 .. important::
173
174 Regarding decorator order and filter precedence:
175 it's important to remember that decorators are evaluated in reverse order,
176 so you have to list the warning filters in the reverse order
177 compared to traditional :py:func:`warnings.filterwarnings` and :option:`-W option <python:-W>` usage.
178 This means in practice that filters from earlier :ref:`@pytest.mark.filterwarnings <pytest.mark.filterwarnings ref>` decorators
179 take precedence over filters from later decorators, as illustrated in the example above.
180
181
182 Filters applied using a mark take precedence over filters passed on the command line or configured
183 by the :confval:`filterwarnings` configuration option.
184
185 You may apply a filter to all tests of a class by using the :ref:`filterwarnings <pytest.mark.filterwarnings ref>` mark as a class
186 decorator or to all tests in a module by setting the :globalvar:`pytestmark` variable:
187
188 .. code-block:: python
189
190 # turns all warnings into errors for this module
191 pytestmark = pytest.mark.filterwarnings("error")
192
193
194 .. note::
195
196 If you want to apply multiple filters
197 (by assigning a list of :ref:`filterwarnings <pytest.mark.filterwarnings ref>` mark to :globalvar:`pytestmark`),
198 you must use the traditional :py:func:`warnings.filterwarnings` ordering approach (later filters take precedence),
199 which is the reverse of the decorator approach mentioned above.
200
201
202 *Credits go to Florian Schulze for the reference implementation in the* `pytest-warnings`_
203 *plugin.*
204
205 .. _`pytest-warnings`: https://github.com/fschulze/pytest-warnings
206
207 Setting a maximum number of warnings
208 -------------------------------------
209
210 .. versionadded:: 9.1
211
212 You can use the :option:`--max-warnings` command-line option to fail the test run
213 if the total number of warnings exceeds a given threshold:
214
215 .. code-block:: bash
216
217 pytest --max-warnings=10
218
219 If all tests pass but the number of warnings exceeds the threshold, pytest will exit with code ``6``
220 (:class:`~pytest.ExitCode` ``MAX_WARNINGS_ERROR``). This is useful for gradually
221 ratcheting down warnings in a codebase.
222
223 Note that :confval:`filtered warnings <filterwarnings>` do not count toward this maximum total.
224
225 The threshold can also be set in the configuration file using :confval:`max_warnings`:
226
227 .. tab:: toml
228
229 .. code-block:: toml
230
231 [pytest]
232 max_warnings = 10
233
234 .. tab:: ini
235
236 .. code-block:: ini
237
238 [pytest]
239 max_warnings = 10
240
241 .. note::
242
243 If tests fail, the exit code will be ``1`` (:class:`~pytest.ExitCode` ``TESTS_FAILED``)
244 regardless of the warning count. ``MAX_WARNINGS_ERROR`` is only reported when all tests pass
245 but the warning threshold is exceeded.
246
247 Disabling warnings summary
248 --------------------------
249
250 Although not recommended, you can use the :option:`--disable-warnings` command-line option to suppress the
251 warning summary entirely from the test run output.
252
253 Disabling warning capture entirely
254 ----------------------------------
255
256 This plugin is enabled by default but can be disabled entirely in your configuration file with:
257
258 .. tab:: toml
259
260 .. code-block:: toml
261
262 [pytest]
263 addopts = ["-p", "no:warnings"]
264
265 .. tab:: ini
266
267 .. code-block:: ini
268
269 [pytest]
270 addopts = -p no:warnings
271
272 Or passing ``-p no:warnings`` in the command-line. This might be useful if your test suite handles warnings
273 using an external system.
274
275
276 .. _`deprecation-warnings`:
277
278 DeprecationWarning and PendingDeprecationWarning
279 ------------------------------------------------
280
281 By default pytest will display ``DeprecationWarning`` and ``PendingDeprecationWarning`` warnings from
282 user code and third-party libraries, as recommended by :pep:`565`.
283 This helps users keep their code modern and avoid breakages when deprecated warnings are effectively removed.
284
285 However, in the specific case where users capture any type of warnings in their test, either with
286 :func:`pytest.warns`, :func:`pytest.deprecated_call` or using the :fixture:`recwarn` fixture,
287 no warning will be displayed at all.
288
289 Sometimes it is useful to hide some specific deprecation warnings that happen in code that you have no control over
290 (such as third-party libraries), in which case you might use the warning filters options (configuration or marks) to ignore
291 those warnings.
292
293 For example:
294
295 .. tab:: toml
296
297 .. code-block:: toml
298
299 [pytest]
300 filterwarnings = [
301 'ignore:.*U.*mode is deprecated:DeprecationWarning',
302 ]
303
304 .. tab:: ini
305
306 .. code-block:: ini
307
308 [pytest]
309 filterwarnings =
310 ignore:.*U.*mode is deprecated:DeprecationWarning
311
312
313 This will ignore all warnings of type ``DeprecationWarning`` where the start of the message matches
314 the regular expression ``".*U.*mode is deprecated"``.
315
316 See :ref:`@pytest.mark.filterwarnings <filterwarnings>` and
317 :ref:`Controlling warnings <controlling-warnings>` for more examples.
318
319 .. note::
320
321 If warnings are configured at the interpreter level, using
322 the :envvar:`python:PYTHONWARNINGS` environment variable or the
323 ``-W`` command-line option, pytest will not configure any filters by default.
324
325 Also pytest doesn't follow :pep:`565` suggestion of resetting all warning filters because
326 it might break test suites that configure warning filters themselves
327 by calling :func:`warnings.simplefilter` (see :issue:`2430` for an example of that).
328
329
330 .. _`ensuring a function triggers a deprecation warning`:
331
332 .. _ensuring_function_triggers:
333
334 Ensuring code triggers a deprecation warning
335 --------------------------------------------
336
337 You can also use :func:`pytest.deprecated_call` for checking
338 that a certain function call triggers a ``DeprecationWarning``, ``PendingDeprecationWarning`` or
339 ``FutureWarning``:
340
341 .. code-block:: python
342
343 import pytest
344
345
346 def test_myfunction_deprecated():
347 with pytest.deprecated_call():
348 myfunction(17)
349
350 This test will fail if ``myfunction`` does not issue a deprecation warning
351 when called with a ``17`` argument.
352
353
354
355
356 .. _`asserting warnings`:
357
358 .. _assertwarnings:
359
360 .. _`asserting warnings with the warns function`:
361
362 .. _warns:
363
364 Asserting warnings with the warns function
365 ------------------------------------------
366
367 You can check that code raises a particular warning using :func:`pytest.warns`,
368 which works in a similar manner to :ref:`raises <assertraises>` (except that
369 :ref:`raises <assertraises>` does not capture all exceptions, only the
370 ``expected_exception``):
371
372 .. code-block:: python
373
374 import warnings
375
376 import pytest
377
378
379 def test_warning():
380 with pytest.warns(UserWarning):
381 warnings.warn("my warning", UserWarning)
382
383 The test will fail if the warning in question is not raised. Use the keyword
384 argument ``match`` to assert that the warning matches a text or regex.
385 To match a literal string that may contain regular expression metacharacters like ``(`` or ``.``, the pattern can
386 first be escaped with ``re.escape``.
387
388 Some examples:
389
390 .. code-block:: pycon
391
392
393 >>> with warns(UserWarning, match="must be 0 or None"):
394 ... warnings.warn("value must be 0 or None", UserWarning)
395 ...
396
397 >>> with warns(UserWarning, match=r"must be \d+$"):
398 ... warnings.warn("value must be 42", UserWarning)
399 ...
400
401 >>> with warns(UserWarning, match=r"must be \d+$"):
402 ... warnings.warn("this is not here", UserWarning)
403 ...
404 Traceback (most recent call last):
405 ...
406 Failed: Regex pattern did not match any of the 1 warnings emitted.
407 Regex: ...
408 Emitted warnings: ...UserWarning...
409
410 >>> with warns(UserWarning, match=re.escape("issue with foo() func")):
411 ... warnings.warn("issue with foo() func")
412 ...
413
414 The function also returns a list of all raised warnings (as
415 ``warnings.WarningMessage`` objects), which you can query for
416 additional information:
417
418 .. code-block:: python
419
420 with pytest.warns(RuntimeWarning) as record:
421 warnings.warn("another warning", RuntimeWarning)
422
423 # check that only one warning was raised
424 assert len(record) == 1
425 # check that the message matches
426 assert record[0].message.args[0] == "another warning"
427
428 Alternatively, you can examine raised warnings in detail using the
429 :fixture:`recwarn` fixture (see :ref:`below <recwarn>`).
430
431
432 The :fixture:`recwarn` fixture automatically ensures to reset the warnings
433 filter at the end of the test, so no global state is leaked.
434
435 .. _`recording warnings`:
436
437 .. _recwarn:
438
439 Recording warnings
440 ------------------
441
442 You can record raised warnings either using the :func:`pytest.warns` context manager or with
443 the :fixture:`recwarn` fixture.
444
445 To record with :func:`pytest.warns` without asserting anything about the warnings,
446 pass no arguments as the expected warning type and it will default to a generic Warning:
447
448 .. code-block:: python
449
450 with pytest.warns() as record:
451 warnings.warn("user", UserWarning)
452 warnings.warn("runtime", RuntimeWarning)
453
454 assert len(record) == 2
455 assert str(record[0].message) == "user"
456 assert str(record[1].message) == "runtime"
457
458 The :fixture:`recwarn` fixture will record warnings for the whole function:
459
460 .. code-block:: python
461
462 import warnings
463
464
465 def test_hello(recwarn):
466 warnings.warn("hello", UserWarning)
467 assert len(recwarn) == 1
468 w = recwarn.pop(UserWarning)
469 assert issubclass(w.category, UserWarning)
470 assert str(w.message) == "hello"
471 assert w.filename
472 assert w.lineno
473
474 Both the :fixture:`recwarn` fixture and the :func:`pytest.warns` context manager return the same interface for recorded
475 warnings: a :class:`~_pytest.recwarn.WarningsRecorder` instance. To view the recorded warnings, you can
476 iterate over this instance, call ``len`` on it to get the number of recorded
477 warnings, or index into it to get a particular recorded warning.
478
479
480 .. _`warns use cases`:
481
482 Additional use cases of warnings in tests
483 -----------------------------------------
484
485 Here are some use cases involving warnings that often come up in tests, and suggestions on how to deal with them:
486
487 - To ensure that **at least one** of the indicated warnings is issued, use:
488
489 .. code-block:: python
490
491 def test_warning():
492 with pytest.warns((RuntimeWarning, UserWarning)):
493 ...
494
495 - To ensure that **only** certain warnings are issued, use:
496
497 .. code-block:: python
498
499 def test_warning(recwarn):
500 ...
501 assert len(recwarn) == 1
502 user_warning = recwarn.pop(UserWarning)
503 assert issubclass(user_warning.category, UserWarning)
504
505 - To ensure that **no** warnings are emitted, use:
506
507 .. code-block:: python
508
509 def test_warning():
510 with warnings.catch_warnings():
511 warnings.simplefilter("error")
512 ...
513
514 - To suppress warnings, use:
515
516 .. code-block:: python
517
518 with warnings.catch_warnings():
519 warnings.simplefilter("ignore")
520 ...
521
522
523 .. _custom_failure_messages:
524
525 Custom failure messages
526 -----------------------
527
528 Recording warnings provides an opportunity to produce custom test
529 failure messages for when no warnings are issued or other conditions
530 are met.
531
532 .. code-block:: python
533
534 def test():
535 with pytest.warns(Warning) as record:
536 f()
537 if not record:
538 pytest.fail("Expected a warning!")
539
540 If no warnings are issued when calling ``f``, then ``not record`` will
541 evaluate to ``True``. You can then call :func:`pytest.fail` with a
542 custom error message.
543
544 .. _internal-warnings:
545
546 Internal pytest warnings
547 ------------------------
548
549 pytest may generate its own warnings in some situations, such as improper usage or deprecated features.
550
551 For example, pytest will emit a warning if it encounters a class that matches :confval:`python_classes` but also
552 defines an ``__init__`` constructor, as this prevents the class from being instantiated:
553
554 .. code-block:: python
555
556 # content of test_pytest_warnings.py
557 class Test:
558 def __init__(self):
559 pass
560
561 def test_foo(self):
562 assert 1 == 1
563
564 .. code-block:: pytest
565
566 $ pytest test_pytest_warnings.py -q
567
568 ============================= warnings summary =============================
569 test_pytest_warnings.py:1
570 /home/sweet/project/test_pytest_warnings.py:1: PytestCollectionWarning: cannot collect test class 'Test' because it has a __init__ constructor (from: test_pytest_warnings.py)
571 class Test:
572
573 -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
574 1 warning in 0.12s
575
576 These warnings might be filtered using the same builtin mechanisms used to filter other types of warnings.
577
578 Please read our :ref:`backwards-compatibility` to learn how we proceed about deprecating and eventually removing
579 features.
580
581 The full list of warnings is listed in :ref:`the reference documentation <warnings ref>`.
582
583
584 .. _`resource-warnings`:
585
586 Resource Warnings
587 -----------------
588
589 Additional information of the source of a :class:`ResourceWarning` can be obtained when captured by pytest if
590 :mod:`tracemalloc` module is enabled.
591
592 One convenient way to enable :mod:`tracemalloc` when running tests is to set the :envvar:`PYTHONTRACEMALLOC` to a large
593 enough number of frames (say ``20``, but that number is application dependent).
594
595 For more information, consult the `Python Development Mode <https://docs.python.org/3/library/devmode.html>`__
596 section in the Python documentation.