Skip to content

Commit 31a9c5c

Browse files
committed
improve pytest.raises - cont'd
a few more iterations on error message and related tests.
1 parent 3444d35 commit 31a9c5c

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

src/_pytest/python_api.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -899,12 +899,11 @@ def raises(
899899
"""
900900
__tracebackhide__ = True
901901

902-
if expected_exception == ():
902+
if not expected_exception:
903903
raise ValueError(
904-
"Passing expected_exception=() is an error, because it's impossible to "
905-
"raise an exception which is not an instance of any type. Raising exceptions "
906-
"is already understood as failing the test, so you don't need any special "
907-
"code to say 'this should never raise an exception'."
904+
f"Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. "
905+
f"Raising exceptions is already understood as failing the test, so you don't need "
906+
f"any special code to say 'this should never raise an exception'."
908907
)
909908
if isinstance(expected_exception, type):
910909
excepted_exceptions: Tuple[Type[E], ...] = (expected_exception,)

testing/python/raises.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,12 @@ def test_raises_function(self):
1919
excinfo = pytest.raises(ValueError, int, "hello")
2020
assert "invalid literal" in str(excinfo.value)
2121

22+
def test_raises_does_not_allow_none(self):
23+
with pytest.raises(ValueError, match="Expected an exception type or"):
24+
pytest.raises(expected_exception=None)
25+
2226
def test_raises_does_not_allow_empty_tuple(self):
23-
with pytest.raises(ValueError):
27+
with pytest.raises(ValueError, match="Expected an exception type or"):
2428
pytest.raises(expected_exception=())
2529

2630
def test_raises_callable_no_exception(self) -> None:

0 commit comments

Comments
 (0)