pyUnit and dynamic test functions

Fabrizio Milo mistobaan at
Thu Dec 22 12:39:59 CET 2005

> 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):
   return {'AK:': 'Alaska', 'CA:': 'California', 'AR:': 'Arkansas',
'CO:': 'Colorado', 'WY:': 'Wyoming', 'AZ:': 'Arizona', 'AL:':

class TestStubException( Exception ):
   Test case creation failed.

class TestStub( unittest.TestCase ):

   def __init__( self, fname, farg, t_out, out ):
       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 ):
       fd = open( filename, 'r')
       tc = TestStub( *"~") )
       del fd
       return tc
       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 ) )


Fabrizio Milo aka Misto

More information about the Python-list mailing list