Skip to content

Commit cd7592c

Browse files
authored
raises: suppress exception cause in raises match failures (#14391)
1 parent a38b20d commit cd7592c

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
@@ -180,6 +180,7 @@ Fraser Stark
180180
Freya Bruhin
181181
Gabriel Landau
182182
Gabriel Reis
183+
Garion Milazzo
183184
Garvit Shubham
184185
Gene Wood
185186
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 ``pytest.raises(..., match=...)`` failures to report the mismatched exception as the direct cause of the resulting ``AssertionError``.

src/_pytest/raises.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -699,7 +699,7 @@ def __exit__(
699699
if not self.matches(exc_val):
700700
if self._just_propagate:
701701
return False
702-
raise AssertionError(self._fail_reason)
702+
raise AssertionError(self._fail_reason) from None
703703

704704
# Cast to narrow the exception type now that it's verified....
705705
# 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
@@ -179,6 +179,33 @@ def test_invalid_regex():
179179
result.stdout.no_fnmatch_line("*File*")
180180
result.stdout.no_fnmatch_line("*line*")
181181

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

0 commit comments

Comments
 (0)