首页 > 编程 > Python > 正文

利用Python中unittest实现简单的单元测试实例详解

2020-02-23 04:14:18
字体:
来源:转载
供稿:网友

前言

单元测试的重要性就不多说了,可恶的是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

# 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

# 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 mainif __name__ == "__main__": unittest.main()

运行这个test_date_service.py,就会打印出如下信息:

运行测试结果

..----------------------------------------------------------------------Ran 2 tests in 0.000s OK

这里的每一个点,就代表运行成功了一个测试,最后会给出运行成功了全部的多少个测试以及测试的时间。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表