Skip to content

Commit ccdee08

Browse files
authored
Merge pull request #9911 from bkeyvani/fix-issue-8646
2 parents 37316ed + a29f4af commit ccdee08

File tree

4 files changed

+19
-0
lines changed

4 files changed

+19
-0
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ Aron Coyle
4444
Aron Curzon
4545
Aviral Verma
4646
Aviv Palivoda
47+
Babak Keyvani
4748
Barney Gale
4849
Ben Gartner
4950
Ben Webb

changelog/8646.improvement.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve :py:func:`pytest.raises`. Previously passing an empty tuple would give a confusing
2+
error. We now raise immediately with a more helpful message.

src/_pytest/python_api.py

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

902+
if not expected_exception:
903+
raise ValueError(
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'."
907+
)
902908
if isinstance(expected_exception, type):
903909
excepted_exceptions: Tuple[Type[E], ...] = (expected_exception,)
904910
else:

testing/python/raises.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,16 @@ 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+
# We're testing that this invalid usage gives a helpful error,
25+
# so we can ignore Mypy telling us that None is invalid.
26+
pytest.raises(expected_exception=None) # type: ignore
27+
28+
def test_raises_does_not_allow_empty_tuple(self):
29+
with pytest.raises(ValueError, match="Expected an exception type or"):
30+
pytest.raises(expected_exception=())
31+
2232
def test_raises_callable_no_exception(self) -> None:
2333
class A:
2434
def __call__(self):

0 commit comments

Comments
 (0)