接上一篇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時,在teardown之后執行順序是后進先出的順序,如下一個用例:
def test_1(self): '''i dont konw''' a='1111' print "test_1" #self.addCleanup(self.delf,a) cleanups = ('bbbbb',) self.addCleanup(self.delf, cleanups[0]) print "2222" self.addCleanup(self.delf, a)
測試結果是如下的:
test_1 2222 this is tearDown 1111 bbbbb
先執行了最后一個addCleanup,再執行倒數第二個addCleanup
如果你又加了doCleanups的話,只會執行doCleaups,不執行addCleanup
筆者有幸看到很多老外開源的框架,在代碼中大量使用的addCleanup函數。大家可以借鑒