gpt4 book ai didi

python - pytest 参数化 fixture 函数和测试函数

转载 作者:行者123 更新时间:2023-12-01 08:32:03 25 4
gpt4 key购买 nike

类似这个问题:py.test: Pass a parameter to a fixture function但是,我们还希望对测试的输入进行参数化。

例如(这是我想做的事情的简化版本):

import pytest


def person_says(name, age):
return f"{name} is {age}"


@pytest.fixture
def add_surname(request):
surname = request.param
return f'Mike {surname}'


NAME1 = "Johnson"
AGE1 = "13"
OUTPUT1 = "Mike Johnson is 13"
NAME2 = "Liam"
AGE2 = "21"
OUTPUT2 = "Mike Liam is 21"

我想传递这样的东西:

@pytest.mark.parametrize('add_surname,age,expected',
[[NAME1, AGE1, OUTPUT1],
[NAME2, AGE2, OUTPUT2]],
indirect=True)
def test_person_says(add_surname, age, expected):
name = add_surname
output = person_says(name, age)
assert expected == output

但这不起作用,因为它寻找不存在的装置age

<小时/>

使用多个装饰器可以实现所有 4 种组合。

@pytest.mark.parametrize('age,expected', [[AGE1, OUTPUT1], [AGE2, OUTPUT2]])
@pytest.mark.parametrize('add_surname', [NAME1, NAME2], indirect=True)
def test_person_says(add_surname, age, expected):
name = add_surname
output = person_says(name, age)
assert expected == output

结果:

Expected :Mike Liam is 21        Actual   :Mike Johnson is 21  # FAIL
Expected :Mike Johnson is 13 Actual :Mike Johnson is 13 # Pass
Expected :Mike Johnson is 13 Actual :Mike Liam is 13 # FAIL
Expected :Mike Liam is 21 Actual :Mike Liam is 21 # Pass

最好的方法是什么?

最佳答案

除了 bool 值之外,间接还可以采用输入名称列表,因此通过固定装置进行的间接参数化仅适用于这些输入。示例:

@pytest.mark.parametrize('x, y, z', [('spam', 'eggs', 'bacon')], indirect=['x', 'y'])

xy 是间接参数化的,因此 spameggs 将通过 x 传递y 固定装置,但 z 是直接参数化的,因此 bacon 将用作纯输入。对于您的情况:

@pytest.mark.parametrize('add_surname,age,expected',
[[NAME1, AGE1, OUTPUT1],
[NAME2, AGE2, OUTPUT2]],
indirect=['add_surname'])

就可以了。

关于python - pytest 参数化 fixture 函数和测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53869278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com