字典抛出的 pytest fixture 产量列表 "yield_fixture function has more than one 'yield':"

pytest fixture yield list of dict throws "yield_fixture function has more than one 'yield':"

我定义了一个固定装置,如:

    @pytest.fixture
    def mock_yield_data(self):
        for data in [
            {
                1: 2, 2: 3
            },
            {
                2: 4, 4: 5
            },
        ]:
            yield data

和像这样的测试方法:

    def test_fixture(self, mock_yield_data):
        for data in mock_yield_data:
            assert data

断言成功但 teardown 抛出,yield_fixture function has more than one 'yield':

==================================================================================================== ERRORS ====================================================================================================
_________________________________________________________________________ ERROR at teardown of TestClass.test_fixture _________________________________________________________________________
yield_fixture function has more than one 'yield':

pytest.yieldfixture 文档的最后一节中:

  • usually yield is used for producing multiple values. But fixture functions can only yield exactly one value. Yielding a second fixture value will get you an error. It’s possible we can evolve pytest to allow for producing multiple values as an alternative to current parametrization. For now, you can just use the normal fixture parametrization mechanisms together with yield-style fixtures.

内存占用这么小,你应该 return 整个事情:

@pytest.fixture
def mock_yield_data(self):
    return [
        {
            1: 2, 2: 3
        },
        {
            2: 4, 4: 5
        },
    ]

您的灯具可能只有一个 yield。但是,您可以将 parameters 传递给灯具,这将为每个参数 运行 灯具。

all_data = [
    {
        1: 2, 2: 3
    },
    {
        2: 4, 4: 5
    }
]

@pytest.fixture(params=all_data)
def mock_yield_data(self, request):
    yield request.param