Python unittest单元测试框架总结


Posted in Python onSeptember 08, 2018

什么是单元测试

单元测试是用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作。

比如对于函数abs(),我们可以编写的测试用例为:

(1)输入正数,比如1、1.2、0.99,期待返回值与输入相同

(2)输入复数,比如-1、-1.2、-0.99,期待返回值与输入相反

(3)输入0,期待返回0

(4)输入非数值类型,比如None、[]、{}、期待抛出TypeError

把上面这些测试用例放到一个测试模块里,就是一个完整的单元测试

 unittest工作原理

unittest中最核心的四部分是:TestCase,TestSuite,TestRunner,TestFixture

(1)一个TestCase的实例就是一个测试用例。测试用例就是指一个完整的测试流程,包括测试前准备环境的搭建(setUp),执行测试代码(run),以及测试后环境的还原(tearDown)。元测试(unit test)的本质也就在这里,一个测试用例是一个完整的测试单元,通过运行这个测试单元,可以对某一个问题进行验证。

(2)而多个测试用例集合在一起,就是TestSuite,而且TestSuite也可以嵌套TestSuite。

(3)TestLoader是用来加载TestCase到TestSuite中的。

(4)TextTestRunner是来执行测试用例的,其中的run(test)会执行TestSuite/TestCase中的run(result)方法

(5)测试的结果会保存到TextTestResult实例中,包括运行了多少测试用例,成功了多少,失败了多少等信息。

 综上,整个流程就是首先要写好TestCase,然后由TestLoader加载TestCase到TestSuite,然后由TextTestRunner来运行TestSuite,运行的结果保存在TextTestResult中,整个过程集成在unittest.main模块中。

python unittest简介

unittest是python下的单元测试框架,是java JUnit的python版本, 跟其它语言下的单元测试框架风格类似,unittest支持自动化测试、共享setup和teardown代码、测试聚合成集、独立于报告框架。unittest模块提供了一个丰富的工具集用于构建和执行用例,先看一个入门的例子:

import unittest

class TestStringMethods(unittest.TestCase):

def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO') 
  def test_isupper(self):
    self.assertTrue('FOO'.isupper())
    self.assertFalse('Foo'.isupper())

  def test_split(self):
    s = 'hello world'
    self.assertEqual(s.split(), ['hello', 'world'])
    # check that s.split fails when the separator is not a string
    with self.assertRaises(TypeError):
      s.split(2)

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

可以通过继承unittest.TestCase创建一个测试用例TestStringMethods,在这个用例中定义了测试函数,这些函数名字都以”test”开头,在执行测试用例TestStringMethods时,这些方法会被自动调用。每个测试函数中都调用了assertTrue()和assertFalse()方法检查预期结果,或者使用assertRaises()确认产生了一个特定异常。现在来看一下这段代码的运行结果:

...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

有时我们需要在用例执行前后做一些工作如初始化和清理,这就需要实现setUp()和tearDown()方法

import unittest

class WidgetTestCase(unittest.TestCase):
  def setUp(self):
    print("setUp()")

  def test_1(self):
    print("test_1")

  def test_2(self):
    print("test_2")

  def tearDown(self):
    print("tearDown()")

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

运行结果:

setUp()
.test_1
tearDown()
setUp()
.test_2
tearDown()
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

注:如果setUp()执行成功(没有异常发生),那么无论测试方法是否通过,tearDown()都会被执行
根据所测的特性测试用例被组合在一起,通过调用unittest.main(),unittest测试框架会自动收集所有模块的测试用例然后执行。

import unittest

class WidgetTestCase(unittest.TestCase):
  def setUp(self):
    print("WidgetTestCase setUp()")

  def test_Widget(self):
    print("test_Widget")

  def tearDown(self):
    print("WidgetTestCase tearDown()")

class FuncTestCase(unittest.TestCase):
  def setUp(self):
    print("FuncTestCase setUp()")

  def test_func(self):
    print("test_func")

  def tearDown(self):
    print("FuncTestCase tearDown()")


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

 运行结果:

