Search code examples
pythonpython-3.xpytestfixtures

how to override a pytest fixture, but still be able to access it?


I have a conftest.py and a plugin, both defining the same fixture with different implementations:

conftest.py

import pytest
@pytest.fixture
def f():
    yield 1

plugin

import pytest
@pytest.fixture
def f():
    yield 2

when installing the plugin, the conftest still overrides the plugin, so a test file will only see the conftest fixture, i.e.

test_.py

def test(f):
    assert f == 1 # True

I want to be able to do something like this:

  1. If the plugin is not installed, continue
  2. Else, from the conftest plugin, yield the value of the plugin's fixture

I managed to get half of the way:

conftest.py

import pytest
@pytest.fixture
def f(pytestconfig):
    if pytestconfig.pluginmanager.has_plugin(plugin_name):
        # now what? I have get_plugin and import_plugin, but I'm not able to get the fixture from there...

Solution

  • The easiest way I see is to try and get the plugin fixture value. If the fixture lookup fails, then no plugin defined it and you can do your own thing. Example:

    import pytest
    from _pytest.fixtures import FixtureLookupError
    
    @pytest.fixture
    def f(request):
        try:  # try finding an already declared fixture with that name
            yield request.getfixturevalue('f')
        except FixtureLookupError:
            # fixture not found, we are the only fixture named 'f'
            yield 1