I am using assertRegexpMatches in my unittests:
self.assertRegexpMatches(text, regexp, msg='custom short message')
The problem is that unittest adds it's own error message to the msg
specified as argument:
AssertionError: <custom short message>: '<regexp>' not found in '<text>'
Since the text to match is quite large (~1 page), it messes up the test reports. Is there any way to suppress unittest from adding the '<regexp>' not found in '<text>'
part to the specified error message?
According to the source code, it's impossible to suppress the message as long as you use 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)
You need to define your own assertion method or use custom string class as follow:
Example (not beautiful solution, but works):
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()
or using re.search
with assertTrue
:
class TestFoo(unittest.TestCase):
def test_foo(self):
self.assertTrue(re.search(regexp, text), msg='custom msg')
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments