首页 > 解决方案 > 将属性添加到junit xml pytest

问题描述

我正在尝试使用自定义属性在 pytest 中创建一个 junit xml 输出文件。我搜索了答案并找到了有关 xml_record_attribute 和 record_attribute 的信息。

def test(record_attribute):
    record_attribute('index', '15')
    ...

起初我认为它适合我的问题,但后来我意识到它需要在每个测试中指定。

我尝试使用 pytest_runtest_call 钩子来做到这一点,因此它会在每次测试运行中添加属性,而无需在每次测试中显式添加属性。但后来发现你不能在钩子中使用固定装置(这是有道理的)。

知道如何在不复制代码的情况下向 junit xml 输出文件添加属性吗?

编辑:我有另一个想法,那就是有一个装饰器来做到这一点。

def xml_decorator(test):
    def runner(xml_record_attribute):
        xml_record_attribute('index', '15')
        test()

    reutrn runner

我正在尝试将它与 pytest_collection_modifyitems 挂钩并装饰每个测试,但它不起作用。

def pytest_collection_modifyitems(session, config, items):
    for item in items:
        item.obj = xml_decorator(item.obj)

标签: python-3.xxmljunitpytest

解决方案


您可以定义一个自动提供给每个测试用例的夹具:

import pytest

@pytest.fixture(autouse=True)
def record_index(record_xml_attribute):
    record_xml_attribute('index', '15')

注意record_xml_attributexunit2 不支持,pytest v6 的默认 junit_family。要record_xml_attribute与 pytest v6 一起使用,在pytest.iniset

[pytest]
junit_family = xunit1

推荐阅读