class MyUnitTest(unittest.TestCase): @classmethod def setUpClass(cls): do_something_expensive_for_all_sets_of_tests() class MyFirstSetOfTests(MyUnitTest): @classmethod def setUpClass(cls): super(MyFirstSetOfTests, cls).setUpClass() do_something_expensive_for_just_these_first_tests()
Here is what the above code is Doing:
1. The MyUnitTest class defines a setUpClass method that does something expensive.
2. The MyFirstSetOfTests class inherits from MyUnitTest and defines its own setUpClass method.
3. The MyFirstSetOfTests class’s setUpClass method calls the MyUnitTest class’s setUpClass method.
4. The MyFirstSetOfTests class’s setUpClass method also does something expensive.
The result is that the expensive operation is performed twice, once for the MyUnitTest class and once for the MyFirstSetOfTests class.
To avoid this, you can use the @unittest.skipUnless decorator to skip the MyUnitTest class’s setUpClass method.
@unittest.skipUnless(sys.platform.startswith(“win”), “requires Windows”)
The above code skips the WindowsTests class’s setUpClass method unless the sys.platform variable starts with “win”.