Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

pytest

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?

like image 237
Ted Jenney Avatar asked Nov 24 '25 01:11

Ted Jenney


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. Closed: not planned (May 2023).

Here is a workaround:

# in conftest.py

def pytest_collection_modifyitems(items):
    for item in items:
        if "postgres" in getattr(item, "fixturenames", ()):
            item.add_marker("slow")
like image 119
wim Avatar answered Nov 26 '25 03:11

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!