[Python-checkins] cpython (3.4): backport: #20145: assert[Raises|Warns]Regex now raise TypeError on bad regex.

r.david.murray python-checkins at python.org
Tue Mar 25 20:35:42 CET 2014


http://hg.python.org/cpython/rev/32407a677215
changeset:   89980:32407a677215
branch:      3.4
parent:      89977:aa2a05fe46ae
user:        R David Murray <rdmurray at bitdance.com>
date:        Tue Mar 25 15:31:50 2014 -0400
summary:
  backport: #20145: assert[Raises|Warns]Regex now raise TypeError on bad regex.

Previously a non-string, non-regex second argument and missing callable
argument could cause the test to appear to always pass.

Initial patch by Kamilla Holanda.

files:
  Lib/unittest/case.py           |   2 +-
  Lib/unittest/test/test_case.py |  12 ++++++++++++
  Misc/ACKS                      |   1 +
  Misc/NEWS                      |   3 +++
  4 files changed, 17 insertions(+), 1 deletions(-)


diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py
--- a/Lib/unittest/case.py
+++ b/Lib/unittest/case.py
@@ -143,7 +143,7 @@
                 self.obj_name = str(callable_obj)
         else:
             self.obj_name = None
-        if isinstance(expected_regex, (bytes, str)):
+        if expected_regex is not None:
             expected_regex = re.compile(expected_regex)
         self.expected_regex = expected_regex
         self.msg = None
diff --git a/Lib/unittest/test/test_case.py b/Lib/unittest/test/test_case.py
--- a/Lib/unittest/test/test_case.py
+++ b/Lib/unittest/test/test_case.py
@@ -1126,6 +1126,18 @@
                 self.assertRaisesRegex, Exception, 'x',
                 lambda: None)
 
+    def testAssertRaisesRegexInvalidRegex(self):
+        # Issue 20145.
+        class MyExc(Exception):
+            pass
+        self.assertRaises(TypeError, self.assertRaisesRegex, MyExc, lambda: True)
+
+    def testAssertWarnsRegexInvalidRegex(self):
+        # Issue 20145.
+        class MyWarn(Warning):
+            pass
+        self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True)
+
     def testAssertRaisesRegexMismatch(self):
         def Stub():
             raise Exception('Unexpected')
diff --git a/Misc/ACKS b/Misc/ACKS
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -546,6 +546,7 @@
 Albert Hofkamp
 Tomas Hoger
 Jonathan Hogg
+Kamilla Holanda
 Steve Holden
 Akintayo Holder
 Thomas Holenstein
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -24,6 +24,9 @@
 Library
 -------
 
+- Issue #20145: `assertRaisesRegex` and `assertWarnsRegex` now raise a
+  TypeError if the second argument is not a string or compiled regex.
+
 - Issue #21058: Fix a leak of file descriptor in
   :func:`tempfile.NamedTemporaryFile`, close the file descriptor if
   :func:`io.open` fails

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list