testbook

raw JSON →
0.4.2 verified Mon Apr 27 auth: no python

A unit testing framework for Jupyter Notebooks. Current version 0.4.2 (release cadence: infrequent, last release Sep 2021). Allows writing and running tests for notebook cells using Python test frameworks.

pip install testbook
error ModuleNotFoundError: No module named 'testbook'
cause testbook is not installed or installed in a different environment.
fix
Install testbook: pip install testbook
error AttributeError: module 'testbook' has no attribute 'testbook'
cause Old import style (import testbook then testbook.testbook) no longer works in recent versions.
fix
Use: from testbook import testbook
error FileNotFoundError: [Errno 2] No such file or directory: 'notebook.ipynb'
cause The notebook path is relative and may not be correct when running tests from a different directory.
fix
Use an absolute path or set the working directory to the notebook's location.
gotcha When using execute=True (default), the entire notebook is executed before test. This may be slow and side-effect heavy. Use execute=False for partial execution.
fix Set execute=False in the decorator: @testbook('notebook.ipynb', execute=False), then run tb.execute_cell(0) to run specific cells in your test.
gotcha Cell indices are 0-based, but non-code cells (e.g. markdown) are skipped. Counting cells manually can be error-prone.
fix Use tb.cell_output_slice() or iterate with tb.cells to find the correct index. Alternatively, use cell tags in the notebook to reference cells by name.
deprecated The old API function 'testbook.testbook' (lowercase) has been deprecated in favor of the decorator usage.
fix Update imports: from testbook import testbook. Use @testbook decorator or context manager.

Decorate a test function with @testbook, specifying the notebook path. The test function receives a Testbook object. Calling tb.cell_output(index) retrieves the output of a cell.

from testbook import testbook

@testbook('notebook.ipynb', execute=True)
def test_something(tb):
    result = tb.cell_output(0)
    assert result == 42