@pytest.fixture()装饰器用于声明函数是一个fixture。如果测试函数的参数列表中包含fixture名,那么pytest会检测到,并在测试函数运行之前执行fixture。>

1、使用fixture传递测试数据
fixture非常适合存放测试数据,并且可以返回任何数据

2、指定fixture作用范围
fixture包含一个scope的可选参数,用于控制fixture执行配置和销毁逻辑的频率。
@pytest.fixture()的scope参数有四个值:
scope='function'
函数级别的fixture每个测试函数 只运行一次。配置代码在测试用例运行之前运行,销毁代码在测试用例运行之后执行。function是fixture参数的默认值。
scope='class'
类级别的fixture每个测试类只运行一次,不管测试类中有多少个类方法都可以共享这个fixture
scope='module'
模块级别的fixture每个模块只运行一次,不管模块里有多少个测试函数,类方法或其他fixture都可以共享这个fixture
scope='session'
会话级别的fixture每次会话只运行一次。一次pytest会话中的所有测试函数、方法都可以共享这个fixture
3、使用usefixtures指定fixture
用@pytest.mark.usefixtures('fixture1','fixture2')标记测试函数或类。

4、fixture的参数化

对测试函数进行参数化处理,可以多次运行的只是该测试函数,而使用参数化fixture,每个使用该fixture的测试函数都可以被运行多次。
网友评论