【问题标题】:Pytest run only tests with specific marker attributePytest 仅运行具有特定标记属性的测试
【发布时间】:2021-04-22 03:13:25
【问题描述】:

我使用@pytest.mark 来唯一标识特定测试,因此我创建了我的自定义标记。

@pytest.mark.key

我就是这样使用它的:

@pytest.mark.key("test-001")
def test_simple(self):
    self.passing_step()
    self.passing_step()
    self.passing_step()
    self.passing_step()
    assert True

现在我想从控制台运行所有带有标记键“test-001”的测试。我怎样才能做到这一点?

我正在寻找的是这样的:

pypi.org/project/pytest-jira/0.3.6

测试可以映射到 Jira 键。我查看了链接的源代码,但我不确定如何实现它以便我运行特定的测试。假设我只想使用密钥“test-001”运行测试。

【问题讨论】:

  • 请关注How to Ask。有些句子合二为一。很难理解想法。

标签: python testing pytest


【解决方案1】:

Pytest 不提供开箱即用的功能。您可以使用-m 选项按标记名称进行过滤,但不能按标记属性
但是,您可以添加自己的选项以按键过滤。这是一个例子:

conftest.py

def pytest_configure(config):
    # register your new marker to avoid warnings
    config.addinivalue_line(
        "markers",
        "key: specify a test key"
    )


def pytest_addoption(parser):
    # add your new filter option (you can name it whatever you want)
    parser.addoption('--key', action='store')


def pytest_collection_modifyitems(config, items):
    # check if you got an option like --key=test-001
    filter = config.getoption("--key")
    if filter:
        new_items = []
        for item in items:
            mark = item.get_closest_marker("key")
            if mark and mark.args and mark.args[0] == filter:
                # collect all items that have a key marker with that value
                new_items.append(item)
        items[:] = new_items

现在你运行类似的东西

pytest --key=test-001

仅使用该标记属性运行测试。

请注意,这仍将显示收集的测试总数,但仅运行过滤后的测试。这是一个例子:

test_key.py

import pytest

@pytest.mark.key("test-001")
def test_simple1():
    pass

@pytest.mark.key("test-002")
def test_simple2():
    pass


@pytest.mark.key("test-001")
def test_simple3():
    pass

def test_simple4():
    pass

$ python -m pytest -v --key=test-001 test_key.py

...
collected 4 items

test_key.py::test_simple1 PASSED
test_key.py::test_simple3 PASSED
================================================== 2 passed in 0.26s ==================================================

【讨论】:

  • 正是我想要的一个很好的解释。谢谢
【解决方案2】:

您可以使用 -m 选项 c 运行 pytest

检查以下命令:

pytest -m 'test-001' <your test file>

【讨论】:

  • 运行我得到“收集 2 个项目 / 2 个取消选择”并且没有运行测试
  • pytest -m 使用标记名称,而不是标记值,例如pytest -m key 将使用标记 key 运行所有测试。您不能在此处指定标记属性值。
  • @MrBeanBremen 好的,我希望做的是类似pypi.org/project/pytest-jira/0.3.6 的事情,我有我的 Jira 密钥并将该密钥映射到测试。这样我就可以根据 Jira 密钥运行特定的测试。实现这一目标的最佳方法是什么?
猜你喜欢
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 2019-10-15
相关资源
最近更新 更多