nbval

0.11.0 · active · verified Mon Apr 13

nbval is a pytest plugin designed to validate Jupyter notebooks. It allows users to execute notebooks as part of their test suite and compare cell outputs against previously saved outputs, ensuring reproducibility and correctness. The current version is 0.11.0, and it has a sporadic but active release cadence, typically with minor releases every 6-12 months.

Warnings

Install

Imports

Quickstart

This quickstart script demonstrates how to programmatically create a simple Jupyter notebook and then run `pytest` with the `nbval` plugin to validate its output. It shows the minimal setup required to get started with notebook testing using `nbval`.

import pytest
import json
import os

# 1. Create a dummy Jupyter notebook file for testing
notebook_content = {
    "cells": [
        {
            "cell_type": "code",
            "execution_count": 1,
            "metadata": {},
            "outputs": [
                {"name": "stdout", "output_type": "stream", "text": ["Hello from nbval!\n"]}
            ],
            "source": ["print('Hello from nbval!')"]
        }
    ],
    "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
}

notebook_filename = "example.ipynb"
with open(notebook_filename, "w") as f:
    json.dump(notebook_content, f, indent=4)

print(f"Created {notebook_filename}. Running nbval tests...")

# 2. Run pytest programmatically with nbval
#    The --nbval flag enables the plugin, and the notebook filename specifies the target.
exit_code = pytest.main(["--nbval", notebook_filename])

# 3. Report results and clean up
# os.remove(notebook_filename) # Uncomment to clean up the notebook file after run

if exit_code == 0:
    print(f"\nnbval tests passed for {notebook_filename}!")
else:
    print(f"\nnbval tests failed for {notebook_filename} with exit code {exit_code}.")

view raw JSON →