runner.py


Overview

`runner.py` is a core module responsible for managing the execution lifecycle of test items within the pytest testing framework. It implements the protocols to **collect**, **setup**, **run**, and **teardown** tests, while handling exceptions, timing, and reporting outcomes. This file orchestrates the phases of test execution—setup, call (test function execution), and teardown—ensuring resources are allocated and cleaned up properly, and detailed reports are generated for consumption by pytest’s reporting subsystems.

Key responsibilities include:


Detailed Explanation of Classes and Functions

Public Hook Implementations


Core Functions


Classes

CallInfo(Generic[TResult])

A data class capturing the result or exception info of a function call within the test lifecycle.

**Attributes:**

**Key Methods:**

**Usage example:**

def some_setup():
    # setup logic here
    return "done"

call_info = CallInfo.from_call(some_setup, when="setup")
if call_info.excinfo is None:
    print(f"Setup succeeded with result: {call_info.result}")
else:
    print("Setup failed with exception")

SetupState

Manages the shared setup/teardown stack for test items and collectors within a test session.

**Purpose:**

**Key Methods:**

**Behavior:**

**Example usage:**

setup_state = SetupState()
setup_state.setup(test_item)
# ... run test ...
setup_state.teardown_exact(next_test_item)

Algorithm and Implementation Details


Interaction with Other System Components


Mermaid Class Diagram

classDiagram
    class CallInfo~TResult~ {
        - _result: TResult | None
        - excinfo: ExceptionInfo[BaseException] | None
        - start: float
        - stop: float
        - duration: float
        - when: Literal["collect", "setup", "call", "teardown"]
        + result: TResult
        + from_call(func: Callable[[], TResult], when, reraise) CallInfo~TResult~
        + __repr__()
    }

    class SetupState {
        - stack: dict~Node, tuple[list[Callable], tuple[Exception, traceback] | None]~
        + setup(item: Item)
        + addfinalizer(finalizer: Callable, node: Node)
        + teardown_exact(nextitem: Item | None)
    }

    CallInfo ..> ExceptionInfo
    SetupState ..> Callable
    SetupState ..> Node

Summary

`runner.py` is the backbone module for pytest's test execution lifecycle. It carefully manages the phases of running tests, ensures resource setup and cleanup across nested collector hierarchies, captures execution results with detailed timing and exception info, and integrates tightly with pytest's hook and reporting systems. Its design supports robustness, extensibility, and detailed user feedback during test runs.

This module directly interacts with test collection nodes, test items, session state, and reporting plugins, forming a critical bridge between test discovery and result presentation.


End of Documentation for runner.py