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

holger krekel hpk at trillke.net
Tue Apr 5 23:34:11 CEST 2005


Hi Roy, 

On Tue, Apr 05, 2005 at 17:11 -0400, Roy Smith wrote:
> 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().

I think i understand your resoning. 

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

Not quite, instead of writing 

    def __init__(self): 
        ... 

you just write 

    def setup_method(self, method): 
        ... 

and be done with it.  This makes it very explicit in which 
scope your code will be invoked, doesn't it? 

It seems a common use case that people want to customize per test
method invocation (after all, that's what unittest's setUp() does) 
so there is a need for setup_method/teardown_method, anyway. 
But why offer a second way (per __init__ which doesn't know about
the method) to do the same thing in a more restricted way? 

> Or am I just not getting it?

test state management is actually a pretty involved issue. 
py.test tries to provide very explicit hooks where their names
leave as few doubts about when and in which way they will
be invoked.

cheers, 

    holger



More information about the Pytest-dev mailing list