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!"
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.
It's always best practice to verify exceptions messages, application throwing is meaningful, and convey the right information.
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.
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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With