Pytest provides a context manager, which can be used to test that a certain piece of code raises an exception.
In order to test different input values and whether or not an exception is raised, pytest's parametrisation feature can be combined with
nullcontext from the contextlib module.
from contextlib import nullcontext as does_not_raise import pytest @pytest.mark.parametrize( "example_input,expectation", [ (3, does_not_raise()), (2, does_not_raise()), (1, does_not_raise()), (0, pytest.raises(ZeroDivisionError)), ], ) def test_division(example_input, expectation): """Test how much I know division.""" with expectation: assert (6 / example_input) is not None