如何使 pytest 中的第二个参数化变量成为第一个参数化变量的函数?

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

我有一个 pytest 测试,如下所示:

@pytest.mark.parametrize('type', ['a', 'b', 'c'])
@pytest.mark.parametrize('val', list(range(0, VAR_THAT_IS_FUNCTION_OF_TYPE)))
def test(type, val):

范围的上限是

VAR_THAT_IS_FUNCTION_OF_TYPE
,它是
type
的函数。然而,问题是第二个参数化调用不知道
type
。有办法让大家知道吗

pytest parameterization
1个回答
0
投票

要实现此目的,您可以使用

fixture
根据类型参数计算
VAR_THAT_IS_FUNCTION_OF_TYPE
的值。然后,您可以在第二次参数化中使用此夹具。

import pytest

@pytest.fixture
def var_function_of_type(request):
    type_value = request.param
    if type_value == 'a':
        return 10
    elif type_value == 'b':
        return 20
    elif type_value == 'c':
        return 30


@pytest.mark.parametrize('type', ['a', 'b', 'c'])
@pytest.mark.parametrize('val', [i for i in range(0, 50)], indirect=['type'], params={'type': var_function_of_type})
def test_function(type, val):
    print(f"type: {type}, val: {val}")
© www.soinside.com 2019 - 2024. All rights reserved.