pytest fixture
[pytest fixture 官网]https://docs.pytest.org/en/stable/fixture.html#fixture)
Fixture 的作用
- 定义传入测试中的数据集
- 配置测试前系统的初始状态
- 为批量测试提供数据源等
Fixture 是pytest 用于将测试前后进行预备,清理工作的代码分离出核心测试逻辑的一种机制,使用方法
import pytest
@pytest.fixture()
def test_login():
print('登录')
username = [1,2,3]
return username
# 调用fixture装饰的方法,传入方法名即可
def test_search(test_login):
print('搜索')
# 获取返回的参数
print(test_login[1])
- fixture作用域
# fixture 作用域,module模块,class类
@pytest.fixture(scope='module')
# yield 关键字,前面相当于 setup,后面的相当于teardown
@pytest.fixture()
def test_c():
print('fangfac')
yield 'fanhuihoumian d jieguo'# 返回后面的结果,相当于return
print('duankai')# 相当于teardown操作
def test_d(test_c):
print('方法d')
print(f'testC的返回值{test_c}')
把所有 fixtrure 方法写在 conftest文件中,无需import 就可以使用
- conftest 名字不可更改,会从当前目录到根目录向上找,不会在兄弟节点中找
- fixture参数化
@ pytest.fixture(params=[[0.1,0, 0.1],[1,1,2],[2,2,4]])
def get_div_datas(self,request):
return request.param
def test_add_fixtrue(self,get_div_datas):
print(f'a={get_div_datas[0]};b={get_div_datas[1]};excpet={get_div_datas[2]}')
assert get_div_datas[2] == self.calc.add(get_div_datas[0], get_div_datas[1])
#pytest 插件
pip install pytest-ordering 控制用例的执行顺序
pip install pytest-dependency 控制用例的依赖关系
pip install pytest-xdist 分布式并发执行测试用例
pip install pytest-rerunfailures 失败重跑
pip install pytest-assume 多重较验
pip install pytest-random-order 用例随机执行
pip install pytest-html 测试报告