Accessing test status in pyunit tearDown

◇◆丶佛笑我妖孽 提交于 2019-12-10 11:09:44

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!