1. Python下的单元测试:PyUnit

一切用代码说话,最为简单

要测试的方法:hello.py

   1 def hello():
   2     return "Hello PyUnit!"

编写测试代码:hellotest.py

   1 import unittest
   2 from hello import *
   3 
   4 class HelloTest(unittest.TestCase):
   5     def setUp(self):
   6         pass
   7     def testHello(self):
   8         self.assertEquals(hello(),"Hello PyUnit!")
   9 
  10 def suite():
  11     suite1 = unittest.makeSuite(HelloTest)
  12     return unittest.TestSuite((suite1))
  13 
  14 
  15 if __name__ == '__main__':
  16     unittest.main()

运行结果:

43020421_72d0f38f0c_o

当测试案例多了以后,我们希望不要一个一个执行,只要执行一个程序就可以全部执行了,参考了一下PyUnit自带的例子,实现如下

   1 import unittest
   2 
   3 def suite():
   4     modules_to_test = ('hellotest',) # and so on
   5     alltests = unittest.TestSuite()
   6     for module in map(__import__, modules_to_test):
   7         alltests.addTest(unittest.findTestCases(module))
   8     return alltests
   9 
  10 if __name__ == '__main__':
  11     unittest.main(defaultTest='suite')

其中比较有趣的代码是

for module in map(__import__, modules_to_test):

_ _import_ _把字符串作为模块导入,这段代码启发很大,我的PyGList应该可以利用一下:)