簡體   English   中英

“間接夾具”錯誤使用 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參數。 您需要確保所有參數都寫為一個字符串。

請參閱文檔

內置的 pytest.mark.parametrize 裝飾器可以對 arguments 進行參數化,以進行測試 function。

參數:
1. argnames – 一個逗號分隔的字符串,表示一個或多個參數名稱,或參數字符串的列表/元組。
2. argvalues - argvalues 列表決定了使用不同參數值調用測試的頻率。

意思是,您應該將要參數化的 arguments 編寫為單個字符串,並使用逗號分隔它們。 因此,您的測試應如下所示:

@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 列表標記測試,則 ids 列表必須是一個命名參數,如下所示:

@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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM