Run code before/after#

In unittest library, there is an option to execute some code before/after executing all the tests described in a class, and before/after each test in the class test separately. So this page is to discover details of how to use this feature.

Each test method (setUp/tearDown)#

Sometimes it’s useful to run some code before or after each test. To do this, you can add setUp, tearDown methods to your inheritance of the TestCase class. setUp is executed before each test described in your program, tearDown after.

This subsection just shows how it works. Here is a test where each method just shows that it has been run in the console. And there are setUp and tearDown which just print a message.

import unittest

class UpDownTests(unittest.TestCase):

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

    def tearDown(self):
        print("tearDown run", end = "\n\n\n")

    def test_1(self):
        print("test_1 run")

    def test_2(self):
        print("test_2 run")

ans = unittest.main(argv=[''], verbosity=2, exit=False)
del UpDownTests
test_1 (__main__.UpDownTests) ... ok
test_2 (__main__.UpDownTests) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK
setUp run
test_1 run
tearDown run


setUp run
test_2 run
tearDown run

Whole test class (setUpClass/tearDownClass)#

There is an option to run some code before/after executing all test methods in the inheritage of unittest.TestCase. You need to use the setUpClass/tearDownClass methods for this. Note You need to wrap it with a classmethod decorator. The following cell only shows how it can be implemented:

import unittest

class UpDownTests(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        print("setUpClass run")

    @classmethod
    def tearDownClass(self):
        print("tearDownClass run", end = "\n\n\n")

    def test_1(self):
        print("test_1 run")

    def test_2(self):
        print("test_2 run")

ans = unittest.main(argv=[''], verbosity=2, exit=False)
del UpDownTests
test_1 (__main__.UpDownTests) ... ok
test_2 (__main__.UpDownTests) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK
setUpClass run
test_1 run
test_2 run
tearDownClass run

There is print from setUpClass before each tests and print from tearDownClass after each test.