Pass a Python unittest if an exception isn't raised

Question:

In the Python unittest framework, is there a way to pass a unit test if an exception wasn’t raised, and fail with an AssertRaise otherwise?

Asked By: Levi Campbell

||

Answers:

If I understand your question correctly, you could do something like this:

def test_does_not_raise_on_valid_input(self):
    raised = False
    try:
        do_something(42)
    except:
        raised = True
    self.assertFalse(raised, 'Exception raised')

…assuming that you have a corresponding test that the correct Exception gets raised on invalid input, of course:

def test_does_raise_on_invalid_input(self):
    self.assertRaises(OutOfCheese, do_something, 43)

However, as pointed out in the comments, you need to consider what it is that you are actually testing. It’s likely that a test like…

def test_what_is_42(self):
    self.assertEquals(do_something(42), 'Meaning of life')

…is better because it tests the desired behaviour of the system and will fail if an exception is raised.

Answered By: johnsyweb

Many of the comments on this page treat errors and failures as equivalent, which they are not. The right solution in my opinion is to explicitly fail the test if the exception is raised. E.g.:

def test_does_not_error(self):
    try:
        code_under_test()
    except ThatException:
        self.fail("code_under_test raised ThatException")
Answered By: Paul Bissex

Simply call your functionality, e.g. do_something(). If an unhandled exception gets raised, the test automatically fails! There is really no reason to do anything else. This is also the reason why assertDoesNotRaise() does not exist.


Credit: comment by Sven

Answered By: Asclepius
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.