Skip to content

Commit 3444d35

Browse files
committed
improve pytest.raises
1 parent e580534 commit 3444d35

File tree

4 files changed

+14
-0
lines changed

4 files changed

+14
-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.improvments.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: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -899,6 +899,13 @@ def raises(
899899
"""
900900
__tracebackhide__ = True
901901

902+
if expected_exception == ():
903+
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'."
908+
)
902909
if isinstance(expected_exception, type):
903910
excepted_exceptions: Tuple[Type[E], ...] = (expected_exception,)
904911
else:

testing/python/raises.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ 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_empty_tuple(self):
23+
with pytest.raises(ValueError):
24+
pytest.raises(expected_exception=())
25+
2226
def test_raises_callable_no_exception(self) -> None:
2327
class A:
2428
def __call__(self):

0 commit comments

Comments
 (0)