python - py.test : get KeyboardInterrupt to call teardown

标签 python pytest

我正在使用 py.test 编写一些测试,并且在我的测试中我使用了 funcargs。这些 funcargs 在 conftest.py 中定义了自己的设置和拆卸,如下所示:

conftest.py:

def pytest_funcarg__resource_name(request):
  def setup():
    # do setup
  def teardown():
    # do teardown

我的问题是,当有人使用 CTRL+C 停止测试执行时,它会留下所有未删除的内容。 我知道有一个钩子(Hook) pytest_keyboard_interrupt 但我不知道从那里做什么。

抱歉这个菜鸟问题。

最佳答案

您没有提供完整的示例,所以我可能遗漏了什么。但这里有一个使用 request.cached_setup() 帮助程序的示例:

def pytest_funcarg__res(request):
    def setup():
        print "res-setup"
    def teardown(val):
        print "res-teardown"
    return request.cached_setup(setup, teardown)

def test_hello(res):
    raise KeyboardInterrupt()

如果你用“py.test”运行它,你会得到:

============================= test session starts ==============================
platform linux2 -- Python 2.7.3 -- pytest-2.2.5.dev4
plugins: xdist, bugzilla, pep8, cache
collected 1 items

tmp/test_keyboardinterrupt.py res-setup
res-teardown


!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! KeyboardInterrupt !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/home/hpk/p/pytest/tmp/test_keyboardinterrupt.py:10: KeyboardInterrupt

这表明如果在测试执行期间发生 KeyboardInterrupt,则会调用设置和拆卸。

关于python - py.test : get KeyboardInterrupt to call teardown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11018265/

相关文章:

python - pytest的文件夹结构和导入问题

python - 可以在 py.test 中使用类似单元测试的装置吗?

python - 如何使用 pytest-mock 指定模拟函数的返回值?

python - 如何对列值的多级索引进行排序

python - 链接到 VS2010 c++ 中特定位置的 dll

python - PIP安装程序中manylinux1和manylinux2020轮文件的区别

python - 参数化 pytest fixture 的输出

python - 使用机器学习解码回溯

python - PIL 图像和 matplotlib 图为 png 图像获取饱和黑白

python - 在 pytest 中运行 Jupyter notebook 测试。操作系统错误