Skip to main content

Pytest plugin for testing notebooks

Project description

nbmake

codecov PyPI versions PyPI versions PyPI Downloads

What? Pytest plugin for testing and releasing notebook documentation

Why? To raise the quality of scientific material through better automation

Who is this for? Research/Machine Learning Software Engineers who maintain packages/teaching materials with documentation written in notebooks.

Functionality

  1. Executes notebooks using pytest and nbclient, allowing parallel notebook testing
  2. Optionally writes back to the repo, allowing faster building of nbsphinx or jupyter book docs

Quick Start

If you have a notebook that runs interactively using an ipython kernel, you can try testing it automatically as follows:

pip install pytest nbmake
pytest --nbmake **/*ipynb

Configure Cell Timeouts

You can configure the cell timeout with the following pytest flag:

pytest --nbmake --nbmake-timeout=3000 # allows each cell 3000 seconds to finish

Allow Errors For a Whole Notebook

This configuration must be placed in the notebook's top-level metadata (not cell-level metadata).

Your notebook should look like this:

{
  "cells": [ ... ],
  "metadata": {
    "kernelspec": { ... },
    "execution": {
      "allow_errors": true,
      "timeout": 300
    }
  }
}

Allow a Cell to Throw an Exception

A cell with the following metadata can throw an exception without failing the test:

{
  "language": "python",
  "custom": {
    "metadata": {
      "tags": [
        "raises-exception"
      ]
    }
  }
}

Ignore a Code Cell

A cell with the following metadata will not be executed by nbmake

{
  "language": "python",
  "custom": {
    "metadata": {
      "tags": [
        "skip-execution"
      ]
    }
  }
}

Override Notebook Kernels when Testing

Regardless of the kernel configured in the notebook JSON, you can force nbmake to use a specific kernel when testing:

pytest --nbmake --nbmake-kernel=mycustomkernel

Add Missing Jupyter Kernel to Your CI Environment

If you are not using the flag above and are using a kernel name other than the default ‘python3’, you will see an error message when executing your notebooks in a fresh CI environment: Error - No such kernel: 'mycustomkernel'

Use ipykernel to install the custom kernel:

python -m ipykernel install --user --name mycustomkernel

If you are using another language such as c++ in your notebooks, you may have a different process for installing your kernel.

Parallelisation

For repos containing a large number of notebooks that run slowly, you can run each notebook in parallel using pytest-xdist.

pip install pytest-xdist

pytest --nbmake -n=auto

It is also possible to parallelise at a CI-level using strategies, see example

Build Jupyter Books Faster

Using xdist and the --overwrite flag let you build a large jupyter book repo faster:

pytest --nbmake --overwrite -n=auto examples
jb build examples

Mock out variables to simplify testing (experimental 🧪)

If your notebook runs a training process that takes a long time to run, you can use nbmake's mocking feature to overwrite variables after a cell runs:

{
  "cells": [
    ...,
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "nbmake": {
          "mock": {
            // these keys will override global variables after this cell runs
            "epochs": 2,
            "config": "/test/config.json",
            "args": {
              "env": "test"
            }
          }
        }
      },
      "outputs": [],
      "source": [
        "epochs = 10\n",
        "..."
      ]
    },
    ...
  ],
  ...
}

Advice on Usage

nbmake is best used in a scenario where you use the ipynb files only for development. Consumption of notebooks is primarily done via a docs site, built through jupyter book, nbsphinx, or some other means. If using one of these tools, you are able to write assertion code in cells which will be hidden from readers.

Pre-commit

Treating notebooks like source files lets you keep your repo minimal. Some tools, such as plotly may drop several megabytes of javascript in your output cells, as a result, stripping out notebooks on pre-commit is advisable:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/kynan/nbstripout
    rev: master
    hooks:
      - id: nbstripout

See https://pre-commit.com/ for more...

Disable Nbmake

Implicitly:

pytest

Explicitly:

pytest -p no:nbmake

See Also:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nbmake-1.3.5.tar.gz (11.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nbmake-1.3.5-py3-none-any.whl (11.8 kB view details)

Uploaded Python 3

File details

Details for the file nbmake-1.3.5.tar.gz.

File metadata

  • Download URL: nbmake-1.3.5.tar.gz
  • Upload date:
  • Size: 11.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.8

File hashes

Hashes for nbmake-1.3.5.tar.gz
Algorithm Hash digest
SHA256 95d4716928171120fae562e69440989a636e2af8616c829573e9574f5bea30db
MD5 4f9b18e0f4717ba36425697b6e3e4183
BLAKE2b-256 6e09008decab85247fc0e7c7d5d7dc11bff8c0da6fe81d5ffef71147d65d567c

See more details on using hashes here.

File details

Details for the file nbmake-1.3.5-py3-none-any.whl.

File metadata

  • Download URL: nbmake-1.3.5-py3-none-any.whl
  • Upload date:
  • Size: 11.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.8

File hashes

Hashes for nbmake-1.3.5-py3-none-any.whl
Algorithm Hash digest
SHA256 8506d2a2d7eb55bdc0db0f1573039c734bd4f4d1c130df4ad8ade72b5b2a8fe0
MD5 4f2be093c3fc8de55e288674b010f0ab
BLAKE2b-256 e979c179e0cfb0a83cd905d805241acc74cc4960c9676c7331b52ceac05da0cc

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page