2016-04-14 110 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