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

holger krekel hpk at trillke.net
Wed Apr 6 00:09:26 MEST 2005


On Tue, Apr 05, 2005 at 16:39 -0500, Ian Bicking wrote:
> holger krekel wrote:
> >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? 
> 
> Where this becomes interesting, is when you do:
> 
> class Test:
> 
>     def __init__(self, input, output):
>         self.input, self.output = input, output
> ...
> 
> def test_Test():
>     for fn in os.listdir('data/'):
>         if fn.startswith('input'):
>             yield Test, fn, fn.replace('input', 'output')
> 
> Can you do that now?  I think Test would be automatically instantiated 
> and throw an error...?

There is no "magic instantiation" for generative tests.  (Sometimes 
i think the existence of "py.magic" makes people afraid that magic is
happening at all sorts of places where in fact it wants to indicate 
that magic is rather localized :-)  

Effectively your above example would just lead to testing the
successful invocation of the __init__ constructor.  FWIW, a
more full blown example of what you might want to do is: 

    def test_Test(): 
        datadir = py.magic.autopath.dirpath('data')  # [1]
        for inputfn in datadir.listdir('input*'): 
            newbasename = inputfn.basename.replace('input', 'output') 
            outputfn = inputfn.new(basename=newbasename) 
            yield Test(inputfn, outputfn) 
            # this assumes you want to run __call__ for the actual test 

Indeed, you may not need a class at all but can just yield a test
function for each input/output pair: 

            yield check_input_output, intputfn, outputfn 

cheers, 

    holger


[1] there it is again, the dreaded but convenient py.magic namespace: 
    py.magic.autopath() looks at your module's __file__ and gives 
    you a path object so that path.dirpath('data') gets you 
    to the 'data' directory accompanying your test file, irrespective
    of the current working directory. 


More information about the py-dev mailing list