Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

py.test: get KeyboardInterrupt to call teardown

Tags:

python

pytest

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.

like image 222
Parham Avatar asked Oct 14 '25 19:10

Parham


1 Answers

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.

like image 133
hpk42 Avatar answered Oct 17 '25 08:10

hpk42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!