01、python测试的测试固件的创建和销毁
--setup()方法用于初始化测试固件
--teardown()方法用于销毁测试固件
--程序会在运行每个测试用例(以 test_ 开头的方法)之前自动执行 setup() 方法来初始化测试固件,并在每个测试用例(以 test_ 开头的方法)运行完成之后自动执行 teardown() 方法来销毁测试固件。
02、函数级别的 setup 和 teardown使用
--setup和teardown函数主要分为:模块级、类级、功能级、函数级别
--当是函数级别的时候,运行测试方法的始末,即运行一次测试函数运行一次setup和teardown.
import pytest
class Test_ABC: # 类测试用例必须Test开头
def setup(self): # 每一个测试用例执行前都会执行该函数,创建相应固件
print("\n-----> setup_method")
def teardown(self): # 每一个测试用执行过后都会执行该函数,销毁响应固件
print("----> teardown_method")
def test_a(self): # 函数测试用例必须test开头
print("----> test_a")
assert 1
def test_b(self):
print("----> test_b")
if __name__ == '__main__':
pytest.main(['-s', 'pytest_hello.py'])
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
pytest_hello.py
-----> setup_method
----> test_a
.----> teardown_method
-----> setup_method
----> test_b
.----> teardown_method
03、类级别的 setup_class 和 teardown_class使用
运行于测试类的始末,即:在一个测试内只运行一次setup_class和teardown_class,不关心测试类 内有多少个测试函数
import pytest
class Test_ABC:
def setup_class(self): # 类级别,必须带上class
print("\n-----> setup_class")
def teardown_class(self): # 类级别,必须带上class
print("----> teardown_class")
def test_a(self):
print("----> test_a")
assert 1
def test_b(self):
print("----> test_b")
if __name__ == '__main__':
pytest.main(['-s', 'pytest_hello.py'])
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-----> setup_class
----> test_a
.----> test_b
.----> teardown_class
04、setup 和 teardown使用场景
--在使用selenium测试网页时,可以在setup中配置各种参数,teardown关闭selenium,相当于上下文管理器