Repository navigation
Description
The current behavior on the released pytest version is:
- if
matchfails,pytest.raisesraises anAssertionError - if the type differs, the exception propagates through.
- if no exception was raised,
pytest.raisesraisespytest.Failed
#13192 complicated this for several reasons, and having RaisesGroup adhere to point 2 was untenable. It became non-trivial to figure out why the "type" of an exceptiongroup with several nested exceptions and groups couldn't get matched against another group. It also became very weird when the "type" started to include matches itself, and it would've necessitated extra logic to figure out if RaisesGroup(RaisesExc(ValueError, match="foo")) failed because of the type or the match in RaisesExc. Or in even weirder cases where it fails for both reasons:
with RaisesGroup(RaisesExc(ValueError), RaisesExc(match="foo")):
raise ExceptionGroup(TypeError("bar"), TypeError("bar"))
So RaisesGroup will raise an exception in all cases.
We're then faced with how this should affect pytest.raises. #13192 made it raise an AssertionError upon type difference (and if check fails), but this would likely be considered a breaking change. I personally think it's very different if a test fails because I got a completely unexpected exception, versus a different exception than the one I specifically expected in a raises block; but I don't think that's a huge win.
The other downside of keeping current behavior is it becoming an arbitrary-but-for-historic-reasons difference between raises and RaisesGroup.
In either case, the original exception is accessible in the __cause__ attribute and adapting code should be straightforward.
I do also find the distinction between raising pytest.Fail versus AssertionError quite arbitrary, and think they should be unified. My instinct would be for all failures to be pytest.Fail, as AssertionError usually signals to users that an explicit assert has failed. We could make this change backward-compatible by having the exception raised inherit from both AssertionError and pytest.Fail if we really want to.
This also matters for ExceptionInfo.match, which ideally should share logic with raises for string matching - but currently doesn't. It currently raises an AssertionError on failure.
tl;dr
- Should
raisespropagate the exception, or raiseAssertionError, orFail? - Is the distinction between raising different exception types useful, or confusing?
- Should
RaisesGroupraisepytest.FailorAssertionErrorwhen failing a match, regardless of reason?
Activity
bluetech commentedon Mar 12, 2025
assertvs.failFirst on
AssertionErrorvsFailed. Ideally we treat this as an implementation detail, i.e. we don't specify what we raise, only that the test fails. I'd saypytest.failis just a little nicerassert False, <message>, so makes sense for the DID NOT RAISE to use that, whilematchis better with anassert, since there's a condition.(To be more precise, there is a difference - we have
pytest_assertrepr_compareandpytest_assertion_passhooks for asserts. But these don't apply tomatchbecause the relevant file doesn't undergo assert rewriting.)That said, there is something to be said for consistency here. If we could make it consistent I would like it just because consistency is good. But both options are a bit problematic:
ExceptionInfo.matchwhich is the public API underlyingraises(match=...)explicitly documents raisesAssertionError. So changing that would be breaking.AssertionErrorfeels less nice thanfail, will probably also break some stuff, and then there's alsoraises.Exceptionwhich isFailed.I don't like the "inherit from both AssertionError and pytest.Fail" solution, feels too icky. But maybe?
My conclusion is to leave it...
Propagate vs. fail-fast
Let me try to weigh which behavior is better.
For propagate:
with pytest.raises(MyExc)as analogous totry .. except MyExecthen propagate is expected.with pytest.raiseswithin awith pytest.raises. It might sound unrealistic, but I can imagine it happening when apytest.raisesis in some helper function, which a test calls but then also has apytest.raisesfor some other unrelated exception.For fail-fast:
match/check/DID NOT RAISE failure behaviorOverall, as far as I considered it, at least for
raiseI prefer propagate.I haven't thought about
RaisesGroup. I assume it's indeed very difficult to have it propagate but still have a decent error message?jakkdl commentedon Mar 13, 2025
assertvsfailI agree it feels less nice, and personally when I get an
AssertionErrorI assume it's gonna be anassertstatement that I've myself written. I think it's non-obvious at a glance thatraisesandExceptionInfo.matchhas assert statements inside them.But for
raises.Exceptionwe can just ... set that to a different value, that's what its for.the case for a new exception
_pytest.outcomes.Failedis not public API, so users shouldn't be catching that - they should be catchingpytest.raises.Exception. (They could be catchingpytest.fail.Exceptionthough). This means that a new exception type wouldn't really need to inherit from it - we just updatepytest.raises.Exception. If we introduce a newRaisesFailurewe get:AssertionError, so we keep backwards compatibilityraisespropagationassertstatementExceptionInfo.matchwe can give that a different error with a little bit of logic. We could also do aMatchFailurethat handles both it andraises, but that feels less fitting for theDID NOT RAISEcase.Propagate vs. fail-fast
though there is an alternate way of conceptualizing it:
No yeah this is probably a thing in the wild. Though it also feels a bit footgunny:
but they'd be getting linter warnings about not using match, and
raisesbeing across a wide scope, so probably a rare scenario.This is a good point, esp for stuff like
KeyboardInterrupt. The way they would do it would be checking forpytest.raises.Exception, but nobody will be doing that currently.Yeah I guess fail-fast for
raiseswould simple break too much stuff, and the gain isn't terribly big. The only way I see of transitioning would be a flag/config option, but kinda unclear if worth the effort.RaisesGroupYeah I mean I just don't know where else to put it. I could of course just dump the error to stderr, maybe there's some pytest-internal way of saying "please output this text string if/when the test ultimately fails"
But that loops back to the problem of deciding if it is a
type-style failure vs amatch-style failure. I think the only way of making it comprehensible to users is to always fail in the same way in both cases, since it can fail for both reasons at once, andRaisesGroup(RaisesExc(match="foo"))is ambiguous which one it is, etc.Though with
RaisesGroupbeing nigh-impossible to adhere to propagate, the points about hooks and helpers will already be a problem (except more niche)....BUTWAIT there's a third option of
which would allow
except*in hooks/helpers/etc to handle the propagated errors. NestingRaisesGroupwould be kinda madness to do here, but maybe somebody would try.But we would need to improve the display of exceptiongroups in order to do this, the current state of play is not great (#10209 and #12975 did kinda hacky solutions, also see #12255)
Zac-HD commentedon Mar 15, 2025
Probably at this point any change to
pytest.raises()will break someone, and the net result will be that they don't update Pytest. The current behavior isn't ideal, but it's not that bad, so I'd leave it as-is."_pytest.outcomes.Failed is not public API, so users shouldn't be catching that" -> unfortunately we have very many creative users, downstream libraries hoping to remain compatible with older versions of pytest, etc. Hyrum's Law again.
I'd just decide on the cleanest behavior for
RaisesGroup, implement and document that with a note thatraises()differs a bit for historical reasons and due to the complexity of groups, and be done.gschaffner commentedon Mar 7, 2026
My initial 2 cents after bumping into this today: it was surprising to me that
pytest.raisesdid not make the assertion that I put it there to make (and instead propagated a different exception). Part of the trouble here is that the propagated third-party exception can get swallowed elsewhere, e.g. in my case today the propagated exception was a TrioCancelled. Of course, I also could have been surprised ifpytest.raiseshad instead swallowed the third-party exception and propagated only anAssertionError.This issue feels somewhat like a dual of python-trio/trio#455 / python-trio/trio#1559 to me:
RaisesExc.__exit__raises an exception that is later swallowed, and blindly suppresses an exception that (IMO) shouldn't be suppressed (theAssertionError) (by neglecting it entirely).This can suppress an exception (
AssertionError) unexpectedly.AsyncResource.__aexit__raises an exception that is later swallowed, and blindly suppresses an exception that shouldn't be suppressed (by sticking the shouldn't-be-suppressed exception into the__context__of an exception that is later swallowed).This can suppress an exception (
KeyboardInterrupt/SystemExit/anything else) unexpectedly.This is a vague and not-thought-through idea, but just to throw it out there: I wonder if there is some benefit to thinking about these two issues as related. E.g. is there some commonality between the approaches that we could use to solve the two issues? In both the pytest and Trio cases, if backwards-compatibility was not needed, suppressing neither exception via raising a group containing both seems (at a first glance) simple and reasonable, but perhaps that is wishful thinking.
jakkdl commentedon Mar 12, 2026
Yeah I briefly considered raising a group towards the end of my previous reply, though the display of exceptiongroups not being great is a blocker for this. I also think there's still a lot of pytest users that are not used to exception groups. I can definitely dream about a world where we introduce a trio-like
strict_exception_groupsparameter to pytest and transition to a consistent format that won't confuse new users, while allowing people doing funky things to opt into the old behavior. We'd probably need to keep that flag for decades though given it's not critical and old code with nestedraisesworks perfectly fine in vast majority of cases.pattersonzoe84-art commentedon Mar 13, 2026
jakkdl commentedon Mar 13, 2026
You can still nest
pytest.raisesif we're raising groups, though the other one might be something likepytest.RaisesGroup(pytest.raises.Exception, InnerException), but I'm not really sure what the scenarios look like where you genuinely need nestedraisesand wouldn't be better off with passing more arguments topytest.raises/pytest.RaisesExc