Search code examples
pythonpython-unittest

Call a warm up function once before all of the unittests in Python


I want to call a warm-up function once before executing all of the unittest. Consider an example:

import unittest

def addnumbers(a,b,c):
    return a+b+c

class Testaddnumbers(unittest.TestCase):
    
    def setUp(self):
        self.a = 10
        print(f'a set up to {self.a}')
        
    def test1(self):
        self.assertEqual(addnumbers(self.a,2,3), 15)

    def test2(self):
        self.assertEqual(addnumbers(self.a,5,6), 21)
        
if __name__ == '__main__':
    unittest.main()

What I want is to set self.a to 10, and then run two tests (test1 and test2). However, I can see that setUp() function was called 2 times (one for each test).


Solution

  • You can use setUpClass:

    class Testaddnumbers(unittest.TestCase):
        @classmethod
        def setUpClass(cls):
            cls.a = 10
            print(f"a set up to {cls.a}")
    
        def test1(self):
            self.assertEqual(addnumbers(self.a, 2, 3), 15)
    
        def test2(self):
            self.assertEqual(addnumbers(self.a, 5, 6), 21)