Is there any way to run setUp and tearDown for each python subTest?

2.2k views Asked by At

My code:

import unittest


class MyTestCase(unittest.TestCase):

    def setUp(self):
        print("setUp")

    def tearDown(self):
        print("tearDown")

    def test_something(self):
        for i in range(4):
            with self.subTest():
                self.assertEqual(True, True)  # add assertion here


if __name__ == '__main__':
    unittest.main()

Run the test test_something in it, and we get the result:

test_something (tests.ui.test_example.MyTestCase) ... setUp
tearDown
ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

You can see I use self.subTest() to parameterize my test, which is convenient. The problem is, I want python unittest to call setUp and tearDown for each subTest, i.e. they should be called 4 times each. However, they are actually only called once each (You can verify that from the test output above). Is there any way to achieve it?

1

There are 1 answers

0
Brian On

This is not the usecase of subTest() method. The Setup() and TearDown() methods are executed before each test case, since you only have one test case, theses two methods will only be called once. See : https://docs.python.org/3/library/unittest.html#test-cases

If your subTests need a set-up that means there are test cases. If you don't want to have many test cases, try to call the SetUp() methods manually inside your loop.