收集并报告pytest结果

use*_*775 2 python pytest selenium-webdriver

我正在通过pytest做一些硒测试。下一步是开始进行一些报告。我想写点东西,让我可以运行测试,收集结果并发送电子邮件。到目前为止,我发现与此最接近的事情是将测试结果写到结果日志中,然后使用插件来检查存在状态并从那里发送电子邮件。这可行,但是有点麻烦,我希望有一种更优雅的方法。尽管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()])
Run Code Online (Sandbox Code Playgroud)

问:从pytest运行并收集结果的最佳方法是什么?


bra*_*ada 11

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

  • 当您执行此操作时,使用“--self-contained-html”选项生成一个 HTML 文件,您可以将其加载到浏览器中以查看结果。 (8认同)

小智 10

如果您想实现报告,Pytest 有许多简单的现成解决方案。以下是其中一些:


Li *_*eng 5

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

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

访问https://pytest.org/latest/usage.html并参考“创建JUnitXML格式文件”部分。

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

if hasattr(request.config, "_xml"):
    request.config._xml.add_custom_property(name, value)
Run Code Online (Sandbox Code Playgroud)

如果在测试用例中,pytest提供了一种夹具来做到这一点:

def test_function(record_xml_property):
    record_xml_property("key", "value")
    assert 0
Run Code Online (Sandbox Code Playgroud)

这会将自定义属性添加到JUnit XML报表中。