Skip to content

Commit 1f5e036

Browse files
erheronnicoddemus
authored andcommitted
Force explicit declaration of args in parametrize
Every argname used in `parametrize` either must be declared explicitly in the python test function, or via `indirect` list Fix #5712
1 parent 4de8e68 commit 1f5e036

File tree

7 files changed

+102
-6
lines changed

7 files changed

+102
-6
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
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

Lines changed: 2 additions & 0 deletions
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

Lines changed: 3 additions & 0 deletions
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

Lines changed: 11 additions & 5 deletions
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
@@ -1280,10 +1279,8 @@ def getfixtureinfo(self, node, func, cls, funcargs=True):
12801279
else:
12811280
argnames = ()
12821281

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

src/_pytest/python.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1012,6 +1012,8 @@ def parametrize(
10121012

10131013
arg_values_types = self._resolve_arg_value_types(argnames, indirect)
10141014

1015+
self._validate_explicit_parameters(argnames, indirect)
1016+
10151017
# Use any already (possibly) generated ids with parametrize Marks.
10161018
if _param_mark and _param_mark._param_ids_from:
10171019
generated_ids = _param_mark._param_ids_from._param_ids_generated
@@ -1162,6 +1164,37 @@ def _validate_if_using_arg_names(self, argnames, indirect):
11621164
pytrace=False,
11631165
)
11641166

1167+
def _validate_explicit_parameters(self, argnames, indirect):
1168+
"""
1169+
The argnames in *parametrize* should either be declared explicitly via
1170+
indirect list or in the function signature
1171+
1172+
:param List[str] argnames: list of argument names passed to ``parametrize()``.
1173+
:param indirect: same ``indirect`` parameter of ``parametrize()``.
1174+
:raise ValueError: if validation fails
1175+
"""
1176+
if isinstance(indirect, bool) and indirect is True:
1177+
return
1178+
parametrized_argnames = list()
1179+
funcargnames = _pytest.compat.getfuncargnames(self.function)
1180+
if isinstance(indirect, Sequence):
1181+
for arg in argnames:
1182+
if arg not in indirect:
1183+
parametrized_argnames.append(arg)
1184+
elif indirect is False:
1185+
parametrized_argnames = argnames
1186+
1187+
usefixtures = fixtures.get_use_fixtures_for_node(self.definition)
1188+
1189+
for arg in parametrized_argnames:
1190+
if arg not in funcargnames and arg not in usefixtures:
1191+
func_name = self.function.__name__
1192+
msg = (
1193+
'In function "{func_name}":\n'
1194+
'Parameter "{arg}" should be declared explicitly via indirect or in function itself'
1195+
).format(func_name=func_name, arg=arg)
1196+
fail(msg, pytrace=False)
1197+
11651198

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

testing/python/collect.py

Lines changed: 1 addition & 1 deletion
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

Lines changed: 51 additions & 0 deletions
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)