py.test: get KeyboardInterrupt to call teardown

核能气质少年 提交于 2019-12-10 22:04:47

问题


I am using py.test to write some tests and in my tests I utilize funcargs. These funcargs have their own setups and teardowns defined in the conftest.py like this:

conftest.py:

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

My problem is when someone uses CTRL+C to stop the test executions it leaves everything un-teardowned. I know there is a hook pytest_keyboard_interrupt but I dont know what to do from there.

Sorry for the noobish question.


回答1:


You don't provide a full example so maybe i am missing something. But here is an example of how it can work, using the request.cached_setup() helper:

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()

If you run this with "py.test" you get:

============================= 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

which shows that setup and teardown are called if a KeyboardInterrupt occurs during test execution.



来源:https://stackoverflow.com/questions/11018265/py-test-get-keyboardinterrupt-to-call-teardown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!