[Tutor] Please help understanding unittest fixtures

Steven D'Aprano steve at pearwood.info
Mon Aug 22 01:19:19 CEST 2011


D. Guandalino wrote:
> Suppose I have this TestCase class.
> 
> class C(TestCase):
>    def setUp():
>       # very time consuming and resources intensive stuffs.
>       pass
> 
>    def test_A(self):
>        pass
>    def test_B(self):
>        pass
>    def test_C(self):
>        pass
> 
> The unittest docs says:
> 
>> Each instance of the TestCase will only be used to run a single test
>> method, so a new fixture is created for each test.
> 
> 
> Does this mean that the setUp() method, which is called to prepare the test
> fixture, get called for test_A, test_B and test_C? 

That's easy enough to find out:

     def setUp(self):
         print("calling setUp")
         ...


See how many times "calling setUp" is printed.


> In this case is there a
> way to force just one setUp() call?


I don't know if this is the best way, but the first way that comes to 
mind is this:


class C(TestCase):
     initialised = False
     def setUp(self):
         if self.initialised:
             return
         # Make sure you save the flag on the class, not the instance!
         self.__class__.initialised = True
         ...


-- 
Steven



More information about the Tutor mailing list