Search code examples
pythonpytestfixtures

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


I have defined a fixture like :

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

and a test method like :

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

The assert is successful but the teardown throws, yield_fixture function has more than one 'yield':.

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

Solution

  • In the last section of the pytest.yieldfixture documentation:

    • 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.

    With a memory footprint that small, you should just return the entire thing:

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