简体   繁体   中英

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.

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
...

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

[pytest]
addopts = -m "not marker"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM