【问题标题】:Suppress supplementary error message from unit test抑制来自单元测试的补充错误消息
【发布时间】:2014-01-16 09:28:25
【问题描述】:

我在单元测试中使用assertRegexpMatches

self.assertRegexpMatches(text, regexp, msg='custom short message')

问题是 unittest 将它自己的错误消息添加到指定为参数的msg

AssertionError: <custom short message>: '<regexp>' not found in '<text>'

由于要匹配的文本很大(约 1 页),它会弄乱测试报告。有什么方法可以禁止 unittest 将'<regexp>' not found in '<text>' 部分添加到指定的错误消息中?

【问题讨论】:

    标签: python unit-testing python-2.7


    【解决方案1】:

    根据the source code,只要你使用TestCase.assertRegexpMatches,就不可能压制消息。

    def assertRegexpMatches(self, text, expected_regexp, msg=None):
        """Fail the test unless the text matches the regular expression."""
        if isinstance(expected_regexp, basestring):
            expected_regexp = re.compile(expected_regexp)
        if not expected_regexp.search(text):
            msg = msg or "Regexp didn't match"
            msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text) #<-
            raise self.failureException(msg)
    

    您需要定义自己的断言方法或使用自定义字符串类,如下所示:

    示例(不是漂亮的解决方案,但有效):

    import unittest
    
    class CustomString(str):
        # XXX: implementation dependant
        # redefine `__repr__` because `assertRegexpMatches` use `%r`
        def __repr__(self):
            return '<Huge string>'
    
    class TestFoo(unittest.TestCase):
        def test_foo(self):
            self.assertRegexpMatches(CustomString('1234'), 'abcd', msg='custom msg')
    
    if __name__ == '__main__':
        unittest.main()
    

    或将re.searchassertTrue 一起使用:

    class TestFoo(unittest.TestCase):
        def test_foo(self):
            self.assertTrue(re.search(regexp, text), msg='custom msg')
    

    【讨论】:

    • 在代码中,有一个属性self.longMessage,许多其他断言函数似乎都尊重它。我想知道为什么决定(决定了吗?) assertRegexpMatches 将不尊重此属性。
    • 还找到了longMessage 属性的文档。
    • @Dhara,我添加了一个解决方法。但是正如您评论的那样,如果assertRegexpMatches 尊重longMessage 属性会很好。
    • 我遇到了与assertIn() 类似的问题,这真的很有帮助。但看起来longMessage 的默认值现在是True。 (见cpython source here。)我最终只在我想抑制长x not found in y消息的个别测试函数中设置self.longMessage = False
    【解决方案2】:

    您可以覆盖 assertRegexpMatches 方法:

    class Test(unittest.TestCase):
        def assertRegexpMatches(self, text, expected_regexp, msg=None):
            try:
                unittest.TestCase.assertRegexpMatches(self, text, expected_regexp, msg)
            except Exception, e:
                msg = str(e)
                shortened_msg = (msg[:100]+'...' if len(msg)>100 else msg)
                raise self.failureException(shortened_msg)
    

    或者,如果您根本不需要该消息:

    class Test(unittest.TestCase):
        def assertRegexpMatches(self, text, expected_regexp, msg=None):
            try:
                unittest.TestCase.assertRegexpMatches(self, text, expected_regexp, msg)
            except Exception, e:
                raise self.failureException(msg or "Regexp didn't match")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 2022-06-28
      相关资源
      最近更新 更多