Is there a function in Python unittest
that is executed at the beginning and end of a test suite, rather than before and after every individual test? I am looking for a way to execute setup and teardown once for all tests in a scenario, rather than for each individual test.
For example, I would like to have something like this:
class TestSequenceFunctions(unittest.TestCase):
def setUpScenario(self):
start() # Launched at the beginning, once
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
def tearDownScenario(self):
end() # Launched at the end, once
Currently, setUp
and tearDown
are run for each test individually, but I want a function that can run only once at the start and end of a group of tests. How can I accomplish this with Python unittest setup?
As of Python 2.7, the unittest framework introduces setUpClass and tearDownClass, which allow you to execute setup and teardown operations for the entire test class, rather than before and after each individual test.
These functions are defined with the @classmethod decorator and are executed only once for the class.
Example:
class TestSequenceFunctions(unittest.TestCase):
@classmethod
def setUpClass(cls):
start() # Launched at the beginning, once for the class
@classmethod
def tearDownClass(cls):
end() # Launched at the end, once for the class
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
If you need to set up and tear down operations for an entire module, rather than just a class, you can use setUpModule and tearDownModule. These functions are executed once for the entire module, making them ideal for cases where the setup and teardown are not class-specific.
Example:
def setUpModule():
start() # Launched at the beginning of the module
def tearDownModule():
end() # Launched at the end of the module
class TestSequenceFunctions(unittest.TestCase):
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)