前言
單元測試的重要性就不多說了,可惡的是Python中有太多的單元測試框架和工具,什么unittest, testtools, subunit, coverage, testrepository, nose, mox, mock, fixtures, discover,再加上setuptools, distutils等等這些,先不說如何寫單元測試,光是怎么運行單元測試就有N多種方法,再因為它是測試而非功能,是很多人沒興趣觸及的東西。但是作為一個優秀的程序員,不僅要寫好功能代碼,寫好測試代碼一樣的彰顯你的實力。如此多的框架和工具,很容易讓人困惑,困惑的原因是因為并沒有理解它的基本原理,如果一些基本的概念都不清楚,怎么能夠寫出思路清晰的測試代碼?
今天的主題就是unittest,作為標準python中的一個模塊,是其它框架和工具的基礎,參考資料是它的官方文檔:http://docs.python.org/2.7/library/unittest.html和源代碼,文檔已經寫的非常好了,本文給出一個實例,很簡單,看一下就明白了。
實例如下
首先給出一個要測試的Python模塊,代碼如下:
待測試的程序:date_service.pyPython
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# coding:utf8 ''' 日期常用類 @author: www.crazyant.net ''' def get_date_year_month(pm_date): """獲取參數pm_date對應的年份和月份 """ if not pm_date: raise Exception( "get_curr_year_month: pm_date can not be None" ) # get date's yyyymmddHHMMSS pattern str_date = str (pm_date).replace( "-" , " ").replace(" ", " ").replace(" : ", " ") year = str_date[: 4 ] month = str_date[ 4 : 6 ] return year, month |
然后就可以編寫測試腳本,代碼如下:
測試程序:test_date_service.pyPython
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
# coding: utf8 """ 測試date_service.py @author: peishuaishuai """ import unittest from service import date_service class DateServiceTest(unittest.TestCase): """ test clean_tb_async_src_acct.py """ def setup( self ): """在這里做資源的初始化 """ pass def tearDown( self ): """在這里做資源的釋放 """ pass def test_get_date_year_month_1( self ): """ 測試方法1,測試方法應該以test_開頭 """ pm_date = "2015-11-25 14:40:52" year, month = date_service.get_date_year_month(pm_date) self .assertEqual(year, "2015" , "year not equal" ) self .assertEqual(month, "11" , "month not equal" ) def test_get_date_year_month_2( self ): """ 測試方法1,測試方法應該以test_開頭 """ pm_date = "20161225144052" year, month = date_service.get_date_year_month(pm_date) self .assertEqual(year, "2016" , "year not equal" ) self .assertEqual(month, "12" , "month not equal" ) # test main if __name__ = = "__main__" : unittest.main() |
運行這個test_date_service.py,就會打印出如下信息:
運行測試結果
1
2
3
4
5
|
.. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Ran 2 tests in 0.000s OK |
這里的每一個點,就代表運行成功了一個測試,最后會給出運行成功了全部的多少個測試以及測試的時間。
之前的很多時間,我一直不知道寫單測有什么用,因為單測只是把寫好的程序運行了一遍,并沒有創建新的邏輯,我心里在疑惑“我已經將程序按照我的想法寫好了,它就會按照我的設計來運行,為什么要用單測重新走一遍呢?”,后來出了一個事情,代碼出了BUG,我調試了好久,才發現問題出在”obja.equals(objb)”,因為obja和objb一個是Long一個是Integer,所以即使數值相同,也不會相等。
從那一刻,我發現單測做的事情,其實就是“驗證程序是否按照我的想法在運行”,這才是它的終極目的,但是,這卻是很關鍵的事情,設計往往沒有錯,但是寫出來的代碼卻經常并不是按照我們所想的去運行的。
單測,就是驗證代碼是不是按照我們想象的在運行,這也是單測這個技術的意義所在。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
原文鏈接:http://www.crazyant.net/1890.html