Computing test methods in unittest.TestCase
James Kew
james.kew at btinternet.com
Tue Mar 2 13:03:23 EST 2004
"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"))
>>> t = testClass()
>>> t.test1()
test: param=1
>>> t.testHello()
test: param=Hello
James
More information about the Python-list
mailing list