doctest.py


Overview

The [doctest.py](/projects/286/67506) file is a core component of the pytest framework that provides comprehensive support for discovering, collecting, running, and reporting **doctests** embedded within Python modules (`.py` files) and standalone text files (e.g., `.txt`, `.rst`). Doctests are interactive Python examples found in documentation strings or text files that serve as both documentation and executable tests.

This module enables pytest to:

By integrating doctests seamlessly into the pytest ecosystem, this file allows users to run doctests alongside pytest tests, benefiting from pytest’s fixtures, reporting, and test selection mechanisms.


Main Classes and Functions

1. pytest_addoption(parser: Parser) -> None

**Purpose:** Registers command-line options and ini-file configuration entries related to doctest collection and execution.

**Key Options Registered:**

**Usage:** This function is automatically called by pytest during plugin registration.


2. pytest_collect_file(file_path: Path, parent: Collector) -> DoctestModule | DoctestTextfile | None

**Purpose:** Hook to determine if a file should be collected as a doctest. Returns a collector instance if the file contains doctests, or [None](/projects/286/67505) otherwise.

**Logic:**


3. class DoctestItem(Item)

Represents a single doctest within a module or text file.

**Constructor Parameters:**

**Key Methods:**

**Example Usage:**

# Typically, created by the collection mechanism:
doctest_item = DoctestItem.from_parent(
    parent=some_doctest_module,
    name="module_name.test_function",
    runner=runner_instance,
    dtest=doctest_obj
)

doctest_item.setup()
doctest_item.runtest()

4. class DoctestTextfile(Module)

Collector for doctests found in external text files (like `.txt` or `.rst`).

**Key Method:**


5. class DoctestModule(Module)

Collector for doctests inside Python `.py` modules.

**Key Method:**

**Implementation Details:**


6. class MultipleDoctestFailures(Exception)

Exception used to aggregate multiple doctest failures within a single doctest run.


7. _init_runner_class() -> type[doctest.DocTestRunner]

Returns a customized doctest runner class `PytestDoctestRunner`:


8. _get_runner(...) -> doctest.DocTestRunner

Returns a singleton instance of the doctest runner (`PytestDoctestRunner`), ensuring lazy import of `doctest`.


9. _init_checker_class() -> type[doctest.OutputChecker]

Returns a customized output checker class `LiteralsOutputChecker` with enhanced output comparison abilities:


10. _get_checker() -> doctest.OutputChecker

Returns a singleton instance of the customized `LiteralsOutputChecker`.


11. doctest_namespace() -> dict[str, Any] (pytest fixture)

Provides a mutable dictionary injected into the namespace of all doctests.

**Usage Example:**

@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
    doctest_namespace["np"] = numpy

This enables doctests to use fixtures and shared objects.


12. Helper Functions


Implementation Details and Algorithms

Doctest Collection

Doctest Execution

Failure Reporting


Interaction with Other Parts of the System


Visual Diagram

flowchart TD
    A[pytest_collect_file]
    A -->|.py & --doctest-modules| B[DoctestModule Collector]
    A -->|matches glob| C[DoctestTextfile Collector]
    B --> D[MockAwareDocTestFinder]
    C --> E[doctest.DocTestParser]
    D --> F[DoctestItem]
    E --> F
    F --> G[DoctestItem.setup()]
    G --> H[Inject fixtures into doctest.globs]
    H --> I[DoctestItem.runtest()]
    I --> J[PytestDoctestRunner.run()]
    J -->|failures| K[MultipleDoctestFailures Exception]
    K --> L[DoctestItem.repr_failure()]
    L --> M[Formatted failure report with diff]

Summary

The [doctest.py](/projects/286/67506) file is the cornerstone of pytest’s support for running doctests. It provides:

This integration empowers users to maintain and test documentation examples confidently within the pytest ecosystem, ensuring high-quality, tested documentation as part of their development workflow.