如何使用 pytest-html 在 HTML 中嵌入 base64 图像?

How to embed base64 image in HTML using pytest-html?

我正在使用 python-appium 客户端并在测试完成后生成 HTML 报告。我想在 HTML 报告中添加失败测试的嵌入式图像。嵌入图像的原因是我也可以从远程机器访问它。这是我尝试过但在另一个系统上不起作用但在本地有效的代码:

@pytest.mark.hookwrapper
def pytest_runtest_makereport(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):
        screenshot = driver.get_screenshot_as_base64()
        extra.append(pytest_html.extras.image(screenshot, ''))
    report.extra = extra

在我看来,编码图像生成不正确,因为这是我在输出 HTML 文件中看到的:

<td class="extra" colspan="4">
        <div class="image"><a href="assets/75870bcbdda50df90d4691fa21d5958b.png"><img src="assets/75870bcbdda50df90d4691fa21d5958b.png"/></a></div>

我希望"src"不要以“.png”结尾,它应该是一长串字符。我不知道如何解决这个问题。

您的代码是正确的。但是,pytest-html 的标准行为是即使您将图像作为 base64 字符串传递,它仍会在 assets 目录中存储一个文件。如果要在报表文件中嵌入资源,需要传入--self-contained-html选项:

$ pytest --html=report.html --self-contained-html

或将选项存储在 pytest.ini:

 # pytest.ini (or tox.ini or setup.cfg)
 [pytest]
 addopts = --self-contained-html

为了完整起见,这里是pytest-html readme中的相关位置:

Creating a self-contained report

In order to respect the Content Security Policy (CSP), several assets such as CSS and images are stored separately by default. You can alternatively create a self-contained report, which can be more convenient when sharing your results. This can be done in the following way:

$ pytest --html=report.html --self-contained-html

Images added as files or links are going to be linked as external resources, meaning that the standalone report HTML-file may not display these images as expected.

The plugin will issue a warning when adding files or links to the standalone report.