【发布时间】:2018-04-19 18:29:44
【问题描述】:
我想向 TestCase 添加一些自定义断言方法。作为一个简单的例子,我只是在下面的测试类中放了一个。它按预期工作,但是当生成输出时,回溯会在输出中包含自定义断言。
要让它表现得像 assertEqual() 的必要步骤是什么? assertEqual 的代码在 TestCase 中,但引发断言的实际行没有出现在回溯中。我需要做什么才能使 test_something2 的输出看起来更像 test_something1 的?
import unittest
class TestCustomAssert(unittest.TestCase):
def assertSomething(self, s):
self.assertEqual(s, 'something')
def test_something1(self):
self.assertEqual('foo', 'something')
def test_something2(self):
self.assertSomething('foo')
if __name__ == '__main__':
unittest.main()
输出
python3 custom_assert.py
FF
======================================================================
FAIL: test_something1 (__main__.TestCustomAssert)
----------------------------------------------------------------------
Traceback (most recent call last):
File "custom_assert.py", line 8, in test_something1
self.assertEqual('foo', 'something')
AssertionError: 'foo' != 'something'
- foo
+ something
======================================================================
FAIL: test_something2 (__main__.TestCustomAssert)
----------------------------------------------------------------------
Traceback (most recent call last):
File "custom_assert.py", line 10, in test_something2
self.assertSomething('foo')
File "custom_assert.py", line 6, in assertSomething
self.assertEqual(s, 'something')
AssertionError: 'foo' != 'something'
- foo
+ something
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=2)
【问题讨论】:
标签: python-3.x python-unittest