Skip to content

Commit 7eb7b3e

Browse files
authored
Add test coverage for compiled regex patterns in pytest.raises() (#14026)
* Add test coverage for compiled regex patterns in pytest.raises() * Add changelog entry for #14026
1 parent 980bb5c commit 7eb7b3e

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@ Niclas Olofsson
338338
Nicolas Delaby
339339
Nicolas Simonds
340340
Nico Vidal
341+
Nikesh Chavhan
341342
Nikolay Kondratyev
342343
Nipunn Koorapati
343344
Oleg Pidsadnyi

changelog/14026.improvement.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added test coverage for compiled regex patterns in :func:`pytest.raises` match parameter.

testing/python/raises.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,3 +407,26 @@ def test_issue_11872(self) -> None:
407407
code=404, msg="Not Found", fp=io.BytesIO(), hdrs=Message(), url=""
408408
)
409409
exc_info.value.close() # avoid a resource warning
410+
411+
def test_raises_match_compiled_regex(self) -> None:
412+
"""Test that compiled regex patterns work with pytest.raises."""
413+
# Test with a compiled pattern that matches
414+
pattern = re.compile(r"with base \d+")
415+
with pytest.raises(ValueError, match=pattern):
416+
int("asdf")
417+
418+
# Test with a compiled pattern that doesn't match
419+
pattern_nomatch = re.compile(r"with base 16")
420+
expr = (
421+
"Regex pattern did not match.\n"
422+
f" Expected regex: {pattern_nomatch.pattern!r}\n"
423+
f" Actual message: \"invalid literal for int() with base 10: 'asdf'\""
424+
)
425+
with pytest.raises(AssertionError, match="^" + re.escape(expr) + "$"):
426+
with pytest.raises(ValueError, match=pattern_nomatch):
427+
int("asdf", base=10)
428+
429+
# Test compiled pattern with flags
430+
pattern_with_flags = re.compile(r"INVALID LITERAL", re.IGNORECASE)
431+
with pytest.raises(ValueError, match=pattern_with_flags):
432+
int("asdf")

0 commit comments

Comments
 (0)