![](/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.