自动化测试中一个测试用例对应一个测试点, 通常一组测试数据无法完全覆盖所有测试范围, 所以需要参数化来传递多组数据。Pytest
的参数化有两种实现方式
pytest.fixture
fixture
的参数params
可以实现参数化的
参数params
:list
类型,提供参数数据(参数化),供调用标记方法的函数使用
参数ids
:配合params
参数使用的, 如果没有设置params
参数,那么ids毫无意义; ids
参数是给每一项params
参数设置自定义名称用的; params
参数值包含的列表有多少项值,那么ids
参数就必须对应有多少项值
fixture返回值
#!/usr/bin/python3
# coding=utf-8
# Author: 文
import pytest
@pytest.fixture()
def need_data():
return 2 # 返回数字2
class Test_One:
def test_a(self, need_data): # need_data返回值2
print("------->test_a")
print("need_data等于" + str(need_data))
assert need_data != 3 # 拿到返回值做一次断言
if __name__ == "__main__":
pytest.main(["-s", "test_two.py::Test_One"])
执行结果如下:
F:\Python3.6.5\python.exe E:/xxx/test_two.py
============================= test session starts =============================
platform win32 -- Python 3.6.5, pytest-6.1.1, py-1.9.0, pluggy-0.13.1
rootdir: E:\xxx, configfile: pytest.ini
plugins: html-2.1.1, metadata-1.10.0
collected 1 item
test_two.py ------->test_a
need_data等于2
.
============================== 1 passed in 0.37s ==============================
Process finished with exit code 0
fixture参数化
#!/usr/bin/python3
# coding=utf-8
# Author: 文
import pytest
@pytest.fixture(params=['aaa', 'bbb', 'ccc'], ids=["data-1", "data-2", "data-3"])
def parameterization(request): # 传入参数request 系统封装参数
return request.param # 取列表中单个值,默认的取值方式
class Test_One():
def test_b(self, parameterization): # 获得返回值 request.par