Computing test methods in unittest.TestCase
Jan Decaluwe
jan at jandecaluwe.com
Mon Mar 15 18:00:26 EST 2004
James Kew wrote:
> "Jan Decaluwe" <jan at jandecaluwe.com> wrote in message
> news:4044BE1E.7000408 at jandecaluwe.com...
>
>>>class FSMTest(unittest.TestCase):
>>
>> ....
>> for st, trs in transitionTable.items():
>> for i, tr in enumerate(trs):
>> def _tmpfunc(self, st=st, tr=tr):
>> sim = Simulation(self.bench(st, tr))
>> sim.run()
>> _tmpfunc.func_doc = "Check state %s - %s" % (st, getDoc(tr))
>> exec "test_%s_%s = _tmpfunc" % (st, i)
>>
>>This works, but uses some "ugly" tricks:
>>
>>* default arguments to pass context info. As the code is executed in
>> class context, not function context, I cannot use free variables.
>>* The use of 'exec'. unittest looks for methods with name prefix
>> 'test_' in the class namespace, and I didn't find another way
>> to achieve that.
>>
>>Anyone with better ideas?
>
>
> Define the test methods after defining the class, and inject them into the
> class with setattr:
>
> class testClass:
> pass
>
> def makeTest(param):
> def test(self):
> print "test: param=%s" % param
> return test
>
> setattr(testClass, "test1", makeTest(1))
> setattr(testClass, "testHello", makeTest("Hello"))
Thanks - this is a nice way to get rid of the exec. However, I found
out that I still need the default arguments in my case. Free variables
do behave differently as shown in the following example:
def funcs():
flist = []
glist = []
for i in range(3):
def f():
print "f: " + str(i)
def g(i=i):
print "g: " + str(i)
flist.append(f)
glist.append(g)
for f, g in zip(flist, glist):
f(); g()
>>> funcs()
f: 2
g: 0
f: 2
g: 1
f: 2
g: 2
When generating such functions (with free variables) in loops,
it's apparently very easy to get it wrong ...
Regards, Jan
--
Jan Decaluwe - Resources bvba - http://jandecaluwe.com
Losbergenlaan 16, B-3010 Leuven, Belgium
Python is fun, and now you can design hardware with it:
http://jandecaluwe.com/Tools/MyHDL/Overview.html
More information about the Python-list
mailing list