Deploy AI apps for free on Ploomber Cloud!

Unit testing

Contents

Unit testing#

ploomber-engine allows you to extract function or class definitions to write unit tests.

Example#

Install dependencies:

%pip install ploomber-engine --quiet
Note: you may need to restart the kernel to use updated packages.

Download sample notebook:

%%sh
curl https://raw.githubusercontent.com/ploomber/ploomber-engine/main/examples/nb.ipynb --output testing-demo.ipynb
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100  1257  100  1257    0     0  23093      0 --:--:-- --:--:-- --:--:-- 23277

Extract the definitions from the notebook (this won’t run the notebook):

from ploomber_engine.ipython import PloomberClient

client = PloomberClient.from_path("testing-demo.ipynb")
definitions = client.get_definitions()
definitions
{'add': <function __main__.add(x, y)>,
 'multiply': <function __main__.multiply(x, y)>}

Get the add and multiply function defined in the notebook:

add = definitions["add"]
multiply = definitions["multiply"]

Test the functions:

assert add(1, 41) == 42
assert add(50, 50) == 100
assert multiply(2, 21) == 42
assert multiply(0, 10) == 0

Note

testbook is another library that helps writing unit tests for Jupyter notebooks. However, testbook has a big limitation since it needs to serialize objects defined in a notebook, which makes debugging tests a lot more difficult. With ploomber-engine this isn’t the case.