Skip to content
Open
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 @@ -180,6 +180,7 @@ Fraser Stark
Freya Bruhin
Gabriel Landau
Gabriel Reis
Garion Milazzo
Garvit Shubham
Gene Wood
George Kussumoto
Expand Down
1 change: 1 addition & 0 deletions changelog/14389.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved ``pytest.raises(..., match=...)`` failures to report the mismatched exception as the direct cause of the resulting ``AssertionError``.
2 changes: 1 addition & 1 deletion src/_pytest/raises.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ def __exit__(
if not self.matches(exc_val):
if self._just_propagate:
return False
raise AssertionError(self._fail_reason)
raise AssertionError(self._fail_reason) from exc_val

# Cast to narrow the exception type now that it's verified....
# even though the TypeGuard in self.matches should be narrowing
Expand Down
23 changes: 23 additions & 0 deletions testing/python/raises.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,29 @@ def test_invalid_regex():
result.stdout.no_fnmatch_line("*File*")
result.stdout.no_fnmatch_line("*line*")

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

def test_raises_match_failure():
with pytest.raises(ValueError, match="expected"):
raise ValueError("actual")
"""
)
result = pytester.runpytest("--tb=short")
assert result.ret == 1
result.stdout.fnmatch_lines(
[
"*ValueError: actual",
"*The above exception was the direct cause of the following exception:*",
"*E*AssertionError: Regex pattern did not match.*",
]
)
result.stdout.no_fnmatch_line(
"*During handling of the above exception, another exception occurred:*"
)

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