Debian Codegraph @

doc/en/how-to/assert.rst

raw
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-9.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 Assertions about approximate equality
68 -------------------------------------
69
70 When comparing floating point values (or arrays of floats), small rounding
71 errors are common. Instead of using ``assert abs(a - b) < tol`` or
72 ``numpy.isclose``, you can use :func:`pytest.approx`:
73
74 .. code-block:: python
75
76 import pytest
77 import numpy as np
78
79
80 def test_floats():
81 assert (0.1 + 0.2) == pytest.approx(0.3)
82
83
84 def test_arrays():
85 a = np.array([1.0, 2.0, 3.0])
86 b = np.array([0.9999, 2.0001, 3.0])
87 assert a == pytest.approx(b)
88
89 ``pytest.approx`` works with scalars, lists, dictionaries, and NumPy arrays.
90 It also supports comparisons involving NaNs.
91
92 See :func:`pytest.approx` for details.
93
94 .. _`assertraises`:
95
96 Assertions about expected exceptions
97 ------------------------------------------
98
99 In order to write assertions about raised exceptions, you can use
100 :func:`pytest.raises` as a context manager like this:
101
102 .. code-block:: python
103
104 import pytest
105
106
107 def test_zero_division():
108 with pytest.raises(ZeroDivisionError):
109 1 / 0
110
111 and if you need to have access to the actual exception info you may use:
112
113 .. code-block:: python
114
115 def test_recursion_depth():
116 with pytest.raises(RuntimeError) as excinfo:
117
118 def f():
119 f()
120
121 f()
122 assert "maximum recursion" in str(excinfo.value)
123
124 ``excinfo`` is an :class:`~pytest.ExceptionInfo` instance, which is a wrapper around
125 the actual exception raised. The main attributes of interest are
126 ``.type``, ``.value`` and ``.traceback``.
127
128 Note that ``pytest.raises`` will match the exception type or any subclasses (like the standard ``except`` statement).
129 If you want to check if a block of code is raising an exact exception type, you need to check that explicitly:
130
131
132 .. code-block:: python
133
134 def test_foo_not_implemented():
135 def foo():
136 raise NotImplementedError
137
138 with pytest.raises(RuntimeError) as excinfo:
139 foo()
140 assert excinfo.type is RuntimeError
141
142 The :func:`pytest.raises` call will succeed, even though the function raises :class:`NotImplementedError`, because
143 :class:`NotImplementedError` is a subclass of :class:`RuntimeError`; however the following `assert` statement will
144 catch the problem.
145
146 Matching exception messages
147 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
148
149 You can pass a ``match`` keyword parameter to the context-manager to test
150 that a regular expression matches on the string representation of an exception
151 (similar to the ``TestCase.assertRaisesRegex`` method from ``unittest``):
152
153 .. code-block:: python
154
155 import pytest
156
157
158 def myfunc():
159 raise ValueError("Exception 123 raised")
160
161
162 def test_match():
163 with pytest.raises(ValueError, match=r".* 123 .*"):
164 myfunc()
165
166 Notes:
167
168 * The ``match`` parameter is matched with the :func:`re.search`
169 function, so in the above example ``match='123'`` would have worked as well.
170 * The ``match`` parameter also matches against `PEP-678 <https://peps.python.org/pep-0678/>`__ ``__notes__``.
171
172
173 .. _`assert-matching-exception-groups`:
174
175 Assertions about expected exception groups
176 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
177
178 When expecting a :exc:`BaseExceptionGroup` or :exc:`ExceptionGroup` you can use :class:`pytest.RaisesGroup`:
179
180 .. code-block:: python
181
182 def test_exception_in_group():
183 with pytest.RaisesGroup(ValueError):
184 raise ExceptionGroup("group msg", [ValueError("value msg")])
185 with pytest.RaisesGroup(ValueError, TypeError):
186 raise ExceptionGroup("msg", [ValueError("foo"), TypeError("bar")])
187
188
189 It accepts a ``match`` parameter, that checks against the group message, and a ``check`` parameter that takes an arbitrary callable which it passes the group to, and only succeeds if the callable returns ``True``.
190
191 .. code-block:: python
192
193 def test_raisesgroup_match_and_check():
194 with pytest.RaisesGroup(BaseException, match="my group msg"):
195 raise BaseExceptionGroup("my group msg", [KeyboardInterrupt()])
196 with pytest.RaisesGroup(
197 Exception, check=lambda eg: isinstance(eg.__cause__, ValueError)
198 ):
199 raise ExceptionGroup("", [TypeError()]) from ValueError()
200
201 It is strict about structure and unwrapped exceptions, unlike :ref:`except* <except_star>`, so you might want to set the ``flatten_subgroups`` and/or ``allow_unwrapped`` parameters.
202
203 .. code-block:: python
204
205 def test_structure():
206 with pytest.RaisesGroup(pytest.RaisesGroup(ValueError)):
207 raise ExceptionGroup("", (ExceptionGroup("", (ValueError(),)),))
208 with pytest.RaisesGroup(ValueError, flatten_subgroups=True):
209 raise ExceptionGroup("1st group", [ExceptionGroup("2nd group", [ValueError()])])
210 with pytest.RaisesGroup(ValueError, allow_unwrapped=True):
211 raise ValueError
212
213 To specify more details about the contained exception you can use :class:`pytest.RaisesExc`
214
215 .. code-block:: python
216
217 def test_raises_exc():
218 with pytest.RaisesGroup(pytest.RaisesExc(ValueError, match="foo")):
219 raise ExceptionGroup("", (ValueError("foo")))
220
221 They both supply a method :meth:`pytest.RaisesGroup.matches` :meth:`pytest.RaisesExc.matches` if you want to do matching outside of using it as a :external+python:std:ref:`context manager <context-managers>`. This can be helpful when checking ``.__context__`` or ``.__cause__``.
222
223 .. code-block:: python
224
225 def test_matches():
226 exc = ValueError()
227 exc_group = ExceptionGroup("", [exc])
228 if RaisesGroup(ValueError).matches(exc_group):
229 ...
230 # helpful error is available in `.fail_reason` if it fails to match
231 r = RaisesExc(ValueError)
232 assert r.matches(e), r.fail_reason
233
234 Check the documentation on :class:`pytest.RaisesGroup` and :class:`pytest.RaisesExc` for more details and examples.
235
236 ``ExceptionInfo.group_contains()``
237 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
238
239 .. warning::
240
241 This helper makes it easy to check for the presence of specific exceptions, but it is very bad for checking that the group does *not* contain *any other exceptions*. So this will pass:
242
243 .. code-block:: python
244
245 class EXTREMELYBADERROR(BaseException):
246 """This is a very bad error to miss"""
247
248
249 def test_for_value_error():
250 with pytest.raises(ExceptionGroup) as excinfo:
251 excs = [ValueError()]
252 if very_unlucky():
253 excs.append(EXTREMELYBADERROR())
254 raise ExceptionGroup("", excs)
255 # This passes regardless of if there's other exceptions.
256 assert excinfo.group_contains(ValueError)
257 # You can't simply list all exceptions you *don't* want to get here.
258
259
260 There is no good way of using :func:`excinfo.group_contains() <pytest.ExceptionInfo.group_contains>` to ensure you're not getting *any* other exceptions than the one you expected.
261 You should instead use :class:`pytest.RaisesGroup`, see :ref:`assert-matching-exception-groups`.
262
263 You can also use the :func:`excinfo.group_contains() <pytest.ExceptionInfo.group_contains>`
264 method to test for exceptions returned as part of an :class:`ExceptionGroup`:
265
266 .. code-block:: python
267
268 def test_exception_in_group():
269 with pytest.raises(ExceptionGroup) as excinfo:
270 raise ExceptionGroup(
271 "Group message",
272 [
273 RuntimeError("Exception 123 raised"),
274 ],
275 )
276 assert excinfo.group_contains(RuntimeError, match=r".* 123 .*")
277 assert not excinfo.group_contains(TypeError)
278
279 The optional ``match`` keyword parameter works the same way as for
280 :func:`pytest.raises`.
281
282 By default ``group_contains()`` will recursively search for a matching
283 exception at any level of nested ``ExceptionGroup`` instances. You can
284 specify a ``depth`` keyword parameter if you only want to match an
285 exception at a specific level; exceptions contained directly in the top
286 ``ExceptionGroup`` would match ``depth=1``.
287
288 .. code-block:: python
289
290 def test_exception_in_group_at_given_depth():
291 with pytest.raises(ExceptionGroup) as excinfo:
292 raise ExceptionGroup(
293 "Group message",
294 [
295 RuntimeError(),
296 ExceptionGroup(
297 "Nested group",
298 [
299 TypeError(),
300 ],
301 ),
302 ],
303 )
304 assert excinfo.group_contains(RuntimeError, depth=1)
305 assert excinfo.group_contains(TypeError, depth=2)
306 assert not excinfo.group_contains(RuntimeError, depth=2)
307 assert not excinfo.group_contains(TypeError, depth=1)
308
309 Alternate `pytest.raises` form (legacy)
310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
311
312 There is an alternate form of :func:`pytest.raises` where you pass
313 a function that will be executed, along with ``*args`` and ``**kwargs``. :func:`pytest.raises`
314 will then execute the function with those arguments and assert that the given exception is raised:
315
316 .. code-block:: python
317
318 def func(x):
319 if x <= 0:
320 raise ValueError("x needs to be larger than zero")
321
322
323 pytest.raises(ValueError, func, x=-1)
324
325 This form was the original :func:`pytest.raises` API, developed before the ``with`` statement was
326 added to the Python language. Nowadays, this form is rarely used, with the context-manager form (using ``with``)
327 being considered more readable.
328
329 xfail mark and pytest.raises
330 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
331
332 It is also possible to specify a ``raises`` argument to
333 :ref:`pytest.mark.xfail <pytest.mark.xfail ref>`, which checks that the test is failing in a more
334 specific way than just having any exception raised:
335
336 .. code-block:: python
337
338 def f():
339 raise IndexError()
340
341
342 @pytest.mark.xfail(raises=IndexError)
343 def test_f():
344 f()
345
346
347 This will only "xfail" if the test fails by raising ``IndexError`` or subclasses.
348
349 * Using :ref:`pytest.mark.xfail <pytest.mark.xfail ref>` with the ``raises`` parameter is probably better for something
350 like documenting unfixed bugs (where the test describes what "should" happen) or bugs in dependencies.
351
352 * Using :func:`pytest.raises` is likely to be better for cases where you are
353 testing exceptions your own code is deliberately raising, which is the majority of cases.
354
355 You can also use :class:`pytest.RaisesGroup`:
356
357 .. code-block:: python
358
359 def f():
360 raise ExceptionGroup("", [IndexError()])
361
362
363 @pytest.mark.xfail(raises=RaisesGroup(IndexError))
364 def test_f():
365 f()
366
367
368 .. _`assertwarns`:
369
370 Assertions about expected warnings
371 -----------------------------------------
372
373
374
375 You can check that code raises a particular warning using
376 :ref:`pytest.warns <warns>`.
377
378
379 .. _newreport:
380
381 Making use of context-sensitive comparisons
382 -------------------------------------------------
383
384
385
386 ``pytest`` has rich support for providing context-sensitive information
387 when it encounters comparisons. For example:
388
389 .. code-block:: python
390
391 # content of test_assert2.py
392 def test_set_comparison():
393 set1 = set("1308")
394 set2 = set("8035")
395 assert set1 == set2
396
397 if you run this module:
398
399 .. code-block:: pytest
400
401 $ pytest test_assert2.py
402 =========================== test session starts ============================
403 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
404 rootdir: /home/sweet/project
405 collected 1 item
406
407 test_assert2.py F [100%]
408
409 ================================= FAILURES =================================
410 ___________________________ test_set_comparison ____________________________
411
412 def test_set_comparison():
413 set1 = set("1308")
414 set2 = set("8035")
415 > assert set1 == set2
416 E AssertionError: assert {'0', '1', '3', '8'} == {'0', '3', '5', '8'}
417 E
418 E Extra items in the left set:
419 E '1'
420 E Extra items in the right set:
421 E '5'
422 E Use -v to get more diff
423
424 test_assert2.py:4: AssertionError
425 ========================= short test summary info ==========================
426 FAILED test_assert2.py::test_set_comparison - AssertionError: assert {'0'...
427 ============================ 1 failed in 0.12s =============================
428
429 Special comparisons are done for a number of cases:
430
431 * comparing long strings: a context diff is shown
432 * comparing long sequences: first failing indices
433 * comparing dicts: different entries
434
435 In string context diffs, lines prefixed with ``-`` come from the left-hand side
436 of ``assert left == right``, while lines prefixed with ``+`` come from the
437 right-hand side.
438
439 See the :ref:`reporting demo <tbreportdemo>` for many more examples.
440
441 Defining your own explanation for failed assertions
442 ---------------------------------------------------
443
444 It is possible to add your own detailed explanations by implementing
445 the ``pytest_assertrepr_compare`` hook.
446
447 .. autofunction:: _pytest.hookspec.pytest_assertrepr_compare
448 :noindex:
449
450 As an example consider adding the following hook in a :ref:`conftest.py <conftest.py>`
451 file which provides an alternative explanation for ``Foo`` objects:
452
453 .. code-block:: python
454
455 # content of conftest.py
456 from test_foocompare import Foo
457
458
459 def pytest_assertrepr_compare(op, left, right):
460 if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":
461 return [
462 "Comparing Foo instances:",
463 f" vals: {left.val} != {right.val}",
464 ]
465
466 now, given this test module:
467
468 .. code-block:: python
469
470 # content of test_foocompare.py
471 class Foo:
472 def __init__(self, val):
473 self.val = val
474
475 def __eq__(self, other):
476 return self.val == other.val
477
478
479 def test_compare():
480 f1 = Foo(1)
481 f2 = Foo(2)
482 assert f1 == f2
483
484 you can run the test module and get the custom output defined in
485 the conftest file:
486
487 .. code-block:: pytest
488
489 $ pytest -q test_foocompare.py
490 F [100%]
491 ================================= FAILURES =================================
492 _______________________________ test_compare _______________________________
493
494 def test_compare():
495 f1 = Foo(1)
496 f2 = Foo(2)
497 > assert f1 == f2
498 E assert Comparing Foo instances:
499 E vals: 1 != 2
500
501 test_foocompare.py:12: AssertionError
502 ========================= short test summary info ==========================
503 FAILED test_foocompare.py::test_compare - assert Comparing Foo instances:
504 1 failed in 0.12s
505
506 .. _`return-not-none`:
507
508 Returning non-None value in test functions
509 ------------------------------------------
510
511 A :class:`pytest.PytestReturnNotNoneWarning` is emitted when a test function returns a value other than ``None``.
512
513 This helps prevent a common mistake made by beginners who assume that returning a ``bool`` (e.g., ``True`` or ``False``) will determine whether a test passes or fails.
514
515 Example:
516
517 .. code-block:: python
518
519 @pytest.mark.parametrize(
520 ["a", "b", "result"],
521 [
522 [1, 2, 5],
523 [2, 3, 8],
524 [5, 3, 18],
525 ],
526 )
527 def test_foo(a, b, result):
528 return foo(a, b) == result # Incorrect usage, do not do this.
529
530 Since pytest ignores return values, it might be surprising that the test will never fail based on the returned value.
531
532 The correct fix is to replace the ``return`` statement with an ``assert``:
533
534 .. code-block:: python
535
536 @pytest.mark.parametrize(
537 ["a", "b", "result"],
538 [
539 [1, 2, 5],
540 [2, 3, 8],
541 [5, 3, 18],
542 ],
543 )
544 def test_foo(a, b, result):
545 assert foo(a, b) == result
546
547
548
549
550 .. _assert-details:
551 .. _`assert introspection`:
552
553 Assertion introspection details
554 -------------------------------
555
556
557 Reporting details about a failing assertion is achieved by rewriting assert
558 statements before they are run. Rewritten assert statements put introspection
559 information into the assertion failure message. ``pytest`` only rewrites test
560 modules directly discovered by its test collection process, so **asserts in
561 supporting modules which are not themselves test modules will not be rewritten**.
562
563 You can manually enable assertion rewriting for an imported module by calling
564 :ref:`register_assert_rewrite <assertion-rewriting>`
565 before you import it (a good place to do that is in your root ``conftest.py``).
566
567 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>`_.
568
569 Assertion rewriting caches files on disk
570 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
571
572 ``pytest`` will write back the rewritten modules to disk for caching. You can disable
573 this behavior (for example to avoid leaving stale ``.pyc`` files around in projects that
574 move files around a lot) by adding this to the top of your ``conftest.py`` file:
575
576 .. code-block:: python
577
578 import sys
579
580 sys.dont_write_bytecode = True
581
582 Note that you still get the benefits of assertion introspection, the only change is that
583 the ``.pyc`` files won't be cached on disk.
584
585 Additionally, rewriting will silently skip caching if it cannot write new ``.pyc`` files,
586 e.g. in a read-only filesystem or a zipfile.
587
588
589 Disabling assert rewriting
590 ~~~~~~~~~~~~~~~~~~~~~~~~~~
591
592 ``pytest`` rewrites test modules on import by using an import
593 hook to write new ``pyc`` files. Most of the time this works transparently.
594 However, if you are working with the import machinery yourself, the import hook may
595 interfere.
596
597 If this is the case you have two options:
598
599 * Disable rewriting for a specific module by adding the string
600 ``PYTEST_DONT_REWRITE`` to its docstring.
601
602 * Disable rewriting for all modules by using :option:`--assert=plain`.