2016-04-14 43 views
0

我想參數化pytest夾具的輸出。舉例來說,假設我有兩個夾具:pytest夾具的參數化輸出

# contents of test_param.py 
import pytest 

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

@pytest.fixture 
def fixture_2(fixture_1): 
    for num in range(5): # the output here should be parametrized 
     return '%d_%s' % (fixture_1, num) # but only returns first iteration 

def test_params(fixture_2): 
    print (fixture_2) 
    assert isinstance(fixture_2, str) 

然後當我運行以下命令:

py.test test_param.py 

只有從夾具2被在夾具1.每個PARAM通過了第一次迭代我怎樣才能參數化fixture_2的輸出,使得for循環中的每個迭代都被傳遞給test_params函數?

編輯:假定第二個燈具不能以與第一個燈具相同的方式進行參數化,因爲在實際問題中,第二個參數的輸出取決於第一個燈具的輸入。

回答

0

您正在使用從夾具功能返回的return

爲什麼不像第一個那樣參數化第二個夾具?

# contents of test_param.py 
import pytest 

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

@pytest.fixture(params=list(range(5))) 
def fixture_2(fixture_1, request): 
    return '%d_%s' % (fixture_1, request.param) 

def test_params(fixture_2): 
    print (fixture_2) 
    assert isinstance(fixture_2, str) 
+0

在這個例子中,它可以工作,但如果第二個輸出取決於第一個輸入的輸出呢?在我正在進行的測試中,例如,第一個夾具返回目錄,第二個夾具返回目錄中文件的第二個子集。 – derchambers

+0

py.test目前不支持從屬參數化 – Ronny