實際上unittest模塊纔是真正意義上的用於測試的模塊,功能強大的單元測試模塊。python
繼續使用前面的例子:函數
# splitter.py def split(line, types=None, delimiter=None): """Splits a line of test and optionally performs type conversion. For example: >>> split('GOOD 100 490.50') ['GOOD', '100', '490.50'] >>> split('GOOD 100 490.50', [str, int, float]) ['GOOD', 100, 490.50] >>> By default, splitting is perfomed on whitespace, but a different delimiter can be selected with the delimiter keyword argument: >>> split('GOOD, 100, 490.50', delimiter=',') ['GOOOD', '100', '490.50'] >>> """ fields = line.split(delimiter) if types: fields = [ty(val) for ty, val in zip(types, fields)] return fields if __name__ == '__main__': # test myself import doctest doctest.testmod()
編寫測試該函數的腳本:單元測試
# testsplitter.py import splitter import unittest # unit test class TestSplitFunction(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testsimplestring(self): r = splitter.split('GOOD 100 490.50') self.assertEqual(r, ['GOOD', '100', '490.50']) def testypeconvert(self): r = splitter.split('GOOD 100 490.50', [str, int, float]) self.assertEqual(r, ['GOOD', 100, 490.50]) def testdelimiter(self): r = splitter.split('GOOD, 100, 490.50', delimiter=',') self.assertEqual(r, ['GOOD', '100', '490.50']) # Run unit test if __name__ == '__main__': unittest.main()
運行結果:測試
>>> F.. ====================================================================== FAIL: testdelimiter (__main__.TestSplitFunction) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Administrator\Desktop\Python Scripts\testsplitter - 副本.py", line 19, in testdelimiter self.assertEqual(r, ['GOOD', '100', '490.50']) AssertionError: Lists differ: ['GOOD', ' 100', ' 490.50'] != ['GOOD', '100', '490.50'] First differing element 1: 100 100 - ['GOOD', ' 100', ' 490.50'] ? - - + ['GOOD', '100', '490.50'] ---------------------------------------------------------------------- Ran 3 tests in 0.059s FAILED (failures=1) Traceback (most recent call last): File "C:\Users\Administrator\Desktop\Python Scripts\testsplitter - 副本.py", line 23, in <module> unittest.main() File "D:\Python33\lib\unittest\main.py", line 125, in __init__ self.runTests() File "D:\Python33\lib\unittest\main.py", line 267, in runTests sys.exit(not self.result.wasSuccessful()) SystemExit: True
unittest裏面unitest.TestCase實例t最經常使用的方法:spa
t.setUp() - 執行測試前的設置步驟orm
t.tearDown() - 測試完,執行清除操做blog
t.assertEqual(x, y [,msg]) - 執行斷言ip
還有其餘各類斷言。element