473,698 Members | 2,158 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Computing test methods in unittest.TestCa se

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(unittes t.TestCase):
....
def test_START_2(se lf):
"""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(unittes t.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_d oc = "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

Jul 18 '05 #1
3 1981

"Jan Decaluwe" <ja*@jandecaluw e.com> wrote in message
news:40******** ******@jandecal uwe.com...
class FSMTest(unittes t.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_d oc = "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(testCla ss, "test1", makeTest(1))
setattr(testCla ss, "testHello" , makeTest("Hello "))
t = testClass()
t.test1() test: param=1 t.testHello()

test: param=Hello

James
Jul 18 '05 #2
Jan Decaluwe wrote:
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
[...]
As the number of transitions can be large, I want to
"compute" the test methods, based on the transitionTable info.
[...]
Anyone with better ideas?


Use a test suite instead and turn each FSMTest.testXXX () method into a
TestCase instance:

class TransitionTest( unittest.TestCa se):
def __init__(self, state, transition):
unittest.TestCa se.__init__(sel f)
self.state = state
self.transition = transition

def bench(self, state, transition):
pass

def runTest(self):
Simulation(self .bench(self.sta te, self.transition )).run()

def __str__(self):
return "Check state %s - %s" % (self.state, getDoc(self.tra nsition))

def makeSuite():
suite = unittest.TestSu ite()
for st, trs in transitionTable .iteritems():
for tr in trs:
suite.addTest(T ransitionTest(s t, tr))
return suite

if __name__ == "__main__":
unittest.main(d efaultTest="mak eSuite")

Peter

Jul 18 '05 #3
James Kew wrote:
"Jan Decaluwe" <ja*@jandecaluw e.com> wrote in message
news:40******** ******@jandecal uwe.com...
class FSMTest(unittes t.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_d oc = "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(testCla ss, "test1", makeTest(1))
setattr(testCla ss, "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
Jul 18 '05 #4

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

Similar topics

0
2051
by: Remy Blank | last post by:
Ok, here we go. I added the possibility for tests using the unittest.py framework to be skipped. Basically, I added two methods to TestCase: TestCase.skip(msg): skips unconditionally TestCase.skipIf(expr, msg): skips if expr is true These can be called either in setUp() or in the test methods. I also added reporting of skipped tests to TestResult, _TextTestResult and
41
10273
by: Roy Smith | last post by:
I've used the standard unittest (pyunit) module on a few projects in the past and have always thought it basicly worked fine but was just a little too complicated for what it did. I'm starting a new project now and I'm thinking of trying py.test (http://codespeak.net/py/current/doc/test.html). It looks pretty cool from the docs. Is there anybody out there who has used both packages and can give a comparative review?
2
2112
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 currently have an "isSupported" method in the TestCase classes that return a bool by which the greater test harness decides whether to run the enclosed test methods or not. We would like to have per-test-method granularity, however, for essentially...
4
1470
by: ajikoe | last post by:
Hello I found something strange in my unittest : This code is ok (will report error ): class MyTest1(unittest.TestCase): def runTest(self): self.assertEqual(2,3) pass
6
2693
by: Ben Finney | last post by:
Howdy all, Summary: I'm looking for idioms in unit tests for factoring out repetitive iteration over test data. I explain my current practice, and why it's unsatisfactory. When following test-driven development, writing tests and then coding to satisfy them, I'll start with some of the simple tests for a class.
5
3550
by: Sakcee | last post by:
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 ):
3
1506
by: Bruce Cropley | last post by:
Hi all I'm trying to generate test methods in a unittest TestCase subclass, using decorators. I'd like to be able to say: class MyTestCase(unittest.TestCase): @genTests(, , ) def something(self, side, price, someFlag): # etc...
2
3851
by: Podi | last post by:
Hi, Newbie question about unittest. I am having trouble passing a variable to a test class object. MyCase class will potentially have many test functions. Any help would be much appreciated. Thanks,
6
5686
by: Vyacheslav Maslov | last post by:
Hi all! I have many many many python unit test, which are used for testing some remote web service. The most important issue here is logging of test execution process and result. I strongly need following: 1. start/end timestamp for each test case (most important) 2. immediate report about exceptions (stacktrace) 3. it will be nice to use logging module for output
0
8683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8871
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6528
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5862
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4371
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.