收集和报告pytest测试结果

14

我正在使用pytest进行一些Selenium测试。下一步是开始做一些报告。我想编写一些代码,能够运行测试、收集结果并发送电子邮件。到目前为止,我发现最接近此功能的方法是将测试结果写入结果日志文件,然后使用插件检查存在状态并从那里发送电子邮件。这种方法虽然可行,但略显麻烦,我希望有更优雅的方式来实现这个目标。虽然整个pytest文档很棒,但插件文档相对较差 - 我甚至找不到pytest_sessionfinish,尽管它似乎可以工作。

import pytest

class MyPlugin:
    def pytest_sessionfinish(self, exitstatus):
        if exitstatus == 0:
            #Send success email
            pass
        else: 
            #Read output.txt
            #Add output.txt to email body
            #Send email
            pass

pytest.main("--resultlog=output.txt", plugins=[MyPlugin()])

Q: 如何以最佳方式运行和收集pytest的结果?


5个回答

10

生成结果报告的一种简单方法是在运行测试时使用pytest选项--junitxml。 pytest将以JUnit格式生成测试报告。

由于JUnit被广泛使用,因此很容易找到解析报告并生成一些漂亮输出(如HTML报告)的工具。据我所知,Jenkins上有一些插件可以很好地解析JUnit报告并提供漂亮的报告。

有关更多信息,请参阅pytest文档中的'创建JUnitXML格式文件'部分

除此之外,当您可以访问pytest对象请求或配置时,pytest还提供了扩展JUnit XML报告的方法:

if hasattr(request.config, "_xml"):
    request.config._xml.add_custom_property(name, value)

如果在测试用例中,pytest提供了一个fixture来实现这个功能:

def test_function(record_xml_property):
    record_xml_property("key", "value")
    assert 0

这将向JUnit XML报告添加自定义属性。


你是如何/在哪里访问request对象的? 你是在pytest_runtest_logreport中完成的吗? - malhar
1
pytest文档中不再包含所提到的部分链接。请使用https://pytest.org/en/latest/how-to/output.html#creating-junitxml-format-files?替换它。 - Samuel Verschelde

10

1
Allure的链接已更改:https://docs.qameta.io/allure-report/ - NSVR

10

安装pytest-html,然后使用--html=pytest_report.html选项运行测试。


7
而且,在执行操作时,请使用“--self-contained-html”选项生成一个单独的HTML文件,你可以将其加载到浏览器中查看结果。 - Jeff Wright

2
另一种创建报告的方法是首先将结果收集为字典或数据框,然后按照您的喜好处理它(编写CSV等)。如果您希望采用这种方法,可以使用pytest-harvest。只需安装它,就可以直接使用预定义的固定装置:
import pytest
import time

@pytest.mark.parametrize('p', ['world', 'self'], ids=str)
def test_foo(p):
    """
    A dummy test, parametrized so that it is executed twice
    """
    print('\n   hello, ' + p + ' !')
    time.sleep(len(p) / 10)

def test_synthesis(module_results_df):
    """
    Shows that the `module_results_df` fixture already contains what you need
    """
    # drop the 'pytest_obj' column
    module_results_df.drop('pytest_obj', axis=1, inplace=True)

    print("\n   `module_results_df` dataframe:\n")
    print(module_results_df)

产生收益/产量。
>>> pytest -s -v

============================= test session starts =============================
...
collecting ... collected 3 items
test_basic.py::test_foo[world] 
   hello, world !
PASSED
test_basic.py::test_foo[self] 
   hello, self !
PASSED
test_basic.py::test_synthesis 
   `module_results_df` dataframe:

                 status  duration_ms      p
test_id                                    
test_foo[world]  passed   500.028610  world
test_foo[self]   passed   400.022745   self
PASSED

========================== 3 passed in 0.05 seconds ===========================

你也可以从 'dict' fixture 开始,其中包含有关设置/拆卸时间的更多详细信息,并使用提供的辅助方法将其转换为数据帧。 有关详细信息,请参阅文档。
最后,如果您还希望使用参数、夹具、步骤等,您可能希望查看此 数据科学基准示例
顺便说一下,我是作者 ;)

我对使用这个库很感兴趣。但是我在理解如何使用它方面遇到了一些困难。我已经安装了它,但是无法使用例如module_results_dct之类的东西而不导入其他内容。示例表明这应该是不必要的。我可能做错了什么。很抱歉以这种方式发送消息,但我试图私下发送消息给您却没有成功。 - Andrew Falanga
1
顺便说一下,@AndrewFalanga的问题已经解决了:https://github.com/smarie/python-pytest-harvest/issues/37 - smarie

1
我发现pytest-json-report非常有用,可以生成pytest报告。
它会创建一个包含所有数据的json文件,然后您可以将其推送到数据仓库中。相比于pytest-html,它需要更多的设置,但我发现这种灵活性是值得的。
我写了一篇关于如何使用pytest-json-report、snowflake和一个工程友好的BI工具Visivo.io构建流水线的中等文章。
文章链接:https://medium.com/@jared_86317/visualizing-pytest-results-with-the-modern-data-stack-29daeab99b66 一旦您的仪表板流水线运行起来,设置电子邮件提醒、额外报告等都非常容易。

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