Skip to content

Commit 2d991b5

Browse files
committed
Fix for warning test arguments with default values
1 parent 9d4f36d commit 2d991b5

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/_pytest/python.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969
from _pytest.scope import _ScopeName
7070
from _pytest.scope import Scope
7171
from _pytest.stash import StashKey
72-
from _pytest.warning_types import PytestCollectionWarning
72+
from _pytest.warning_types import PytestCollectionWarning, PytestDefaultArgumentWarning, warn_explicit_for
7373

7474

7575
if TYPE_CHECKING:
@@ -143,9 +143,23 @@ def async_fail(nodeid: str) -> None:
143143
fail(msg, pytrace=False)
144144

145145

146+
def async_default_arg_warn(nodeid: str, function_name, param) -> None:
147+
msg = (
148+
"Test function '" + function_name + "' has a default argument '" + param.name + "=" + str(param.default) + "'.\n"
149+
)
150+
warnings.simplefilter("always", PytestDefaultArgumentWarning)
151+
warnings.warn(PytestDefaultArgumentWarning(msg))
152+
153+
146154
@hookimpl(trylast=True)
147155
def pytest_pyfunc_call(pyfuncitem: Function) -> object | None:
148156
testfunction = pyfuncitem.obj
157+
sig = inspect.signature(testfunction)
158+
for param in sig.parameters.values():
159+
if param.default is not param.empty:
160+
function_name = testfunction.__name__
161+
async_default_arg_warn(pyfuncitem.nodeid, function_name, param)
162+
149163
if is_async_function(testfunction):
150164
async_fail(pyfuncitem.nodeid)
151165
funcargs = pyfuncitem.funcargs

src/_pytest/warning_types.py

+7
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@ class PytestCollectionWarning(PytestWarning):
4444
__module__ = "pytest"
4545

4646

47+
@final
48+
class PytestDefaultArgumentWarning(PytestWarning):
49+
"""Warning emitted when a test function has default arguments."""
50+
51+
__module__ = "pytest"
52+
53+
4754
class PytestDeprecationWarning(PytestWarning, DeprecationWarning):
4855
"""Warning class for features that will be removed in a future version."""
4956

0 commit comments

Comments
 (0)