'Is there a way to collect fixture values into another fixture?

I'm writing a series of mathematical tests for a project and could not find a satisfactory way to achieve the following.

I have a parameterized fixture single_element() which is used to verify a mathematical test test_one() per instantiation of the fixture.

At the same time I need to write a "higher-order" test test_all() which needs all values instantiated by single_element() to run.

import pytest

class TestExample:
    @pytest.fixture(params=range(10))
    def single_element(self, request) -> int:
        return request.param

    @pytest.fixture
    def all_elements(self) -> list[int]:
        # desired behaviour: list of all values returned by single_element().
        # But I want all_elements() to gather values automatically.
        # Here I'm doing it by hand.
        return list(range(10))

    def test_one(self, single_element):
        assert 0 <= single_element < 10

    def test_all(self, all_elements):
        assert all(0 <= _ < 10 for _ in all_elements)

At the moment I need to write single_element() and all_elements() since I could not find a mechanism in pytest to achieve this.

Is there a way to construct all_elements() such that it automatically captures all realizations of one_element()?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source