pytest.mark.Parameterize在pytest.lazy_夹具中无法按预期工作

2024-09-27 19:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对以下代码有问题-最终结果与预期不符:

env.yaml

config:
  requestenv: [test, uat]
  envinfo:
    test: [{imp: 111, clk: 111, "act": 111}, {imp: 222, clk: 222, act: 222}]
    uat: [{ imp: 333, clk: 333, act: 333 }, { imp: 444, clk: 444, act: 444 }]

测试环境py

import pytest
from utils import configutil

configpath = r".\monitor.request.config.yaml"

config = configutil.readyamlconfig(configpath)


requestenv = config["config"]["requestenv"]


@pytest.fixture(scope="function", params=requestenv)
def one(request):
    env = request.param
    return config["config"]["envinfo"][request.param]


@pytest.mark.parametrize("testdata", [pytest.lazy_fixture("one")])
def test_func01(testdata):
    print()
    print("*" * 10)
    print(testdata)

测试数据总是附带一个env.yaml配置文件,并且取决于测试环境(testuat)。我想在运行pytest -s .\test_env.py之后循环每个环境和该环境中的每个项目,如下所示:

[预期]

test_env.py::test_func01[test-{ imp: 111, clk: 111, act: 111 }]
test_env.py::test_func01[test-{ imp: 222, clk: 222, act: 222 }]
test_env.py::test_func01[saas-{ imp: 333, clk: 333, act: 333 }]
test_env.py::test_func01[saas-{ imp: 444, clk: 444, act: 444 }]

[实际]

test_env.py::test_func01[test-[[{imp: 111, clk: 111, "act": 111}, {imp: 222, clk: 222, act: 222}]]]
test_env.py::test_func01[test-[{ imp: 333, clk: 333, act: 333 }, { imp: 444, clk: 444, act: 444 }]]

Tags: pytestenvconfigyamlpytestrequestact
1条回答
网友
1楼 · 发布于 2024-09-27 19:26:51

我还不知道如何使用lazy-fixture实现这一点。问题是每个测试环境中的测试数量可能不同,我不知道如何在夹具中反映这一点。如果测试的数量相同(如您的示例中所示),则以下操作可行:

@pytest.fixture(params=requestenv)
def envs(request):
    yield envinfo[request.param]

@pytest.fixture(params=range(len(envinfo["test"])))
def data(request, envs):
    yield envs[request.param]

def test_func01(data):
    print(data)

如果数据的长度是可变的,唯一想到的是使用钩子手动参数化函数:

def mydata():
    data = []
    ids = []  # not needed, just to make make the test name better readable
    for key in requestenv:
        data.extend([d for d in envinfo[key]])
        ids.extend([key + "-" + str(i) for i in range(len(envinfo[key]))])
    return data, ids

@pytest.hookimpl
def pytest_generate_tests(metafunc):
    if "testdata" in metafunc.fixturenames:
        data, ids = mydata()
        metafunc.parametrize("testdata", data, ids=ids)

def test_func02(testdata):
    print()
    print(testdata)

这两种变体都会生成预期的输出

也许我遗漏了一些东西,还有更好的解决办法

相关问题 更多 >

    热门问题