Skip to content
Advertisement

Assert exception message?

I’m using pytest in a project with a good many custom exceptions.

pytest provides a handy syntax for checking that an exception has been raised, however, I’m not aware of one that asserts that the correct exception message has been raised.

Say I had a CustomException that prints “boo!”, how could I assert that “boo!” has indeed been printed and not, say, “<unprintable CustomException object>”?

#errors.py
class CustomException(Exception):
    def __str__(self): return "ouch!"
#test.py
import pytest, myModule

def test_custom_error(): # SHOULD FAIL
    with pytest.raises(myModule.CustomException):
        raise myModule.CustomException == "boo!"

Advertisement

Answer

I think what you’re looking for is:

def failer():
    raise myModule.CustomException()

def test_failer():
    with pytest.raises(myModule.CustomException) as excinfo:
        failer()

    assert str(excinfo.value) == "boo!"
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement