I need to make a call to a web API after each pyunit test in a test suite passes or fails, so I basically need access to the test status in the tearDown method.
But I can't find (or I've completely missed it) any documentation on who to access this data.
Any ideas?
Use TestResult.
import unittest
class TestFoo(unittest.TestCase):
def test_ok(self):
self.assertEqual(1+2, 3)
def test_fail(self):
self.assertEqual(1+2, 4)
def test_error(self):
1/0
@unittest.skip('blah')
def test_skip(self):
self.assertEqual(42, 42)
class MyResult(unittest.TextTestResult):
def addError(self, test, err):
self.call_web_api(test, err)
return super(MyResult, self).addError(test, err)
def addFailure(self, test, err):
self.call_web_api(test, err)
return super(MyResult, self).addFailure(test, err)
def call_web_api(self, test, err):
print('***', test, err)
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestFoo))
runner = unittest.TextTestRunner(resultclass=MyResult)
runner.run(suite)
You can also use as follow:
...
runner = unittest.TextTestRunner()
result = runner.run(suite)
print(result.errors)
print(result.failures)
print(result.skipped)
来源:https://stackoverflow.com/questions/17319515/accessing-test-status-in-pyunit-teardown