From 31a9c5c66709609f8adfa81a9e3e4bf1147e0369 Mon Sep 17 00:00:00 2001 From: Babak Keyvani Date: Mon, 9 May 2022 21:15:02 -0400 Subject: [PATCH] improve `pytest.raises` - cont'd a few more iterations on error message and related tests. --- src/_pytest/python_api.py | 9 ++++----- testing/python/raises.py | 6 +++++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/_pytest/python_api.py b/src/_pytest/python_api.py index 410877c88..bef9ec47b 100644 --- a/src/_pytest/python_api.py +++ b/src/_pytest/python_api.py @@ -899,12 +899,11 @@ def raises( """ __tracebackhide__ = True - if expected_exception == (): + if not expected_exception: raise ValueError( - "Passing expected_exception=() is an error, because it's impossible to " - "raise an exception which is not an instance of any type. Raising exceptions " - "is already understood as failing the test, so you don't need any special " - "code to say 'this should never raise an exception'." + f"Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. " + f"Raising exceptions is already understood as failing the test, so you don't need " + f"any special code to say 'this should never raise an exception'." ) if isinstance(expected_exception, type): excepted_exceptions: Tuple[Type[E], ...] = (expected_exception,) diff --git a/testing/python/raises.py b/testing/python/raises.py index e1680623a..b3fa0fc0e 100644 --- a/testing/python/raises.py +++ b/testing/python/raises.py @@ -19,8 +19,12 @@ class TestRaises: excinfo = pytest.raises(ValueError, int, "hello") assert "invalid literal" in str(excinfo.value) + def test_raises_does_not_allow_none(self): + with pytest.raises(ValueError, match="Expected an exception type or"): + pytest.raises(expected_exception=None) + def test_raises_does_not_allow_empty_tuple(self): - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="Expected an exception type or"): pytest.raises(expected_exception=()) def test_raises_callable_no_exception(self) -> None: