Installation and Getting Started¶
testbook
is a unit testing framework for testing code in Jupyter Notebooks.
Installing testbook
¶
Using a virtual environment or system Python:
pip install testbook
Using Anaconda:
conda install testbook
What is a Jupyter Notebook?¶
Installing and Launching Jupyter Notebook¶
jupyter lab
Create your first test¶
Create a new notebook:
To do add image
Write the following code into the first cell of a Jupyter Notebook:
def foo(x):
return x + 1
Save this Notebook as notebook.ipynb
.
Create a new .py
file. In this new file, write the following unit test:
from testbook import testbook
@testbook('notebook.ipynb', execute=True)
def test_foo(tb):
foo = tb.get("foo")
assert foo(2) == 3
That’s it! You can now execute the test.
General workflow when using testbook to write a unit test¶
Use
testbook.testbook
as a decorator or context manager to specify the path to the Jupyter Notebook. Passingexecute=True
will execute all the cells, and passingexecute=['cell-tag-1', 'cell-tag-2']
will only execute specific cells identified by cell tags.Obtain references to objects under test using the
.get
method.Write the test!