Skip to content

Commit 866904a

Browse files
committed
Revert "Let context-managers for raises and warns handle unknown keyword arguments"
This reverts commit dfe54cd. The idea in the commit was to simplify the code by removing the check and instead letting it TypeError which has the same effect. However this type error is caught by mypy, and rather than ignoring the error we think it's better and clearer to go back to the previous explicit check.
1 parent 35a57a0 commit 866904a

File tree

4 files changed

+24
-4
lines changed

4 files changed

+24
-4
lines changed

src/_pytest/python_api.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -653,9 +653,12 @@ def raises(expected_exception, *args, match=None, **kwargs):
653653
message = "DID NOT RAISE {}".format(expected_exception)
654654

655655
if not args:
656-
return RaisesContext(
657-
expected_exception, message=message, match_expr=match, **kwargs
658-
)
656+
if kwargs:
657+
msg = "Unexpected keyword arguments passed to pytest.raises: "
658+
msg += ", ".join(sorted(kwargs))
659+
msg += "\nUse context-manager form instead?"
660+
raise TypeError(msg)
661+
return RaisesContext(expected_exception, message, match)
659662
else:
660663
func = args[0]
661664
if not callable(func):

src/_pytest/recwarn.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,12 @@ def warns(expected_warning, *args, match=None, **kwargs):
7676
"""
7777
__tracebackhide__ = True
7878
if not args:
79-
return WarningsChecker(expected_warning, match_expr=match, **kwargs)
79+
if kwargs:
80+
msg = "Unexpected keyword arguments passed to pytest.warns: "
81+
msg += ", ".join(sorted(kwargs))
82+
msg += "\nUse context-manager form instead?"
83+
raise TypeError(msg)
84+
return WarningsChecker(expected_warning, match_expr=match)
8085
else:
8186
func = args[0]
8287
if not callable(func):

testing/python/raises.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,3 +248,9 @@ def __class__(self):
248248
with pytest.raises(CrappyClass()):
249249
pass
250250
assert "via __class__" in excinfo.value.args[0]
251+
252+
def test_raises_context_manager_with_kwargs(self):
253+
with pytest.raises(TypeError) as excinfo:
254+
with pytest.raises(Exception, foo="bar"):
255+
pass
256+
assert "Unexpected keyword arguments" in str(excinfo.value)

testing/test_recwarn.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,3 +374,9 @@ def f():
374374
assert f() == 10
375375
assert pytest.warns(UserWarning, f) == 10
376376
assert pytest.warns(UserWarning, f) == 10
377+
378+
def test_warns_context_manager_with_kwargs(self):
379+
with pytest.raises(TypeError) as excinfo:
380+
with pytest.warns(UserWarning, foo="bar"):
381+
pass
382+
assert "Unexpected keyword arguments" in str(excinfo.value)

0 commit comments

Comments
 (0)