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

Roy Smith roy at panix.com
Tue Apr 5 23:11:56 CEST 2005


holger krekel wrote:

>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
>  
>
OK, but this seems a little strange to me.

Most of the time, all I'm really interested in is that I've got a fresh 
instance of the class being tested.  While it may be true that old 
instances (from previous test methods) may not have been finalized yet, 
that's only going to be of concern when there's something significant to 
finalize (i.e. close a file handle or something like that).  In those 
specific (but rare) cases, I could then use the teardown() hook to clean 
things up, and most of the time I could get away without a teardown().

This way, it seems like I need to do:

def setup_method (self, method):
    self.testInstance = ClassUnderTest()

def teardown_method (self, method):
    del self.testInstance

to get a clean instance for every test method.  This I get for free with 
unittest.  And of course with this, everyplace I'd normally use self.foo 
in my test methods, I'd now have to use self.testInstance.foo.

It seems like things would be a lot simplier if a new instance was 
created for each test method call.  You could still use the 
teardown_method for force finalizations when needed, but most of the 
time you wouldn't have to bother.

Or am I just not getting it?




More information about the Pytest-dev mailing list