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>”?
JavaScript
x
4
1
#errors.py
2
class CustomException(Exception):
3
def __str__(self): return "ouch!"
4
JavaScript
1
7
1
#test.py
2
import pytest, myModule
3
4
def test_custom_error(): # SHOULD FAIL
5
with pytest.raises(myModule.CustomException):
6
raise myModule.CustomException == "boo!"
7
Advertisement
Answer
I think what you’re looking for is:
JavaScript
1
9
1
def failer():
2
raise myModule.CustomException()
3
4
def test_failer():
5
with pytest.raises(myModule.CustomException) as excinfo:
6
failer()
7
8
assert str(excinfo.value) == "boo!"
9