python的unittest框架中如何删除测试数据,清理环境,可以通过addCleanup函数

python

 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))

添加针对每个测试用例执行完tearDown()方法之后的清理方法,添加进去的函数按照LIFO的顺序,通过参数添加进去

如果setUp()执行失败,就不会执行tearDown(),自然也不会执行addCleanup()里添加的函数。

使用场景:正常的测试用例,创建资源后,需要清理环境再在用例中删除资源,或者tearDown()后进行资源清理,不方便,如果用了addCleanup()后,直接在用例中写入函数,在tearDown()用例后,会再次调用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):

print(a)

def setUp(self):

self.driver = webdriver.Firefox()

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',)

self.addCleanup(self.abc,

cleanups[0])

def tearDown(self):

self.driver.quit()

print ("This is tearDown")

if __name__ == '__main__':

unittest.main()

# testsuit = unittest.TestSuite()

# testsuit.addTest(Baidu("test_baidu_search"))

执行结果如下,可以看到会在用例结束之后,执行addCleanup里的函数,因此可以用来进行,测试环境数据清理工作。

This is setUp
.
----------------------------------------------------------------------
Ran 1 test in 16.072s

OK
This is tearDown
abcdefg

以上是 python的unittest框架中如何删除测试数据,清理环境,可以通过addCleanup函数 的全部内容, 来源链接: utcz.com/z/388772.html

回到顶部