Skip to content

Commit bbf5949

Browse files
Apply comments and and an improvement
1 parent aa5d09d commit bbf5949

File tree

3 files changed

+33
-39
lines changed

3 files changed

+33
-39
lines changed

src/_pytest/fixtures.py

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1326,6 +1326,12 @@ def _get_direct_parametrize_args(node: nodes.Node) -> List[str]:
13261326
return parametrize_argnames
13271327

13281328

1329+
def deduplicate_names(seq: Iterable[str]) -> Tuple[str, ...]:
1330+
"""De-duplicate the sequence of names while keeping the original order."""
1331+
# Ideally we would use a set, but it does not preserve insertion order.
1332+
return tuple(dict.fromkeys(seq))
1333+
1334+
13291335
class FixtureManager:
13301336
"""pytest fixture definitions and information is stored and managed
13311337
from this class.
@@ -1404,13 +1410,8 @@ def getfixtureinfo(
14041410
usefixtures = tuple(
14051411
arg for mark in node.iter_markers(name="usefixtures") for arg in mark.args
14061412
)
1407-
initialnames = cast(
1408-
Tuple[str],
1409-
tuple(
1410-
dict.fromkeys(
1411-
tuple(self._getautousenames(node.nodeid)) + usefixtures + argnames
1412-
)
1413-
),
1413+
initialnames = deduplicate_names(
1414+
tuple(self._getautousenames(node.nodeid)) + usefixtures + argnames
14141415
)
14151416

14161417
arg2fixturedefs: Dict[str, Sequence[FixtureDef[Any]]] = {}
@@ -1459,23 +1460,19 @@ def _getautousenames(self, nodeid: str) -> Iterator[str]:
14591460
def getfixtureclosure(
14601461
self,
14611462
parentnode: nodes.Node,
1462-
initialnames: Tuple[str],
1463+
initialnames: Tuple[str, ...],
14631464
arg2fixturedefs: Dict[str, Sequence[FixtureDef[Any]]],
14641465
ignore_args: Sequence[str] = (),
14651466
) -> List[str]:
14661467
# Collect the closure of all fixtures, starting with the given
1467-
# initialnames as the initial set. As we have to visit all
1468-
# factory definitions anyway, we also populate arg2fixturedefs
1469-
# mapping so that the caller can reuse it and does not have
1470-
# to re-discover fixturedefs again for each fixturename
1468+
# initialnames containing function arguments, `usefixture` markers
1469+
# and `autouse` fixtures as the initial set. As we have to visit all
1470+
# factory definitions anyway, we also populate arg2fixturedefs mapping
1471+
# for the args missing therein so that the caller can reuse it and does
1472+
# not have to re-discover fixturedefs again for each fixturename
14711473
# (discovering matching fixtures for a given name/node is expensive).
14721474

1473-
fixturenames_closure = list(initialnames)
1474-
1475-
def merge(otherlist: Iterable[str]) -> None:
1476-
for arg in otherlist:
1477-
if arg not in fixturenames_closure:
1478-
fixturenames_closure.append(arg)
1475+
fixturenames_closure = initialnames
14791476

14801477
lastlen = -1
14811478
parentid = parentnode.nodeid
@@ -1489,7 +1486,9 @@ def merge(otherlist: Iterable[str]) -> None:
14891486
if fixturedefs:
14901487
arg2fixturedefs[argname] = fixturedefs
14911488
if argname in arg2fixturedefs:
1492-
merge(arg2fixturedefs[argname][-1].argnames)
1489+
fixturenames_closure = deduplicate_names(
1490+
fixturenames_closure + arg2fixturedefs[argname][-1].argnames
1491+
)
14931492

14941493
def sort_by_scope(arg_name: str) -> Scope:
14951494
try:
@@ -1499,8 +1498,7 @@ def sort_by_scope(arg_name: str) -> Scope:
14991498
else:
15001499
return fixturedefs[-1]._scope
15011500

1502-
fixturenames_closure.sort(key=sort_by_scope, reverse=True)
1503-
return fixturenames_closure
1501+
return sorted(fixturenames_closure, key=sort_by_scope, reverse=True)
15041502

15051503
def pytest_generate_tests(self, metafunc: "Metafunc") -> None:
15061504
"""Generate new tests based on parametrized fixtures used by the given metafunc"""

src/_pytest/python.py

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
from collections import Counter
1212
from collections import defaultdict
1313
from functools import partial
14-
from functools import wraps
1514
from pathlib import Path
1615
from typing import Any
1716
from typing import Callable
@@ -382,12 +381,13 @@ class _EmptyClass: pass # noqa: E701
382381
# fmt: on
383382

384383

385-
def unwrap_metafunc_parametrize_and_possibly_prune_dependency_tree(metafunc):
386-
metafunc.parametrize = metafunc._parametrize
387-
del metafunc._parametrize
388-
if metafunc.has_dynamic_parametrize:
384+
def prune_dependency_tree_if_test_is_dynamically_parametrized(metafunc):
385+
if metafunc._calls:
389386
# Dynamic direct parametrization may have shadowed some fixtures
390-
# so make sure we update what the function really needs.
387+
# so make sure we update what the function really needs. Note that
388+
# we didn't need to do this if only indirect dynamic parametrization
389+
# had taken place, but anyway we did it as differentiating between direct
390+
# and indirect requires a dirty hack.
391391
definition = metafunc.definition
392392
fixture_closure = definition.parent.session._fixturemanager.getfixtureclosure(
393393
definition,
@@ -396,7 +396,6 @@ def unwrap_metafunc_parametrize_and_possibly_prune_dependency_tree(metafunc):
396396
ignore_args=_get_direct_parametrize_args(definition) + ["request"],
397397
)
398398
definition._fixtureinfo.names_closure[:] = fixture_closure
399-
del metafunc.has_dynamic_parametrize
400399

401400

402401
class PyCollector(PyobjMixin, nodes.Collector):
@@ -503,22 +502,12 @@ def _genfunctions(self, name: str, funcobj) -> Iterator["Function"]:
503502
module=module,
504503
_ispytest=True,
505504
)
506-
methods = [unwrap_metafunc_parametrize_and_possibly_prune_dependency_tree]
505+
methods = [prune_dependency_tree_if_test_is_dynamically_parametrized]
507506
if hasattr(module, "pytest_generate_tests"):
508507
methods.append(module.pytest_generate_tests)
509508
if cls is not None and hasattr(cls, "pytest_generate_tests"):
510509
methods.append(cls().pytest_generate_tests)
511510

512-
setattr(metafunc, "has_dynamic_parametrize", False)
513-
514-
@wraps(metafunc.parametrize)
515-
def set_has_dynamic_parametrize(*args, **kwargs):
516-
setattr(metafunc, "has_dynamic_parametrize", True)
517-
metafunc._parametrize(*args, **kwargs) # type: ignore[attr-defined]
518-
519-
setattr(metafunc, "_parametrize", metafunc.parametrize)
520-
setattr(metafunc, "parametrize", set_has_dynamic_parametrize)
521-
522511
# pytest_generate_tests impls call metafunc.parametrize() which fills
523512
# metafunc._calls, the outcome of the hook.
524513
self.ihook.pytest_generate_tests.call_extra(methods, dict(metafunc=metafunc))

testing/python/fixtures.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4681,3 +4681,10 @@ def test(fm):
46814681
)
46824682
reprec = pytester.inline_run()
46834683
reprec.assertoutcome(passed=5)
4684+
4685+
4686+
def test_deduplicate_names(pytester: Pytester) -> None:
4687+
items = fixtures.deduplicate_names("abacd")
4688+
assert items == ("a", "b", "c", "d")
4689+
items = fixtures.deduplicate_names(items + ("g", "f", "g", "e", "b"))
4690+
assert items == ("a", "b", "c", "d", "g", "f", "e")

0 commit comments

Comments
 (0)