Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run code when unit test assert fails [closed]

I'm using assertEquals() from unittest.TestCase. What I want to do now is to call a function and do something there when the assertion fails, I wonder if there's a way of doing this?

like image 728
J Freebird Avatar asked Jan 11 '23 08:01

J Freebird


1 Answers

In general you shouldn't do it, but if you really want to, here is a simple example:

import unittest

def testFailed():
    print("test failed")

class T(unittest.TestCase):
    def test_x(self):
        try:
            self.assertTrue(False)
        except AssertionError:
            testFailed()
            raise

if __name__ == "__main__":
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(T)
    unittest.TextTestRunner().run(suite)

Another, more generic possibility is to write your own runTest method (as mentioned in the documentation) which will wrap all tests with try/except block. This would be even more recommended if you really need to do it, as it will keep your test code clean.

like image 168
BartoszKP Avatar answered Jan 19 '23 02:01

BartoszKP