Search code examples
pythonpytestfixtures

Can't pass argument to fixture indirectly


I can't get the indirect fixture argument pass right:

@pytest.fixture(scope="function")
def sorted_array(to_power):
    assert to_power.param >= 2
    size = int(math.pow(2, to_power.param))
    array = [i for i in range(size)]
    return array


@pytest.mark.parametrize(
    "sorted_array",
    [(2)],
    indirect=["sorted_array"],
)
def test_binary_search_2(sorted_array):
    times_elapsed = []
    ...

I've read Pass a parameter to a fixture function and the official documentation ont the topic. My code seems to follow the advice in those documents and yet, when trying to run the tests copied above I get:

test setup failed
file /Users/mwasilewski/Code/algorithms/python/tests/test_binary_search.py, line 38
  @pytest.mark.parametrize(
      "sorted_array",
      [(2)],
      indirect=["sorted_array"],
  )
  def test_binary_search_2(sorted_array):
file /Users/mwasilewski/Code/algorithms/python/tests/test_binary_search.py, line 30
  @pytest.fixture(scope="function")
  def sorted_array(to_power):
E       fixture 'to_power' not found

I am puzzled and any advice would be much appreciated.


Solution

  • request is not a usual parameter, it's a SubRequest that is used for handling getting a fixture from a test function or another fixture. If you change it to any other variable, to_power for example, pytest will look for another fixture with that name. In addition the indirect should be a boolean True, not a list

    @pytest.fixture(scope="function")
    def sorted_array(request):
        assert request.param >= 2
        size = int(math.pow(2, request.param))
        array = [i for i in range(size)]
        return array
    
    
    @pytest.mark.parametrize(
        "sorted_array",
        [2],
        indirect=True
    )
    def test_binary_search_2(sorted_array):
        print(sorted_array) # [0, 1, 2, 3]