| 1 |
.. _`assert`: |
| 2 |
|
| 3 |
How to write and report assertions in tests |
| 4 |
================================================== |
| 5 |
|
| 6 |
.. _`assert with the assert statement`: |
| 7 |
|
| 8 |
Asserting with the ``assert`` statement |
| 9 |
--------------------------------------------------------- |
| 10 |
|
| 11 |
``pytest`` allows you to use the standard Python ``assert`` for verifying |
| 12 |
expectations and values in Python tests. For example, you can write the |
| 13 |
following: |
| 14 |
|
| 15 |
.. code-block:: python |
| 16 |
|
| 17 |
# content of test_assert1.py |
| 18 |
def f(): |
| 19 |
return 3 |
| 20 |
|
| 21 |
|
| 22 |
def test_function(): |
| 23 |
assert f() == 4 |
| 24 |
|
| 25 |
to assert that your function returns a certain value. If this assertion fails |
| 26 |
you will see the return value of the function call: |
| 27 |
|
| 28 |
.. code-block:: pytest |
| 29 |
|
| 30 |
$ pytest test_assert1.py |
| 31 |
=========================== test session starts ============================ |
| 32 |
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y |
| 33 |
rootdir: /home/sweet/project |
| 34 |
collected 1 item |
| 35 |
|
| 36 |
test_assert1.py F [100%] |
| 37 |
|
| 38 |
================================= FAILURES ================================= |
| 39 |
______________________________ test_function _______________________________ |
| 40 |
|
| 41 |
def test_function(): |
| 42 |
> assert f() == 4 |
| 43 |
E assert 3 == 4 |
| 44 |
E + where 3 = f() |
| 45 |
|
| 46 |
test_assert1.py:6: AssertionError |
| 47 |
========================= short test summary info ========================== |
| 48 |
FAILED test_assert1.py::test_function - assert 3 == 4 |
| 49 |
============================ 1 failed in 0.12s ============================= |
| 50 |
|
| 51 |
``pytest`` has support for showing the values of the most common subexpressions |
| 52 |
including calls, attributes, comparisons, and binary and unary |
| 53 |
operators. (See :ref:`tbreportdemo`). This allows you to use the |
| 54 |
idiomatic python constructs without boilerplate code while not losing |
| 55 |
introspection information. |
| 56 |
|
| 57 |
If a message is specified with the assertion like this: |
| 58 |
|
| 59 |
.. code-block:: python |
| 60 |
|
| 61 |
assert a % 2 == 0, "value was odd, should be even" |
| 62 |
|
| 63 |
it is printed alongside the assertion introspection in the traceback. |
| 64 |
|
| 65 |
See :ref:`assert-details` for more information on assertion introspection. |
| 66 |
|
| 67 |
.. _`assertraises`: |
| 68 |
|
| 69 |
Assertions about expected exceptions |
| 70 |
------------------------------------------ |
| 71 |
|
| 72 |
In order to write assertions about raised exceptions, you can use |
| 73 |
:func:`pytest.raises` as a context manager like this: |
| 74 |
|
| 75 |
.. code-block:: python |
| 76 |
|
| 77 |
import pytest |
| 78 |
|
| 79 |
|
| 80 |
def test_zero_division(): |
| 81 |
with pytest.raises(ZeroDivisionError): |
| 82 |
1 / 0 |
| 83 |
|
| 84 |
and if you need to have access to the actual exception info you may use: |
| 85 |
|
| 86 |
.. code-block:: python |
| 87 |
|
| 88 |
def test_recursion_depth(): |
| 89 |
with pytest.raises(RuntimeError) as excinfo: |
| 90 |
|
| 91 |
def f(): |
| 92 |
f() |
| 93 |
|
| 94 |
f() |
| 95 |
assert "maximum recursion" in str(excinfo.value) |
| 96 |
|
| 97 |
``excinfo`` is an :class:`~pytest.ExceptionInfo` instance, which is a wrapper around |
| 98 |
the actual exception raised. The main attributes of interest are |
| 99 |
``.type``, ``.value`` and ``.traceback``. |
| 100 |
|
| 101 |
Note that ``pytest.raises`` will match the exception type or any subclasses (like the standard ``except`` statement). |
| 102 |
If you want to check if a block of code is raising an exact exception type, you need to check that explicitly: |
| 103 |
|
| 104 |
|
| 105 |
.. code-block:: python |
| 106 |
|
| 107 |
def test_foo_not_implemented(): |
| 108 |
def foo(): |
| 109 |
raise NotImplementedError |
| 110 |
|
| 111 |
with pytest.raises(RuntimeError) as excinfo: |
| 112 |
foo() |
| 113 |
assert excinfo.type is RuntimeError |
| 114 |
|
| 115 |
The :func:`pytest.raises` call will succeed, even though the function raises :class:`NotImplementedError`, because |
| 116 |
:class:`NotImplementedError` is a subclass of :class:`RuntimeError`; however the following `assert` statement will |
| 117 |
catch the problem. |
| 118 |
|
| 119 |
Matching exception messages |
| 120 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 121 |
|
| 122 |
You can pass a ``match`` keyword parameter to the context-manager to test |
| 123 |
that a regular expression matches on the string representation of an exception |
| 124 |
(similar to the ``TestCase.assertRaisesRegex`` method from ``unittest``): |
| 125 |
|
| 126 |
.. code-block:: python |
| 127 |
|
| 128 |
import pytest |
| 129 |
|
| 130 |
|
| 131 |
def myfunc(): |
| 132 |
raise ValueError("Exception 123 raised") |
| 133 |
|
| 134 |
|
| 135 |
def test_match(): |
| 136 |
with pytest.raises(ValueError, match=r".* 123 .*"): |
| 137 |
myfunc() |
| 138 |
|
| 139 |
Notes: |
| 140 |
|
| 141 |
* The ``match`` parameter is matched with the :func:`re.search` |
| 142 |
function, so in the above example ``match='123'`` would have worked as well. |
| 143 |
* The ``match`` parameter also matches against `PEP-678 <https://peps.python.org/pep-0678/>`__ ``__notes__``. |
| 144 |
|
| 145 |
|
| 146 |
.. _`assert-matching-exception-groups`: |
| 147 |
|
| 148 |
Matching exception groups |
| 149 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 150 |
|
| 151 |
You can also use the :func:`excinfo.group_contains() <pytest.ExceptionInfo.group_contains>` |
| 152 |
method to test for exceptions returned as part of an :class:`ExceptionGroup`: |
| 153 |
|
| 154 |
.. code-block:: python |
| 155 |
|
| 156 |
def test_exception_in_group(): |
| 157 |
with pytest.raises(ExceptionGroup) as excinfo: |
| 158 |
raise ExceptionGroup( |
| 159 |
"Group message", |
| 160 |
[ |
| 161 |
RuntimeError("Exception 123 raised"), |
| 162 |
], |
| 163 |
) |
| 164 |
assert excinfo.group_contains(RuntimeError, match=r".* 123 .*") |
| 165 |
assert not excinfo.group_contains(TypeError) |
| 166 |
|
| 167 |
The optional ``match`` keyword parameter works the same way as for |
| 168 |
:func:`pytest.raises`. |
| 169 |
|
| 170 |
By default ``group_contains()`` will recursively search for a matching |
| 171 |
exception at any level of nested ``ExceptionGroup`` instances. You can |
| 172 |
specify a ``depth`` keyword parameter if you only want to match an |
| 173 |
exception at a specific level; exceptions contained directly in the top |
| 174 |
``ExceptionGroup`` would match ``depth=1``. |
| 175 |
|
| 176 |
.. code-block:: python |
| 177 |
|
| 178 |
def test_exception_in_group_at_given_depth(): |
| 179 |
with pytest.raises(ExceptionGroup) as excinfo: |
| 180 |
raise ExceptionGroup( |
| 181 |
"Group message", |
| 182 |
[ |
| 183 |
RuntimeError(), |
| 184 |
ExceptionGroup( |
| 185 |
"Nested group", |
| 186 |
[ |
| 187 |
TypeError(), |
| 188 |
], |
| 189 |
), |
| 190 |
], |
| 191 |
) |
| 192 |
assert excinfo.group_contains(RuntimeError, depth=1) |
| 193 |
assert excinfo.group_contains(TypeError, depth=2) |
| 194 |
assert not excinfo.group_contains(RuntimeError, depth=2) |
| 195 |
assert not excinfo.group_contains(TypeError, depth=1) |
| 196 |
|
| 197 |
Alternate form (legacy) |
| 198 |
~~~~~~~~~~~~~~~~~~~~~~~ |
| 199 |
|
| 200 |
There is an alternate form where you pass |
| 201 |
a function that will be executed, along ``*args`` and ``**kwargs``, and :func:`pytest.raises` |
| 202 |
will execute the function with the arguments and assert that the given exception is raised: |
| 203 |
|
| 204 |
.. code-block:: python |
| 205 |
|
| 206 |
def func(x): |
| 207 |
if x <= 0: |
| 208 |
raise ValueError("x needs to be larger than zero") |
| 209 |
|
| 210 |
|
| 211 |
pytest.raises(ValueError, func, x=-1) |
| 212 |
|
| 213 |
The reporter will provide you with helpful output in case of failures such as *no |
| 214 |
exception* or *wrong exception*. |
| 215 |
|
| 216 |
This form was the original :func:`pytest.raises` API, developed before the ``with`` statement was |
| 217 |
added to the Python language. Nowadays, this form is rarely used, with the context-manager form (using ``with``) |
| 218 |
being considered more readable. |
| 219 |
Nonetheless, this form is fully supported and not deprecated in any way. |
| 220 |
|
| 221 |
xfail mark and pytest.raises |
| 222 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 223 |
|
| 224 |
It is also possible to specify a ``raises`` argument to |
| 225 |
:ref:`pytest.mark.xfail <pytest.mark.xfail ref>`, which checks that the test is failing in a more |
| 226 |
specific way than just having any exception raised: |
| 227 |
|
| 228 |
.. code-block:: python |
| 229 |
|
| 230 |
def f(): |
| 231 |
raise IndexError() |
| 232 |
|
| 233 |
|
| 234 |
@pytest.mark.xfail(raises=IndexError) |
| 235 |
def test_f(): |
| 236 |
f() |
| 237 |
|
| 238 |
|
| 239 |
This will only "xfail" if the test fails by raising ``IndexError`` or subclasses. |
| 240 |
|
| 241 |
* Using :ref:`pytest.mark.xfail <pytest.mark.xfail ref>` with the ``raises`` parameter is probably better for something |
| 242 |
like documenting unfixed bugs (where the test describes what "should" happen) or bugs in dependencies. |
| 243 |
|
| 244 |
* Using :func:`pytest.raises` is likely to be better for cases where you are |
| 245 |
testing exceptions your own code is deliberately raising, which is the majority of cases. |
| 246 |
|
| 247 |
|
| 248 |
.. _`assertwarns`: |
| 249 |
|
| 250 |
Assertions about expected warnings |
| 251 |
----------------------------------------- |
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
You can check that code raises a particular warning using |
| 256 |
:ref:`pytest.warns <warns>`. |
| 257 |
|
| 258 |
|
| 259 |
.. _newreport: |
| 260 |
|
| 261 |
Making use of context-sensitive comparisons |
| 262 |
------------------------------------------------- |
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
``pytest`` has rich support for providing context-sensitive information |
| 267 |
when it encounters comparisons. For example: |
| 268 |
|
| 269 |
.. code-block:: python |
| 270 |
|
| 271 |
# content of test_assert2.py |
| 272 |
def test_set_comparison(): |
| 273 |
set1 = set("1308") |
| 274 |
set2 = set("8035") |
| 275 |
assert set1 == set2 |
| 276 |
|
| 277 |
if you run this module: |
| 278 |
|
| 279 |
.. code-block:: pytest |
| 280 |
|
| 281 |
$ pytest test_assert2.py |
| 282 |
=========================== test session starts ============================ |
| 283 |
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y |
| 284 |
rootdir: /home/sweet/project |
| 285 |
collected 1 item |
| 286 |
|
| 287 |
test_assert2.py F [100%] |
| 288 |
|
| 289 |
================================= FAILURES ================================= |
| 290 |
___________________________ test_set_comparison ____________________________ |
| 291 |
|
| 292 |
def test_set_comparison(): |
| 293 |
set1 = set("1308") |
| 294 |
set2 = set("8035") |
| 295 |
> assert set1 == set2 |
| 296 |
E AssertionError: assert {'0', '1', '3', '8'} == {'0', '3', '5', '8'} |
| 297 |
E |
| 298 |
E Extra items in the left set: |
| 299 |
E '1' |
| 300 |
E Extra items in the right set: |
| 301 |
E '5' |
| 302 |
E Use -v to get more diff |
| 303 |
|
| 304 |
test_assert2.py:4: AssertionError |
| 305 |
========================= short test summary info ========================== |
| 306 |
FAILED test_assert2.py::test_set_comparison - AssertionError: assert {'0'... |
| 307 |
============================ 1 failed in 0.12s ============================= |
| 308 |
|
| 309 |
Special comparisons are done for a number of cases: |
| 310 |
|
| 311 |
* comparing long strings: a context diff is shown |
| 312 |
* comparing long sequences: first failing indices |
| 313 |
* comparing dicts: different entries |
| 314 |
|
| 315 |
See the :ref:`reporting demo <tbreportdemo>` for many more examples. |
| 316 |
|
| 317 |
Defining your own explanation for failed assertions |
| 318 |
--------------------------------------------------- |
| 319 |
|
| 320 |
It is possible to add your own detailed explanations by implementing |
| 321 |
the ``pytest_assertrepr_compare`` hook. |
| 322 |
|
| 323 |
.. autofunction:: _pytest.hookspec.pytest_assertrepr_compare |
| 324 |
:noindex: |
| 325 |
|
| 326 |
As an example consider adding the following hook in a :ref:`conftest.py <conftest.py>` |
| 327 |
file which provides an alternative explanation for ``Foo`` objects: |
| 328 |
|
| 329 |
.. code-block:: python |
| 330 |
|
| 331 |
# content of conftest.py |
| 332 |
from test_foocompare import Foo |
| 333 |
|
| 334 |
|
| 335 |
def pytest_assertrepr_compare(op, left, right): |
| 336 |
if isinstance(left, Foo) and isinstance(right, Foo) and op == "==": |
| 337 |
return [ |
| 338 |
"Comparing Foo instances:", |
| 339 |
f" vals: {left.val} != {right.val}", |
| 340 |
] |
| 341 |
|
| 342 |
now, given this test module: |
| 343 |
|
| 344 |
.. code-block:: python |
| 345 |
|
| 346 |
# content of test_foocompare.py |
| 347 |
class Foo: |
| 348 |
def __init__(self, val): |
| 349 |
self.val = val |
| 350 |
|
| 351 |
def __eq__(self, other): |
| 352 |
return self.val == other.val |
| 353 |
|
| 354 |
|
| 355 |
def test_compare(): |
| 356 |
f1 = Foo(1) |
| 357 |
f2 = Foo(2) |
| 358 |
assert f1 == f2 |
| 359 |
|
| 360 |
you can run the test module and get the custom output defined in |
| 361 |
the conftest file: |
| 362 |
|
| 363 |
.. code-block:: pytest |
| 364 |
|
| 365 |
$ pytest -q test_foocompare.py |
| 366 |
F [100%] |
| 367 |
================================= FAILURES ================================= |
| 368 |
_______________________________ test_compare _______________________________ |
| 369 |
|
| 370 |
def test_compare(): |
| 371 |
f1 = Foo(1) |
| 372 |
f2 = Foo(2) |
| 373 |
> assert f1 == f2 |
| 374 |
E assert Comparing Foo instances: |
| 375 |
E vals: 1 != 2 |
| 376 |
|
| 377 |
test_foocompare.py:12: AssertionError |
| 378 |
========================= short test summary info ========================== |
| 379 |
FAILED test_foocompare.py::test_compare - assert Comparing Foo instances: |
| 380 |
1 failed in 0.12s |
| 381 |
|
| 382 |
.. _assert-details: |
| 383 |
.. _`assert introspection`: |
| 384 |
|
| 385 |
Assertion introspection details |
| 386 |
------------------------------- |
| 387 |
|
| 388 |
|
| 389 |
Reporting details about a failing assertion is achieved by rewriting assert |
| 390 |
statements before they are run. Rewritten assert statements put introspection |
| 391 |
information into the assertion failure message. ``pytest`` only rewrites test |
| 392 |
modules directly discovered by its test collection process, so **asserts in |
| 393 |
supporting modules which are not themselves test modules will not be rewritten**. |
| 394 |
|
| 395 |
You can manually enable assertion rewriting for an imported module by calling |
| 396 |
:ref:`register_assert_rewrite <assertion-rewriting>` |
| 397 |
before you import it (a good place to do that is in your root ``conftest.py``). |
| 398 |
|
| 399 |
For further information, Benjamin Peterson wrote up `Behind the scenes of pytest's new assertion rewriting <http://pybites.blogspot.com/2011/07/behind-scenes-of-pytests-new-assertion.html>`_. |
| 400 |
|
| 401 |
Assertion rewriting caches files on disk |
| 402 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 403 |
|
| 404 |
``pytest`` will write back the rewritten modules to disk for caching. You can disable |
| 405 |
this behavior (for example to avoid leaving stale ``.pyc`` files around in projects that |
| 406 |
move files around a lot) by adding this to the top of your ``conftest.py`` file: |
| 407 |
|
| 408 |
.. code-block:: python |
| 409 |
|
| 410 |
import sys |
| 411 |
|
| 412 |
sys.dont_write_bytecode = True |
| 413 |
|
| 414 |
Note that you still get the benefits of assertion introspection, the only change is that |
| 415 |
the ``.pyc`` files won't be cached on disk. |
| 416 |
|
| 417 |
Additionally, rewriting will silently skip caching if it cannot write new ``.pyc`` files, |
| 418 |
i.e. in a read-only filesystem or a zipfile. |
| 419 |
|
| 420 |
|
| 421 |
Disabling assert rewriting |
| 422 |
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 423 |
|
| 424 |
``pytest`` rewrites test modules on import by using an import |
| 425 |
hook to write new ``pyc`` files. Most of the time this works transparently. |
| 426 |
However, if you are working with the import machinery yourself, the import hook may |
| 427 |
interfere. |
| 428 |
|
| 429 |
If this is the case you have two options: |
| 430 |
|
| 431 |
* Disable rewriting for a specific module by adding the string |
| 432 |
``PYTEST_DONT_REWRITE`` to its docstring. |
| 433 |
|
| 434 |
* Disable rewriting for all modules by using ``--assert=plain``. |