Skip to content

Support conditional raising with pytest.raises(None) #13424

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

Closed
andyclegg opened this issue May 15, 2025 · 2 comments
Closed

Support conditional raising with pytest.raises(None) #13424

andyclegg opened this issue May 15, 2025 · 2 comments

Comments

@andyclegg
Copy link

andyclegg commented 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) 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.

@pytest.mark.parametrize('x, exc', [(2, None), (0, ZeroDivisionError)])
def test_divide(x, exc):
    with pytest.raises(exc):
         print(1/x)

With Hypothesis tests, this becomes even more useful:

@given(x=st.integers())
def test_divide(x):
    with pytest.raises(ZeroDivisionError if x == 0 else None):
         print(1/x)

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 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.

@andyclegg
Copy link
Author

This may also help with #13410 , though this was not the motivation for submitting this issue.

@andyclegg andyclegg changed the title pytest.raises(None) should work like contextlib.nullcontext Support conditional raising with pytest.raises(None) May 15, 2025
@Zac-HD
Copy link
Member

Zac-HD commented May 15, 2025

See #1830 #4324 #4682 #5165 #9402 #9404 #10654 etc.; we've considered this carefully and think it would be net-negative for our users overall.

@Zac-HD Zac-HD closed this as not planned Won't fix, can't repro, duplicate, stale May 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants