一. pytest.fixture() 使用 fixture 传 params 参数实现参数化
1.1 方法1
• 步骤:
1. 导入pytest
2. 在登陆的函数上面加@pytest.fixture()
3. 在要使用的测试方法中传入(登陆函数名称),就先登陆 4. 不传入的就不登陆直接执行测试方法
import pytest
@pytest.fixture(params=[1,2,3,'linda'])------可以是元组,也可以是列表
def prepara_data(request):------reuest是固定写法
return request.param------reuest.param是固定写法
#应用
@pytest.fixture(params=[1,2,3,'linda'])
def prepara_data(request):
return request.param
def test_one(prepara_data):
print('testdata:%s'%prepara_data)
def test_two(prepara_data):
if type(prepara_data)is str: -----test2只执行传递参数为str类型的
print('testdata2:%s'%prepara_data)
if __name__ == '__main__':
pytest.main()
二. @ pytest.mark.parametrize 允许在测试函数或类中定义多组参数,在用例中实现参数化
@pytest.mark.parametrize("user,pwd",[("18221124104",111111),("18200000000",111111)])
def test(user,pwd):
print(user,pwd)
三. pytest_generate_tests 允许定义自定义参数化方案或扩展。
通过数据驱动测试——Fixture参数化我们知道fixture可以使测试数据和测试用例分离,达到数据驱动测试的效果,但是这样会有有个问题,测试数据集是直接写死在代码里的,然而更多的时候测试数据的内容依赖于测试条件而变化,所以固定的数据是无法满足我们的要求的。好在pytest提供一个钩子函数pytest_generate_tests,它会在collection时执行,利用传入的参数metafunc为fixture赋值参数。
# conftest.py
def pytest_addoption(parser):
parser.addoption("--ip_type", action="store", default="loopback",
help="ip type includes loopback, domain and local_network")
def pytest_generate_tests(metafunc):
if 'test_data' in metafunc.fixturenames: #test_data --测试文件中测试方法的入参名;
ip_type = metafunc.config.getoption("ip_type")
if ip_type == "loopback":
metafunc.parametrize("test_data", ["127.0.0.1"]) #构造对应测试方法的入参
elif ip_type == "local":
metafunc.parametrize("test_data", ["192.168.1.1", "192.168.1.2"])
# metafunc.fixturenames -- test_开头的测试方法的形参列表
# test_ping.py
import os
import re
import pytest
import time
def get_ping_response(ip_addr):
pid = os.popen("ping " + ip_addr)
prompt = pid.read()
m = re.search(r"Sent = (\d+), Received = (\d+), Lost = (\d+) \((\d+)% loss\)", prompt)
sent_num = int(m.group(1))
recv_num = int(m.group(2))
lost_num = int(m.group(3))
lost_rate = int(m.group(4))
return sent_num, recv_num, lost_num, lost_rate
def test_case1(test_data):
lost_rate = get_ping_response(test_data)[3]
assert lost_rate == 0
根据metafunc.config.getoption("ip_type")获取到命令行参数值,并根据不同的输入利用metafunc.parametrize对test_data赋值参数,达到了动态参数化的功能。
param metafunc:共有五个属性值
metafunc.fixturenames:参数化收集时的参数名称
metafunc.module:使用参数名称进行参数化的测试用例所在的模块d对象
metafunc.config:测试用例会话
metafunc.function:测试用例对象,即函数或方法对象
metafunc.cls: 测试用例所属的类的类对象
https://www.cnblogs.com/vevian/articles/12631861.html
四. (拓展)利用其他钩子函数根据pytest框架执行顺序自定义参数化方案
钩子函数在pytest执行的整个生命周期的各个阶段会执行 ,开发者可以根据钩子函数的特点和自己的实际需求进行开发
pytest(13)钩子函数_python开发笔记的博客-CSDN博客_pytest 钩子函数
参考:
pytest文档69-Hook函数之参数化生成测试用例pytest_generate_tests - 上海-悠悠 - 博客园
How to parametrize fixtures and test functions — pytest documentation