Marking a Pytest fixture instead of all the tests using the fixture

Viewed 1601

Is there a way to define a mark in a PyTest fixture?

I am trying to disable slow tests when I specify -m "not slow" in pytest.

I have been able to disable individual tests, but not a fixture that I use for multiple tests.

My fixture code looks like this:

@pytest.fixture()
@pytest.mark.slow
def postgres():
    # get a postgres connection (or something else that uses a slow resource)
    yield conn 

and several tests have this general form:

def test_run_my_query(postgres):
    # Use my postgres connection to insert test data, then run a test
    assert ...

I found the following comment within https://docs.pytest.org/en/latest/mark.html (updated link):

"Marks can only be applied to tests, having no effect on fixtures." Is the reason for this comment that fixtures are essentially function calls and marks can only be specified at compile time?

Is there a way to specify that all tests using a specific fixture (postgres in this case) can be marked as slow without specifying @pytest.mark.slow on each test?

1 Answers

It seems you already found the answer in the docs. Subscribe to https://github.com/pytest-dev/pytest/issues/1368 for watching this feature, it might be added in a later pytest version.

For now, you can sort of do a hack to workaround:

# in conftest.py

def pytest_collection_modifyitems(items):
    for item in items:
        if 'postgres' in getattr(item, 'fixturenames', ()):
            item.add_marker("slow")
Related