python unittest框架中doCleanups妙用
2017-08-11 10:40
281 查看
偶看unittest官方文档中,发现一个很好用的功能函数doCleanups,看看官方是怎么解释的:
该功能函数在2.7之后就支持了
来来来,简单用中文说明一下吧,大概意思如下:
看完后大家都明白了吧,平时我们使用tearDown函数时,当setUp运行失败时,tearDown就不执行了,所以就会有遗留资源的存在,正好doCleanups帮我们解决了这个困扰,不用再写try...except....finally了。
下面,用个实例来看看doCleanups怎么运行的
我们运行后看看结果:
看看,从运行结果中可以看出。即使setUp出现错误的情况下,doCleanups还是运行了。
doCleanups() This method is called unconditionally after tearDown(), or after setUp() if setUp() raises an exception. It is responsible for calling all the cleanup functions added by addCleanup(). If you need cleanup functions to be called prior to tearDown() then you can call doCleanups() yourself. doCleanups() pops methods off the stack of cleanup functions one at a time, so it can be called at any time.
该功能函数在2.7之后就支持了
来来来,简单用中文说明一下吧,大概意思如下:
无条件的执行改函数,在tearnDown()之后或者在setUp()之后即使setUp失败的情况下也会执行 与addCleanup搭配使用
看完后大家都明白了吧,平时我们使用tearDown函数时,当setUp运行失败时,tearDown就不执行了,所以就会有遗留资源的存在,正好doCleanups帮我们解决了这个困扰,不用再写try...except....finally了。
下面,用个实例来看看doCleanups怎么运行的
#coding:utf-8 ''' Created on 2016年8月31日 @author: zq ''' import unittest class my(unittest.TestCase): def a(self): print "aaaa" def setUp(self): print "setUp" raise IOError,"errorororororo" #这里特意让setUp产生错误 def test_1(self): '''i dont konw''' print "test_1" def tearDown(self): print 'this tearDown' def doCleanups(self): print "this is cleanups" def test_2(self): print "test_2" @classmethod def tearDownClass(cls): print "teardownClass...." if __name__=="__main__": test=unittest.TestSuite() test.addTest(my('test_1')) test.addTest(my('test_2')) runner=unittest.TextTestRunner() runner.run(test)
我们运行后看看结果:
setUp this is cleanups setUp this is cleanups teardownClass.... EE
看看,从运行结果中可以看出。即使setUp出现错误的情况下,doCleanups还是运行了。
相关文章推荐
- python单元测试unittest框架
- Python之使用unittest框架和HTMLTestRunner.py文件实现多个测试用例执行与测试报告生成
- selenium-webdriver(python) (十六) --unittest 框架
- Python单元测试框架使用unittestpyUnit
- Python 之unittest框架
- Python Unittest 自动化单元测试框架Demo
- python unitTest使用框架
- Python+Selenium框架设计篇之8-unittest执行脚本方法之addTest
- Python单元测试框架 — unittest
- Selenium-Webdriver(python) (六) --- Unittest框架分析
- python实例编写(6)--引入unittest测试框架,构造测试集批量测试(以微信统一管理平台为例)
- python测试框架——unittest和nosetest
- python:unittest(测试框架)
- Python+Selenium框架-unittest执行脚本方法之addTest
- python+selenium的unittest框架通过读取properties文件自定义选择IE/Firefox/Chrome浏览器
- python unittest测试框架介绍
- Python单元测试框架unittest简介
- B001:python单元测试框架unittest
- Python接口测试之unittest框架(五)
- python unittest框架中addCleanup函数详解