Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop running tests if setUp raises an exception in Python unittest

Tags:

python

testing

I have this test class:

class mytest(unittest.TestCase):
    def setUp(self):
        os.mkdir(...)
        ...

    def tearDown(self):
        shutil.rmtree(...)

    def test_one(self):
        ...

    def test_two(self):
        ...

If something fails after mkdir has ran when running setUp of test_one, it will still try to run setUp of test_two. At this point I'll get an error on mkdir because rmtree didn't run.

Is there any way to tell Python unittest to stop running the current test if setUp fails? I'm not looking to stop on a regular test failure.

like image 438
Idan K Avatar asked Oct 15 '11 17:10

Idan K


People also ask

How do you stop a test in Python?

Once you are in a TestCase , the stop() method for the TestResult is not used when iterating through the tests. Somewhat related to your question, if you are using python 2.7, you can use the -f/--failfast flag when calling your test with python -m unittest . This will stop the test at the first failure.

How do you handle exceptions in unit test Python?

assertRaises(exception, callable, *args, **kwds) Test that an exception (first argument) is raised when a function is called with any positional or keyword arguments. The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised.

How do I skip a test in unittest?

Alternate syntax for skipping test is using instance method skipTest() inside the test function.

Which item in Python will stop unit test abruptly?

An exception object is created when a Python script raises an exception. If the script explicitly doesn't handle the exception, the program will be forced to terminate abruptly.


1 Answers

Add a failure call in the setUp method.

def setUp(self):
    try:
        somethingThatMightFail()
    except:
        self.fail()
like image 99
JiminyCricket Avatar answered Sep 19 '22 13:09

JiminyCricket