user197674 user197674 - 9 months ago 59
Python Question

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

I'm extending the python 2.7

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
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
attribute, and a
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?


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.


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

def assertStopTestsIfFalse(self, statement, reason=''):
        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())

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