【问题标题】:How can I ensure tests with a marker are only run if explicitly asked in pytest?如何确保仅在 pytest 中明确询问时才运行带有标记的测试?
【发布时间】:2019-10-15 21:26:47
【问题描述】:

我用适当的标记标记了一些测试。如果我运行 pytest,默认情况下它们会运行,但我想默认跳过它们。我知道的唯一选择是在调用 pytest 时明确地说“非标记”,但我希望它们默认不运行,除非在命令行中明确询问标记。

【问题讨论】:

  • 看来Control skipping of tests according to command line option 中的示例与您的用例相符。
  • @hoefling 没有。我不想添加命令行选项。我想在没有任何命令行选项的情况下运行 pytest 并获取所有测试除了标记的那些,但是如果我使用 -k "marker" 运行,我希望它们(并且只有它们)运行
  • 当然,这不是复制粘贴示例,您需要删除自定义参数并替换读取参数的一行;请参阅我的答案中的改编示例。
  • @hoefling 完美。我错过了 config.option.keyword 知识。谢谢。

标签: python pytest


【解决方案1】:

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)

示例测试:

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

【讨论】:

    【解决方案2】:

    您可以在 pytest.ini 中添加以下内容,而不是在 pytest 调用时明确说“非标记”

    [pytest]
    addopts = -m "not marker"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      相关资源
      最近更新 更多