Search code examples
pytestfixturesparametrized-testingpytest-fixtures

pytest fixture not found when used in parametrize


@pytest.fixture
def text():
    return "My fixture text for testing.\n"

@pytest.mark.parametrize(
    ("some_boolean_param", "text"),
    [
        (True, text), 
        (False, text),
    ],
)
def test_my_function(some_boolean_param, text, request):
    fixture_text = request.getfixturevalue(text)
    # do something with fixture_text and some_boolean param...

Results in:

E       fixture '<function text at 0x160acb280>' not found
>       available fixtures: fixture1, ..., text, another_fixture, ...

However if I put the fixture value inside a string, it just returns the string:

@pytest.fixture
def text():
    return "My fixture text for testing.\n"

@pytest.mark.parametrize(
    ("some_boolean_param", "text"),
    [
        (True, "text"), 
        (False, "text"),
    ],
)
def test_my_function(some_boolean_param, text, request):
    fixture_text = request.getfixturevalue(text)

Results in:

>>> text
>>> "text"
>>> fixture_text
>>> "text"

How can I pass in the fixture to parametrize and get parametrize to find it?


Solution

  • your code overrides the fixture name, please work with the following code:

    import pytest
    @pytest.fixture
    def text():
        return "My fixture text for testing.\n"
    
    @pytest.mark.parametrize(
        ("some_boolean_param", "fixture_name"), # dont override fixture name
        [
            (True, "text"), 
            (False, "text"),
        ],
    )
    def test_my_function(some_boolean_param, fixture_name, request):
        fixture_text = request.getfixturevalue(fixture_name)
        print(f"text from fixture:{fixture_text}")