我开始使用IPython笔记本记录一些代码,并提供交互式使用示例。为了避免文档与代码差距太大而过时,我希望笔记本中的代码定期执行以捕捉任何输出更改并标记运行时错误。
我使用nosetests
来运行回归测试,并想知道是否有一种方式可以让它执行IPython笔记本。请注意,我不是要在IPython笔记本中运行nosetests
(如在ipython_nose中所做的那样)。更像doctest
插件的东西。是否存在此类插件?
我开始使用IPython笔记本记录一些代码,并提供交互式使用示例。为了避免文档与代码差距太大而过时,我希望笔记本中的代码定期执行以捕捉任何输出更改并标记运行时错误。
我使用nosetests
来运行回归测试,并想知道是否有一种方式可以让它执行IPython笔记本。请注意,我不是要在IPython笔记本中运行nosetests
(如在ipython_nose中所做的那样)。更像doctest
插件的东西。是否存在此类插件?
我最近写了一个类似的脚本,其中大部分内容都基于“测试Jupyter笔记本电脑”的这篇博客
下面是稍微修改过的版本:
from glob import glob
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors.execute import CellExecutionError
def _notebook_run(path):
"""
Execute a notebook via nbconvert and collect output.
:returns (parsed nb object, execution errors)
"""
kernel_name = 'python%d' % sys.version_info[0]
this_file_directory = os.path.dirname(__file__)
errors = []
with open(path) as f:
nb = nbformat.read(f, as_version=4)
nb.metadata.get('kernelspec', {})['name'] = kernel_name
ep = ExecutePreprocessor(kernel_name=kernel_name, timeout=10) #, allow_errors=True
try:
ep.preprocess(nb, {'metadata': {'path': this_file_directory}})
except CellExecutionError as e:
if "SKIP" in e.traceback:
print(str(e.traceback).split("\n")[-2])
else:
raise e
return nb, errors
现在你可以这样使用该函数:
def test_notebooks():
for notebook in glob("./*.ipynb"):
nb, errors = _notebook_run(notebook)
assert errors == []
最近Andrea Zonca发布了pytest-ipynb。我还没有测试过它,但它似乎符合您的要求(也许不是针对nose的,但它具有很好的特性,如在失败时指示单元格)。我一定会用它来测试学生的作业和材料:)