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!"
snazzybouche
  • 2,241
  • 3
  • 21
  • 51
  • `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 '19 at 16:21
  • If you actually want to capture stdout or stderr, then you might want to look at the capsys fixture: https://docs.pytest.org/en/latest/capture.html#accessing-captured-output-from-a-test-function – Tom Dalton Aug 19 '19 at 16:22
  • Take a look at this: https://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 '19 at 16:24

2 Answers2

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!"
Tom Dalton
  • 6,122
  • 24
  • 35
8

You can use match keyword in raises. Try something like

with pytest.raises(
        RuntimeError, match=<error string here>
    ):
     pass
manu datta
  • 141
  • 2
  • 4