Pytest - 从夹具参数化测试方法

问题描述 投票:0回答:1

我有一个场景,其中有一个固定装置(在conftest.py 中)可以从文件中读取数据并返回一个字典。我必须使用这个字典来参数化测试方法。有人可以帮我吗?

问题是我无法直接在参数化中传递夹具

pytest pytest-fixtures parametrize
1个回答
0
投票

Parametrize 尝试在调用固定装置之前获取列表参数,因此如果您使用以下参数化测试,它将不起作用:

@pytest.mark.parametrize("name", list_name)

因此,作为解决方法,您可以通过在 conftest.py 文件中添加以下行来更改方法。

def pytest_generate_tests(metafunc):
    # read file and create your list/dict (lets assume you named it as: parametrize_list)
    if "parametrize" in metafunc.fixturenames:
        metafunc.parametrize("parametrize", parametrize_list)

然后你需要将参数添加到你的测试函数中:

def test_example(parametrize):
    # your code

您可以根据自己的情况使用更好的命名。

© www.soinside.com 2019 - 2024. All rights reserved.