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