[py-dev] Does each test method get called with a new instance?

holger krekel hpk at trillke.net
Tue Apr 5 15:19:33 CEST 2005


Hi Roy, 

On Tue, Apr 05, 2005 at 09:15 -0400, Roy Smith wrote:
> Is the control flow example at  
> http://codespeak.net/py/current/doc/test.html#example-for-managing- 
> state-at-module-class-and-method-level correct?  It implies that  
> instance.test_42() and instance.test_23() both get called with the same  
> instance.  I would have thought a new instance would be created for  
> each call.
> 
> Hmmmm, a little experimenting shows that it is indeed correct.  This  
> seems counter-intuitive.  I've always considered it a basic maxim of  
> unit tests that each test ran in a pristine environment.  What's the  
> logic here?

If you want to customize a test class instance per test method invocation
you should use 

    def setup_method(self, meth): ... 
    def teardown_method(self, meth): ... 

to do that.  Relying on __init__() and __del__() for such state
management is not sensible because Python - the language - does 
not guarantee timely finalization/cleanup via __del__().  It is 
thus more sensible to advertise setup_method/teardown_method
as the way to reliably handle test state management. 

HTH, 

    holger



More information about the Pytest-dev mailing list