![](/img/trans.png)
[英]how to specify test specific setup and teardown in python unittest
[英]how to get the traceback of failed test (unittest) in the tearDown() function
我想将我运行的每个失败测试的所有异常的所有回溯保存到外部文件。 除了在每个测试中都使用try and之外,我想使用unittest的tearDown,这样它将更加通用。
就像是:
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中获得的异常无法在拆解中使用traceback调用(tracebacke返回None)
有什么建议吗?
因此,在检查了大部分的单元测试代码之后,我找到了解决方案!
TestCase
类具有_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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.