我正在使用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')
关于python - 抑制单元测试中的补充错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21157905/