Skip to content

Commit e885db4

Browse files
authored
Merge pull request #14420 from pytest-dev/patchback/backports/9.0.x/cd7592c41c40ebc9663c2984447d72e95c731bda/pr-14391
[PR #14391/cd7592c4 backport][9.0.x] Use direct cause for raises match failures
2 parents 68a341f + 0931840 commit e885db4

4 files changed

Lines changed: 30 additions & 1 deletion

File tree

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@ Fraser Stark
179179
Freya Bruhin
180180
Gabriel Landau
181181
Gabriel Reis
182+
Garion Milazzo
182183
Garvit Shubham
183184
Gene Wood
184185
George Kussumoto

changelog/14389.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improved :func:`pytest.raises(..., match=...) <pytest.raises>` failures to suppress the mismatched exception as a cause of the resulting ``AssertionError``.

src/_pytest/raises.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -716,7 +716,7 @@ def __exit__(
716716
if not self.matches(exc_val):
717717
if self._just_propagate:
718718
return False
719-
raise AssertionError(self._fail_reason)
719+
raise AssertionError(self._fail_reason) from None
720720

721721
# Cast to narrow the exception type now that it's verified....
722722
# even though the TypeGuard in self.matches should be narrowing

testing/python/raises.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,33 @@ def test_invalid_regex():
177177
result.stdout.no_fnmatch_line("*File*")
178178
result.stdout.no_fnmatch_line("*line*")
179179

180+
def test_raises_match_failure_suppresses_exception_context(
181+
self, pytester: Pytester
182+
) -> None:
183+
pytester.makepyfile(
184+
"""
185+
import pytest
186+
187+
def test_raises_match_failure():
188+
with pytest.raises(ValueError, match="expected"):
189+
raise ValueError("actual")
190+
"""
191+
)
192+
result = pytester.runpytest("--tb=short")
193+
assert result.ret == 1
194+
result.stdout.fnmatch_lines(
195+
[
196+
"*E*AssertionError: Regex pattern did not match.*",
197+
]
198+
)
199+
result.stdout.no_fnmatch_line("*ValueError: actual")
200+
result.stdout.no_fnmatch_line(
201+
"*The above exception was the direct cause of the following exception:*"
202+
)
203+
result.stdout.no_fnmatch_line(
204+
"*During handling of the above exception, another exception occurred:*"
205+
)
206+
180207
def test_noclass(self) -> None:
181208
with pytest.raises(TypeError):
182209
pytest.raises("wrong", lambda: None) # type: ignore[call-overload]

0 commit comments

Comments
 (0)