如何使用junitxml在pytest中收集数据结果?

Jak*_*cki 5 python xml pytest

让我们使用以下代码(conftest.py):

import random
def test_val():
    value = random.random()
    assert value < 0.5
Run Code Online (Sandbox Code Playgroud)

运行py.test --junitxml=result.xml conftest.py生成result.xml(通过测试时):

<?xml version="1.0" encoding="utf-8"?>
<testsuite errors="0" failures="0" name="" skips="0" tests="1" time="0.047">
<testcase classname="conftest" name="test_val" time="0.0"/>
</testsuite>
Run Code Online (Sandbox Code Playgroud)

现在。我想做的就是存储test_val()in 生成的值results.xml。有办法吗?我似乎在pytest doc中找不到任何相关内容

Kon*_*rdź 6

多年过去了,最好的解决方案应该被记录下来。

来自 Pytest 的record_property固定装置文档:

向调用测试添加额外的属性。

用户属性成为测试报告的一部分,可供配置的报告器使用,如 JUnit XML。

该装置可通过名称、值进行调用。该值自动进行 XML 编码。

捕获通过和失败案例的属性。

套房:

def test_passes(record_property):
    record_property("key", "value1")
    assert 1 == 1


def test_fails(record_property):
    record_property("key", "value2")
    assert 1 == 2
Run Code Online (Sandbox Code Playgroud)

pytest运行时的结果--junitxml=result.xml

生成的Junit测试报告:

<?xml version="1.0" encoding="utf-8"?>
<testsuites>
    <testsuite name="pytest" errors="0" failures="1" skipped="0" tests="2" time="0.085"
               timestamp="2021-04-12T14:25:09.900867" hostname="DESKTOP">
        <testcase classname="test_something" name="test_passes" time="0.001">
            <properties>
                <property name="key" value="value1"/>
            </properties>
        </testcase>
        <testcase classname="test_something" name="test_fails" time="0.001">
            <properties>
                <property name="key" value="value2"/>
            </properties>
            <failure message="assert 1 == 2">record_property = &lt;function record_property.&lt;locals&gt;.append_property
                at 0x000001A1A9EB40D0&gt;

                def test_fails(record_property):
                record_property("key", "value2")
                &gt; assert 1 == 2
                E assert 1 == 2

                test_something.py:8: AssertionError
            </failure>
        </testcase>
    </testsuite>
</testsuites>
Run Code Online (Sandbox Code Playgroud)

如果您运行的 Pytest 版本相当新,您将看到弃用警告

test_something.py::test_fails
  test_something.py:6: PytestWarning: record_property is incompatible with junit_family 'xunit2' (use 'legacy' or 'xunit1')
    def test_fails(record_property):
Run Code Online (Sandbox Code Playgroud)

这是因为 Xunit 报告的架构已更改。来自 Pytest变更日志

  • record_property 现在与 junit_family=xunit2 一起使用时发出 PytestWarning:固定装置生成属性标签作为测试用例的子级,根据最新的架构,这是不允许的 <https://github.com/jenkinsci/xunit-plugin/blob/master /

要克服警告,您可以:

  1. 使用覆盖标志运行 Pytest-o junit_family="xunit1"或将此属性放在pytest.ini

  2. 使用record_testsuite_property会话范围的固定装置。尽管如此,这仅允许将属性附加到测试套件级别。


小智 5

附带的 junitxml 插件没有添加此类数据的钩子,但您可以将其打印到 stdout,因为它会添加到 junitxml 数据中。

所以只要打印出日志你至少就能知道数据。