简体   繁体   中英

Stop running tests if setUp raises an exception in Python unittest

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.

Add a failure call in the setUp method.

def setUp(self):
    try:
        somethingThatMightFail()
    except:
        self.fail()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM