user197674 user197674 - 5 months ago 29
Python Question

How to stop all tests from inside a test or setUp using unittest?

I'm extending the python 2.7

unittest
framework to do some function testing. One of the things I would like to do is to stop all the tests from running inside of a test, and inside of a
setUpClass()
method. Sometimes if a test fails, the program is so broken it is no longer of any use to keep testing, so I want to stop the tests from running.

I noticed that a TestResult has a
shouldStop
attribute, and a
stop()
method, but I'm not sure how to get access to that inside of a test.

Does anyone have any ideas? Is there a better way?

Answer

Here's another answer I came up with after a while:

First, I added a new exception:

class StopTests(Exception):
"""
Raise this exception in a test to stop the test run.

"""
    pass

then I added a new assert to my child test class:

def assertStopTestsIfFalse(self, statement, reason=''):
    try:
        assert statement            
    except AssertionError:
        result.addFailure(self, sys.exc_info())

and last I overrode the run function to include this right below the testMethod() call:

except StopTests:
    result.addFailure(self, sys.exc_info())
    result.stop()

I like this better since any test now has the ability to stop all the tests, and there is no cpython-specific code.