pytest初始化与清除(一)
一.初始化函数
1.测试用例级别:def setup()
2.套件级别(在模块文件中定义):def setup_module()
3.套件级别(在类中定义): @classmethod
def setup_class()
二.清除函数
1.测试用例级别:def teardown()
2.套件级别(在模块文件中定义):def teardown_module()
3.套件级别(在类中定义):@classmethod
def teardown_class()
三.代码示例1(模块文件中定义测试用例级别)
from api.compare_result import CompareResult from api.gy import gy_v4 def test_gy1(): inputxml1 = 'C:/Users/cale/checkapi/data/input/gyopt.xml' outputxml1 = 'C:/Users/cale/checkapi/data/output/gyopt.xml' cmpr=CompareResult() cmpr.compareXML(gy_v4,inputxml1,outputxml1) def test_gy2(): inputxml2 = 'C:/Users/cl/checkapi/data/input/gyipt.xml' outputxml2 = 'C:/Users/cl/checkapi/data/output/gyipt.xml' cmpr2=CompareResult() cmpr2.compareXML(gy_v4,inputxml2,outputxml2) def setup(): print("执行测试用例前会先执行此方法") def teardown(): print('执行完测试用例后会执行此方法')
执行结果:
结论:测试用例级别的套件,初始化清除的功能作用于每一个测试用例
代码示例2(模块文件中定义测试套件级别)
from api.compare_result import CompareResult from api.gy import gy_v4 def test_gy1(): inputxml1 = 'C:/Users/cale/checkapi/data/input/gyopt.xml' outputxml1 = 'C:/Users/cale/checkapi/data/output/gyopt.xml' cmpr=CompareResult() cmpr.compareXML(gy_v4,inputxml1,outputxml1) def test_gy2(): inputxml2 = 'C:/Users/cl/checkapi/data/input/gyipt.xml' outputxml2 = 'C:/Users/cl/checkapi/data/output/gyipt.xml' cmpr2=CompareResult() cmpr2.compareXML(gy_v4,inputxml2,outputxml2) def setup_module(): print("执行测试套件前会先执行此方法") def teardown_module(): print('执行完测试套件后会执行此方法')
执行结果:
代码示例3(类中定义测试套件级别,注意方法名的改变)
from api.compare_result import CompareResult from api.gy import gy_v4 class TestSuite(): def test_gy1(self): inputxml1 = 'C:/Users/cale/checkapi/data/input/gyopt.xml' outputxml1 = 'C:/Users/cale/checkapi/data/output/gyopt.xml' cmpr=CompareResult() cmpr.compareXML(gy_v4,inputxml1,outputxml1) def test_gy2(self): inputxml2 = 'C:/Users/cl/checkapi/data/input/gyipt.xml' outputxml2 = 'C:/Users/cl/checkapi/data/output/gyipt.xml' cmpr2=CompareResult() cmpr2.compareXML(gy_v4,inputxml2,outputxml2) @classmethod def setup_class(self): print("执行测试套件前会先执行此方法") @classmethod def teardown_class(self): print('执行完测试套件后会执行此方法')
结果: