Testing notebooks, literate modules, and pytest

Run notebook examples, literate .py docstring examples, and conventional pytest suites under one command.

ship-test executes notebook cells (test_nb), literate .py modules by importing them and running their ```{python} docstring examples (test_py / run_py_mod, including re-exported compiled PyO3 docstrings), and conventional pytest tests once when tests/ or pytest testpaths ([tool.pytest.ini_options], [tool.pytest]) is configured. Each notebook and literate module runs in an isolated execnb.shell.CaptureShell process.

ship-test
ship-test --flags slow
ship-test --do-all
ship-test ship/api/01_maker.ipynb
ship-test fastship/test.py

Press Ctrl-C during a hung notebook run to dump each worker's synchronous stack and pending asyncio task await chains. Export cells containing nbdev_export() or ship_export() are skipped automatically during testing so legacy #| hide-only notebooks remain safe without edits.

nb_test_cells

def nb_test_cells(
    fn, # Notebook path or `Notebook`
    skip_flags=None, # Flags marking cells to skip
    force_flags=None, # Flags marking cells to always run
):

Return the cells test_nb would run in the notebook at fn.

from fastcore.nbio import new_nb, mk_cell
nb = new_nb([mk_cell('---\neval: false\n---', 'raw'), mk_cell('raise Exception("unmarked: must not run")'),
    mk_cell('#| eval: true\nx = 1')])
assert [c.source for c in nb_test_cells(nb)] == ['#| eval: true\nx = 1']
_nb = Path('tests/directives.ipynb')
if _nb.exists():
    cells = nb_test_cells(_nb, skip_flags=['notest'])
    assert not any('notest' in c.source for c in cells)
    assert len(cells) < len(nb_test_cells(_nb))

test_nb

def test_nb(
    fn, # Notebook path to test
    skip_flags=None, # Flags marking cells to skip
    force_flags=None, # Flags marking cells to always run
    do_print:bool=False, # Print start and completion lines
    showerr:bool=True, # Write tracebacks to stderr on failure
    basepath=None, # Path prepended to `sys.path`
    verbose:bool=False, # Stream stdout and stderr from cells
    save:bool=False, # Write executed outputs back to the notebook on success
    use_ipython:bool=False, # Run with real IPython instead of `execnb.minipy`
    cell_timeout:int=600, # Seconds before each cell times out (`None` disables limit)
    cell_timing_min:float=None, # Print cells slower than this many seconds
)->tuple[bool, float]: # `(passed, elapsed_seconds)`

Execute eligible cells in notebook fn inside a fresh CaptureShell.

_nb = Path('tests/directives.ipynb')
if _nb.exists():
    assert test_nb(_nb, skip_flags=['notest'])[0]
    assert not test_nb(_nb, showerr=False)[0]

test_py

def test_py(
    fn:str | pathlib._local.Path, # Path to the `.py` module to execute
    mod_nm:str=None, # Importable module name (inferred from project layout when omitted)
    pkg:str=None, # Parent package name for relative imports (inferred from `mod_nm`)
    root:pathlib._local.Path=None, # Working directory during execution (defaults to project root or `fn.parent`)
    skip_flags=None, # Directive flags that skip a `{python}` block unless forced
    force_flags=None, # Directive flags forced to run despite `skip_flags`
    do_print:bool=False, # Print start and completion lines
    showerr:bool=True, # Write failure traceback to stderr
    verbose:bool=False, # Stream stdout and stderr from executed blocks
    timeout:int=600, # Per-step timeout in seconds (`None` disables timeout)
)->tuple[bool, float]: # `(passed, elapsed_seconds)`

Execute literate tests in fn, printing formatted tracebacks to stderr on failure.

run_py_mod

def run_py_mod(
    fn:str | pathlib._local.Path, # Path to the `.py` module to test
    mod_nm:str=None, # Importable module name (inferred from project layout when omitted)
    pkg:str=None, # Parent package name for relative imports (inferred from `mod_nm`)
    root:pathlib._local.Path=None, # Working directory during execution (defaults to project root or `fn.parent`)
    skip_flags=None, # Directive flags that skip a `{python}` block unless forced
    force_flags=None, # Directive flags forced to run despite `skip_flags`
    verbose:bool=False, # Stream stdout and stderr from executed blocks
    timeout:int=600, # Per-step timeout in seconds (`None` disables timeout)
)->tuple[bool, float, str]: # `(passed, elapsed_seconds, error_text)`

Import fn normally and execute its ```{python} examples in order with shared state inside a CaptureShell.

Discovering and extracting literate module steps

