Skip to content

Instantly share code, notes, and snippets.

@justinmklam
Last active July 6, 2021 00:23
Show Gist options
  • Save justinmklam/b2aca28cb3a6896678e2e2927c6b6a38 to your computer and use it in GitHub Desktop.
Save justinmklam/b2aca28cb3a6896678e2e2927c6b6a38 to your computer and use it in GitHub Desktop.
Skip tests by default in pytest

Skip Tests By Default in Pytest

Adapted from https://docs.pytest.org/en/latest/example/simple.html#control-skipping-of-tests-according-to-command-line-option

Configuration

Add the following to conftest.py:

import pytest

SKIP_DEFAULT_FLAGS = ["integration_dev", "integration_stg"]


def pytest_addoption(parser):
    for flag in SKIP_DEFAULT_FLAGS:
        parser.addoption(
            "--{}".format(flag),
            action="store_true",
            default=False,
            help="run {} tests".format(flag),
        )


def pytest_configure(config):
    for flag in SKIP_DEFAULT_FLAGS:
        config.addinivalue_line("markers", flag)


def pytest_collection_modifyitems(config, items):
    for flag in SKIP_DEFAULT_FLAGS:
        if config.getoption("--{}".format(flag)):
            return

        skip_mark = pytest.mark.skip(reason="need --{} option to run".format(flag))
        for item in items:
            if flag in item.keywords:
                item.add_marker(skip_mark)

Then in your test module(s):

import pytest


def test_func():
    pass


@pytest.mark.integration_dev
def test_func_integration_dev():
    pass
  
  
@pytest.mark.integration_stg
def test_func_integration_stg():
    pass

Usage

Run tests excluding the ones defined in SKIP_DEFAULT_FLAGS:

pytest

To include all tests:

pytest --integration_dev --integration_stg

To only run specifically marked tests:

pytest -m integration_dev --integration_dev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment