Computing test methods in unittest.TestCase

Jan Decaluwe jan at jandecaluwe.com
Tue Mar 2 12:02:22 EST 2004


I'm working on a unit test for a finite state machine (FSM).  The FSM
behavior is specified in a dictionary called transitionTable. It has a
key per state with a tuple of possible transitions as the corresponding
value.  A transition is defined as a number of input values, a next
state, and a documentation string.

I want to test each possible transition in a separate test method. For
a particular transition, a test method could look as follows:

class FSMTest(unittest.TestCase):
    ....
    def test_START_2(self):
        """Check state START - Switched channels before data started"""
        state, transition = START, transitionTable[START][2]
        sim = Simulation(self.bench(state, transition))
        sim.run()

As the number of transitions can be large, I want to
"compute" the test methods, based on the transitionTable info.
Currently, I have the following:

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?

-- 
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