我在单元测试中使用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>'
零件添加到指定的错误消息中?
根据源代码,只要您使用,就不可能抑制该消息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')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句