How do you call a function after each test in a Python unittest.TestCase derived class based on the test result?
For instance, lets say we have the following test class:
import sys
from unittest import TestCase
class TestFeedback(TestCase):
def msg(self, text):
sys.stdout.write(text + ' ...')
def on_fail(self):
sys.stdout.write(' FAILED!\n')
def on_success(self):
sys.stdout.write(' SUCCEEDED!\n')
def test_something(self):
self.msg('Testing whether True == 1')
self.assertTrue(True == 1)
def test_another(self):
self.msg('Testing whether None == 0')
self.assertEqual(None, 0)
I would like the methods on_success() or on_fail() to be called after each test depending on the outcome of the test, e.g.
>>> unittest.main()
...
Testing whether True == 1 ... SUCCEEDED!
Testing whether None == 0 ... FAILED!
<etc.>
Can this be done and, if so, how?
As of right now, I don't think you can do this. The TestResult object is gone before you get to your tearDown method, which would most likely be the easiest.
Instead, you could roll your own TestSuite (see here for a basic explanation), which should give you access to the results for each test. The downside is that you would have to add each test individually or create your own discovery method.
Another option would be to pass an error message into your asserts; the messages will be printed on fail:
self.assertEqual(None, 0, 'None is not 0')
What is your end goal here? Running the unittests will tell you which tests failed with traceback information, so I imagine you have a different goal in mind.
Edit:
Alright, I think one solution would be to write your own custom TestCase class and override the __call__ method (note: I haven't tested this):
from unittest import TestCase
class CustomTestCase(TestCase):
def __call__(self, *args, **kwds):
result = self.run(*args, **kwds)
<do something with result>
return result
Edit 2:
Another possible solution...check out this answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With