FuncTestCase setUp()                                                 
test_func                                                            
FuncTestCase tearDown()                                              
.WidgetTestCase setUp()                                              
test_Widget                                                          
WidgetTestCase tearDown()                                            
.                                                                    
----------------------------------------------------------------------
Ran 2 tests in 0.003s                                                

OK  

如果想构建自已的用例集,只需要这么做:

import unittest

class WidgetTestCase(unittest.TestCase):
  def setUp(self):
    print("WidgetTestCase setUp()")

  def test_Widget(self):
    print("test_Widget")

  def tearDown(self):
    print("WidgetTestCase tearDown()")

class FuncTestCase(unittest.TestCase):
  def setUp(self):
    print("FuncTestCase setUp()")

  def test_func(self):
    print("test_func")

  def tearDown(self):
    print("FuncTestCase tearDown()")

def suite():
  suite = unittest.TestSuite()
  suite.addTest(FuncTestCase('test_func'))
  return suite

if __name__ == '__main__':
  runner=unittest.TextTestRunner()
  runner.run(suite())

运行结果:

FuncTestCase setUp()
test_func
FuncTestCase tearDown()
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

unittest中相关类和函数

在unittest中 TestCase类的实例代表逻辑测试单元,这个类通常被当作测试类的基类使用, TestCase类实现了许多测试相关的接口,主要是以下三组方法:

1.执行测试用例的方法

setUp()
#在每个测试方法之前执行,这个方法引发的异常会被认为是错误,而非测试失败,默认实现是不做任何事
tearDown()
#在每个测试方法之后执行,即使测试方法抛出异常tearDown()方法仍会执行,并且只有setUp()成功执行时tearDown()才会执行,
#同样这个方法引发的异常会被认为是错误,而非测试失败。默认实现是不做任何事
setUpClass()
#在一个测试类的所有测试方法执行之前执行,相当于google test中的SetUpTestCase()方法,setUpClass()必须被装饰成一个classmethod()
@classmethod
def setUpClass(cls):
  ...
tearDownClass()
#在一个测试类的所有测试方法执行之后执行,相当于google test中的TearDownTestCase()方法,tearDownClass()必须被装饰成一个classmethod()
@classmethod
def tearDownClass(cls):
  ...

2.检查条件和报告错误的方法

