Pytest – how to skip tests unless you declare an option/flag?

The pytest documentation offers a nice example on how to skip tests marked “slow” by default and only run them with a --runslow option:

# conftest.py

import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--runslow", action="store_true", default=False, help="run slow tests"
    )


def pytest_configure(config):
    config.addinivalue_line("markers", "slow: mark test as slow to run")


def pytest_collection_modifyitems(config, items):
    if config.getoption("--runslow"):
        # --runslow given in cli: do not skip slow tests
        return
    skip_slow = pytest.mark.skip(reason="need --runslow option to run")
    for item in items:
        if "slow" in item.keywords:
            item.add_marker(skip_slow)

We can now mark our tests in the following way:

# test_module.py
from time import sleep

import pytest


def test_func_fast():
    sleep(0.1)


@pytest.mark.slow
def test_func_slow():
    sleep(10)

The test test_func_fast is always executed (calling e.g. pytest). The “slow” function test_func_slow, however, will only be executed when calling pytest --runslow.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)