0

我的目标是从test_add将值传递给夹具, 并且夹具返回一个元组列表,需要将其作为参数传递给test_add函数。

下面是我正在尝试的代码,但它不起作用

文件:conftest.py

@pytest.fixture
def testme(request):
    in_value = request.param
    return [(1*in_value,1),(3*in_value,2),(4*in_value,5)]

文件:test_demo.py

@pytest.mark.parametrize("testme",[(10)])
@pytest.mark.parametrize("input_a,input_b",testme)
def test_add(input_a,input_b):
    print(input_a+input_b)

提前感谢所有帮助。

4

1 回答 1

0

问题是您不能直接在 中访问固定装置pytest.mark.parametrize,所以这不起作用。最接近这种方式的方法可能是在同一个测试中运行所有参数化测试:

@pytest.mark.parametrize("testme", [10], indirect=True)
def test_add(testme):
    for (input_a, input_b) in testme:
        print(input_a, input_b)

如果您想真正对测试进行参数化,则必须在运行时使用pytest_generate_tests. 在这种情况下,您不能使用夹具来提供所需的参数。一种可能性是使用包含该值的自定义标记,以及在运行时从该值生成参数的函数:

def pytest_generate_tests(metafunc):
    # read the marker value, if the marker is set
    mark = metafunc.definition.get_closest_marker("in_value")
    if mark is not None and mark.args:
        in_value = mark.args[0]
        # make sure the needed arguments are there
        if metafunc.fixturenames[:2] == ["input_a", "input_b"]:
            metafunc.parametrize("input_a,input_b", get_value(in_value))

def get_value(in_value):
    return [(1 * in_value, 1), (3 * in_value, 2), (4 * in_value, 5)]

@pytest.mark.in_value(10)
def test_add(input_a, input_b):
    print(input_a, input_b)

在这种情况下,您还希望在您的中注册自定义标记conftest.py以避免警告:

def pytest_configure(config):
    config.addinivalue_line("markers",
                            "in_value: provides the value for....")
于 2021-06-12T19:19:49.203 回答