Testing Expected Exceptions

pytest
Author

Imad Dabbura

Published

December 27, 2022

Tests generally fails for 3 reasons:

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 exception
def test_raises_exc():
    msg_regex = "something .* final"
    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()
    expected = "Some exception message"
    assert expected in str(exc.value)