使用pytest的“间接夹具”错误。怎么了?

2024-10-01 05:04:19 发布

您现在位置:Python中文网/ 问答频道 /正文

 def fatorial(n):
    if n <= 1:
        return 1
    else:
        return n*fatorial(n - 1)


import pytest

@pytest.mark.parametrize("entrada","esperado",[
    (0,1),
    (1,1),
    (2,2),
    (3,6),
    (4,24),
    (5,120)
])

def testa_fatorial(entrada,esperado):
    assert fatorial(entrada)  == esperado

错误:

 ERROR collecting Fatorial_pytest.py ____________________________________________________________________
In testa_fatorial: indirect fixture '(0, 1)' doesn't exist

我不知道为什么会有“间接固定装置”,知道吗? 我使用的是Python3.7和Windows1064位


Tags: importreturnifpytestdef错误errorassert
3条回答

对于出于与我相同的原因来到这里的任何其他人,如果您使用ID列表标记测试,则ID列表必须是一个名为参数,如下所示:

@pytest.mark.parametrize("arg1, arg2", paramlist, ids=param_ids)

而不是

@pytest.mark.parametrize("arg1, arg2", paramlist, param_ids)

TL;DR-
问题出在线路上

@pytest.mark.parametrize("entrada","esperado",[ ... ])

应将其写入逗号分隔的字符串:

@pytest.mark.parametrize("entrada, esperado",[ ... ])

您获得了indirect fixture,因为pytest无法解压缩给定的argvalues,因为它获得了错误的argnames参数。您需要确保所有参数都作为一个字符串写入

请参阅documentation

The builtin pytest.mark.parametrize decorator enables parametrization of arguments for a test function.

Parameters:
1. argnames – a comma-separated string denoting one or more argument names, or a list/tuple of argument strings.
2. argvalues – The list of argvalues determines how often a test is invoked with different argument values.

也就是说,您应该将要参数化的参数编写为单个字符串,并使用逗号分隔它们。因此,您的测试应该如下所示:

@pytest.mark.parametrize("n, expected", [
    (0, 1),
    (1, 1),
    (2, 2),
    (3, 6),
    (4, 24),
    (5, 120)
])
def test_factorial(n, expected):
    assert factorial(n) == expected

由于省略了参数值周围的方括号,我得到了类似的错误,例如

@pytest.mark.parametrize('task_status', State.PENDING,
                                         State.PROCESSED,
                                         State.FAILED)

给出错误“间接夹具“p”不存在”。修复方法:

@pytest.mark.parametrize('task_status', [State.PENDING,
                                         State.PROCESSED,
                                         State.FAILED])

相关问题 更多 >