-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Match causing exceptions with pytest.raises #12763
Comments
The You can always just access the exception object itself and act on that instead: import pytest
def i_raise_a_causing_exception():
raise RuntimeError("i'm an exception") from ValueError("i'm a causing exception")
def test_exception():
with pytest.raises(RuntimeError) as excinfo:
i_raise_a_causing_exception()
assert str(excinfo.value.__cause__) == "i'm a causing exception" |
the issue with |
having a matcher object that expresses this explicit with a explcit api thats not barking up the wrong tree of DWIM is the way to go here, matcher objects are still pre-planning and in early discussion |
oh! Would love to see matcher objects! Should I close this issue then? |
We should link it up with the other discussions first |
read more about causing / context exceptions in the python doc
What's the problem this feature will solve?
It is quite unintuitive to match a causing exceptions (
raise Exception("i'm an exception") from Exception("I'm the causing exception")
) with pytest.As for an example, imagine you want to match a ValueError with the message "i'm a causing exception"
If you want to do that now, you have to use the workaround described below.
Describe the solution you'd like
pytest.raises
could have an option to match the causing/context exception. Of course, now comes the problem of recursivity since causing/context exceptions can themselves be causing exceptions.This would allow us to do something along the lines of
if we have multiple caused exception chained together, we could also have:
Of course, we would have the same thing for context exceptions:
Alternative Solutions
I just found a workaround in https://stackoverflow.com/a/78939835/12550791 (disclaimer, i'm the author of the question and of the solution).
However, if you have multiple level of cause exceptions you will have to rely on recursivity or make one with the mess.
Additional context
The text was updated successfully, but these errors were encountered: