Skip to content

Commit 9e26203

Browse files
authored
[parametrize] enforce explicit argnames declaration (#6330)
Every argname used in `parametrize` either must be declared explicitly in the python test function, or via `indirect` list Fix #5712
1 parent 39d9f7c commit 9e26203

File tree

7 files changed

+102
-6
lines changed

7 files changed

+102
-6
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ Vidar T. Fauske
274274
Virgil Dupras
275275
Vitaly Lashmanov
276276
Vlad Dragos
277+
Vladyslav Rachek
277278
Volodymyr Piskun
278279
Wei Lin
279280
Wil Cooley

changelog/5712.feature.rst

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Now all arguments to ``@pytest.mark.parametrize`` need to be explicitly declared in the function signature or via ``indirect``.
2+
Previously it was possible to omit an argument if a fixture with the same name existed, which was just an accident of implementation and was not meant to be a part of the API.

doc/en/example/parametrize.rst

+3
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,9 @@ The result of this test will be successful:
398398
399399
.. regendoc:wipe
400400
401+
Note, that each argument in `parametrize` list should be explicitly declared in corresponding
402+
python test function or via `indirect`.
403+
401404
Parametrizing test methods through per-class configuration
402405
--------------------------------------------------------------
403406

src/_pytest/fixtures.py

+11-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import functools
22
import inspect
3-
import itertools
43
import sys
54
import warnings
65
from collections import defaultdict
@@ -1279,10 +1278,8 @@ def getfixtureinfo(self, node, func, cls, funcargs=True):
12791278
else:
12801279
argnames = ()
12811280

1282-
usefixtures = itertools.chain.from_iterable(
1283-
mark.args for mark in node.iter_markers(name="usefixtures")
1284-
)
1285-
initialnames = tuple(usefixtures) + argnames
1281+
usefixtures = get_use_fixtures_for_node(node)
1282+
initialnames = usefixtures + argnames
12861283
fm = node.session._fixturemanager
12871284
initialnames, names_closure, arg2fixturedefs = fm.getfixtureclosure(
12881285
initialnames, node, ignore_args=self._get_direct_parametrize_args(node)
@@ -1479,3 +1476,12 @@ def _matchfactories(self, fixturedefs, nodeid):
14791476
for fixturedef in fixturedefs:
14801477
if nodes.ischildnode(fixturedef.baseid, nodeid):
14811478
yield fixturedef
1479+
1480+
1481+
def get_use_fixtures_for_node(node) -> Tuple[str, ...]:
1482+
"""Returns the names of all the usefixtures() marks on the given node"""
1483+
return tuple(
1484+
str(name)
1485+
for mark in node.iter_markers(name="usefixtures")
1486+
for name in mark.args
1487+
)

src/_pytest/python.py

+33
Original file line numberDiff line numberDiff line change
@@ -955,6 +955,8 @@ def parametrize(
955955

956956
arg_values_types = self._resolve_arg_value_types(argnames, indirect)
957957

958+
self._validate_explicit_parameters(argnames, indirect)
959+
958960
# Use any already (possibly) generated ids with parametrize Marks.
959961
if _param_mark and _param_mark._param_ids_from:
960962
generated_ids = _param_mark._param_ids_from._param_ids_generated
@@ -1105,6 +1107,37 @@ def _validate_if_using_arg_names(self, argnames, indirect):
11051107
pytrace=False,
11061108
)
11071109

1110+
def _validate_explicit_parameters(self, argnames, indirect):
1111+
"""
1112+
The argnames in *parametrize* should either be declared explicitly via
1113+
indirect list or in the function signature
1114+
1115+
:param List[str] argnames: list of argument names passed to ``parametrize()``.
1116+
:param indirect: same ``indirect`` parameter of ``parametrize()``.
1117+
:raise ValueError: if validation fails
1118+
"""
1119+
if isinstance(indirect, bool) and indirect is True:
1120+
return
1121+
parametrized_argnames = list()
1122+
funcargnames = _pytest.compat.getfuncargnames(self.function)
1123+
if isinstance(indirect, Sequence):
1124+
for arg in argnames:
1125+
if arg not in indirect:
1126+
parametrized_argnames.append(arg)
1127+
elif indirect is False:
1128+
parametrized_argnames = argnames
1129+
1130+
usefixtures = fixtures.get_use_fixtures_for_node(self.definition)
1131+
1132+
for arg in parametrized_argnames:
1133+
if arg not in funcargnames and arg not in usefixtures:
1134+
func_name = self.function.__name__
1135+
msg = (
1136+
'In function "{func_name}":\n'
1137+
'Parameter "{arg}" should be declared explicitly via indirect or in function itself'
1138+
).format(func_name=func_name, arg=arg)
1139+
fail(msg, pytrace=False)
1140+
11081141

11091142
def _find_parametrized_scope(argnames, arg2fixturedefs, indirect):
11101143
"""Find the most appropriate scope for a parametrized call based on its arguments.

testing/python/collect.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ def fix3():
463463
return '3'
464464
465465
@pytest.mark.parametrize('fix2', ['2'])
466-
def test_it(fix1):
466+
def test_it(fix1, fix2):
467467
assert fix1 == '21'
468468
assert not fix3_instantiated
469469
"""

testing/python/metafunc.py

+51
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ def __init__(self, names):
2828
class DefinitionMock(python.FunctionDefinition):
2929
obj = attr.ib()
3030

31+
def listchain(self):
32+
return []
33+
3134
names = fixtures.getfuncargnames(func)
3235
fixtureinfo = FixtureInfo(names)
3336
definition = DefinitionMock._create(func)
@@ -1877,3 +1880,51 @@ def test_converted_to_str(a, b):
18771880
"*= 6 passed in *",
18781881
]
18791882
)
1883+
1884+
def test_parametrize_explicit_parameters_func(self, testdir):
1885+
testdir.makepyfile(
1886+
"""
1887+
import pytest
1888+
1889+
1890+
@pytest.fixture
1891+
def fixture(arg):
1892+
return arg
1893+
1894+
@pytest.mark.parametrize("arg", ["baz"])
1895+
def test_without_arg(fixture):
1896+
assert "baz" == fixture
1897+
"""
1898+
)
1899+
result = testdir.runpytest()
1900+
result.assert_outcomes(error=1)
1901+
result.stdout.fnmatch_lines(
1902+
[
1903+
'*In function "test_without_arg"*',
1904+
'*Parameter "arg" should be declared explicitly via indirect or in function itself*',
1905+
]
1906+
)
1907+
1908+
def test_parametrize_explicit_parameters_method(self, testdir):
1909+
testdir.makepyfile(
1910+
"""
1911+
import pytest
1912+
1913+
class Test:
1914+
@pytest.fixture
1915+
def test_fixture(self, argument):
1916+
return argument
1917+
1918+
@pytest.mark.parametrize("argument", ["foobar"])
1919+
def test_without_argument(self, test_fixture):
1920+
assert "foobar" == test_fixture
1921+
"""
1922+
)
1923+
result = testdir.runpytest()
1924+
result.assert_outcomes(error=1)
1925+
result.stdout.fnmatch_lines(
1926+
[
1927+
'*In function "test_without_argument"*',
1928+
'*Parameter "argument" should be declared explicitly via indirect or in function itself*',
1929+
]
1930+
)

0 commit comments

Comments
 (0)