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

“ indirect fixture” error using pytest. What is wrong?

 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

我不知道为什么我得到“间接夹具”。有什么想法吗? 我正在使用 python 3.7 和 windows 10 64 位。

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

对于出于与我相同的原因来到这里的任何其他人,如果您使用 ID 列表标记测试,则 ID 列表必须是 named 参数像这样:

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

而不是

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

我在省略参数值周围的方括号时遇到了类似的错误,例如

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

给出错误“间接夹具 'P' 不存在”。修复:

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