Skip to main content
 首页 » 编程设计

python之抑制来自单元测试的补充错误消息

2024年11月01日9qlqwjy

我正在使用 assertRegexpMatches在我的单元测试中:

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

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

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

由于要匹配的文本非常大(约 1 页),它会弄乱测试报告。有什么办法可以抑制单元测试添加 '<regexp>' not found in '<text>'指定错误消息的一部分?

请您参考如下方法:

根据 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.search 与 assertTrue 一起使用:

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