Search code examples
pythonpytestfixtures

pytest fixture with argument


It seems it it possible to pass argument to fixtures:

Pass a parameter to a fixture function

yet, when implementing this minimal example, I get an error.

import pytest

@pytest.fixture
def my_fixture(v):
    print("fixture in")
    yield v+1
    print("fixture out")

@pytest.mark.parametrize("my_fixture",[1], indirect=True)
def test_myfixture(my_fixture):
    print(my_fixture)

@pytest.fixture def my_fixture(v): E fixture 'v' not found

Is anything wrong with the code above ?

(python 3.8.10, pytest-6.2.5)


Solution

  • This works:

    @pytest.fixture
    def my_fixture(request):
        print("fixture in")
        yield request.param+1 # difference here !
        print("fixture out")
    
    @pytest.mark.parametrize("my_fixture",[1], indirect=True)
    def test_myfixture(my_fixture):
        print(my_fixture)