Tests generally fails for 3 reasons:
- The assetion test fails
pytest.fail()
is called with the test- An exception is raised in the code that is being tested and not handled
We can use pytest.fail()
to test for exceptions that our code is expected to raise in certain cases.
We can test if the code raises expected exception (here ValueError
):
def test_raises_exc():
with pytest.fail(ValueError):
fn()
We can test if the code raises expected exception and exception message matches correct message:
# One way using regular expressions to test the message using re.search over
value of the exceptiondef test_raises_exc():
= "something .* final"
msg_regex with pytest.fail(ValueError, match=msg_regex):
fn()
# Another way to test the exact message
def test_raises_exc():
with pytest.fail(ValueError) as exc:
fn()= "Some exception message"
expected assert expected in str(exc.value)