Pure helpers for turning a module's AST and docstrings into ordered PyStep objects, filtering by directives, and finding eligible literate test modules.

PyStep

def PyStep(
    code:str, lineno:int, label:str, directives:dict[str, str]
):

One executable ```{python} block from a Python module docstring or top-level Markdown section.

py_steps

def py_steps(
    src:str, # Python module source text
    ns:dict=None, # Optional imported module namespace for extracting native re-export docstrings
    pkg:str=None, # Optional package name for resolving relative imports of native extensions
)->list[fastship.test.PyStep]: # Extracted `{python}` steps in source order, with module-docstring examples deferred to the end

Extract ```{python} docstring and section examples in execution order.

st = py_steps('def f(x):\n    "Hi\\n\\n```{python}\\nassert f(1) == 2\\n```"\n    return x + 1\n')
assert [s.label for s in st] == ['f docstring'] and st[0].code.strip() == 'assert f(1) == 2'

native_doc_steps

def native_doc_steps(
    code:str, # Single top-level `from ... import ...` statement source
    ns:dict, # Execution namespace after running `code`
    pkg:str, # Package name used to resolve relative imports
    lineno:int=1, # 1-based line number of the import statement
)->list[fastship.test.PyStep]: # Extracted `{python}` steps from compiled native extension docstrings

Extract ```{python} blocks from compiled native extension symbols imported by code.

should_run_step

def should_run_step(
    step:fastship.test.PyStep, # Step returned by `py_steps` or `native_doc_steps`
    default_eval:bool=True, # Module-level default eval flag from frontmatter
    skip_flags:tuple=(), # Flag names that skip matching `{python}` blocks
    force_flags:tuple=(), # Flag names that override `skip_flags`
)->bool: # `True` when `step` should execute

Return True when step participates in a test run under the given default_eval and flags.

has_py_tests

def has_py_tests(
    path:str | pathlib._local.Path, # Path to a `.py` source file
    mod_nm:str=None, # Optional importable module name (used only for native `.so` re-export checks)
    pkg:str=None, # Optional package name for relative import resolution
)->bool: # `True` when `path` contains runnable `{python}` blocks and is not `skip_exec` or autogenerated

Return True when path is eligible for literate module testing.

find_test_mods

def find_test_mods(
    path:str | pathlib._local.Path | None=None, # Project directory or single `.py` file (defaults to nearest `pyproject.toml`)
    file_re:str=None, # Optional regex filter matched against repo-relative paths
)->list[tuple[pathlib._local.Path, str, str, pathlib._local.Path]]: # `(py_path, mod_nm, pkg_nm, root)` tuples in sorted path order

Find eligible non-autogenerated literate-test .py modules under a project (or a single specified .py file).

Running tests

Run ship_test across an entire project (notebooks, literate .py modules, and pytest once) or target a single notebook, literate module, or test file.

ship_test

def ship_test(
    path:str=None, # Project directory, glob, or single `.ipynb`/`.py` file
    flags:str='', # Space-separated test flags to enable (e.g. `"slow"`)
    do_all:bool=False, # Run all flagged cells/blocks regardless of `tst-flags`
    n_workers:int=None, # Parallel worker processes (defaults to `0` for one item, else up to 8)
    timing:bool=False, # Print per-file elapsed time sorted slowest first
    do_print:bool=False, # Print start and completion lines for each file
    pause:float=0.01, # Seconds to pause between launching parallel workers
    ignore_fname:str='.notest', # Sibling marker file that skips notebooks in that directory
    verbose:bool=False, # Stream stdout and stderr from executed code
    save:bool=False, # Write executed outputs back to notebooks on success
    cell_timeout:int=None, # Seconds before each cell/step times out (`0` disables limit; default 600)
    cell_timing_min:float=None, # Print notebook cells slower than this many seconds
    use_ipython:bool=False, # Run notebooks with real IPython instead of `execnb.minipy`
    file_re:str=None, # Only run notebooks/modules whose path matches this regex
    *, symlinks:bool=False, # Follow symlinks?
    file_glob:str='*.ipynb', # Only include files matching glob
    path_glob:str=None, # Only include files whose full paths match glob (wildcards match separators)
    path_re:str=None, # Only include files whose full paths match regex
    folder_re:str=None, # Only enter folders matching regex
    skip_file_glob:str=None, # Skip files matching glob
    skip_file_re:str='^[_.]', # Skip files matching regex
    skip_folder_re:str='^[_.]', # Skip folders matching regex
)->None:

Run notebook tests, literate .py module tests, and pytest (when tests/ or testpaths is present).