Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ef1c267

Browse files
committed
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.
1 parent 87d13ea commit ef1c267

4 files changed

Lines changed: 17 additions & 1 deletion

File tree

Lib/unittest/case.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ def __init__(self, expected, test_case, callable_obj=None,
143143
self.obj_name = str(callable_obj)
144144
else:
145145
self.obj_name = None
146-
if isinstance(expected_regex, (bytes, str)):
146+
if expected_regex is not None:
147147
expected_regex = re.compile(expected_regex)
148148
self.expected_regex = expected_regex
149149
self.msg = None

Lib/unittest/test/test_case.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,6 +1126,18 @@ def testAssertNotRaisesRegex(self):
11261126
self.assertRaisesRegex, Exception, 'x',
11271127
lambda: None)
11281128

1129+
def testAssertRaisesRegexInvalidRegex(self):
1130+
# Issue 20145.
1131+
class MyExc(Exception):
1132+
pass
1133+
self.assertRaises(TypeError, self.assertRaisesRegex, MyExc, lambda: True)
1134+
1135+
def testAssertWarnsRegexInvalidRegex(self):
1136+
# Issue 20145.
1137+
class MyWarn(Warning):
1138+
pass
1139+
self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True)
1140+
11291141
def testAssertRaisesRegexMismatch(self):
11301142
def Stub():
11311143
raise Exception('Unexpected')

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,7 @@ Stefan Hoffmeister
546546
Albert Hofkamp
547547
Tomas Hoger
548548
Jonathan Hogg
549+
Kamilla Holanda
549550
Steve Holden
550551
Akintayo Holder
551552
Thomas Holenstein

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ Core and Builtins
2424
Library
2525
-------
2626

27+
- Issue #20145: `assertRaisesRegex` and `assertWarnsRegex` now raise a
28+
TypeError if the second argument is not a string or compiled regex.
29+
2730
- Issue #21058: Fix a leak of file descriptor in
2831
:func:`tempfile.NamedTemporaryFile`, close the file descriptor if
2932
:func:`io.open` fails

0 commit comments

Comments
 (0)