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

Question:

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).

Asked By: Mikhail Genkin

||

Answers:

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)
Answered By: kosciej16
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.