使用标记收集py.test测试信息

8

我正在使用py.test,并且希望获取包含标记信息的测试列表。当我使用--collect-only标志时,我得到了测试函数。是否有一种方法也可以获取每个测试分配的标记?


根据Frank T的答案,我创建了一个解决方法代码示例:

from _pytest.mark import MarkInfo, MarkDecorator
import json


def pytest_addoption(parser):
    parser.addoption(
        '--collect-only-with-markers',
        action='store_true',
        help='Collect the tests with marker information without executing them'
    )


def pytest_collection_modifyitems(session, config, items):
    if config.getoption('--collect-only-with-markers'):
        for item in items:
            data = {}

            # Collect some general information
            if item.cls:
                data['class'] = item.cls.__name__
            data['name'] = item.name
            if item.originalname:
                data['originalname'] = item.originalname
            data['file'] = item.location[0]

            # Get the marker information
            for key, value in item.keywords.items():
                if isinstance(value, (MarkDecorator, MarkInfo)):
                    if 'marks' not in data:
                        data['marks'] = []

                    data['marks'].append(key)

            print(json.dumps(data))

        # Remove all items (we don't want to execute the tests)
        items.clear()

现在可以使用 markers = [mark.name for mark in item.iter_markers()] 检索标记。 - xverges
2个回答

5
我不认为pytest有内置的行为来列出测试函数以及这些测试的标记信息。一个--markers命令可以列出所有已注册的标记,但这不是你想要的。我简要查看了pytest插件列表,没有看到任何相关的内容。
您可以编写自己的pytest插件来列出测试和标记信息。这里是编写pytest插件的文档。
我建议尝试使用"pytest_collection_modifyitems"钩子。它传递了一个收集的所有测试列表,并且不需要修改它们。(这里所有钩子的列表)。
传递给该钩子的测试如果您知道要查找的标记的名称,则具有get_marker()方法(例如,请参见this code)。当我浏览该代码时,我无法找到官方API以列出所有标记。我发现以下内容可完成此工作:test.keywords.__dict__['_markers'](请参见herehere)。

谢谢您的建议,我根据它们创建了一个解决方案。 - László Ács

1

您可以通过 request.function.pytestmark 对象中的 name 属性找到标记。

@pytest.mark.scenarious1
@pytest.mark.scenarious2
@pytest.mark.scenarious3
def test_sample():
    pass

@pytest.fixture(scope='function',autouse=True)
def get_markers():
    print([marker.name for marker in request.function.pytestmark])

>>> ['scenarious3', 'scenarious2', 'scenarious1']

请注意,默认情况下它们是以相反的顺序列出的。

这将只选取函数标记,而非所有标记。 - Fruch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接