Wednesday, December 17, 2008

Adding unittest in python with TestSuite

Unittest is an important fundamental for solid software development. At the same time, maintaining proper unittests is also a burden. Managing good unittest is always a challenge.

One of the challenge in python comes when unittest.TestSuite is needed. Generally, each class will split out to each of unittest.TestCase class. But, to teach TestSuite what TestCase to load, we have to pass a list of TestCases, and writing a list manually like this isn't fun.

suite = unittest.TestSuite([
unittest.TestLoader().loadTestsFromTestCase(FirstTest),
unittest.TestLoader().loadTestsFromTestCase(SecondTest),
unittest.TestLoader().loadTestsFromTestCase(ThirdTest),
.....
])

It is error prone. More annoyingly, if I add a new test case, I have to modify suite, also. Using this driver will auto discover test classes in the current module.


moduleList = [ globals()[mod] for mod in globals().keys() if mod.endswith('Test') ]
suite = unittest.TestSuite([
unittest.TestLoader().loadTestsFromTestCase(i) for i in moduleList
])
unittest.TextTestRunner(verbosity=1).run(suite)


This uses naming convention of "SomethingTest" as a test case for class "Something".
Keeping this convention will be a keystroke save.

No comments: