max
max

Reputation: 52235

Performing an action whenever a unit test fails

I'm using unittest.

In case on of my tests in the testcase fails, I like to do something (e.g., save the erroneous output to a temporary folder for later review, etc.).

Where does this code belong?

At first, I thought I could check if self.assertEqual(...), but it turns out this function doesn't return any value. It makes sense now, since it is intended to kick the execution out of the test function once failure is detected.

tearDown is called regardless of the test success, so it doesn't seem to help either.

Upvotes: 4

Views: 2237

Answers (1)

zifot
zifot

Reputation: 2688

One way would be to set a flag on the test case instance and then check its value upon tear down:

def setUp(self):
    self.test_passed = false

def tearDown(self):
    if not self.test_passed:
        log()

def test_something(self):
    self.assertEquals(something())
    self.test_passed = true

You could write a decorator to avoid the need to set your flag to true at the end of every test.

Upvotes: 4

Related Questions