簡體   English   中英

使用 pytest.lazy_fixture 列表值作為另一個夾具中的參數

[英]Use pytest.lazy_fixture list values as parameters in another fixture

我試圖將一個夾具值列表用作另一個夾具值的參數。 這是我的設置:

import pytest

d = {
    "first": [1, 2, 3],
    "second": [4, 5, 6]
}

@pytest.fixture(params=['first', 'second'])
def foo(request):
    return d.get(request.param)

@pytest.fixture(params=[pytest.lazy_fixture('foo')])
def bar(request):
    return request.param

def test_1(bar):
    pass

問題是bar()總是獲取完整列表作為request.param ([1, 2, 3] 不是列表的值。如果在bar()夾具的params中直接發送數據,例如:

@pytest.fixture(params=[1, 2, 3])
def bar(request):
    return request.param

def test_1(bar):
    pass

然后參數請求將正常工作(測試開始 3 次)。 同樣的情況,如果我不是直接將參數傳遞給params ,而是從沒有夾具裝飾器的任何方法中傳遞參數,即:

def some():
    return [1, 2, 3]

@pytest.fixture(params=some())
def more(request):
    return request.param

def test_2(more):
    logging.error(more)
    pass

那么,我的問題是否可以從列表中一一獲取數據然后在我的測試中使用它? 我嘗試“解析”列表:

@pytest.fixture(params=[i for i in i pytest.lazy_fixture('foo')])
def bar(request):
    return request.param

但在這種情況下,我得到TypeError: 'LazyFixture' object is not iterable

請參閱一個非常相似的問題的答案:根據設計,夾具值不能用作參數化測試的參數列表。 實際上,在 pytest 收集階段解析參數,而在 pytest 節點執行期間稍后解析夾具。

您可以使用lazy_fixturepytest_cases.fixture_ref做的最好的pytest_cases.fixture_ref是使用單個夾具值作為參數。 隨着lazy_fixture你有限制(如果我沒有記錯,夾具不能被參數化),而與pytest_cases你可以做幾乎任何事情(使用fixture_ref在參數元組,使用幾個fixture_ref s各自具有不同的參數化,等等)。 順便說一下,我是pytest_cases的作者;)

另請參閱此線程

暫無
暫無

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

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