diff --git a/AUTHORS b/AUTHORS index e8140292aa4..f2f419cf642 100644 --- a/AUTHORS +++ b/AUTHORS @@ -179,6 +179,7 @@ Fraser Stark Freya Bruhin Gabriel Landau Gabriel Reis +Garion Milazzo Garvit Shubham Gene Wood George Kussumoto diff --git a/changelog/14389.bugfix.rst b/changelog/14389.bugfix.rst new file mode 100644 index 00000000000..f0d85169d0b --- /dev/null +++ b/changelog/14389.bugfix.rst @@ -0,0 +1 @@ +Improved :func:`pytest.raises(..., match=...) ` failures to suppress the mismatched exception as a cause of the resulting ``AssertionError``. diff --git a/src/_pytest/raises.py b/src/_pytest/raises.py index 7c246fde280..3ab109c0641 100644 --- a/src/_pytest/raises.py +++ b/src/_pytest/raises.py @@ -716,7 +716,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 None # Cast to narrow the exception type now that it's verified.... # even though the TypeGuard in self.matches should be narrowing diff --git a/testing/python/raises.py b/testing/python/raises.py index c9d57918a83..9fd43ecbdaf 100644 --- a/testing/python/raises.py +++ b/testing/python/raises.py @@ -177,6 +177,33 @@ def test_invalid_regex(): result.stdout.no_fnmatch_line("*File*") result.stdout.no_fnmatch_line("*line*") + def test_raises_match_failure_suppresses_exception_context( + 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( + [ + "*E*AssertionError: Regex pattern did not match.*", + ] + ) + result.stdout.no_fnmatch_line("*ValueError: actual") + result.stdout.no_fnmatch_line( + "*The above exception was the direct cause of the following exception:*" + ) + result.stdout.no_fnmatch_line( + "*During handling of the above exception, another exception occurred:*" + ) + def test_noclass(self) -> None: with pytest.raises(TypeError): pytest.raises("wrong", lambda: None) # type: ignore[call-overload]