473,246 Members | 1,553 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

pyUnit and dynamic test functions

Hi

I am trying to use pyUnit to create a framework for testing functions

I am reading function name, expected output, from a text file.
and in python generating dynamic test functions
something like this
class getUsStatesTest( unittest.TestCase ):

self.setUp = lambda : function_call
self.testReturnVal = lambda : self.assertEqual( fileInput,
function_returnedVals )
self.testLength = lambda : self.assertEqual( len(returnedVals)
, len(inp) )

is it possible to load these dynamic functions via pyUnit, instead of
defining in text form ,
can i use loadfromname etc to load these dynamic test functions.

something like this

unittest.TestSuite(unittest.defaultTestLoader.load TestsFromName(
getUsStatesTest() ))

in this way I can completely automate every function that returns some
output by dynamically generating its
test functions

thanks

Dec 21 '05 #1
5 3515

Please anyone help, is this kind of dynamin thing possible? any
suggestion for creating frameworks for automated testing ,

all comments appreciated

thanks
Sakcee wrote:
Hi

I am trying to use pyUnit to create a framework for testing functions

I am reading function name, expected output, from a text file.
and in python generating dynamic test functions
something like this
class getUsStatesTest( unittest.TestCase ):

self.setUp = lambda : function_call
self.testReturnVal = lambda : self.assertEqual( fileInput,
function_returnedVals )
self.testLength = lambda : self.assertEqual( len(returnedVals)
, len(inp) )

is it possible to load these dynamic functions via pyUnit, instead of
defining in text form ,
can i use loadfromname etc to load these dynamic test functions.

something like this

unittest.TestSuite(unittest.defaultTestLoader.load TestsFromName(
getUsStatesTest() ))

in this way I can completely automate every function that returns some
output by dynamically generating its
test functions

thanks


Dec 21 '05 #2
Sakcee wrote:
Hi

I am trying to use pyUnit to create a framework for testing functions

I am reading function name, expected output, from a text file.
Can you show a sample of what the text file might look like, and what tests you want to
generate from it?
and in python generating dynamic test functions
something like this
class getUsStatesTest( unittest.TestCase ):

self.setUp = lambda : function_call
self.testReturnVal = lambda : self.assertEqual( fileInput,
function_returnedVals )
self.testLength = lambda : self.assertEqual( len(returnedVals)
, len(inp) )


I don't understand the above at all. What do function_call, function_returnedVals,
returnedVals and inp refer to? What is the point of the lambdas and the assignment to
attributes of (undefined) self?

Kent
Dec 21 '05 #3
Thanks for reply, here is the script with trucated datafile

The data file is following ,

--- data file--------
getUSStates~~dict~
{AK: Alaska,
AL: Alabama,
AR: Arkansas,
AZ: Arizona,
CA: California,
CO: Colorado,
....
....
WY: Wyoming }
----data file--------

I want to test function:getUSStates that takes input none and outputs a
dict
of us states.the first line shows function
name~input~output_format~expected_output

Now I have following class and loadTestInfoFromFile function for
loading the values for file and assinging the data to self.outputOfFunc
etc

class getUsStates( unittest.TestCase ):
func_name = None
inputToFunc = None
outputOfFunc = None
outputType = None

setup = None
testUsStates = None
testLength = None

def loadTestInfoFromFile(self):
""" read function name, input to function, output format
and output from file"""

rest = file('data.txt').read()
self.func_name , self.inputToFunc,
self.outputType,outputOfFuncRaw = rest.split("~")

if self.outputType == 'dict':
outputOfFuncRaw = outputOfFuncRaw.split(",")
self.outputOfFunc = {}

for i in range(0,len(outputOfFuncRaw)):
li= ( (outputOfFuncRaw[i].strip()).replace('}','')
).split(':')
self.outputOfFunc[li[0]]=li[1]

def buildTestFunctions( self, returnedVals, func_name, inp ):
self.testReturnVal = lambda : self.assertEqual( inp,
returnedVals )
self.testLength = lambda : self.assertEqual(
len(returnedVals) , len(inp) )
def runFunction():
g = getUsStatesTest()
g.loadTestInfoFromFile()
g.buildFunctions(g.returnedVals,g.func_name,g.outp utOfFunc)
if __name__ == "__main__":
unittest.main(defaultTest="runFunction")
Now in the buildTestFunctions() I want to setup 2 unittest test
function that do assertEqual
so that I have 2 functions which are dynamically created from file ,
now I want to associate
these function with unittest and run them.

the above runs correctly reads the data and make 2 funcitons
testReturnVal and testLength
but then I want to associate those funcitons to unittest. and run unit
test but that part i dont
know how to do.

in this way I can define 100 functions with inputs and expected outputs
in a data file
and this type of script will generate similar assert functions for all
of them on fly
and run them

thanks for any input or any alternate approach to it
Kent Johnson wrote:
Sakcee wrote:
Hi

I am trying to use pyUnit to create a framework for testing functions

I am reading function name, expected output, from a text file.


Can you show a sample of what the text file might look like, and what tests you want to
generate from it?
and in python generating dynamic test functions
something like this
class getUsStatesTest( unittest.TestCase ):

self.setUp = lambda : function_call
self.testReturnVal = lambda : self.assertEqual( fileInput,
function_returnedVals )
self.testLength = lambda : self.assertEqual( len(returnedVals)
, len(inp) )


I don't understand the above at all. What do function_call, function_returnedVals,
returnedVals and inp refer to? What is the point of the lambdas and the assignment to
attributes of (undefined) self?

Kent


Dec 21 '05 #4
> 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
Dec 22 '05 #5
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


Dec 22 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Bill Mill | last post by:
Hello all, I have a misunderstanding about dynamic class methods. I don't expect this behavior: In : class test: ...: def __init__(self, method): ...: self.method = method ...:...
2
by: could ildg | last post by:
I want to know something about unittest these days, and since I'm learning python, I want to touch it through python. But when I found the newest pyunit is even so old, I wonder if it is still...
2
by: chris | last post by:
We have a number of TestCase classes that have multiple test methods. We are interested in removing any of the individual test methods on the fly (dynamically, at runtime, whatever). We...
1
by: Steve Jorgensen | last post by:
I was working with a friend on a project Monday night, and tried to run a pyunit test from Eclipse, and nothing seemed to happen. We finally figured out that the test is doing exactly what it's...
1
by: travislspencer | last post by:
Hey All, I am trying to write a script that runs all of my pyunit tests for me. Ideally, I would like to be able to drop a new module into my project's test subdirectory, and the testing script...
1
by: Nathan Bloomfield | last post by:
Does anyone know if there is any documentation which relates to Access2k + ? or can anyone help adjust the code? I am having trouble converting the DAO references. TITLE :INF: How to...
60
by: Peter Olcott | last post by:
I need to know how to get the solution mentioned below to work. The solution is from gbayles Jan 29 2001, 12:50 pm, link is provided below: >...
1
by: Noah | last post by:
Is there a way for a test case method in a class derived from unittest.TestCase to tell if the harness was started with the verbose option? I would like my test cases to print out a little extra...
0
by: winston.yang | last post by:
Is it possible to use PyUnit to test with multiple threads? I want to send many commands to a database at the same time. The order of execution of the commands is indeterminate, and therefore, so...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.