def addCleanup(self, function, *args, **kwargs): """Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are
called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown)."""
self._cleanups.append((function, args, kwargs)) 添加針對(duì)每個(gè)測(cè)試用例執(zhí)行完tearDown()方法之后的清理方法,添加進(jìn)去的函數(shù)按照LIFO的順序,通過參數(shù)添加進(jìn)去 如果setUp()執(zhí)行失敗,就不會(huì)執(zhí)行tearDown(),自然也不會(huì)執(zhí)行addCleanup()里添加的函數(shù)。 使用場(chǎng)景:正常的測(cè)試用例,創(chuàng)建資源后,需要清理環(huán)境再在用例中刪除資源,或者tearDown()后進(jìn)行資源清理,不方便,如果用了addCleanup()后,直接在用例中寫入函數(shù),在tearDown()用例后,會(huì)再次調(diào)用addCleanup來刪除資源,減少代碼量以及遺漏刪除。 # _*_ encoding:utf-8 _*_
from selenium import webdriver from selenium.webdriver.common.by import By import unittest import time
class Baidu(unittest.TestCase):
def abc(self,a,b): print(a+b)
def setUp(self): self.driver = webdriver.Ie() self.driver.implicitly_wait(10) self.base_url = 'http://www.baidu.com' print ("This is setUp")
def test_baidu_search(self): driver = self.driver driver.get(self.base_url) driver.find_element_by_id("kw").send_keys("HTMLTestRunner") driver.find_element_by_id("su").click() cleanups = ('abcdefg','123312') self.addCleanup(self.abc, cleanups[0], cleanups[1])
def tearDown(self): self.driver.quit() print ("This is tearDown")
if __name__ == '__main__': unittest.main()
執(zhí)行結(jié)果如下,可以看到會(huì)在用例結(jié)束之后,執(zhí)行addCleanup里的函數(shù),因此可以用來進(jìn)行,測(cè)試環(huán)境數(shù)據(jù)清理工作。 Ran 1 test in 12.008s OK This is tearDown abcdefg123312 Process finished with exit code 0
|