接上一篇doCleanups說明,此次介紹下另外一個很好用的函數:addCleanuphtml
仍是老規矩,看官方文檔說明:python
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來刪除資源,減小代碼量及遺漏刪除ui
看看一個簡單實例吧this
#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)
運行結果以下:spa
.. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK setUp test_1 this is tearDown bbbbb setUp test_2 this is tearDown teardown....
看看紅色部分,就是addCleanup的功效code
後進先出的體現就是測試用例中使用了多個addCleanup時,在teardown以後執行順序是後進先出的順序,以下一個用例:htm
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函數。你們能夠借鑑