Unittest setUp/tearDown for several tests

PythonUnit Testing

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

As of 2.7 (per http://docs.python.org/library/unittest.html#setupclass-and-teardownclass">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 (http://docs.python.org/library/unittest.html#setupmodule-and-teardownmodule">documentation</a>;).

Otherwise your best bet is probably going to be to create your own derived http://docs.python.org/library/unittest.html#unittest.TestSuite">TestSuite</a> 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.

Solution 2 - Python

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

import unittest

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

    @classmethod
    def tearDownClass(cls):
        cls._connection.destroy()

Solution 3 - Python

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

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

    @classmethod
    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)

Solution 4 - Python

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:
            self.setUpClass()
        
        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.

Solution 5 - Python

import unittest

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

    @classmethod
    def tearDownClass(cls):
        cls.shared_data.destroy()

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

For more visit Python unit test document

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionswanView Question on Stackoverflow
Solution 1 - PythonDavid H. ClementsView Answer on Stackoverflow
Solution 2 - PythonCuriousLearnerView Answer on Stackoverflow
Solution 3 - Pythonkadir malakView Answer on Stackoverflow
Solution 4 - Pythonsanderd17View Answer on Stackoverflow
Solution 5 - PythonChandan SharmaView Answer on Stackoverflow