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 changelog/13192.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed `|` (pipe) not being treated as a regex meta-character that needs escaping in :func:`pytest.raises(match=...) <pytest.raises>`.
4 changes: 2 additions & 2 deletions src/_pytest/raises.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,14 +363,14 @@ def _check_raw_type(

def is_fully_escaped(s: str) -> bool:
# we know we won't compile with re.VERBOSE, so whitespace doesn't need to be escaped
metacharacters = "{}()+.*?^$[]"
metacharacters = "{}()+.*?^$[]|"
return not any(
c in metacharacters and (i == 0 or s[i - 1] != "\\") for (i, c) in enumerate(s)
)


def unescape(s: str) -> str:
return re.sub(r"\\([{}()+-.*?^$\[\]\s\\])", r"\1", s)
return re.sub(r"\\([{}()+-.*?^$\[\]\s\\|])", r"\1", s)


# These classes conceptually differ from ExceptionInfo in that ExceptionInfo is tied, and
Expand Down
9 changes: 9 additions & 0 deletions testing/python/raises.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,3 +430,12 @@ def test_raises_match_compiled_regex(self) -> None:
pattern_with_flags = re.compile(r"INVALID LITERAL", re.IGNORECASE)
with pytest.raises(ValueError, match=pattern_with_flags):
int("asdf")

def test_pipe_is_treated_as_regex_metacharacter(self) -> None:
"""| (pipe) must be recognized as a regex metacharacter."""
from _pytest.raises import is_fully_escaped
from _pytest.raises import unescape

assert not is_fully_escaped("foo|bar")
assert is_fully_escaped(r"foo\|bar")
assert unescape(r"foo\|bar") == "foo|bar"
Loading