14

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!"
3
  • a CustomException that prints "boo!" - do you mean a custom Exception whose string representation is "boo"? e.g. you want to assert str(exc) == "Boo!"?
    – Tom Dalton
    Aug 19, 2019 at 16:21
  • If you actually want to capture stdout or stderr, then you might want to look at the capsys fixture: docs.pytest.org/en/latest/…
    – Tom Dalton
    Aug 19, 2019 at 16:22
  • Take a look at this: stackoverflow.com/a/23514853/2372812, excinfo.value is the actual exeption raised so you can do assert str(excinfo.value) == "Boo"
    – Tom Dalton
    Aug 19, 2019 at 16:24

2 Answers 2

23

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!"
3
  • That is indeed what I'm looking for, thank you very much! Aug 20, 2019 at 8:24
  • 4
    Note: you have to access it outside the with block as in this answer. You can't access it after failer()
    – J.Kirk.
    Mar 19, 2021 at 17:55
  • That's true, and it's because any code directly after failer() will never be executed - the exception means it wont' get that far.
    – Tom Dalton
    Feb 7, 2022 at 15:11
9

You can use match keyword in raises. Try something like

with pytest.raises(
        RuntimeError, match=<error string here>
    ):
     pass

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.