将屏幕截图添加到 pytest-html 报告

问题描述 投票:0回答:1

我使用以下代码在 pytest-html 报告中添加屏幕截图,它没有给出任何错误,但运行代码后

.png
文件为空。

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
    :param item:
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_") + ".png"
            _capture_screenshot(file_name)
            if file_name:
                html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % file_name
                extra.append(pytest_html.extras.html(html))
        report.extra = extra


def _capture_screenshot(name):
    driver.get_screenshot_as_file(name)


@pytest.fixture(scope='session', autouse=True)
def browser():
    global driver
    if driver is None:
        driver = webdriver.Chrome()
    return driver

enter image description here

python pytest pytest-html
1个回答
0
投票

使用 Allure Report 截屏可能会更容易。

开箱即用,它提供了 Selenium 在测试失败时自动截取屏幕截图的链接。

默认 Selenium 屏幕截图

任意时间截图是这样完成的:

import allure
from allure_commons.types import AttachmentType

def _capture_screenshot(name):
    png = driver.get_screenshot_as_png()
    allure.attach(body=png, name=name, attachment_type=AttachmentType.PNG, extension='.png')

最后,要自动截取测试失败的屏幕截图,您自己的钩子可以这样修改:

@pytest.mark.hookwrapper
def pytest_runtest_makereport():
    """
    Extends the PyTest Plugin to take and embed screenshot in allure report, whenever test fails.
    """
    outcome = yield
    report = outcome.get_result()

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_") + ".png"
            _capture_screenshot(browser.config.driver, file_name)

这更短且不易出错。结果报告如下所示:

通过钩子添加屏幕截图

如果您决定走那条路,您需要

  1. 在您的系统上安装Allure
  2. 在项目中安装 python 解释器的 allure-pytest 集成。

对于第二部分,您可以按照此处的说明进行操作。或者,您可以从 Allure Start 下载一个预配置的空项目,其中 pytest 和 allure 可以开箱即用。

© www.soinside.com 2019 - 2024. All rights reserved.