如何在 tearDown() 函数中获取失败测试(unittest)的回溯

how to get the traceback of failed test (unittest) in the tearDown() function

我想将每个失败测试的所有异常的所有回溯保存到外部文件中 运行。 我不想在每个测试中使用 try 和 except,而是使用 unittest 的拆解,这样它会更通用。

类似于:

import traceback
import unittest

class SomeTestCase(unittest.TestCase):
    def setUp(self):
        pass

    def test_some_test(self):
        self.assertTrue(False)

    def tearDown(self):
        with open(logger.txt, 'a') as doc:
            doc.write(traceback.format_exc())

问题是您在 test_some_test 中获得的异常无法在拆解中使用回溯调用(回溯 return None)

有什么建议吗?

所以在我检查了一大段单元测试代码后,我找到了解决方案!

TestCase class 有一个 _outcome 属性。
_outcome 有一个名为 errors 的列表类型属性。
errors[0][1] 是一个元组,与包含回溯的 sys.exc_info() 输出完全一样。
所以现在我有了这个可以在 traceback.format_exception() 中使用的元组,就像 traceback.format_exc() 使用它并且 问题解决了 .

def tearDown(self):
    try:
        etype, value, tb = self._outcome.errors[0][1]
        trace = ''.join(traceback.format_exception(etype=etype, value=value, tb=tb, limit=None))
        date = '{date}\n'.format(date=str(datetime.datetime.now()))
        name = '\n' + self._testMethodName + '-\n'
        with open(self.logger, 'a') as doc:
            doc.write(name + date + trace)
    except:
        pass