| 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-8.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 |
test_show_warnings.py:10: |
| 71 |
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ |
| 72 |
|
| 73 |
def api_v1(): |
| 74 |
> warnings.warn(UserWarning("api v1, should use functions from v2")) |
| 75 |
E UserWarning: api v1, should use functions from v2 |
| 76 |
|
| 77 |
test_show_warnings.py:5: UserWarning |
| 78 |
========================= short test summary info ========================== |
| 79 |
FAILED test_show_warnings.py::test_one - UserWarning: api v1, should use ... |
| 80 |
1 failed in 0.12s |
| 81 |
|
| 82 |
The same option can be set in the ``pytest.ini`` or ``pyproject.toml`` file using the |
| 83 |
``filterwarnings`` ini option. For example, the configuration below will ignore all |
| 84 |
user warnings and specific deprecation warnings matching a regex, but will transform |
| 85 |
all other warnings into errors. |
| 86 |
|
| 87 |
.. code-block:: ini |
| 88 |
|
| 89 |
# pytest.ini |
| 90 |
[pytest] |
| 91 |
filterwarnings = |
| 92 |
error |
| 93 |
ignore::UserWarning |
| 94 |
ignore:function ham\(\) is deprecated:DeprecationWarning |
| 95 |
|
| 96 |
.. code-block:: toml |
| 97 |
|
| 98 |
# pyproject.toml |
| 99 |
[tool.pytest.ini_options] |
| 100 |
filterwarnings = [ |
| 101 |
"error", |
| 102 |
"ignore::UserWarning", |
| 103 |
# note the use of single quote below to denote "raw" strings in TOML |
| 104 |
'ignore:function ham\(\) is deprecated:DeprecationWarning', |
| 105 |
] |
| 106 |
|
| 107 |
|
| 108 |
When a warning matches more than one option in the list, the action for the last matching option |
| 109 |
is performed. |
| 110 |
|
| 111 |
|
| 112 |
.. note:: |
| 113 |
|
| 114 |
The ``-W`` flag and the ``filterwarnings`` ini option use warning filters that are |
| 115 |
similar in structure, but each configuration option interprets its filter |
| 116 |
differently. For example, *message* in ``filterwarnings`` is a string containing a |
| 117 |
regular expression that the start of the warning message must match, |
| 118 |
case-insensitively, while *message* in ``-W`` is a literal string that the start of |
| 119 |
the warning message must contain (case-insensitively), ignoring any whitespace at |
| 120 |
the start or end of message. Consult the `warning filter`_ documentation for more |
| 121 |
details. |
| 122 |
|
| 123 |
|
| 124 |
.. _`filterwarnings`: |
| 125 |
|
| 126 |
``@pytest.mark.filterwarnings`` |
| 127 |
------------------------------- |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
You can use the ``@pytest.mark.filterwarnings`` to add warning filters to specific test items, |
| 132 |
allowing you to have finer control of which warnings should be captured at test, class or |
| 133 |
even module level: |
| 134 |
|
| 135 |
.. code-block:: python |
| 136 |
|
| 137 |
import warnings |
| 138 |
|
| 139 |
|
| 140 |
def api_v1(): |
| 141 |
warnings.warn(UserWarning("api v1, should use functions from v2")) |
| 142 |
return 1 |
| 143 |
|
| 144 |
|
| 145 |
@pytest.mark.filterwarnings("ignore:api v1") |
| 146 |
def test_one(): |
| 147 |
assert api_v1() == 1 |
| 148 |
|
| 149 |
|
| 150 |
Filters applied using a mark take precedence over filters passed on the command line or configured |
| 151 |
by the ``filterwarnings`` ini option. |
| 152 |
|
| 153 |
You may apply a filter to all tests of a class by using the ``filterwarnings`` mark as a class |
| 154 |
decorator or to all tests in a module by setting the :globalvar:`pytestmark` variable: |
| 155 |
|
| 156 |
.. code-block:: python |
| 157 |
|
| 158 |
# turns all warnings into errors for this module |
| 159 |
pytestmark = pytest.mark.filterwarnings("error") |
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
*Credits go to Florian Schulze for the reference implementation in the* `pytest-warnings`_ |
| 164 |
*plugin.* |
| 165 |
|
| 166 |
.. _`pytest-warnings`: https://github.com/fschulze/pytest-warnings |
| 167 |
|
| 168 |
Disabling warnings summary |
| 169 |
-------------------------- |
| 170 |
|
| 171 |
Although not recommended, you can use the ``--disable-warnings`` command-line option to suppress the |
| 172 |
warning summary entirely from the test run output. |
| 173 |
|
| 174 |
Disabling warning capture entirely |
| 175 |
---------------------------------- |
| 176 |
|
| 177 |
This plugin is enabled by default but can be disabled entirely in your ``pytest.ini`` file with: |
| 178 |
|
| 179 |
.. code-block:: ini |
| 180 |
|
| 181 |
[pytest] |
| 182 |
addopts = -p no:warnings |
| 183 |
|
| 184 |
Or passing ``-p no:warnings`` in the command-line. This might be useful if your test suites handles warnings |
| 185 |
using an external system. |
| 186 |
|
| 187 |
|
| 188 |
.. _`deprecation-warnings`: |
| 189 |
|
| 190 |
DeprecationWarning and PendingDeprecationWarning |
| 191 |
------------------------------------------------ |
| 192 |
|
| 193 |
By default pytest will display ``DeprecationWarning`` and ``PendingDeprecationWarning`` warnings from |
| 194 |
user code and third-party libraries, as recommended by :pep:`565`. |
| 195 |
This helps users keep their code modern and avoid breakages when deprecated warnings are effectively removed. |
| 196 |
|
| 197 |
However, in the specific case where users capture any type of warnings in their test, either with |
| 198 |
:func:`pytest.warns`, :func:`pytest.deprecated_call` or using the :ref:`recwarn <recwarn>` fixture, |
| 199 |
no warning will be displayed at all. |
| 200 |
|
| 201 |
Sometimes it is useful to hide some specific deprecation warnings that happen in code that you have no control over |
| 202 |
(such as third-party libraries), in which case you might use the warning filters options (ini or marks) to ignore |
| 203 |
those warnings. |
| 204 |
|
| 205 |
For example: |
| 206 |
|
| 207 |
.. code-block:: ini |
| 208 |
|
| 209 |
[pytest] |
| 210 |
filterwarnings = |
| 211 |
ignore:.*U.*mode is deprecated:DeprecationWarning |
| 212 |
|
| 213 |
|
| 214 |
This will ignore all warnings of type ``DeprecationWarning`` where the start of the message matches |
| 215 |
the regular expression ``".*U.*mode is deprecated"``. |
| 216 |
|
| 217 |
See :ref:`@pytest.mark.filterwarnings <filterwarnings>` and |
| 218 |
:ref:`Controlling warnings <controlling-warnings>` for more examples. |
| 219 |
|
| 220 |
.. note:: |
| 221 |
|
| 222 |
If warnings are configured at the interpreter level, using |
| 223 |
the :envvar:`python:PYTHONWARNINGS` environment variable or the |
| 224 |
``-W`` command-line option, pytest will not configure any filters by default. |
| 225 |
|
| 226 |
Also pytest doesn't follow :pep:`506` suggestion of resetting all warning filters because |
| 227 |
it might break test suites that configure warning filters themselves |
| 228 |
by calling :func:`warnings.simplefilter` (see :issue:`2430` for an example of that). |
| 229 |
|
| 230 |
|
| 231 |
.. _`ensuring a function triggers a deprecation warning`: |
| 232 |
|
| 233 |
.. _ensuring_function_triggers: |
| 234 |
|
| 235 |
Ensuring code triggers a deprecation warning |
| 236 |
-------------------------------------------- |
| 237 |
|
| 238 |
You can also use :func:`pytest.deprecated_call` for checking |
| 239 |
that a certain function call triggers a ``DeprecationWarning`` or |
| 240 |
``PendingDeprecationWarning``: |
| 241 |
|
| 242 |
.. code-block:: python |
| 243 |
|
| 244 |
import pytest |
| 245 |
|
| 246 |
|
| 247 |
def test_myfunction_deprecated(): |
| 248 |
with pytest.deprecated_call(): |
| 249 |
myfunction(17) |
| 250 |
|
| 251 |
This test will fail if ``myfunction`` does not issue a deprecation warning |
| 252 |
when called with a ``17`` argument. |
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
.. _`asserting warnings`: |
| 258 |
|
| 259 |
.. _assertwarnings: |
| 260 |
|
| 261 |
.. _`asserting warnings with the warns function`: |
| 262 |
|
| 263 |
.. _warns: |
| 264 |
|
| 265 |
Asserting warnings with the warns function |
| 266 |
------------------------------------------ |
| 267 |
|
| 268 |
You can check that code raises a particular warning using :func:`pytest.warns`, |
| 269 |
which works in a similar manner to :ref:`raises <assertraises>` (except that |
| 270 |
:ref:`raises <assertraises>` does not capture all exceptions, only the |
| 271 |
``expected_exception``): |
| 272 |
|
| 273 |
.. code-block:: python |
| 274 |
|
| 275 |
import warnings |
| 276 |
|
| 277 |
import pytest |
| 278 |
|
| 279 |
|
| 280 |
def test_warning(): |
| 281 |
with pytest.warns(UserWarning): |
| 282 |
warnings.warn("my warning", UserWarning) |
| 283 |
|
| 284 |
The test will fail if the warning in question is not raised. Use the keyword |
| 285 |
argument ``match`` to assert that the warning matches a text or regex. |
| 286 |
To match a literal string that may contain regular expression metacharacters like ``(`` or ``.``, the pattern can |
| 287 |
first be escaped with ``re.escape``. |
| 288 |
|
| 289 |
Some examples: |
| 290 |
|
| 291 |
.. code-block:: pycon |
| 292 |
|
| 293 |
|
| 294 |
>>> with warns(UserWarning, match="must be 0 or None"): |
| 295 |
... warnings.warn("value must be 0 or None", UserWarning) |
| 296 |
... |
| 297 |
|
| 298 |
>>> with warns(UserWarning, match=r"must be \d+$"): |
| 299 |
... warnings.warn("value must be 42", UserWarning) |
| 300 |
... |
| 301 |
|
| 302 |
>>> with warns(UserWarning, match=r"must be \d+$"): |
| 303 |
... warnings.warn("this is not here", UserWarning) |
| 304 |
... |
| 305 |
Traceback (most recent call last): |
| 306 |
... |
| 307 |
Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted... |
| 308 |
|
| 309 |
>>> with warns(UserWarning, match=re.escape("issue with foo() func")): |
| 310 |
... warnings.warn("issue with foo() func") |
| 311 |
... |
| 312 |
|
| 313 |
You can also call :func:`pytest.warns` on a function or code string: |
| 314 |
|
| 315 |
.. code-block:: python |
| 316 |
|
| 317 |
pytest.warns(expected_warning, func, *args, **kwargs) |
| 318 |
pytest.warns(expected_warning, "func(*args, **kwargs)") |
| 319 |
|
| 320 |
The function also returns a list of all raised warnings (as |
| 321 |
``warnings.WarningMessage`` objects), which you can query for |
| 322 |
additional information: |
| 323 |
|
| 324 |
.. code-block:: python |
| 325 |
|
| 326 |
with pytest.warns(RuntimeWarning) as record: |
| 327 |
warnings.warn("another warning", RuntimeWarning) |
| 328 |
|
| 329 |
# check that only one warning was raised |
| 330 |
assert len(record) == 1 |
| 331 |
# check that the message matches |
| 332 |
assert record[0].message.args[0] == "another warning" |
| 333 |
|
| 334 |
Alternatively, you can examine raised warnings in detail using the |
| 335 |
:ref:`recwarn <recwarn>` fixture (see below). |
| 336 |
|
| 337 |
|
| 338 |
The :ref:`recwarn <recwarn>` fixture automatically ensures to reset the warnings |
| 339 |
filter at the end of the test, so no global state is leaked. |
| 340 |
|
| 341 |
.. _`recording warnings`: |
| 342 |
|
| 343 |
.. _recwarn: |
| 344 |
|
| 345 |
Recording warnings |
| 346 |
------------------ |
| 347 |
|
| 348 |
You can record raised warnings either using :func:`pytest.warns` or with |
| 349 |
the ``recwarn`` fixture. |
| 350 |
|
| 351 |
To record with :func:`pytest.warns` without asserting anything about the warnings, |
| 352 |
pass no arguments as the expected warning type and it will default to a generic Warning: |
| 353 |
|
| 354 |
.. code-block:: python |
| 355 |
|
| 356 |
with pytest.warns() as record: |
| 357 |
warnings.warn("user", UserWarning) |
| 358 |
warnings.warn("runtime", RuntimeWarning) |
| 359 |
|
| 360 |
assert len(record) == 2 |
| 361 |
assert str(record[0].message) == "user" |
| 362 |
assert str(record[1].message) == "runtime" |
| 363 |
|
| 364 |
The ``recwarn`` fixture will record warnings for the whole function: |
| 365 |
|
| 366 |
.. code-block:: python |
| 367 |
|
| 368 |
import warnings |
| 369 |
|
| 370 |
|
| 371 |
def test_hello(recwarn): |
| 372 |
warnings.warn("hello", UserWarning) |
| 373 |
assert len(recwarn) == 1 |
| 374 |
w = recwarn.pop(UserWarning) |
| 375 |
assert issubclass(w.category, UserWarning) |
| 376 |
assert str(w.message) == "hello" |
| 377 |
assert w.filename |
| 378 |
assert w.lineno |
| 379 |
|
| 380 |
Both ``recwarn`` and :func:`pytest.warns` return the same interface for recorded |
| 381 |
warnings: a WarningsRecorder instance. To view the recorded warnings, you can |
| 382 |
iterate over this instance, call ``len`` on it to get the number of recorded |
| 383 |
warnings, or index into it to get a particular recorded warning. |
| 384 |
|
| 385 |
Full API: :class:`~_pytest.recwarn.WarningsRecorder`. |
| 386 |
|
| 387 |
.. _`warns use cases`: |
| 388 |
|
| 389 |
Additional use cases of warnings in tests |
| 390 |
----------------------------------------- |
| 391 |
|
| 392 |
Here are some use cases involving warnings that often come up in tests, and suggestions on how to deal with them: |
| 393 |
|
| 394 |
- To ensure that **at least one** of the indicated warnings is issued, use: |
| 395 |
|
| 396 |
.. code-block:: python |
| 397 |
|
| 398 |
def test_warning(): |
| 399 |
with pytest.warns((RuntimeWarning, UserWarning)): |
| 400 |
... |
| 401 |
|
| 402 |
- To ensure that **only** certain warnings are issued, use: |
| 403 |
|
| 404 |
.. code-block:: python |
| 405 |
|
| 406 |
def test_warning(recwarn): |
| 407 |
... |
| 408 |
assert len(recwarn) == 1 |
| 409 |
user_warning = recwarn.pop(UserWarning) |
| 410 |
assert issubclass(user_warning.category, UserWarning) |
| 411 |
|
| 412 |
- To ensure that **no** warnings are emitted, use: |
| 413 |
|
| 414 |
.. code-block:: python |
| 415 |
|
| 416 |
def test_warning(): |
| 417 |
with warnings.catch_warnings(): |
| 418 |
warnings.simplefilter("error") |
| 419 |
... |
| 420 |
|
| 421 |
- To suppress warnings, use: |
| 422 |
|
| 423 |
.. code-block:: python |
| 424 |
|
| 425 |
with warnings.catch_warnings(): |
| 426 |
warnings.simplefilter("ignore") |
| 427 |
... |
| 428 |
|
| 429 |
|
| 430 |
.. _custom_failure_messages: |
| 431 |
|
| 432 |
Custom failure messages |
| 433 |
----------------------- |
| 434 |
|
| 435 |
Recording warnings provides an opportunity to produce custom test |
| 436 |
failure messages for when no warnings are issued or other conditions |
| 437 |
are met. |
| 438 |
|
| 439 |
.. code-block:: python |
| 440 |
|
| 441 |
def test(): |
| 442 |
with pytest.warns(Warning) as record: |
| 443 |
f() |
| 444 |
if not record: |
| 445 |
pytest.fail("Expected a warning!") |
| 446 |
|
| 447 |
If no warnings are issued when calling ``f``, then ``not record`` will |
| 448 |
evaluate to ``True``. You can then call :func:`pytest.fail` with a |
| 449 |
custom error message. |
| 450 |
|
| 451 |
.. _internal-warnings: |
| 452 |
|
| 453 |
Internal pytest warnings |
| 454 |
------------------------ |
| 455 |
|
| 456 |
pytest may generate its own warnings in some situations, such as improper usage or deprecated features. |
| 457 |
|
| 458 |
For example, pytest will emit a warning if it encounters a class that matches :confval:`python_classes` but also |
| 459 |
defines an ``__init__`` constructor, as this prevents the class from being instantiated: |
| 460 |
|
| 461 |
.. code-block:: python |
| 462 |
|
| 463 |
# content of test_pytest_warnings.py |
| 464 |
class Test: |
| 465 |
def __init__(self): |
| 466 |
pass |
| 467 |
|
| 468 |
def test_foo(self): |
| 469 |
assert 1 == 1 |
| 470 |
|
| 471 |
.. code-block:: pytest |
| 472 |
|
| 473 |
$ pytest test_pytest_warnings.py -q |
| 474 |
|
| 475 |
============================= warnings summary ============================= |
| 476 |
test_pytest_warnings.py:1 |
| 477 |
/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) |
| 478 |
class Test: |
| 479 |
|
| 480 |
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html |
| 481 |
1 warning in 0.12s |
| 482 |
|
| 483 |
These warnings might be filtered using the same builtin mechanisms used to filter other types of warnings. |
| 484 |
|
| 485 |
Please read our :ref:`backwards-compatibility` to learn how we proceed about deprecating and eventually removing |
| 486 |
features. |
| 487 |
|
| 488 |
The full list of warnings is listed in :ref:`the reference documentation <warnings ref>`. |
| 489 |
|
| 490 |
|
| 491 |
.. _`resource-warnings`: |
| 492 |
|
| 493 |
Resource Warnings |
| 494 |
----------------- |
| 495 |
|
| 496 |
Additional information of the source of a :class:`ResourceWarning` can be obtained when captured by pytest if |
| 497 |
:mod:`tracemalloc` module is enabled. |
| 498 |
|
| 499 |
One convenient way to enable :mod:`tracemalloc` when running tests is to set the :envvar:`PYTHONTRACEMALLOC` to a large |
| 500 |
enough number of frames (say ``20``, but that number is application dependent). |
| 501 |
|
| 502 |
For more information, consult the `Python Development Mode <https://docs.python.org/3/library/devmode.html>`__ |
| 503 |
section in the Python documentation. |