前言
單元測試的重要性就不多說了,可惡的是Python中有太多的單元測試框架和工具,什么unittest, testtools, subunit, coverage, testrepository, nose, mox, mock, fixtures, discover,再加上setuptools, distutils等等這些,先不說如何寫單元測試,光是怎么運行單元測試就有N多種方法,再因為它是測試而非功能,是很多人沒興趣觸及的東西。但是作為一個優(yōu)秀的程序員,不僅要寫好功能代碼,寫好測試代碼一樣的彰顯你的實力。如此多的框架和工具,很容易讓人困惑,困惑的原因是因為并沒有理解它的基本原理,如果一些基本的概念都不清楚,怎么能夠?qū)懗鏊悸非逦臏y試代碼?
今天的主題就是unittest,作為標(biāo)準(zhǔn)python中的一個模塊,是其它框架和工具的基礎(chǔ),參考資料是它的官方文檔:http://docs.python.org/2.7/library/unittest.html和源代碼,文檔已經(jīng)寫的非常好了,本文給出一個實例,很簡單,看一下就明白了。
實例如下
首先給出一個要測試的Python模塊,代碼如下:
待測試的程序:date_service.pyPython
# coding:utf8'''日期常用類 @author: www.crazyant.net''' def get_date_year_month(pm_date): """獲取參數(shù)pm_date對應(yīng)的年份和月份 """ 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
# 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,測試方法應(yīng)該以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,測試方法應(yīng)該以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 mainif __name__ == "__main__": unittest.main()
運行這個test_date_service.py,就會打印出如下信息:
運行測試結(jié)果
..----------------------------------------------------------------------Ran 2 tests in 0.000s OK
這里的每一個點,就代表運行成功了一個測試,最后會給出運行成功了全部的多少個測試以及測試的時間。
新聞熱點
疑難解答
圖片精選