8
我想将一个自定义断言方法添加到TestCase
子类。我试图从unittest
模块中复制我的实现,以便尽可能匹配常规TestCase
的行为。 (我宁愿只是委托给self.assertEqual()
,但这会导致更多的回溯噪音,请参阅下文)。unittest
模块似乎在报告失败的断言时会自动隐藏其实施的一些内部细节。如何隐藏我的堆栈框架在TestCase子类中?
import unittest
class MyTestCase(unittest.TestCase):
def assertLengthIsOne(self, sequence, msg=None):
if len(sequence) != 1:
msg = self._formatMessage(msg, "length is not one")
raise self.failureException(msg)
class TestFoo(MyTestCase):
seq = (1, 2, 3, 4, 5)
def test_stock_unittest_assertion(self):
self.assertEqual(len(self.seq), 1)
def test_custom_assertion(self):
self.assertLengthIsOne(self.seq)
unittest.main()
的这个输出是这样:
[email protected] $ python unittest-demo.py
FF
======================================================================
FAIL: test_custom_assertion (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "unittest-demo.py", line 16, in test_custom_assertion
self.assertLengthIsOne(self.seq)
File "unittest-demo.py", line 7, in assertLengthIsOne
raise self.failureException(msg)
AssertionError: length is not one
======================================================================
FAIL: test_stock_unittest_assertion (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "unittest-demo.py", line 13, in test_stock_unittest_assertion
self.assertEqual(len(self.seq), 1)
AssertionError: 5 != 1
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=2)
注意,定制的断言方法导致与两个框架,一个方法本身内的堆栈跟踪,而库存unittest
方法仅具有一个框架,用户代码中的相关行。我怎样才能将这个框架隐藏行为应用于我自己的方法?
我不能相信这个问题/答案没有得到更多的投票!伟大的信息,以及为什么我<3 SO。 – dbn
该解决方案非常有用! –
不确定是否更改了python.org上的pipermail,但正确链接到Peter的解决方案是https://mail.python.org/pipermail/python-list/2012-October/632386.html。除此之外,非常感谢你的指针,真的帮助了我。 –