pyUnit and dynamic test functions

Sakcee sakcee at gmail.com
Thu Dec 22 15:25:47 EST 2005


Excellent , your example is elegant and runs beautifully

so the idea is to create a testcase which runs a general function
"testRun" (which calls the function defined in file )and loads data
based on type ,

add this testcase to suite and run suite.

thanks , this is exactly what I was looking for.

Fabrizio Milo wrote:
> > thanks for any input or any alternate approach to it
>
> I think that your approach is not fair.
>
> You should create a TestCase for each of your data input, add it to a TestSuite
> and run the test suite.
>
> Here is a stub for loading just a 'dict' type, hoping it is helpful
>
>
> import unittest
> import glob
> from string import split,strip
>
> def getUSStates(*args):
>    #Fake
>    return {'AK:': 'Alaska', 'CA:': 'California', 'AR:': 'Arkansas',
> 'CO:': 'Colorado', 'WY:': 'Wyoming', 'AZ:': 'Arizona', 'AL:':
> 'Alabama'}
>
> class TestStubException( Exception ):
>    '''
>    Test case creation failed.
>    '''
>
> class TestStub( unittest.TestCase ):
>
>    def __init__( self, fname, farg, t_out, out ):
>        unittest.TestCase.__init__(self,'testRun')
>        self.fname = eval(fname,globals())
>        self.input = farg
>        self.fparse = getattr(self,'load_%s' % t_out)
>        self.output = self.fparse( out )
>
>    def load_dict(self,data):
>        assert data[0] is '{', 'Wrong dict format %s' % data
>        assert data[-1] is '}', 'Wrong dict format %s' % data
>        items = data[1:-1].split(',')
>        return dict( map( split, map( strip, items ) ) )
>
>    def testRun(self):
>        self.assertEquals( self.fname(self.input), self.output )
>
>
> def build_tests( filename ):
>    try:
>        fd = open( filename, 'r')
>        tc = TestStub( *fd.read().split("~") )
>        del fd
>        return tc
>    except:
>        import traceback; traceback.print_exc()
>        raise TestStubException( 'Failed creating test case from file
> : %s'%filename )
>
> if __name__== '__main__':
>
>    tc_data = glob.glob('*.txt') # all text files with data
>
>    ts = unittest.TestSuite()
>
>    for tc_file in tc_data:
>        ts.addTest( build_tests( tc_file ) )
>
>    unittest.TextTestRunner().run(ts)
> 
> 
> Fabrizio Milo aka Misto




More information about the Python-list mailing list