''' pytest的夹具(fixture)相比较unittest更强大,与unittest类似也是提供前后置 1、setup_function、teardown_function、setup_method、teardown_method 函数级别前后置和类级别前后置 2、pytest的fixture的包是放在conftest中,使用@pytest.fixture() 装饰器定义前置和后置,而且可以把前后置条件封装起来,将里面的一些参数给我们的测试用例使用,如果我们要用的时候直接调用就行了 3、@pytest.fixture装饰器有几个参数scope是作为作用范围,这个是很重要的概念,类似setup、teardown中的function和method,function:默认作用域,函数级别,class是测试类,module,每个模块,package 每个python包,session会话级别 4、使用yield区分前后置,前面是前置后面是后置 5、顺序: session -> 包 -》 模块 -》 类 -》函数 同一级别,哪个在前,先执行 '''
#下面是conftest的测试夹具
import pytest # 夹具(前置后置) @pytest.fixture() def init(): print("用例级别前置") # yield 之前的就是前置 yield #执行用例 # yield 之后的就是后置 print("用例级别后置") @pytest.fixture(scope='module') def read_excel(): print("模块级别前置") yield print("模块级别后置") @pytest.fixture(scope='class') def db(): print("类级别前置") yield print("类级别后置") # package @pytest.fixture(scope='session') def session(): print("我是session级别前置") yield print("我是session级别后置")
#下面是测试用例类里面的使用方法,直接当入参调用即可
class testClass1: def test1(self, init, read_excel, db,session): pass def test2(self, init, read_excel, db,session): pass class TestClass2: def test3(self, init, read_excel, db,session): pass def test4(self, init, read_excel, db,session): pass #看运行结果,可以看到运行顺序以及在类、方法中前后置使用的次数是怎么样的