Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 354
Stefano Borini Avatar asked Dec 10 '22 02:12

Stefano Borini


2 Answers

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
...
like image 87
hoefling Avatar answered Jan 13 '23 14:01

hoefling


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

[pytest]
addopts = -m "not marker"
like image 44
user3270865 Avatar answered Jan 13 '23 12:01

user3270865