如何访问夹具的值作为参数化测试的输入

2024-06-26 10:50:02 发布

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

py.test中,我需要根据我在文件中定义的测试动态定义测试

所以我想的是在conftest.py中定义一个fixture,它读取文件并返回一个包含测试的字典

文件tests.json

{
    "test1": "text",
    "test2": "42",
    "test3": 1
}

然后,我在conftest.py中定义一个fixture以返回带有测试的字典:

def pytest_addoption(parser):
    parser.addoption(
        "--tests",
        default="tests.json",
    )

@pytest.fixture
def mytests(request):
    testfile = request.config.getoption("--tests")
    with open(testfile) as f:
        tests = json.load(f)
    return tests

然后我可以在test_pytest.py中使用参数化测试,如下所示:

@pytest.mark.parametrize("test_name", [(key) for key, value in mytests.items()])
def test1(test_name):
    print(test_name)

这不起作用,因为在这一点上,py.test似乎不知道mytests是一个固定装置。我犯了一个错误

E   NameError: name 'mytests' is not defined

如何正确处理?我只希望能够运行json文件中定义的所有测试,或者能够使用-k选项(如果py.test)从中选择单个测试

怎么做


根据下面给出的一些评论,我尝试实现以下内容:

@pytest.hookimpl
def pytest_generate_tests(metafunc):
    if "myparam" in metafunc.fixturenames:
        with open(metafunc.config.option.tests) as f:
            tests = json.load(f)

        # add parametrization for each fixture name
        for name, value in tests.items():
            print(name, value)
            metafunc.parametrize("mparam", (name, value))

def test1(myparam):
    print(myparam)

但是我犯了一个错误

ERROR test_pytest.py - ValueError: duplicate 'myparam'

Tags: 文件namepytestjson定义pytestvalue
1条回答
网友
1楼 · 发布于 2024-06-26 10:50:02

如注释中所述,您不能在mark.parametrize中使用装置。夹具只能用于测试功能和其他夹具

要像本例中那样进行动态参数化,可以实现钩子函数pytest_generate_tests

@pytest.hookimpl
def pytest_generate_tests(metafunc):
    if "test_name" in metafunc.fixturenames:
        testfile = metafunc.config.getoption(" tests")
        with open(testfile) as f:
            tests = json.load(f)
        metafunc.parametrize("test_name", tests.items())


def test1(test_name):
    print(test_name)

这将使用“test_name”参数(例如fixture)和配置文件中的项目参数化所有测试

使用给定的json文件运行此命令将导致如下结果:

$ python -m pytest -s
...
collected 3 items

test_pytest.py ('test1', 'text')
.('test2', '42')
.('test3', 1)
.

相关问题 更多 >