Literate module testing
Execute literate .py modules as tests by running top-level code interspersed with ```{python} docstring examples.
Run octavo-test from the command line or test_py / run_py_mod in Python to execute each top-level AST statement in a fresh execnb.shell.CaptureShell alongside every ```{python} block in module, class, function, method, and top-level section docstrings (including compiled PyO3 extension docstrings on explicitly re-exported symbols). On [tool.nbdev] repositories, octavo-test runs nbdev-test on notebooks and also tests any hand-written (non-autogenerated) literate .py modules.
octavo-test
octavo-test --flags slow
octavo-test --do-all
octavo-test octavo/pydocs.py
Plain ```python fences remain non-executed illustrative examples. Start a top-level string with #| hide to keep setup imports or inline assertions out of doc() and rendered docs while still running its ```{python} blocks. Inside ```{python} blocks, fastcore.nbio directives (#| eval: false, #| slow, #| notest, #| hide) and module frontmatter (# - skip_exec: true, # - eval: false) mirror nbdev-test. Installing aai-octavo also registers a pytest11 plugin so pytest -q runs eligible literate modules alongside tests/.
Commands raise CliError when execnb or nbdev is missing, and FileNotFoundError when a target path or project package cannot be found.
Running tests
Execute one module directly with run_py_mod or test_py, or run all eligible package modules in isolated worker processes via octavo_test.
octavo_test
def octavo_test(
path:str=None, # Project directory or single `.py` file (defaults to nearest `pyproject.toml`)
flags:str='', # Space-separated test flags to enable (e.g. `"slow"`)
do_all:bool=False, # Run all flagged blocks regardless of `tst-flags`
n_workers:int=None, # Parallel worker processes (defaults to `0` for one module, else up to 8)
timing:bool=False, # Print per-module elapsed time sorted slowest first
do_print:bool=False, # Print start and completion lines for each module
pause:float=0.01, # Seconds to pause between launching parallel workers
verbose:bool=False, # Stream stdout and stderr from executed code blocks
timeout:int=600, # Per-step timeout in seconds (`0` disables timeout)
file_re:str=None, # Only run modules whose path matches this regex
)->None:
Run literate .py module tests in parallel, each in an isolated process; also runs nbdev-test on [tool.nbdev] repos.
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 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`
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)`
Execute top-level code and ```{python} blocks in fn inside a fresh CaptureShell.
Discovering and extracting steps
Pure helpers for turning a module's AST and docstrings into ordered PyStep objects, filtering by directives, and finding eligible test modules.
PyStep
def PyStep(
kind:Literal['code', 'doc'], code:str, lineno:int, label:str, directives:dict[str, str]
):
One executable unit from a Python module: top-level code (kind='code') or a ```{python} block (kind='doc').
py_steps
def py_steps(
src:str
)->list[octavo.test.PyStep]:
Extract top-level code statements and ```{python} docstring blocks 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.kind for s in st] == ['code', 'doc']
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[octavo.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:octavo.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).