Python 單元測試

測試

測試用例

對函數 abs(),這個函數的作用就是取絕對值,我們可以編寫以下幾個測試用例:

  1. 輸入正數,比如 1、 1.5、 0.99,期待返回值與輸入相同
  2. 輸入負數,比如 -1、 -1.5、 -0.99, 期待返回值與輸入值相反
  3. 輸入0, 期待返回0;
  4. 輸入非數值類型,比如 None、 []、 {}, 期待拋出 TypeError
    把上面的測試用例,放到測試模塊中,就是一個完整的單元測試。
    單元測試通過說明我們的函數能夠正常工作,要是不過,就說明函數還有bug,
    那麼就得修改,直到單元測試通過。
單元測試得意義
  • 一旦測試通過,以後的修改不會對abs()有影響,如果造成影響,測試就不能通過
  • 單元測試,在重構中,也是經常用到的,有了單元測試,就可以放心的重構

mydict.py 代碼:

class Dict(dict):
    def __init__(self, **kw):
        super().__init__(**kw)


    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

編寫單元測試

我們需要引入 Python 自帶的 unittest 模塊,編寫 mydict_test 如下:

import  unittest

from learn.two.測試.mydict import Dict


class TestDict(unittest.TestCase):
    def test_init(self):
        d = Dict(a = 1, b = '測試')
        self.assertEqual(d.a, 1)
        self.assertEqual(d.b, '測試')
        self.assertTrue(isinstance(d, dict))

    # def test_key(self):        #這部分是測試用例通不過的例子
    #     d = Dict()
    #     d['key'] = 'value'
    #     self.assertSetEqual(d.key, 'value')

    def test_attr(self):
        d = Dict()
        d.key = 'value'
        self.assertTrue('key' in d)
        self.assertEqual(d['key'], 'value')

    def test_keyerror(self):
        d = Dict()
        with self.assertRaises(KeyError):
            value = d['empty']

    def test_attrerror(self):
        d = Dict()
        with self.assertRaises(AttributeError):
            value = d.empty

if __name__ == '__main__':
    unittest.main()

直接運行 mydict_test.py

Testing started at 22:54 ...
E:\py\venv\Scripts\python.exe "D:\JetBrains\PyCharm 2018.1.1\helpers\pycharm\_jb_unittest_runner.py" --target mydict_test.TestDict
Launching unittests with arguments python -m unittest mydict_test.TestDict in E:\pyplace\learn_python3\learn\two\測試


Ran 4 tests in 0.012s

OK

Process finished with exit code 0

以上這就說明單元測試通過了

下面是測試不通過的示範(將註釋的部分放開):

import  unittest

from learn.two.測試.mydict import Dict


class TestDict(unittest.TestCase):
    def test_init(self):
        d = Dict(a = 1, b = '測試')
        self.assertEqual(d.a, 1)
        self.assertEqual(d.b, '測試')
        self.assertTrue(isinstance(d, dict))

    def test_key(self):                  #這部分是測試用例通不過的例子
        d = Dict()
        d['key'] = 'value'
        self.assertSetEqual(d.key, 'value')

    def test_attr(self):
        d = Dict()
        d.key = 'value'
        self.assertTrue('key' in d)
        self.assertEqual(d['key'], 'value')

    def test_keyerror(self):
        d = Dict()
        with self.assertRaises(KeyError):
            value = d['empty']

    def test_attrerror(self):
        d = Dict()
        with self.assertRaises(AttributeError):
            value = d.empty

if __name__ == '__main__':
    unittest.main()

運行 mydict_test.py 結果:

Testing started at 22:58 ...
E:\py\venv\Scripts\python.exe "D:\JetBrains\PyCharm 2018.1.1\helpers\pycharm\_jb_unittest_runner.py" --target mydict_test.TestDict
Launching unittests with arguments python -m unittest mydict_test.TestDict in E:\pyplace\learn_python3\learn\two\測試


Ran 5 tests in 0.027s

FAILED (failures=1)

Failure
Traceback (most recent call last):
  File "D:\python\Python36\lib\unittest\case.py", line 1055, in assertSetEqual
    difference1 = set1.difference(set2)
AttributeError: 'str' object has no attribute 'difference'
  File "D:\python\Python36\lib\unittest\case.py", line 670, in fail
    raise self.failureException(msg)
AssertionError: first argument does not support set difference: 'str' object has no attribute 'difference'

可以看到,控制檯輸入了紅色的錯誤日誌,意味着單元測試不通過

單元測試的寫法

  • 需要編寫一個測試類,從 unittest.TestCase 繼承
  • 以 test 開頭的就是測試方法,不是 test 開頭的不被認爲是測試方法,測試的時候不被執行
  • 每個類測試都需要編寫 test_xxx() 方法,由於 unittest.TestCase 提供了很多內置的條件判斷,我們只需要調用就可以了
常用方法
  • 常用的斷言就是 assertEqual();
 self.assertEqual(abs(-1), 1)    # 斷言返回的結果與1相等
  • 另一種是拋出指定類型的錯誤,比如 d['empty']訪問不到存在的Key時,就拋出 KeyError
with self.assertRaises(KeyError):
    value = d['empty']

如果通過 d.empty 訪問不存在的 key 時,我們期待拋出 AttributeError:

with self.assertRaises(AttributeError):
    value = d.empty

運行單元測試

  • 在編寫好的單元測試中,添加以下兩行代碼,我們就可以運行單元測試
if __name__ == '__main___':
    unittest.main()
  • 這樣,我們就可以把 mydict_test.py 當作正常的 Python 腳本運行:
$ python mydict_test.py

總結

  1. 寫被測試的類
  2. 繼承 unittest.TestCase 寫單元測試類
  3. 通過會顯示綠色 Tests passed,並在輸出日誌中顯示 OK
  4. 不通過顯示紅色 Tests failed,並在輸出日誌中顯示 FAILD

github地址: https://github.com/shenshizhong/learn_python3

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