Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert exception message?

Tags:

python

pytest

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!"
like image 975
snazzybouche Avatar asked Aug 19 '19 16:08

snazzybouche


People also ask

What is assert exception?

If the expected exception is thrown, assertThrows returns the exception, which enables us to also assert on the message. Furthermore, it's important to note that this assertion is satisfied when the enclosed code throws an exception of type NumberFormatException or any of its derived types.

Should you test exception messages?

It's always best practice to verify exceptions messages, application throwing is meaningful, and convey the right information.

How do you handle exceptions in assert?

In order to handle the assertion error, we need to declare the assertion statement in the try block and catch the assertion error in the catch block.


1 Answers

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!"
like image 108
Tom Dalton Avatar answered Oct 12 '22 12:10

Tom Dalton