Stefano Borini
Stefano Borini

Reputation: 143785

How can I ensure tests with a marker are only run if explicitly asked in pytest?

I have some tests I marked with an appropriate marker. If I run pytest, by default they run, but I would like to skip them by default. The only option I know is to explicitly say "not marker" at pytest invocation, but I would like them not to run by default unless the marker is explicitly asked at command line.

Upvotes: 7

Views: 3262

Answers (2)

user3270865
user3270865

Reputation: 376

Instead of explicitly say "not marker" at pytest invocation, you can add following to pytest.ini

[pytest]
addopts = -m "not marker"

Upvotes: 5

hoefling
hoefling

Reputation: 66251

A slight modification of the example in Control skipping of tests according to command line option:

# conftest.py

import pytest


def pytest_collection_modifyitems(config, items):
    keywordexpr = config.option.keyword
    markexpr = config.option.markexpr
    if keywordexpr or markexpr:
        return  # let pytest handle this

    skip_mymarker = pytest.mark.skip(reason='mymarker not selected')
    for item in items:
        if 'mymarker' in item.keywords:
            item.add_marker(skip_mymarker)

Example tests:

import pytest


def test_not_marked():
    pass


@pytest.mark.mymarker
def test_marked():
    pass

Running the tests with the marker:

$ pytest -v -k mymarker
...
collected 2 items / 1 deselected / 1 selected
test_spam.py::test_marked PASSED
...

Or:

$ pytest -v -m mymarker
...
collected 2 items / 1 deselected / 1 selected
test_spam.py::test_marked PASSED
...

Without the marker:

$ pytest -v
...
collected 2 items

test_spam.py::test_not_marked PASSED
test_spam.py::test_marked SKIPPED
...

Upvotes: 13

Related Questions