Skip to content

Dynamically adding fixture with getfixturevalue and fixturenames behavior #3057

@benjaminrigaud

Description

@benjaminrigaud

Hello,

I would like to know if there is a pattern to dynamically configure a fixture from another fixture such as it would be available in the fixturenames list.

I tried something like that:

import pytest


@pytest.fixture
def mode_b_only(request):
    print 'mode_b_only'


@pytest.fixture
def setup(request):
    print 'setup', request.fixturenames
    if 'mode_b_only' in request.fixturenames:
        pass  # do something


@pytest.fixture(scope='function', params=[
    'mode_a',
    # disabled by default
    # 'mode_b',
    # 'mode_c',
])
@pytest.mark.early
def two(request):
    print 'two'

    if request.param == 'mode_b':
        request.getfixturevalue('mode_b_only')

    return request.param


def test_default(two, setup):
    pass


@pytest.mark.parametrize('two', ['mode_a', 'mode_b'], indirect=True)
def test_a_and_b(two, setup):
    pass

Unfortunately, setup doesn't see mode_b_only fixture in request.fixturenames when executing test_a_and_b[mode_b]

tests/test_fixtures.py::test_default[mode_a] two
setup ['two', 'setup', 'request']
PASSED

tests/test_fixtures.py::test_a_and_b[mode_a] two
setup ['two', 'setup', 'request']
PASSED

tests/test_fixtures.py::test_a_and_b[mode_b] two
mode_b_only
setup ['two', 'setup', 'request']
PASSED

Is there any way to make it work or some patterns to do that differently?
In my case, setup is an external fixture I have to override & tweak its behavior.

pytest==3.3.1 under Ubuntu

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions