Unittest setUp/tearDown for several tests


Is there a function that is fired at the beginning/end of a scenario of tests? The functions setUp and tearDown are fired before/after every single test.

I typically would like to have 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

For now, these setUp and tearDown are unit tests and spread in all my scenarios (containing many tests), one is the first test, the other is the last test.

Asked By: swan



As of 2.7 (per the documentation) you get setUpClass and tearDownClass which execute before and after the tests in a given class are run, respectively. Alternatively, if you have a group of them in one file, you can use setUpModule and tearDownModule (documentation).

Otherwise your best bet is probably going to be to create your own derived TestSuite and override run(). All other calls would be handled by the parent, and run would call your setup and teardown code around a call up to the parent’s run method.

Answered By: David H. Clements

I have the same scenario, for me setUpClass and tearDownClass methods works perfectly

import unittest

class Test(unittest.TestCase):
    def setUpClass(cls):
        cls._connection = createExpensiveConnectionObject()

    def tearDownClass(cls):
Answered By: CuriousLearner

For python 2.5, and when working with pydev, it’s a bit hard. It appears that pydev doesn’t use the test suite, but finds all individual test cases and runs them all separately.

My solution for this was using a class variable like this:

class TestCase(unittest.TestCase):
    runCount = 0

    def setUpClass(self):
        pass # overridden in actual testcases

    def run(self, result=None):
        if type(self).runCount == 0:

        super(TestCase, self).run(result)
        type(self).runCount += 1

With this trick, when you inherit from this TestCase (instead of from the original unittest.TestCase), you’ll also inherit the runCount of 0. Then in the run method, the runCount of the child testcase is checked and incremented. This leaves the runCount variable for this class at 0.

This means the setUpClass will only be ran once per class and not once per instance.

I don’t have a tearDownClass method yet, but I guess something could be made with using that counter.

Answered By: sanderd17

Here is an example: 3 test methods access a shared resource, which is created once, not per test.

import unittest
import random

class TestSimulateLogistics(unittest.TestCase):

    shared_resource = None

    def setUpClass(cls):
        cls.shared_resource = random.randint(1, 100)

    def tearDownClass(cls):
        cls.shared_resource = None

    def test_1(self):
        print('test 1:', self.shared_resource)

    def test_2(self):
        print('test 2:', self.shared_resource)

    def test_3(self):
        print('test 3:', self.shared_resource)

Answered By: kadir malak
import unittest

class Test(unittest.TestCase):
    def setUpClass(cls):
        cls.shared_data = "dddd"

    def tearDownClass(cls):

    def test_one(self):
        print("Test one")
    def test_two(self):
        print("Test 2")

For more visit Python
unit test document

Answered By: Chandan Sharma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.