三言兩語聊Python模塊–單元測試模塊unittest

實際上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]) - 執行斷言

還有其他各種斷言。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章