You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When writing parameterised tests, we often find that code within the test should either raise or not raise an Exception based on the parameters. The docs suggest passing the context manager itself as a parameter, either pytest.raises(X) or contextlib.nullcontext. This can make test code less concise than it could otherwise be.
Describe the solution you'd like
pytest.raises(None) could be overloaded to behave semantically the same as contextlib.nullcontext.
I'm happy to try implementing this, but wanted to raise a discussion first. It looks like something like a NullRaisesExc(AbstractRaises) could be returned by raises(None).
I would also propose that the 'legacy form' where we pass a callable to raises would not gain this new syntactic sugar.
The text was updated successfully, but these errors were encountered:
This may also help with #13410 , though this was not the motivation for submitting this issue.
andyclegg
changed the title
pytest.raises(None) should work like contextlib.nullcontext
Support conditional raising with pytest.raises(None)
May 15, 2025
What's the problem this feature will solve?
When writing parameterised tests, we often find that code within the test should either raise or not raise an Exception based on the parameters. The docs suggest passing the context manager itself as a parameter, either
pytest.raises(X)
orcontextlib.nullcontext
. This can make test code less concise than it could otherwise be.Describe the solution you'd like
pytest.raises(None)
could be overloaded to behave semantically the same ascontextlib.nullcontext
.With Hypothesis tests, this becomes even more useful:
Alternative Solutions
https://docs.pytest.org/en/stable/example/parametrize.html#parametrizing-conditional-raising is the documented solution, but I think this could be improved
Additional context
I'm happy to try implementing this, but wanted to raise a discussion first. It looks like something like a
NullRaisesExc(AbstractRaises)
could be returned byraises(None)
.I would also propose that the 'legacy form' where we pass a callable to
raises
would not gain this new syntactic sugar.The text was updated successfully, but these errors were encountered: