#10273: Rename assertRegexpMatches and assertRaisesRegexp to assertRegex and assertRaisesRegex.

This commit is contained in:
Ezio Melotti 2010-12-01 02:32:32 +00:00
parent f10c400b91
commit ed3a7d2d60
21 changed files with 203 additions and 186 deletions

View File

@ -835,7 +835,7 @@ Test cases
+-----------------------------------------+-----------------------------+---------------+
All the assert methods (except :meth:`assertRaises`,
:meth:`assertRaisesRegexp`, :meth:`assertWarns`, :meth:`assertWarnsRegexp`)
:meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`)
accept a *msg* argument that, if specified, is used as the error message on
failure (see also :data:`longMessage`).
@ -919,14 +919,14 @@ Test cases
| :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | |
| <TestCase.assertRaises>` | | |
+---------------------------------------------------------+--------------------------------------+------------+
| :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
| <TestCase.assertRaisesRegexp>` | and the message matches `re` | |
| :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 |
| <TestCase.assertRaisesRegex>` | and the message matches `re` | |
+---------------------------------------------------------+--------------------------------------+------------+
| :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
| <TestCase.assertWarns>` | | |
+---------------------------------------------------------+--------------------------------------+------------+
| :meth:`assertWarnsRegexp(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
| <TestCase.assertWarnsRegexp>` | and the message matches `re` | |
| :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 |
| <TestCase.assertWarnsRegex>` | and the message matches `re` | |
+---------------------------------------------------------+--------------------------------------+------------+
.. method:: assertRaises(exception, callable, *args, **kwds)
@ -962,23 +962,25 @@ Test cases
Added the :attr:`exception` attribute.
.. method:: assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
assertRaisesRegexp(exception, regexp)
.. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
assertRaisesRegex(exception, regex)
Like :meth:`assertRaises` but also tests that *regexp* matches
on the string representation of the raised exception. *regexp* may be
Like :meth:`assertRaises` but also tests that *regex* matches
on the string representation of the raised exception. *regex* may be
a regular expression object or a string containing a regular expression
suitable for use by :func:`re.search`. Examples::
self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
int, 'XYZ')
self.assertRaisesRegex(ValueError, 'invalid literal for.*XYZ$',
int, 'XYZ')
or::
with self.assertRaisesRegexp(ValueError, 'literal'):
with self.assertRaisesRegex(ValueError, 'literal'):
int('XYZ')
.. versionadded:: 3.1
.. versionadded:: 3.1 ``assertRaisesRegexp``
.. versionchanged:: 3.2
The method has been renamed to :meth:`assertRaisesRegex`
.. method:: assertWarns(warning, callable, *args, **kwds)
@ -1015,21 +1017,21 @@ Test cases
.. versionadded:: 3.2
.. method:: assertWarnsRegexp(warning, regexp, callable, *args, **kwds)
assertWarnsRegexp(warning, regexp)
.. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
assertWarnsRegex(warning, regex)
Like :meth:`assertWarns` but also tests that *regexp* matches on the
message of the triggered warning. *regexp* may be a regular expression
Like :meth:`assertWarns` but also tests that *regex* matches on the
message of the triggered warning. *regex* may be a regular expression
object or a string containing a regular expression suitable for use
by :func:`re.search`. Example::
self.assertWarnsRegexp(DeprecationWarning,
r'legacy_function\(\) is deprecated',
legacy_function, 'XYZ')
self.assertWarnsRegex(DeprecationWarning,
r'legacy_function\(\) is deprecated',
legacy_function, 'XYZ')
or::
with self.assertWarnsRegexp(RuntimeWarning, 'unsafe frobnicating'):
with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
frobnicate('/etc/passwd')
.. versionadded:: 3.2
@ -1059,11 +1061,11 @@ Test cases
| :meth:`assertLessEqual(a, b) | ``a <= b`` | 3.1 |
| <TestCase.assertLessEqual>` | | |
+---------------------------------------+--------------------------------+--------------+
| :meth:`assertRegexpMatches(s, re) | ``regex.search(s)`` | 3.1 |
| <TestCase.assertRegexpMatches>` | | |
| :meth:`assertRegex(s, re) | ``regex.search(s)`` | 3.1 |
| <TestCase.assertRegex>` | | |
+---------------------------------------+--------------------------------+--------------+
| :meth:`assertNotRegexpMatches(s, re) | ``not regex.search(s)`` | 3.2 |
| <TestCase.assertNotRegexpMatches>` | | |
| :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 |
| <TestCase.assertNotRegex>` | | |
+---------------------------------------+--------------------------------+--------------+
| :meth:`assertDictContainsSubset(a, b) | all the key/value pairs | 3.1 |
| <TestCase.assertDictContainsSubset>` | in `a` exist in `b` | |
@ -1108,17 +1110,19 @@ Test cases
.. versionadded:: 3.1
.. method:: assertRegexpMatches(text, regexp, msg=None)
assertNotRegexpMatches(text, regexp, msg=None)
.. method:: assertRegex(text, regex, msg=None)
assertNotRegex(text, regex, msg=None)
Test that a *regexp* search matches (or does not match) *text*. In case
Test that a *regex* search matches (or does not match) *text*. In case
of failure, the error message will include the pattern and the *text* (or
the pattern and the part of *text* that unexpectedly matched). *regexp*
the pattern and the part of *text* that unexpectedly matched). *regex*
may be a regular expression object or a string containing a regular
expression suitable for use by :func:`re.search`.
.. versionadded:: 3.1 :meth:`~TestCase.assertRegexpMatches`
.. versionadded:: 3.2 :meth:`~TestCase.assertNotRegexpMatches`
.. versionadded:: 3.1 ``.assertRegexpMatches``
.. versionchanged:: 3.2
``.assertRegexpMatches`` has been renamed to :meth:`.assertRegex`
.. versionadded:: 3.2 :meth:`.assertNotRegex`
.. method:: assertDictContainsSubset(expected, actual, msg=None)
@ -1420,13 +1424,17 @@ along with their deprecated aliases:
:meth:`.assertRaises` failUnlessRaises
:meth:`.assertAlmostEqual` failUnlessAlmostEqual assertAlmostEquals
:meth:`.assertNotAlmostEqual` failIfAlmostEqual assertNotAlmostEquals
:meth:`.assertRegex` assertRegexpMatches
:meth:`.assertRaisesRegex` assertRaisesRegexp
============================== ====================== ======================
.. deprecated-removed:: 3.1 3.3
the fail* aliases listed in the second column.
.. deprecated:: 3.2
the assert* aliases listed in the third column.
.. deprecated:: 3.2
``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
:meth:`.assertRegex` and :meth:`.assertRaisesRegex`
.. _testsuite-objects:

View File

@ -192,8 +192,8 @@ class TestABC(unittest.TestCase):
def test_register_non_class(self):
class A(metaclass=abc.ABCMeta):
pass
self.assertRaisesRegexp(TypeError, "Can only register classes",
A.register, 4)
self.assertRaisesRegex(TypeError, "Can only register classes",
A.register, 4)
def test_registration_transitiveness(self):
class A(metaclass=abc.ABCMeta):

View File

@ -312,8 +312,8 @@ class DispatcherTests(unittest.TestCase):
d = asyncore.dispatcher(socket.socket())
# make sure the error message no longer refers to the socket
# object but the dispatcher instance instead
self.assertRaisesRegexp(AttributeError, 'dispatcher instance',
getattr, d, 'foo')
self.assertRaisesRegex(AttributeError, 'dispatcher instance',
getattr, d, 'foo')
# cheap inheritance with the underlying socket is supposed
# to still work but a DeprecationWarning is expected
with warnings.catch_warnings(record=True) as w:

View File

@ -682,18 +682,18 @@ class FutureTests(unittest.TestCase):
self.assertTrue(was_cancelled)
def test_repr(self):
self.assertRegexpMatches(repr(PENDING_FUTURE),
'<Future at 0x[0-9a-f]+ state=pending>')
self.assertRegexpMatches(repr(RUNNING_FUTURE),
'<Future at 0x[0-9a-f]+ state=running>')
self.assertRegexpMatches(repr(CANCELLED_FUTURE),
'<Future at 0x[0-9a-f]+ state=cancelled>')
self.assertRegexpMatches(repr(CANCELLED_AND_NOTIFIED_FUTURE),
'<Future at 0x[0-9a-f]+ state=cancelled>')
self.assertRegexpMatches(
self.assertRegex(repr(PENDING_FUTURE),
'<Future at 0x[0-9a-f]+ state=pending>')
self.assertRegex(repr(RUNNING_FUTURE),
'<Future at 0x[0-9a-f]+ state=running>')
self.assertRegex(repr(CANCELLED_FUTURE),
'<Future at 0x[0-9a-f]+ state=cancelled>')
self.assertRegex(repr(CANCELLED_AND_NOTIFIED_FUTURE),
'<Future at 0x[0-9a-f]+ state=cancelled>')
self.assertRegex(
repr(EXCEPTION_FUTURE),
'<Future at 0x[0-9a-f]+ state=finished raised IOError>')
self.assertRegexpMatches(
self.assertRegex(
repr(SUCCESSFUL_FUTURE),
'<Future at 0x[0-9a-f]+ state=finished returned int>')

View File

@ -231,7 +231,7 @@ class TestContextDecorator(unittest.TestCase):
def test_contextdecorator_with_exception(self):
context = mycontext()
with self.assertRaisesRegexp(NameError, 'foo'):
with self.assertRaisesRegex(NameError, 'foo'):
with context:
raise NameError('foo')
self.assertIsNotNone(context.exc)
@ -265,7 +265,7 @@ class TestContextDecorator(unittest.TestCase):
self.assertTrue(context.started)
raise NameError('foo')
with self.assertRaisesRegexp(NameError, 'foo'):
with self.assertRaisesRegex(NameError, 'foo'):
test()
self.assertIsNotNone(context.exc)
self.assertIs(context.exc[0], NameError)

View File

@ -354,14 +354,14 @@ class CodeInfoTests(unittest.TestCase):
def test_code_info(self):
self.maxDiff = 1000
for x, expected in self.test_pairs:
self.assertRegexpMatches(dis.code_info(x), expected)
self.assertRegex(dis.code_info(x), expected)
def test_show_code(self):
self.maxDiff = 1000
for x, expected in self.test_pairs:
with captured_stdout() as output:
dis.show_code(x)
self.assertRegexpMatches(output.getvalue(), expected+"\n")
self.assertRegex(output.getvalue(), expected+"\n")
def test_main():
run_unittest(DisTests, CodeInfoTests)

View File

@ -226,7 +226,7 @@ class AbstractMemoryTests:
self.assertTrue(wr() is None, wr())
def _check_released(self, m, tp):
check = self.assertRaisesRegexp(ValueError, "released")
check = self.assertRaisesRegex(ValueError, "released")
with check: bytes(m)
with check: m.tobytes()
with check: m.tolist()

View File

@ -329,7 +329,7 @@ argv0 = sys.argv[0]
def _check_import_error(self, script_name, msg):
msg = re.escape(msg)
self.assertRaisesRegexp(ImportError, msg, run_path, script_name)
self.assertRaisesRegex(ImportError, msg, run_path, script_name)
def test_basic_script(self):
with temp_dir() as script_dir:
@ -403,7 +403,7 @@ argv0 = sys.argv[0]
script_name = self._make_test_script(script_dir, mod_name, source)
zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
msg = "recursion depth exceeded"
self.assertRaisesRegexp(RuntimeError, msg, run_path, zip_name)
self.assertRaisesRegex(RuntimeError, msg, run_path, zip_name)

View File

@ -319,12 +319,12 @@ class DebuggingServerTests(unittest.TestCase):
self.assertEqual(self.output.getvalue(), mexpect)
debugout = smtpd.DEBUGSTREAM.getvalue()
sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
self.assertRegexpMatches(debugout, sender)
self.assertRegex(debugout, sender)
for addr in ('John', 'Sally', 'Fred', 'root@localhost',
'warped@silly.walks.com'):
to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
re.MULTILINE)
self.assertRegexpMatches(debugout, to_addr)
self.assertRegex(debugout, to_addr)
def testSendMessageWithSomeAddresses(self):
# Make sure nothing breaks if not all of the three 'to' headers exist
@ -347,11 +347,11 @@ class DebuggingServerTests(unittest.TestCase):
self.assertEqual(self.output.getvalue(), mexpect)
debugout = smtpd.DEBUGSTREAM.getvalue()
sender = re.compile("^sender: foo@bar.com$", re.MULTILINE)
self.assertRegexpMatches(debugout, sender)
self.assertRegex(debugout, sender)
for addr in ('John', 'Dinsdale'):
to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
re.MULTILINE)
self.assertRegexpMatches(debugout, to_addr)
self.assertRegex(debugout, to_addr)
class NonConnectingTests(unittest.TestCase):

View File

@ -185,17 +185,17 @@ class BasicSocketTests(unittest.TestCase):
def test_errors(self):
sock = socket.socket()
self.assertRaisesRegexp(ValueError,
self.assertRaisesRegex(ValueError,
"certfile must be specified",
ssl.wrap_socket, sock, keyfile=CERTFILE)
self.assertRaisesRegexp(ValueError,
self.assertRaisesRegex(ValueError,
"certfile must be specified for server-side operations",
ssl.wrap_socket, sock, server_side=True)
self.assertRaisesRegexp(ValueError,
self.assertRaisesRegex(ValueError,
"certfile must be specified for server-side operations",
ssl.wrap_socket, sock, server_side=True, certfile="")
s = ssl.wrap_socket(sock, server_side=True, certfile=CERTFILE)
self.assertRaisesRegexp(ValueError, "can't connect in server-side mode",
self.assertRaisesRegex(ValueError, "can't connect in server-side mode",
s.connect, (HOST, 8080))
with self.assertRaises(IOError) as cm:
with socket.socket() as sock:
@ -310,7 +310,7 @@ class ContextTests(unittest.TestCase):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ctx.set_ciphers("ALL")
ctx.set_ciphers("DEFAULT")
with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"):
with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"):
ctx.set_ciphers("^$:,;?*'dorothyx")
@skip_if_broken_ubuntu_ssl
@ -358,24 +358,24 @@ class ContextTests(unittest.TestCase):
with self.assertRaises(IOError) as cm:
ctx.load_cert_chain(WRONGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(BADCERT)
with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(EMPTYCERT)
# Separate key and cert
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
ctx.load_cert_chain(ONLYCERT, ONLYKEY)
ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY)
ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY)
with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(ONLYCERT)
with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(ONLYKEY)
with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT)
# Mismatching key and cert
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
with self.assertRaisesRegexp(ssl.SSLError, "key values mismatch"):
with self.assertRaisesRegex(ssl.SSLError, "key values mismatch"):
ctx.load_cert_chain(SVN_PYTHON_ORG_ROOT_CERT, ONLYKEY)
def test_load_verify_locations(self):
@ -389,7 +389,7 @@ class ContextTests(unittest.TestCase):
with self.assertRaises(IOError) as cm:
ctx.load_verify_locations(WRONGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_verify_locations(BADCERT)
ctx.load_verify_locations(CERTFILE, CAPATH)
ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH)
@ -434,8 +434,8 @@ class NetworkedTests(unittest.TestCase):
# this should fail because we have no verification certs
s = ssl.wrap_socket(socket.socket(socket.AF_INET),
cert_reqs=ssl.CERT_REQUIRED)
self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed",
s.connect, ("svn.python.org", 443))
self.assertRaisesRegex(ssl.SSLError, "certificate verify failed",
s.connect, ("svn.python.org", 443))
s.close()
# this should succeed because we specify the root cert
@ -469,7 +469,7 @@ class NetworkedTests(unittest.TestCase):
# This should fail because we have no verification certs
ctx.verify_mode = ssl.CERT_REQUIRED
s = ctx.wrap_socket(socket.socket(socket.AF_INET))
self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed",
self.assertRaisesRegex(ssl.SSLError, "certificate verify failed",
s.connect, ("svn.python.org", 443))
s.close()
# This should succeed because we specify the root cert
@ -587,7 +587,7 @@ class NetworkedTests(unittest.TestCase):
cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT")
s.connect(remote)
# Error checking can happen at instantiation or when connecting
with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"):
with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"):
with socket.socket(socket.AF_INET) as sock:
s = ssl.wrap_socket(sock,
cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx")
@ -1499,8 +1499,8 @@ else:
c.settimeout(0.2)
c.connect((host, port))
# Will attempt handshake and time out
self.assertRaisesRegexp(ssl.SSLError, "timed out",
ssl.wrap_socket, c)
self.assertRaisesRegex(ssl.SSLError, "timed out",
ssl.wrap_socket, c)
finally:
c.close()
try:
@ -1508,8 +1508,8 @@ else:
c = ssl.wrap_socket(c)
c.settimeout(0.2)
# Will attempt handshake and time out
self.assertRaisesRegexp(ssl.SSLError, "timed out",
c.connect, (host, port))
self.assertRaisesRegex(ssl.SSLError, "timed out",
c.connect, (host, port))
finally:
c.close()
finally:

View File

@ -1427,7 +1427,7 @@ class UnicodeTest(string_tests.CommonTest,
# non-ascii format, ascii argument: ensure that PyUnicode_FromFormat()
# raises an error for a non-ascii format string.
self.assertRaisesRegexp(ValueError,
self.assertRaisesRegex(ValueError,
'^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
'string, got a non-ASCII byte: 0xe9$',
format_unicode, b'unicode\xe9=%s', 'ascii')

View File

@ -629,25 +629,25 @@ class UrlParseTestCase(unittest.TestCase):
def test_mixed_types_rejected(self):
# Several functions that process either strings or ASCII encoded bytes
# accept multiple arguments. Check they reject mixed type input
with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlparse("www.python.org", b"http")
with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlparse(b"www.python.org", "http")
with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlsplit("www.python.org", b"http")
with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlsplit(b"www.python.org", "http")
with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunparse(( b"http", "www.python.org","","","",""))
with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunparse(("http", b"www.python.org","","","",""))
with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunsplit((b"http", "www.python.org","","",""))
with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urlunsplit(("http", b"www.python.org","","",""))
with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urljoin("http://python.org", b"http://python.org")
with self.assertRaisesRegexp(TypeError, "Cannot mix str"):
with self.assertRaisesRegex(TypeError, "Cannot mix str"):
urllib.parse.urljoin(b"http://python.org", "http://python.org")
def _check_result_type(self, str_type):

View File

@ -715,8 +715,8 @@ class GzipServerTestCase(BaseServerTestCase):
t.encode_threshold = None
t.fake_gzip = True
p = xmlrpclib.ServerProxy(URL, transport=t)
cm = self.assertRaisesRegexp(xmlrpclib.ProtocolError,
re.compile(r"\b400\b"))
cm = self.assertRaisesRegex(xmlrpclib.ProtocolError,
re.compile(r"\b400\b"))
with cm:
p.pow(6, 8)

View File

@ -143,7 +143,7 @@ class CompressTestCase(BaseCompressTestCase, unittest.TestCase):
def test_incomplete_stream(self):
# An useful error message is given
x = zlib.compress(HAMLET_SCENE)
self.assertRaisesRegexp(zlib.error,
self.assertRaisesRegex(zlib.error,
"Error -5 while decompressing data: incomplete or truncated stream",
zlib.decompress, x[:-1])

View File

@ -94,7 +94,7 @@ def expectedFailure(func):
class _AssertRaisesBaseContext(object):
def __init__(self, expected, test_case, callable_obj=None,
expected_regexp=None):
expected_regex=None):
self.expected = expected
self.failureException = test_case.failureException
if callable_obj is not None:
@ -104,9 +104,9 @@ class _AssertRaisesBaseContext(object):
self.obj_name = str(callable_obj)
else:
self.obj_name = None
if isinstance(expected_regexp, (bytes, str)):
expected_regexp = re.compile(expected_regexp)
self.expected_regexp = expected_regexp
if isinstance(expected_regex, (bytes, str)):
expected_regex = re.compile(expected_regex)
self.expected_regex = expected_regex
class _AssertRaisesContext(_AssertRaisesBaseContext):
@ -132,13 +132,13 @@ class _AssertRaisesContext(_AssertRaisesBaseContext):
return False
# store exception, without traceback, for later retrieval
self.exception = exc_value.with_traceback(None)
if self.expected_regexp is None:
if self.expected_regex is None:
return True
expected_regexp = self.expected_regexp
if not expected_regexp.search(str(exc_value)):
expected_regex = self.expected_regex
if not expected_regex.search(str(exc_value)):
raise self.failureException('"%s" does not match "%s"' %
(expected_regexp.pattern, str(exc_value)))
(expected_regex.pattern, str(exc_value)))
return True
@ -172,8 +172,8 @@ class _AssertWarnsContext(_AssertRaisesBaseContext):
continue
if first_matching is None:
first_matching = w
if (self.expected_regexp is not None and
not self.expected_regexp.search(str(w))):
if (self.expected_regex is not None and
not self.expected_regex.search(str(w))):
continue
# store warning for later retrieval
self.warning = w
@ -183,7 +183,7 @@ class _AssertWarnsContext(_AssertRaisesBaseContext):
# Now we simply try to choose a helpful failure message
if first_matching is not None:
raise self.failureException('"%s" does not match "%s"' %
(self.expected_regexp.pattern, str(first_matching)))
(self.expected_regex.pattern, str(first_matching)))
if self.obj_name:
raise self.failureException("{0} not triggered by {1}"
.format(exc_name, self.obj_name))
@ -689,24 +689,6 @@ class TestCase(object):
raise self.failureException(msg)
def _deprecate(original_func):
def deprecated_func(*args, **kwargs):
warnings.warn(
'Please use {0} instead.'.format(original_func.__name__),
DeprecationWarning, 2)
return original_func(*args, **kwargs)
return deprecated_func
# The fail* methods can be removed in 3.3, the 5 assert* methods will
# have to stay around for a few more versions. See #9424.
failUnlessEqual = assertEquals = _deprecate(assertEqual)
failIfEqual = assertNotEquals = _deprecate(assertNotEqual)
failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)
failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
failUnless = assert_ = _deprecate(assertTrue)
failUnlessRaises = _deprecate(assertRaises)
failIf = _deprecate(assertFalse)
def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
"""An equality assertion for ordered sequences (like lists and tuples).
@ -1095,27 +1077,27 @@ class TestCase(object):
standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
self.fail(self._formatMessage(msg, standardMsg))
def assertRaisesRegexp(self, expected_exception, expected_regexp,
callable_obj=None, *args, **kwargs):
"""Asserts that the message in a raised exception matches a regexp.
def assertRaisesRegex(self, expected_exception, expected_regex,
callable_obj=None, *args, **kwargs):
"""Asserts that the message in a raised exception matches a regex.
Args:
expected_exception: Exception class expected to be raised.
expected_regexp: Regexp (re pattern object or string) expected
expected_regex: Regex (re pattern object or string) expected
to be found in error message.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.
"""
context = _AssertRaisesContext(expected_exception, self, callable_obj,
expected_regexp)
expected_regex)
if callable_obj is None:
return context
with context:
callable_obj(*args, **kwargs)
def assertWarnsRegexp(self, expected_warning, expected_regexp,
callable_obj=None, *args, **kwargs):
def assertWarnsRegex(self, expected_warning, expected_regex,
callable_obj=None, *args, **kwargs):
"""Asserts that the message in a triggered warning matches a regexp.
Basic functioning is similar to assertWarns() with the addition
that only warnings whose messages also match the regular expression
@ -1123,42 +1105,64 @@ class TestCase(object):
Args:
expected_warning: Warning class expected to be triggered.
expected_regexp: Regexp (re pattern object or string) expected
expected_regex: Regex (re pattern object or string) expected
to be found in error message.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.
"""
context = _AssertWarnsContext(expected_warning, self, callable_obj,
expected_regexp)
expected_regex)
if callable_obj is None:
return context
with context:
callable_obj(*args, **kwargs)
def assertRegexpMatches(self, text, expected_regexp, msg=None):
def assertRegex(self, text, expected_regex, msg=None):
"""Fail the test unless the text matches the regular expression."""
if isinstance(expected_regexp, (str, bytes)):
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)
if isinstance(expected_regex, (str, bytes)):
expected_regex = re.compile(expected_regex)
if not expected_regex.search(text):
msg = msg or "Regex didn't match"
msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
raise self.failureException(msg)
def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
def assertNotRegexMatches(self, text, unexpected_regex, msg=None):
"""Fail the test if the text matches the regular expression."""
if isinstance(unexpected_regexp, (str, bytes)):
unexpected_regexp = re.compile(unexpected_regexp)
match = unexpected_regexp.search(text)
if isinstance(unexpected_regex, (str, bytes)):
unexpected_regex = re.compile(unexpected_regex)
match = unexpected_regex.search(text)
if match:
msg = msg or "Regexp matched"
msg = msg or "Regex matched"
msg = '%s: %r matches %r in %r' % (msg,
text[match.start():match.end()],
unexpected_regexp.pattern,
unexpected_regex.pattern,
text)
raise self.failureException(msg)
def _deprecate(original_func):
def deprecated_func(*args, **kwargs):
warnings.warn(
'Please use {0} instead.'.format(original_func.__name__),
DeprecationWarning, 2)
return original_func(*args, **kwargs)
return deprecated_func
# The fail* methods can be removed in 3.3, the 5 assert* methods will
# have to stay around for a few more versions. See #9424.
failUnlessEqual = assertEquals = _deprecate(assertEqual)
failIfEqual = assertNotEquals = _deprecate(assertNotEqual)
failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)
failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
failUnless = assert_ = _deprecate(assertTrue)
failUnlessRaises = _deprecate(assertRaises)
failIf = _deprecate(assertFalse)
assertRaisesRegexp = _deprecate(assertRaisesRegex)
assertRegexpMatches = _deprecate(assertRegex)
class FunctionTestCase(TestCase):
"""A test case that wraps a test function.

View File

@ -92,15 +92,15 @@ class Test_Assertions(unittest.TestCase):
else:
self.fail("assertRaises() didn't let exception pass through")
def testAssertNotRegexpMatches(self):
self.assertNotRegexpMatches('Ala ma kota', r'r+')
def testAssertNotRegexMatches(self):
self.assertNotRegexMatches('Ala ma kota', r'r+')
try:
self.assertNotRegexpMatches('Ala ma kota', r'k.t', 'Message')
self.assertNotRegexMatches('Ala ma kota', r'k.t', 'Message')
except self.failureException as e:
self.assertIn("'kot'", e.args[0])
self.assertIn('Message', e.args[0])
else:
self.fail('assertNotRegexpMatches should have failed.')
self.fail('assertNotRegexMatches should have failed.')
class TestLongMessage(unittest.TestCase):
@ -153,15 +153,15 @@ class TestLongMessage(unittest.TestCase):
test = self.testableTrue
return getattr(test, methodName)
for i, expected_regexp in enumerate(errors):
for i, expected_regex in enumerate(errors):
testMethod = getMethod(i)
kwargs = {}
withMsg = i % 2
if withMsg:
kwargs = {"msg": "oops"}
with self.assertRaisesRegexp(self.failureException,
expected_regexp=expected_regexp):
with self.assertRaisesRegex(self.failureException,
expected_regex=expected_regex):
testMethod(*args, **kwargs)
def testAssertTrue(self):

View File

@ -872,44 +872,44 @@ test case
self.assertIsNotNone('DjZoPloGears on Rails')
self.assertRaises(self.failureException, self.assertIsNotNone, None)
def testAssertRegexpMatches(self):
self.assertRegexpMatches('asdfabasdf', r'ab+')
self.assertRaises(self.failureException, self.assertRegexpMatches,
def testAssertRegex(self):
self.assertRegex('asdfabasdf', r'ab+')
self.assertRaises(self.failureException, self.assertRegex,
'saaas', r'aaaa')
def testAssertRaisesRegexp(self):
def testAssertRaisesRegex(self):
class ExceptionMock(Exception):
pass
def Stub():
raise ExceptionMock('We expect')
self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub)
self.assertRaisesRegex(ExceptionMock, 'expect$', Stub)
def testAssertNotRaisesRegexp(self):
self.assertRaisesRegexp(
def testAssertNotRaisesRegex(self):
self.assertRaisesRegex(
self.failureException, '^Exception not raised by <lambda>$',
self.assertRaisesRegexp, Exception, re.compile('x'),
self.assertRaisesRegex, Exception, re.compile('x'),
lambda: None)
self.assertRaisesRegexp(
self.assertRaisesRegex(
self.failureException, '^Exception not raised by <lambda>$',
self.assertRaisesRegexp, Exception, 'x',
self.assertRaisesRegex, Exception, 'x',
lambda: None)
def testAssertRaisesRegexpMismatch(self):
def testAssertRaisesRegexMismatch(self):
def Stub():
raise Exception('Unexpected')
self.assertRaisesRegexp(
self.assertRaisesRegex(
self.failureException,
r'"\^Expected\$" does not match "Unexpected"',
self.assertRaisesRegexp, Exception, '^Expected$',
self.assertRaisesRegex, Exception, '^Expected$',
Stub)
self.assertRaisesRegexp(
self.assertRaisesRegex(
self.failureException,
r'"\^Expected\$" does not match "Unexpected"',
self.assertRaisesRegexp, Exception,
self.assertRaisesRegex, Exception,
re.compile('^Expected$'), Stub)
def testAssertRaisesExcValue(self):
@ -993,26 +993,26 @@ test case
with self.assertWarns(DeprecationWarning):
_runtime_warn()
def testAssertWarnsRegexpCallable(self):
def testAssertWarnsRegexCallable(self):
def _runtime_warn(msg):
warnings.warn(msg, RuntimeWarning)
self.assertWarnsRegexp(RuntimeWarning, "o+",
_runtime_warn, "foox")
self.assertWarnsRegex(RuntimeWarning, "o+",
_runtime_warn, "foox")
# Failure when no warning is triggered
with self.assertRaises(self.failureException):
self.assertWarnsRegexp(RuntimeWarning, "o+",
lambda: 0)
self.assertWarnsRegex(RuntimeWarning, "o+",
lambda: 0)
# Failure when another warning is triggered
with warnings.catch_warnings():
# Force default filter (in case tests are run with -We)
warnings.simplefilter("default", RuntimeWarning)
with self.assertRaises(self.failureException):
self.assertWarnsRegexp(DeprecationWarning, "o+",
_runtime_warn, "foox")
self.assertWarnsRegex(DeprecationWarning, "o+",
_runtime_warn, "foox")
# Failure when message doesn't match
with self.assertRaises(self.failureException):
self.assertWarnsRegexp(RuntimeWarning, "o+",
_runtime_warn, "barz")
self.assertWarnsRegex(RuntimeWarning, "o+",
_runtime_warn, "barz")
# A little trickier: we ask RuntimeWarnings to be raised, and then
# check for some of them. It is implementation-defined whether
# non-matching RuntimeWarnings are simply re-raised, or produce a
@ -1020,15 +1020,15 @@ test case
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
with self.assertRaises((RuntimeWarning, self.failureException)):
self.assertWarnsRegexp(RuntimeWarning, "o+",
_runtime_warn, "barz")
self.assertWarnsRegex(RuntimeWarning, "o+",
_runtime_warn, "barz")
def testAssertWarnsRegexpContext(self):
# Same as above, but with assertWarnsRegexp as a context manager
def testAssertWarnsRegexContext(self):
# Same as above, but with assertWarnsRegex as a context manager
def _runtime_warn(msg):
warnings.warn(msg, RuntimeWarning)
_runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1]
with self.assertWarnsRegexp(RuntimeWarning, "o+") as cm:
with self.assertWarnsRegex(RuntimeWarning, "o+") as cm:
_runtime_warn("foox")
self.assertIsInstance(cm.warning, RuntimeWarning)
self.assertEqual(cm.warning.args[0], "foox")
@ -1036,18 +1036,18 @@ test case
self.assertEqual(cm.lineno, _runtime_warn_lineno + 1)
# Failure when no warning is triggered
with self.assertRaises(self.failureException):
with self.assertWarnsRegexp(RuntimeWarning, "o+"):
with self.assertWarnsRegex(RuntimeWarning, "o+"):
pass
# Failure when another warning is triggered
with warnings.catch_warnings():
# Force default filter (in case tests are run with -We)
warnings.simplefilter("default", RuntimeWarning)
with self.assertRaises(self.failureException):
with self.assertWarnsRegexp(DeprecationWarning, "o+"):
with self.assertWarnsRegex(DeprecationWarning, "o+"):
_runtime_warn("foox")
# Failure when message doesn't match
with self.assertRaises(self.failureException):
with self.assertWarnsRegexp(RuntimeWarning, "o+"):
with self.assertWarnsRegex(RuntimeWarning, "o+"):
_runtime_warn("barz")
# A little trickier: we ask RuntimeWarnings to be raised, and then
# check for some of them. It is implementation-defined whether
@ -1056,7 +1056,7 @@ test case
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
with self.assertRaises((RuntimeWarning, self.failureException)):
with self.assertWarnsRegexp(RuntimeWarning, "o+"):
with self.assertWarnsRegex(RuntimeWarning, "o+"):
_runtime_warn("barz")
def testDeprecatedMethodNames(self):
@ -1078,7 +1078,9 @@ test case
(self.assert_, (True,)),
(self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
(self.failIf, (False,)),
(self.assertSameElements, ([1, 1, 2, 3], [1, 2, 3]))
(self.assertSameElements, ([1, 1, 2, 3], [1, 2, 3])),
(self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])),
(self.assertRegexpMatches, ('bar', 'bar')),
)
for meth, args in old:
with self.assertWarns(DeprecationWarning):

View File

@ -354,7 +354,7 @@ class TestDiscovery(unittest.TestCase):
expected_dir = os.path.abspath('foo')
msg = re.escape(r"'foo' module incorrectly imported from %r. Expected %r. "
"Is this module globally installed?" % (mod_dir, expected_dir))
self.assertRaisesRegexp(
self.assertRaisesRegex(
ImportError, '^%s$' % msg, loader.discover,
start_dir='foo', pattern='foo.py'
)

View File

@ -186,7 +186,7 @@ class Test_TestLoader(unittest.TestCase):
self.assertEqual(suite.countTestCases(), 1)
test = list(suite)[0]
self.assertRaisesRegexp(TypeError, "some failure", test.m)
self.assertRaisesRegex(TypeError, "some failure", test.m)
################################################################
### /Tests for TestLoader.loadTestsFromModule()

View File

@ -500,7 +500,7 @@ class TestSetups(unittest.TestCase):
messages = ('setUpModule', 'tearDownModule', 'setUpClass', 'tearDownClass', 'test_something')
for phase, msg in enumerate(messages):
with self.assertRaisesRegexp(Exception, msg):
with self.assertRaisesRegex(Exception, msg):
suite.debug()
if __name__ == '__main__':

View File

@ -46,6 +46,9 @@ Core and Builtins
Library
-------
- Issue #10273: Rename `assertRegexpMatches` and `assertRaisesRegexp` to
`assertRegex` and `assertRaisesRegex`.
- Issue #10535: Enable silenced warnings in unittest by default.
- Issue #9873: The URL parsing functions in urllib.parse now accept