Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 974
max Avatar asked Sep 08 '25 11:09

max


1 Answers

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.

like image 70
zifot Avatar answered Sep 11 '25 04:09

zifot