gpt4 book ai didi

python - 一个 pytest 函数中的多个测试

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:03 24 4
gpt4 key购买 nike

我有一个关于 pytest 以及我应该如何处理多个测试的“概念性”问题。

假设我需要测试一堆字符串:names = ["", "a ", "a", "a "]

我可以创建多个 test_ 函数来单独测试它们,但它们会完全相同,但输入不同。

我正在考虑做类似的事情:

def test_names():
names = [" ", "a ", " a", " a "]
for name in names:
with pytest.raises(errors.MyFooError) as ex:
random_method(name)

问题是:这样做,如果一个元素没有引发 errors.MyFooError,我会收到这个:

Failed: DID NOT RAISE <class 'errors.MyFooError'

消息是通用的,我不知道这是在哪个元素中发生的。

我可能会分成 4 个测试,一个用于列表中的每个元素,我想这是正确的方法吗?如果列表很大会怎样?

最佳答案

您应该使用 pytestparametrize 功能,如图所示 here .

你的代码看起来像

import pytest

@pytest.mark.parametrize('input', [" ", "a ", " a", " a "])
def test_names(input):
with pytest.raises(errors.MyFooError) as ex:
random_method(input)

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

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