Jupyter Notebook 验证工具 nbval 使用教程
nbval A py.test plugin to validate Jupyter notebooks 项目地址: https://gitcode.com/gh_mirrors/nb/nbval
1. 项目介绍
nbval
是一个 py.test
插件,用于验证 Jupyter 笔记本。它通过比较笔记本中存储的输入和输出,确保笔记本的执行结果一致性。这个插件非常适合用于确保参考和文档中的 Jupyter 笔记本能够稳定运行,每个单元格被视为一个测试案例,如果单元格无法重现预期输出,则测试失败。
2. 项目快速启动
首先,确保你已经安装了 py.test
。接下来,可以通过以下方式安装 nbval
:
pip install nbval
或者,如果你想安装最新版本的 nbval
,可以克隆仓库并运行:
git clone https://github.com/computationalmodelling/nbval.git
cd nbval
pip install .
安装完成后,可以使用以下命令来执行笔记本的验证:
py.test --nbval
如果你想指定一个特定的笔记本进行验证,可以使用:
py.test --nbval my_notebook.ipynb
如果需要调整笔记本使用的内核,可以使用以下选项:
py.test --nbval-kernel-name mykernel my_notebook.ipynb
或者使用当前环境中的内核:
py.test --current-env my_notebook.ipynb
如果输出需要被清理,可以提供一个配置文件:
py.test --nbval my_notebook.ipynb --nbval-sanitize-with path/to/my_sanitize_file
其中 my_sanitize_file
应包含正则表达式和替换规则。
3. 应用案例和最佳实践
案例一:自动化测试
在你的持续集成(CI)流程中集成 nbval
,确保每次代码更新时笔记本都能正确执行。
# 在CI配置文件中添加
py.test --nbval
案例二:输出清理
如果你不希望某些输出(如时间戳)影响测试结果,可以在 my_sanitize_file
中定义相应的正则表达式和替换规则。
4. 典型生态项目
nbval
可以与 pytest-cov
插件结合使用,生成导入代码的覆盖率报告。
py.test --nbval --cov=my_module
此外,它还兼容 pytest-xdist
插件,可以进行并行测试。
py.test --nbval --dist loadscope
以上就是 nbval
的基本使用教程,希望对你有所帮助。
nbval A py.test plugin to validate Jupyter notebooks 项目地址: https://gitcode.com/gh_mirrors/nb/nbval
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考