Method Checks that New in
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a, b) a is b 3.1
assertIsNot(a, b) a is not b 3.1
assertIsNone(x) x is None 3.1
assertIsNotNone(x) x is not None 3.1
assertIn(a, b) a in b 3.1
assertNotIn(a, b) a not in b 3.1
assertIsInstance(a, b) isinstance(a, b) 3.2
assertNotIsInstance(a, b) not isinstance(a, b) 3.2
assertRaises(exc, fun, *args, **kwds) fun(*args, **kwds) raises exc
assertRaisesRegex(exc, r, fun, *args, **kwds) fun(*args, **kwds) raises exc and the message matches regex r 3.1
assertWarns(warn, fun, *args, **kwds) fun(*args, **kwds) raises warn 3.2
assertNotAlmostEqual(a, b) round(a-b, 7) != 0
assertGreater(a, b) a > b 3.1
assertGreaterEqual(a, b) a >= b 3.1
assertLess(a, b) a 3.1
assertLessEqual(a, b) a 3.1
assertRegex(s, r) r.search(s) 3.1
assertNotRegex(s, r) not r.search(s) 3.2
assertCountEqual(a, b) a and b have the same elements in the same number, regardless of their order 3.2
assertWarnsRegex(warn, r, fun, *args, **kwds) fun(*args, **kwds) raises warn and the message matches regex r 3.2
assertLogs(logger, level) The with block logs on logger with minimum level 3.4
assertMultiLineEqual(a, b) strings 3.1
assertSequenceEqual(a, b) sequences 3.1
assertListEqual(a, b) lists 3.1
assertTupleEqual(a, b) tuples 3.1
assertSetEqual(a, b) sets or frozensets 3.1
assertDictEqual(a, b) dicts 3.1
Python 相关文章推荐
python中argparse模块用法实例详解
Jun 03 Python
python实现简单socket通信的方法
Apr 19 Python
基于numpy.random.randn()与rand()的区别详解
Apr 17 Python
Python判断两个文件是否相同与两个文本进行相同项筛选的方法
Mar 01 Python
解决django中ModelForm多表单组合的问题
Jul 18 Python
Python解决pip install时出现的Could not fetch URL问题
Aug 01 Python
pandas的to_datetime时间转换使用及学习心得
Aug 11 Python
python实现简易版学生成绩管理系统
Jun 22 Python
Python实现GIF图倒放
Jul 16 Python
Python中的套接字编程是什么?
Jun 21 Python
Python函数式编程中itertools模块详解
Sep 15 Python
Pandas-DataFrame知识点汇总
Mar 16 Python
tensorflow实现加载mnist数据集
Sep 08 #Python
使用tensorflow实现线性回归
Sep 08 #Python
Python  unittest单元测试框架的使用
Sep 08 #Python
tensorflow实现逻辑回归模型
Sep 08 #Python
Django实现表单验证
Sep 08 #Python
python实现排序算法解析
Sep 08 #Python
TensorFlow实现Logistic回归
Sep 07 #Python
You might like
PHP中创建并处理图象
2006/10/09 PHP
php include类文件超时问题处理
2015/02/06 PHP
php使用cookie实现记住登录状态
2015/04/27 PHP
php实现URL加密解密的方法
2016/11/17 PHP
Laravel框架控制器,视图及模型操作图文详解
2019/12/04 PHP
CheckBox 如何实现全选?
2006/06/23 Javascript
Prototype 学习 Prototype对象
2009/07/12 Javascript
可编辑下拉框的2种实现方式
2014/06/13 Javascript
jQuery功能函数详解
2015/02/01 Javascript
探究Javascript模板引擎mustache.js使用方法
2016/01/26 Javascript
javascript 广告移动特效的实现代码
2016/06/25 Javascript
jquery之别踩白块游戏的简单实现
2016/07/25 Javascript
Vue.2.0.5过渡效果使用技巧
2017/03/16 Javascript
原生JS实现图片无缝滚动方法(附带封装的运动框架)
2017/10/01 Javascript
Node.js Buffer用法解读
2018/05/18 Javascript
jQuery实现获取选中复选框的值实例详解
2018/06/28 jQuery
基于Vue+elementUI实现动态表单的校验功能(根据条件动态切换校验格式)
2019/04/04 Javascript
深入分析JavaScript 事件循环(Event Loop)
2020/06/19 Javascript
[09:40]DAC2018 4.5 SOLO赛 MidOne vs Miracle
2018/04/06 DOTA
Python中常用操作字符串的函数与方法总结
2016/02/04 Python
python实现简单登陆系统
2018/10/18 Python
在Python中,不用while和for循环遍历列表的实例
2019/02/20 Python
python在回调函数中获取返回值的方法
2019/02/22 Python
python动态进度条的实现代码
2019/07/03 Python
Python List列表对象内置方法实例详解
2019/10/22 Python
pycharm运行scrapy过程图解
2019/11/22 Python
Python判断字符串是否为空和null方法实例
2020/04/26 Python
CSS3中的opacity属性使用教程
2015/08/19 HTML / CSS
小橄榄树:Le Petit Olivier
2018/04/23 全球购物
质检部部长职责
2013/12/16 职场文书
优秀大学生的自我评价
2014/01/16 职场文书
消防安全汇报材料
2014/02/08 职场文书
任命书标准格式
2015/03/02 职场文书
2015年幼儿教师个人工作总结
2015/05/20 职场文书
python 实现德洛内三角剖分的操作
2021/04/22 Python
postgreSQL数据库基础知识介绍
2022/04/12 PostgreSQL