Where to catch a KeyboardInterrupt in unittests?
<p>I'm UI testing on mobile devices using an Appium server. I want to be able to cancel the testing process while developing the tests. Currently, when I <code>CTRL-C</code> out of the process (the python unittest), I have to restart the appium server, since the session was not shut down properly (this would have been done in the <code>tearDown()</code> method of the test, but since I press CTRL-C, that won't be executed.) Instead I wanna have the <code>tearDown()</code> fire everytime the test gets canceled by a <code>KeyboardInterrupt</code>.</p>

<p>Now's my question: Where do I put the try-catch block to achieve this? Is there a best practice handling this in Python unittests? I need to access a class variable (<code>self.driver.quit()</code>), right after <code>KeyboardInterrupt</code> fires. The class variable is inside the class that was put into the <code>unittest.TestSuite</code> that the <code>unittest.TextTestRunner</code> is running. </p>

<pre><code>try:
  self.test_something()
except KeyboadInterrupt:
  self.driver.quit()
</code></pre>

<p>I've looked a bit into <code>unittest.TestResult</code> and its <code>stop()</code> method but haven't found practical examples explaining its usage properly.</p>

<p>You can change the default behaviour of Python regarding SIGINT to suit your needs:</p>

<pre><code>import signal

def my_ctrlc_handler(signal, frame):
    driver_class.quit()
    raise KeyboardInterrupt

signal.signal(signal.SIGINT, my_ctrlc_handler)
</code></pre>

python unit-testing python-unittest