从单元测试中抑制补充错误消息

时间:2014-01-16 09:28:25

标签: python unit-testing python-2.7

我在我的单元测试中使用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>'部分添加到指定的错误消息?

2 个答案:

答案 0 :(得分:2)

根据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')

答案 1 :(得分:0)

您可以覆盖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")