nbmake
nbmake is a pytest plugin designed for testing Jupyter notebooks. It executes notebooks programmatically, allowing for continuous integration and automated quality checks on documentation and research materials. Currently at version 1.5.5, the library maintains an active development cadence, frequently releasing updates to support new Python and Pytest versions and address user feedback.
Warnings
- breaking nbmake v1.5.0 dropped support for Python 3.7. Users on older Python versions will need to upgrade their Python environment or use an older nbmake version.
- breaking nbmake v1.5.5 dropped support for Python 3.8, which reached end-of-life in October 2024. Users running Python 3.8 should upgrade their Python environment.
- gotcha Notebooks can fail during testing due to missing Python package dependencies or an incorrect Jupyter kernel in the execution environment, particularly in CI setups. This results in `ModuleNotFoundError` or 'No such kernel' errors.
- gotcha Long-running cells in notebooks can cause tests to time out. Default timeouts might be too strict for some computational tasks.
- gotcha Some notebook cells or entire notebooks are designed to raise exceptions. By default, `nbmake` will treat these as failures.
- gotcha Relative imports within notebooks (e.g., `from .. import my_module`) often fail when run by `pytest --nbmake` if the project structure isn't correctly handled by pytest or the package isn't installed in 'editable' mode.
Install
-
pip install nbmake pytest
Imports
- nbmake
nbmake is primarily used as a pytest plugin via the command line; direct Python imports of 'nbmake' are generally not required for basic usage.
Quickstart
import os
# Create a dummy notebook for testing
notebook_content = """
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = 1\n",
"y = 2\n",
"assert x + y == 3"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print('Notebook executed successfully')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
"""
with open("test_notebook.ipynb", "w") as f:
f.write(notebook_content)
# To run this, save it as a .py file and execute from your terminal:
# python -c "$(cat your_script.py)" # (or simply run the file)
# Then, in the same directory:
# pytest --nbmake test_notebook.ipynb
print("Created test_notebook.ipynb. Run 'pytest --nbmake test_notebook.ipynb' in your terminal.")