Skip to content

Commit 471adac

Browse files
committed
nodes: add Node.iterchain() function
This is a useful addition to the existing `listchain`. While `listchain` returns top-to-bottom, `iterchain` is bottom-to-top and doesn't require an internal full iteration + `reverse`.
1 parent b1c4308 commit 471adac

File tree

3 files changed

+21
-25
lines changed

3 files changed

+21
-25
lines changed

src/_pytest/fixtures.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1513,7 +1513,7 @@ def pytest_plugin_registered(self, plugin: _PluggyPlugin) -> None:
15131513

15141514
def _getautousenames(self, node: nodes.Node) -> Iterator[str]:
15151515
"""Return the names of autouse fixtures applicable to node."""
1516-
for parentnode in reversed(list(nodes.iterparentnodes(node))):
1516+
for parentnode in node.listchain():
15171517
basenames = self._nodeid_autousenames.get(parentnode.nodeid)
15181518
if basenames:
15191519
yield from basenames
@@ -1781,7 +1781,7 @@ def getfixturedefs(
17811781
def _matchfactories(
17821782
self, fixturedefs: Iterable[FixtureDef[Any]], node: nodes.Node
17831783
) -> Iterator[FixtureDef[Any]]:
1784-
parentnodeids = {n.nodeid for n in nodes.iterparentnodes(node)}
1784+
parentnodeids = {n.nodeid for n in node.iterchain()}
17851785
for fixturedef in fixturedefs:
17861786
if fixturedef.baseid in parentnodeids:
17871787
yield fixturedef

src/_pytest/nodes.py

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,6 @@
4949
tracebackcutdir = Path(_pytest.__file__).parent
5050

5151

52-
def iterparentnodes(node: "Node") -> Iterator["Node"]:
53-
"""Return the parent nodes, including the node itself, from the node
54-
upwards."""
55-
parent: Optional[Node] = node
56-
while parent is not None:
57-
yield parent
58-
parent = parent.parent
59-
60-
6152
_NodeType = TypeVar("_NodeType", bound="Node")
6253

6354

@@ -265,12 +256,20 @@ def setup(self) -> None:
265256
def teardown(self) -> None:
266257
pass
267258

268-
def listchain(self) -> List["Node"]:
269-
"""Return list of all parent collectors up to self, starting from
270-
the root of collection tree.
259+
def iterchain(self) -> Iterator["Node"]:
260+
"""Iterate over self and all parent collectors up to root of the
261+
collection tree, starting from self.
271262
272-
:returns: The nodes.
263+
.. versionadded:: 8.1
273264
"""
265+
parent: Optional[Node] = self
266+
while parent is not None:
267+
yield parent
268+
parent = parent.parent
269+
270+
def listchain(self) -> List["Node"]:
271+
"""Return a list of all parent collectors up to and including self,
272+
starting from the root of the collection tree."""
274273
chain = []
275274
item: Optional[Node] = self
276275
while item is not None:
@@ -319,7 +318,7 @@ def iter_markers_with_node(
319318
:param name: If given, filter the results by the name attribute.
320319
:returns: An iterator of (node, mark) tuples.
321320
"""
322-
for node in reversed(self.listchain()):
321+
for node in self.iterchain():
323322
for mark in node.own_markers:
324323
if name is None or getattr(mark, "name", None) == name:
325324
yield node, mark
@@ -363,17 +362,16 @@ def addfinalizer(self, fin: Callable[[], object]) -> None:
363362
self.session._setupstate.addfinalizer(fin, self)
364363

365364
def getparent(self, cls: Type[_NodeType]) -> Optional[_NodeType]:
366-
"""Get the next parent node (including self) which is an instance of
365+
"""Get the closest parent node (including self) which is an instance of
367366
the given class.
368367
369368
:param cls: The node class to search for.
370369
:returns: The node, if found.
371370
"""
372-
current: Optional[Node] = self
373-
while current and not isinstance(current, cls):
374-
current = current.parent
375-
assert current is None or isinstance(current, cls)
376-
return current
371+
for node in self.iterchain():
372+
if isinstance(node, cls):
373+
return node
374+
return None
377375

378376
def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:
379377
return excinfo.traceback

src/_pytest/python.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -333,10 +333,8 @@ def _getobj(self):
333333

334334
def getmodpath(self, stopatmodule: bool = True, includemodule: bool = False) -> str:
335335
"""Return Python path relative to the containing module."""
336-
chain = self.listchain()
337-
chain.reverse()
338336
parts = []
339-
for node in chain:
337+
for node in self.iterchain():
340338
name = node.name
341339
if isinstance(node, Module):
342340
name = os.path.splitext(name)[0]

0 commit comments

Comments
 (0)