如何确保仅在 pytest 中明确询问时才运行带有标记的测试? [英] How can I ensure tests with a marker are only run if explicitly asked in pytest?

查看:47
本文介绍了如何确保仅在 pytest 中明确询问时才运行带有标记的测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用适当的标记标记了一些测试.如果我运行 pytest,默认情况下它们会运行,但我想默认跳过它们.我知道的唯一选择是在 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.

推荐答案

根据命令行选项控制跳过测试:

# 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)

示例测试:

import pytest


def test_not_marked():
    pass


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

使用标记运行测试:

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

或者:

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

没有标记:

$ pytest -v
...
collected 2 items

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

这篇关于如何确保仅在 pytest 中明确询问时才运行带有标记的测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