Skip to content

Commit f4a4c44

Browse files
committed
Handle match with pytest.raises()
Fixes pytest-dev#6752.
1 parent 478a244 commit f4a4c44

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

changelog/6752.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Handle ``match`` with :py:func:`pytest.raises` used as a function.

src/_pytest/python_api.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -710,6 +710,15 @@ def raises( # noqa: F811
710710
except expected_exception as e:
711711
# We just caught the exception - there is a traceback.
712712
assert e.__traceback__ is not None
713+
if match:
714+
excinfo = _pytest._code.ExceptionInfo.from_exc_info(
715+
(type(e), e, e.__traceback__)
716+
)
717+
excinfo.match(match)
718+
try:
719+
return excinfo
720+
finally:
721+
del excinfo
713722
return _pytest._code.ExceptionInfo.from_exc_info(
714723
(type(e), e, e.__traceback__)
715724
)

testing/python/raises.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import re
12
import sys
23

34
import pytest
@@ -154,7 +155,7 @@ def test_no_raise_message(self):
154155
else:
155156
assert False, "Expected pytest.raises.Exception"
156157

157-
@pytest.mark.parametrize("method", ["function", "with"])
158+
@pytest.mark.parametrize("method", ["function", "function_match", "with"])
158159
def test_raises_cyclic_reference(self, method):
159160
"""
160161
Ensure pytest.raises does not leave a reference cycle (#1965).
@@ -175,6 +176,8 @@ def __call__(self):
175176

176177
if method == "function":
177178
pytest.raises(ValueError, t)
179+
elif method == "function_match":
180+
pytest.raises(ValueError, t, match="^$")
178181
else:
179182
with pytest.raises(ValueError):
180183
t()
@@ -194,13 +197,19 @@ def test_raises_match(self):
194197
int("asdf")
195198

196199
msg = "with base 16"
197-
expr = r"Pattern '{}' does not match \"invalid literal for int\(\) with base 10: 'asdf'\"".format(
200+
expr = "Pattern {!r} does not match \"invalid literal for int() with base 10: 'asdf'\"".format(
198201
msg
199202
)
200-
with pytest.raises(AssertionError, match=expr):
203+
with pytest.raises(AssertionError, match=re.escape(expr)):
201204
with pytest.raises(ValueError, match=msg):
202205
int("asdf", base=10)
203206

207+
# "match" without context manager.
208+
pytest.raises(ValueError, int, "asdf", match="invalid literal")
209+
with pytest.raises(AssertionError) as excinfo:
210+
pytest.raises(ValueError, int, "asdf", match=msg)
211+
assert str(excinfo.value) == expr
212+
204213
def test_match_failure_string_quoting(self):
205214
with pytest.raises(AssertionError) as excinfo:
206215
with pytest.raises(AssertionError, match="'foo"):

0 commit comments

Comments
 (0)