Links

Testing Jupyter Notebook Code with Code Pattern Checks

There is a really great way of testing Jupyter Notebooks using pytest that does not involve code patterns. Code patterns should only be used if the pytest method is insufficient.
In this guide, we cover how to use code pattern checks in conjunction with Jupyter Notebook.
Code patterns allow you to search for specific snippets within code files. To use these with Jupyter Notebook, you should first look at the IPYNB notebook file in its JSON plain text format. You can see this by clicking the "Edit" button after selecting the file:
The code pattern must match the code in Jupyter notebook file.
Note that the code in the notebook file may not necessarily be what you see in the Jupyter notebook cell due to whitespaces, escaped characters, etc.

Example

If the Jupyter notebook file contains the following for a specific cell:
"source": [
"import pandas as pd\n",
"df= pd.read_csv(\"example.csv\")"
]
You can ensure that the user has correctly imported the .csv file using the pandas library by using the following code pattern:
.+ =\s*pd\.read_csv\(\\['"]example\.csv\\['"]\)
Note that, using the pytest method of testing Jupyter Notebooks, you can simply execute the cell to ensure the library is loaded.