实际上unittest模块才是真正意义上的用于测试的模块,功能强大的单元测试模块。
继续使用前面的例子:
# 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最常用的方法:
t.setUp() - 执行测试前的设置步骤
t.tearDown() - 测试完,执行清除操作
t.assertEqual(x, y [,msg]) - 执行断言
还有其他各种断言。