Python: self.assertEqual(a, b, msg) --> 我想要 diff 和 msg
Python: self.assertEqual(a, b, msg) --> I want diff AND msg
如果我这样称呼它,我会看到一个很好的差异:
self.assertEqual(a, b)
如果我这样调用它,我只会看到消息:
self.assertEqual(a, b, msg)
有没有简单的方法来显示差异和消息?
我自己实施 assertEqual()
会奏效,但我问自己这是否真的是最好的方法。
平台:Python2.7 和 pytest 2.6.2.
如果您设置 longMessage
attribute True
,您将看到这两条消息。
示例:
class TestFoo(unittest.TestCase):
longMessage = True # <--
def test_foo(self):
self.assertEqual(1+2, 2, 'custom message')
输出:
F
======================================================================
FAIL: test_foo (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "t.py", line 6, in test_foo
self.assertEqual(1+2, 2, 'custom message')
AssertionError: 3 != 2 : custom message
----------------------------------------------------------------------
Ran 1 test in 0.000s
由于您使用的是 pytest,因此您也可以使用 pytest 的普通断言而不是单元测试兼容性:
def test_foo():
assert "abcdefg" == "abcde", "My message"
输出:
====================== FAILURES ======================
______________________ test_foo ______________________
def test_foo():
> assert "abcdefg" == "abcde", "My message"
E AssertionError: My message
E assert 'abcdefg' == 'abcde'
E - abcdefg
E ? --
E + abcde
如果我这样称呼它,我会看到一个很好的差异:
self.assertEqual(a, b)
如果我这样调用它,我只会看到消息:
self.assertEqual(a, b, msg)
有没有简单的方法来显示差异和消息?
我自己实施 assertEqual()
会奏效,但我问自己这是否真的是最好的方法。
平台:Python2.7 和 pytest 2.6.2.
如果您设置 longMessage
attribute True
,您将看到这两条消息。
示例:
class TestFoo(unittest.TestCase):
longMessage = True # <--
def test_foo(self):
self.assertEqual(1+2, 2, 'custom message')
输出:
F
======================================================================
FAIL: test_foo (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "t.py", line 6, in test_foo
self.assertEqual(1+2, 2, 'custom message')
AssertionError: 3 != 2 : custom message
----------------------------------------------------------------------
Ran 1 test in 0.000s
由于您使用的是 pytest,因此您也可以使用 pytest 的普通断言而不是单元测试兼容性:
def test_foo():
assert "abcdefg" == "abcde", "My message"
输出:
====================== FAILURES ======================
______________________ test_foo ______________________
def test_foo():
> assert "abcdefg" == "abcde", "My message"
E AssertionError: My message
E assert 'abcdefg' == 'abcde'
E - abcdefg
E ? --
E + abcde