Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip a test method if another previous test method failed with unittest in Python?

I have one unittest test case with two different methods. I'd like that my second method to be skipped, if the first one fails.

I am using the decorator @unittest.skipIf but I cannot find the proper condition for it.

class myTest(unittest.TestCase):
    def test_1(self):
        self.assertEqual(1,2)

    @unittest.skipIf(????,'test_2 was skipped because test_1 failed')
    def test_2(self):
        pass

 if __name__ == '__main__':
    unittest.main()
like image 728
Pablo Romero Avatar asked Oct 20 '25 13:10

Pablo Romero


1 Answers

skipIf is evaluated at class declaration time, which is too early to know the result of test_1. Unit tests are meant to be independent, and you're implying that these tests aren't independent, so one option would be to put the test 2 logic within test 1; it won't execute if the earlier part of the test fails:

class myTest(unittest.TestCase):
    def test_1(self):
        self.assertEqual(1,2)
        # move test 2 logic here
        self.assertTrue(something)

Alternatively, relying on the fact that tests are sorted alphabetically, you could use the failfast option, which will cause the test runner to stop as soon as the first test fails. Obviously this approach will also skip any subsequent tests after test_2 as well.

if __name__ == '__main__':
    unittest.main(failfast=True)
like image 158
Brian from QuantRocket Avatar answered Oct 23 '25 19:10

Brian from QuantRocket



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!