Skip to content

Commit b8b7433

Browse files
authored
Improve docs for Parametrizing conditional raising (#11279)
What one typically actually wants in such a case is both, checking for some resulting values *and* checking for some expected exception. Since this is easily possible with the `nullcontext` context manager, adapt the example accordingly (needlessly using a different name rather just confuses people). Signed-off-by: Christoph Anton Mitterer <[email protected]>
1 parent 4797dea commit b8b7433

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

doc/en/example/parametrize.rst

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -657,30 +657,34 @@ Use :func:`pytest.raises` with the
657657
:ref:`pytest.mark.parametrize ref` decorator to write parametrized tests
658658
in which some tests raise exceptions and others do not.
659659

660-
It may be helpful to use ``nullcontext`` as a complement to ``raises``.
660+
``contextlib.nullcontext`` can be used to test cases that are not expected to
661+
raise exceptions but that should result in some value. The value is given as the
662+
``enter_result`` parameter, which will be available as the ``with`` statement’s
663+
target (``e`` in the example below).
661664

662665
For example:
663666

664667
.. code-block:: python
665668
666-
from contextlib import nullcontext as does_not_raise
669+
from contextlib import nullcontext
667670
668671
import pytest
669672
670673
671674
@pytest.mark.parametrize(
672675
"example_input,expectation",
673676
[
674-
(3, does_not_raise()),
675-
(2, does_not_raise()),
676-
(1, does_not_raise()),
677+
(3, nullcontext(2)),
678+
(2, nullcontext(3)),
679+
(1, nullcontext(6)),
677680
(0, pytest.raises(ZeroDivisionError)),
678681
],
679682
)
680683
def test_division(example_input, expectation):
681684
"""Test how much I know division."""
682-
with expectation:
683-
assert (6 / example_input) is not None
685+
with expectation as e:
686+
assert (6 / example_input) == e
684687
685-
In the example above, the first three test cases should run unexceptionally,
686-
while the fourth should raise ``ZeroDivisionError``.
688+
In the example above, the first three test cases should run without any
689+
exceptions, while the fourth should raise a``ZeroDivisionError`` exception,
690+
which is expected by pytest.

0 commit comments

Comments
 (0)