首页 > 代码库 > python unittest框架中addCleanup函数详解

python unittest框架中addCleanup函数详解

接上一篇doCleanups说明,这次介绍下另一个很好用的函数:addCleanup

还是老规矩,看官方文档说明:

addCleanup(function, *args, **kwargs)?
Add a function to be called after tearDown() to cleanup resources used during the test. Functions will be called in reverse order to the order they are added (LIFO). They are called with any arguments and keyword arguments passed into addCleanup() when they are added.

If setUp() fails, meaning that tearDown() is not called, then any cleanup functions added will still be called.

New in version 2.7.

中文解释一下:

添加针对每个测试用例执行完tearDown()方法之后的清理方法,添加进去的函数按照后进先出(LIFO)的顺序执行,要加参数进去
当然,如果setUp()方法执行失败,那么不会执行tearDown()方法,自然也不会执行addCleanup()里添加的函数。

那其实在实际使用时,也不会写多个函数进去。

那么,应用场景是怎么样的呢?

场景是这样的:正常的测试用例是这样的,你创建资源后,需要在用例中去进行删除资源,或者要在tearDown中进行资源清理,相当不方便,用addCleanup后,直接在用例中写入函数,在tearDown用例后,会再次调用addCleanup来删除资源,减少代码量及遗漏删除

看看一个简单实例吧

#coding:utf-8
‘‘‘
Created on 2016年8月31日
@author: huzq
‘‘‘
import unittest

class my(unittest.TestCase):
    
    def delf(self,a):
        print a
    
    def setUp(self):
        print "setUp"

        
    def test_1(self):
        ‘‘‘i dont konw‘‘‘
        a=1111
        print "test_1"       
        cleanups = (bbbbb,)
        self.addCleanup(self.delf,
                        cleanups [0])
        
    def tearDown(self):
        print this is tearDown
        
    #def doCleanups(self):
     #   print "this is cleanups"
    
    def test_2(self):
        print "test_2"
    
    @classmethod
    def tearDownClass(cls):
        print "teardown...."
        
if __name__=="__main__":
    test=unittest.TestSuite()
    test.addTest(my(test_1))
    test.addTest(my(test_2))
    runner=unittest.TextTestRunner()
    runner.run(test)

运行结果如下:

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

OK
setUp
test_1
this is tearDown
bbbbb
setUp
test_2
this is tearDown
teardown....

看看红色部分,就是addCleanup的功效

 

笔者有幸看到很多老外开源的框架,在代码中大量使用的addCleanup函数。大家可以借鉴

python unittest框架中addCleanup函数详解