= Python下的单元测试:PyUnit = 一切用代码说话,最为简单 要测试的方法:hello.py {{{#!python def hello(): return "Hello PyUnit!" }}} 编写测试代码:hellotest.py {{{#!python import unittest from hello import * class HelloTest(unittest.TestCase): def setUp(self): pass def testHello(self): self.assertEquals(hello(),"Hello PyUnit!") def suite(): suite1 = unittest.makeSuite(HelloTest) return unittest.TestSuite((suite1)) if __name__ == '__main__': unittest.main() }}} 运行结果: {{http://static.flickr.com/27/43020421_72d0f38f0c_o.gif}} 当测试案例多了以后,我们希望不要一个一个执行,只要执行一个程序就可以全部执行了,参考了一下PyUnit自带的例子,实现如下 {{{#!python import unittest def suite(): modules_to_test = ('hellotest',) # and so on alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests if __name__ == '__main__': unittest.main(defaultTest='suite') }}} 其中比较有趣的代码是 {{{ for module in map(__import__, modules_to_test): }}} _ _import_ _把字符串作为模块导入,这段代码启发很大,我的PyGList应该可以利用一下:)