【问题标题】:How can I only show the custom error message for Python's unittest module如何只显示 Python 的 unittest 模块的自定义错误消息
【发布时间】:2016-11-04 02:43:34
【问题描述】:

使用 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。

我可以这样做吗?

【问题讨论】:

    标签: python unit-testing assertion


    【解决方案1】:

    您可以取消 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)
    

    要抑制“假为真”部分,请将 longMessage 类属性更改为 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
    

    【讨论】:

    • @Tyler 没问题。祝你好运。
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 2012-02-27
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    相关资源
    最近更新 更多