nodes.py

Overview

The [nodes.py](/projects/286/67419) file defines the core abstraction and base classes for pytest's **test collection tree nodes**. This includes both **collectors** (nodes that contain other nodes, typically directories, packages, modules, classes) and **items** (leaf nodes representing runnable test cases). It establishes a hierarchy of node types to represent the structure of a test suite as discovered by pytest.

Key responsibilities of this file include:

This file plays a foundational role in how pytest builds the **collection tree**, which represents the entire test suite structure, enabling discovery, parametrization, setup/teardown management, and test execution orchestration.


Detailed Explanation of Classes and Functions

Helper Functions

_imply_path(node_type: type[Node], path: Path | None, fspath: LEGACY_PATH | None) -> Path


Class NodeMeta(abc.ABCMeta)


Class Node(abc.ABC, metaclass=NodeMeta)

parent_node = some_collector_node
child_node = Node.from_parent(parent=parent_node, name="child")
child_node.add_marker("slow")
child_node.warn(UserWarning("This test is slow"))

Function get_fslocation_from_item(node: Node) -> tuple[str | Path, int | None]


Class Collector(Node, abc.ABC)

class MyCollector(Collector):
    def collect(self):
        # Collect child nodes here
        yield some_item

Class FSCollector(Collector, abc.ABC)

file_collector = File.from_parent(parent=some_directory_collector, path=Path("test_example.py"))

Class File(FSCollector, abc.ABC)


Class Directory(FSCollector, abc.ABC)


Class Item(Node, abc.ABC)

class MyTest(Item):
    def runtest(self):
        assert 1 + 1 == 2

test_item = MyTest.from_parent(parent=some_collector, name="test_addition")
test_item.runtest()

Function _check_initialpaths_for_relpath(initial_paths: frozenset[Path], path: Path) -> str | None


Important Implementation Details and Algorithms


Interaction with Other Parts of the System


Mermaid Class Diagram

classDiagram
    class NodeMeta {
        <<metaclass>>
        +__call__(*args, **kwargs) : NoReturn
        +_create(*args, **kwargs) : Node
    }

    class Node {
        +name: str
        +parent: Node | None
        +config: Config
        +session: Session
        +path: pathlib.Path
        +keywords: MutableMapping[str, Any]
        +own_markers: list[Mark]
        +extra_keyword_matches: set[str]
        +stash: Stash
        +nodeid: str
        +from_parent(parent: Node, **kw) : Self
        +warn(warning: Warning) : None
        +iter_parents() : Iterator[Node]
        +listchain() : list[Node]
        +add_marker(marker: str | MarkDecorator, append: bool) : None
        +iter_markers(name: str | None) : Iterator[Mark]
        +get_closest_marker(name: str, default: Mark | None) : Mark | None
        +addfinalizer(fin: Callable) : None
        +getparent(cls) : Node | None
        +repr_failure(excinfo: ExceptionInfo, style: TracebackStyle | None) : str | TerminalRepr
    }

    class Collector {
        +collect() : Iterable[Item | Collector]
        +repr_failure(excinfo: ExceptionInfo) : str | TerminalRepr
    }

    class FSCollector {
        +__init__(...)
    }

    class File {
    }

    class Directory {
    }

    class Item {
        +nextitem: Item | None
        +_report_sections: list[tuple[str, str, str]]
        +user_properties: list[tuple[str, object]]
        +runtest() : None
        +add_report_section(when: str, key: str, content: str) : None
        +reportinfo() : tuple
        +location() : tuple
    }

    NodeMeta <|-- Node
    Node <|-- Collector
    Collector <|-- FSCollector
    FSCollector <|-- File
    FSCollector <|-- Directory
    Node <|-- Item

Summary

The [nodes.py](/projects/286/67419) file defines the **abstract syntax and behavior of pytest's collection tree nodes**. It provides base classes and foundational utilities that enable pytest to structure discovered tests in a hierarchical and extensible manner. The strict node construction pattern, marker and keyword management, detailed failure representation, and seamless integration with the pytest session and configuration make it a cornerstone of pytest’s test discovery and execution framework.

By defining collectors and items with clear responsibilities and interfaces, this module allows pytest to flexibly build and traverse the test suite tree, supporting powerful features like parametrization, test selection, reporting, and plugin extensibility.


End of documentation for nodes.py