自定义 pytest junitxml 失败报告

2024-04-28

我正在尝试内省测试失败并将附加数据包含到 junit xml 测试报告中。具体来说,这是对外部产品的一套功能测试,我想将产品的日志包含到故障报告中。

使用找到的方法here https://stackoverflow.com/questions/10754970/in-which-py-test-callout-can-i-find-both-item-and-report-data,我能够在执行多重调用之前将日志打印到标准输出,最终显示在詹金的失败报告中。但我确信有更好的方法来实现这一目标。

我尝试使用 pytest_runtest_logreport 挂钩将日志附加到“sections”属性中,该属性已经包含“捕获的标准输出”和“捕获的标准错误”流。但新添加的部分不会进入 xml 文件。我也直接在 pytest_runtest_makereport 挂钩中尝试了上述技术,得到了类似的结果。

pytest 2.7 的发行说明指出,2.8 中不再使用多重调用支持,并且 @pytest.mark.hookwrapper 是执行此操作的新方法,但我似乎根本无法使其工作 - “yield”返回None 而不是 CallOutcome 对象(在 makereport 挂钩中尝试过)。即使它返回了某些内容,我也不确定是否可以向其中添加会显示在 xml 报告中的内容。

我是否缺少任何功能可以让我以灵活的方式执行此操作? (灵活我的意思是:不绑定到标准输出或记录调用,如捕获日志插件)


编辑:由于我需要访问测试项目的 funcargs (和测试结果)以进行报告,因此我能够将逻辑移至pytest_runtest_makereport(item, __multicall__)钩。诀窍是执行多重调用,它返回报告对象:

@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
    report = __multicall__.execute()
    # then I was able to manipulate report and get the same results as below

布鲁诺的回答给了我更彻底地分析这个功能所需的动力:)

那么它的工作原理如下:

def pytest_runtest_logreport(report):
    if report.failed:
        report.longrepr.sections.append(("Header", "Message", "-"))
        report.sections.append(("Captured stdout", "This is added to stdout"))
        report.sections.append(("Captured stderr", "This is added to stderr"))
        report.sections.append(("Custom Section", "This can only be seen in the console - the xml won't have it."))

The longrepr属性仅在失败时可用。它采用一个三元组,最后一个值是用于装饰标题的装饰/包围的字符。它将出现在报告的“失败”部分:

----------------------------------- Header ------------------------------------
Message

自定义部分将创建额外的结果部分以打印到console。但他们不会进入 junitxml:

------------------------------- Custom Section --------------------------------
This can only be seen in the console - the xml won't have it.

junitxml 报告只有 2 个部分:out 和 err。要向其中添加自定义文本,您必须创建名为“Captured std”的部分,并且只有这些部分才会写入 xml 文件。任何其他名称都会产生一个仅在控制台中可见的自定义部分。

这是使用上面的代码生成的 junitxml,为了本文的目的进行了一些重新格式化:

<?xml version="1.0" encoding="utf-8" ?> 
<testsuite errors="0" failures="1" name="pytest" skips="0" tests="1" time="0.646">
  <testcase classname="test_reporting" name="test_fail" time="0.000999927520752">
    <failure message="test failure">
      @ut def test_fail(): > assert 0, "It failed"
      E AssertionError: It failed 
      E assert 0 test_reporting.py:346: AssertionError
      ----------------------------------- Header ------------------------------------
      Message
    </failure> 
    <system-out>This is added to stdout</system-out> 
    <system-err>This is added to stderr</system-err> 
  </testcase>
</testsuite>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自定义 pytest junitxml 失败报告 的相关文章

随机推荐