Skip to content

Plugin - API

plugin

Pytest plugin to collect jupyter Notebooks.

  • Identifies all cells which use the %%ipytest magic
  • adds the notebook, cell and any test functions to the collection tree
  • relies on pytest logic and configuration to identify test functions.

ipynb2_monkeypatches module-attribute

ipynb2_monkeypatches = StashKey[
    dict[tuple[ModuleType, str], FunctionType]
]()

Original functions indexed by (module, functionname) to allow setattr(module, functionname, original).

Cell

A collector for jupyter notebook cells.

pytest will recognise these cells as pytest.Modules and use standard collection on them as it would any other python module.

__repr__

__repr__() -> str

Don't duplicate the word "Cell" in the repr.

_getobj

_getobj() -> ModuleType

The main magic.

  • loads the cell's source
  • applies assertion rewriting
  • creates a pseudo-module for the cell, with a pseudo-filename
  • executes all non-test code cells above inside the pseudo-module.dict
  • then executes the test cell inside the pseudo-module.dict
  • finally adds the test cell to the linecache so that inspect can find the source

Notebook

A collector for jupyter notebooks.

collect

collect() -> Generator[Cell, None, None]

Yield Cells for all cells which contain tests.

pytest_collect_file

pytest_collect_file(
    file_path: Path, parent: Collector
) -> Notebook | None

Hook implementation to collect jupyter notebooks.

pytest_load_initial_conftests

pytest_load_initial_conftests(
    early_config, parser, args: list[str]
) -> Generator[None, None, None]

Convert any CellPaths passed as commandline args to "::"-separated nodeids.

Even though we are using path/to/notebook.ipynb[Celln]::test_func as nodeid format, pytest will still accept path/to/notebook.ipynb::Celln::test_func as a valid nodeid. For unknown reasons, _pytest.main.resolve_collection_argument removes anything after the first [

pytest_sessionfinish

pytest_sessionfinish(
    session: Session, exitstatus: int | ExitCode
) -> Generator[None, None, None]

Revert Monkeypatches based on stashed versions.

pytest_sessionstart

pytest_sessionstart(
    session: Session,
) -> Generator[None, None, None]

Monkeypatch pytest to handle CellPath, store patches in stash to revert later.