【问题标题】:parametrize output of pytest fixture参数化pytest夹具的输出
【发布时间】:2016-04-14 03:00:09
【问题描述】:

我想参数化 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 

对于fixture 1 中的每个参数,只有来自fixture 2 的第一次迭代被传递。如何参数化fixture_2 的输出,以便for 循环中的每次迭代都传递给test_params 函数?

编辑:假设第二个夹具不能以与第一个夹具相同的方式参数化,因为在实际问题中,第二个参数的输出取决于第一个夹具的输入。

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    您正在使用从夹具函数返回的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)
    

    【讨论】:

    • 在这个例子中它可以工作,但是如果第二个的输出依赖于第一个的输入呢?例如,在我正在进行的测试中,第一个夹具返回一个目录,第二个夹具返回目录中文件的子集。
    • py.test 目前不支持依赖参数化
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2015-11-23
    相关资源
    最近更新 更多