Skip to content

Commit 49bb5c8

Browse files
Improved handling of invalid regex pattern in pytest.raises (#12526)
1 parent e8aee21 commit 49bb5c8

File tree

4 files changed

+31
-0
lines changed

4 files changed

+31
-0
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,7 @@ Victor Rodriguez
430430
Victor Uriarte
431431
Vidar T. Fauske
432432
Vijay Arora
433+
Virendra Patil
433434
Virgil Dupras
434435
Vitaly Lashmanov
435436
Vivaan Verma

changelog/12505.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve handling of invalid regex patterns in :func:`pytest.raises(match=r'...') <pytest.raises>` by providing a clear error message.

src/_pytest/python_api.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import math
88
from numbers import Complex
99
import pprint
10+
import re
1011
from types import TracebackType
1112
from typing import Any
1213
from typing import Callable
@@ -986,6 +987,14 @@ def __init__(
986987
self.message = message
987988
self.match_expr = match_expr
988989
self.excinfo: _pytest._code.ExceptionInfo[E] | None = None
990+
if self.match_expr is not None:
991+
re_error = None
992+
try:
993+
re.compile(self.match_expr)
994+
except re.error as e:
995+
re_error = e
996+
if re_error is not None:
997+
fail(f"Invalid regex pattern provided to 'match': {re_error}")
989998

990999
def __enter__(self) -> _pytest._code.ExceptionInfo[E]:
9911000
self.excinfo = _pytest._code.ExceptionInfo.for_later()

testing/python/raises.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,26 @@ def test_division(example_input, expectation):
132132
result = pytester.runpytest()
133133
result.stdout.fnmatch_lines(["*2 failed*"])
134134

135+
def test_raises_with_invalid_regex(self, pytester: Pytester) -> None:
136+
pytester.makepyfile(
137+
"""
138+
import pytest
139+
140+
def test_invalid_regex():
141+
with pytest.raises(ValueError, match="invalid regex character ["):
142+
raise ValueError()
143+
"""
144+
)
145+
result = pytester.runpytest()
146+
result.stdout.fnmatch_lines(
147+
[
148+
"*Invalid regex pattern provided to 'match': unterminated character set at position 24*",
149+
]
150+
)
151+
result.stdout.no_fnmatch_line("*Traceback*")
152+
result.stdout.no_fnmatch_line("*File*")
153+
result.stdout.no_fnmatch_line("*line*")
154+
135155
def test_noclass(self) -> None:
136156
with pytest.raises(TypeError):
137157
pytest.raises("wrong", lambda: None) # type: ignore[call-overload]

0 commit comments

Comments
 (0)