在jupyter笔记本中运行pytest测试函数

abi*_*ham 19 python pytest jupyter jupyter-notebook

我正在编写关于python测试选项的演示文稿,我想要演示的技术之一是pytest.我打算用jupyter/ipython笔记本做演示.理想情况下,我希望能够在单元格中定义测试函数,然后使用pytest运行该函数; 这样我就可以展示pytest等的个性化特征.

有现成的方法吗?我在pytest api中看到的所有交互功能似乎都不符合要求,但我当然不是pytest专家.我很乐意写一个插件来做这个,所以关于这个方向的最佳方法的任何建议都会很棒.

我确实看到了pytest-ipynb,但它似乎没有做我需要的.如果评估错误,关于如何使用它的建议也会很好.

aka*_*ola 11

我为此创建了ipython_pytest,并在我的PyCon Helsinki 2016演示中使用它.

您可以使用这样的工具:

%%pytest

def test_my_stuff():
    assert 42 == 42
Run Code Online (Sandbox Code Playgroud)

遗憾的是,我无法找到一种方法来使笔记本中定义的函数和类可用于测试单元中的测试函数.如果有人想出一个解决方案,我会很感激.


Jea*_* T. 8

There is a similar module that looks very mature: https://github.com/chmp/ipytest

It is referenced in the module developed by @akaiola and looks more active.

I am not personally using Jupyter so I have not tested it myself but it looks like a good solution.

Here is an example from the Github repository (https://github.com/chmp/ipytest/blob/master/Example.ipynb)

具有iPytest的Jupyter笔记本


Aus*_*_10 6

我的 2 美分在这里,因为我已经为自己解决了这个问题 2 次,并且两次都回到了这个网站。对于未来的自己:

对于按以下方式构建的项目

prod_folder:
* data
* code
    * run_notebook.ipynb
* tests
   * test_some_test.py
Run Code Online (Sandbox Code Playgroud)

如果您想从run_notebook.ipynb中运行pytest,以下 cell-magic 可以满足我的目的:

prod_folder:
* data
* code
    * run_notebook.ipynb
* tests
   * test_some_test.py
Run Code Online (Sandbox Code Playgroud)