我怎样才能只显示 Python 的单元测试模块的自定义错误消息
How can I only show the custom error message for Python's unittest module
使用Python的unittest
模块,断言
self.assertTrue(a > b - 0.5 && a < b + 0.5, "The two values did not agree")
失败时输出以下内容:
AssertionError: False is not true : The two values did not agree
我不想打印 False is not true
。理想情况下,也不应打印 AssertionError
。只应打印 The two values did not agree
。
我可以这样做吗?
你可以抑制 False is true
部分,但是,这里要记住一件事,你正在 提出 一个例外,你看到的是标准Python 中提出的断言的输出。你想看到这个。此外,这是在断言方法中直接调用的,正如您从下面的 assertTrue
中看到的那样:
def assertTrue(self, expr, msg=None):
"""Check that the expression is true."""
if not expr:
msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
raise self.failureException(msg)
要抑制 'False is true' 部分,请将 longMessage class 属性更改为 False:
class TestCompare(unittest.TestCase):
longMessage = False
def test_thing(self):
self.assertTrue(5 == 6, "The two values did not agree")
输出:
Failure
Traceback (most recent call last):
File "/Users/XXX/dev/rough/test_this.py", line 21, in test_things
self.assertTrue(5 == 6, "The two values did not agree")
AssertionError: The two values did not agree
使用Python的unittest
模块,断言
self.assertTrue(a > b - 0.5 && a < b + 0.5, "The two values did not agree")
失败时输出以下内容:
AssertionError: False is not true : The two values did not agree
我不想打印 False is not true
。理想情况下,也不应打印 AssertionError
。只应打印 The two values did not agree
。
我可以这样做吗?
你可以抑制 False is true
部分,但是,这里要记住一件事,你正在 提出 一个例外,你看到的是标准Python 中提出的断言的输出。你想看到这个。此外,这是在断言方法中直接调用的,正如您从下面的 assertTrue
中看到的那样:
def assertTrue(self, expr, msg=None):
"""Check that the expression is true."""
if not expr:
msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
raise self.failureException(msg)
要抑制 'False is true' 部分,请将 longMessage class 属性更改为 False:
class TestCompare(unittest.TestCase):
longMessage = False
def test_thing(self):
self.assertTrue(5 == 6, "The two values did not agree")
输出:
Failure
Traceback (most recent call last):
File "/Users/XXX/dev/rough/test_this.py", line 21, in test_things
self.assertTrue(5 == 6, "The two values did not agree")
AssertionError: The two values did not agree