将属性添加到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)

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

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

注意:xunit2不支持record_xml_attribute,xunit2是pytest v6的默认junit_file。要将record_xml_attribute与pytest v6一起使用,请在pytest.ini中设置

[pytest]
junit_family = xunit1

最新更新