我正在使用 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,则调用 setup 和 teardown。

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

10-11 15:04