Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,7 @@ Victor Rodriguez
Victor Uriarte
Vidar T. Fauske
Vijay Arora
Virendra Patil
Virgil Dupras
Vitaly Lashmanov
Vivaan Verma
Expand Down
1 change: 1 addition & 0 deletions changelog/12505.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve handling of invalid regex patterns in :func:`pytest.raises(match=r'...') <pytest.raises>` by providing a clear error message.
9 changes: 9 additions & 0 deletions src/_pytest/python_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import math
from numbers import Complex
import pprint
import re
from types import TracebackType
from typing import Any
from typing import Callable
Expand Down Expand Up @@ -986,6 +987,14 @@ def __init__(
self.message = message
self.match_expr = match_expr
self.excinfo: _pytest._code.ExceptionInfo[E] | None = None
if self.match_expr is not None:
re_error = None
try:
re.compile(self.match_expr)
except re.error as e:
re_error = e
if re_error is not None:
fail(f"Invalid regex pattern provided to 'match': {re_error}")

def __enter__(self) -> _pytest._code.ExceptionInfo[E]:
self.excinfo = _pytest._code.ExceptionInfo.for_later()
Expand Down
20 changes: 20 additions & 0 deletions testing/python/raises.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,26 @@ def test_division(example_input, expectation):
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 failed*"])

def test_raises_with_invalid_regex(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest

def test_invalid_regex():
with pytest.raises(ValueError, match="invalid regex character ["):
raise ValueError()
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*Invalid regex pattern provided to 'match': unterminated character set at position 24*",
]
)
result.stdout.no_fnmatch_line("*Traceback*")
result.stdout.no_fnmatch_line("*File*")
result.stdout.no_fnmatch_line("*line*")

def test_noclass(self) -> None:
with pytest.raises(TypeError):
pytest.raises("wrong", lambda: None) # type: ignore[call-overload]
Expand Down