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

标签 pytest python-appium 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 中存储一个文件目录。如果要将 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.

关于pytest - 如何使用 pytest-html 在 HTML 中嵌入 base64 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50804524/

相关文章:

python - Atlassian Bamboo 如何识别 python pytest 报告

python - 使用 Flask 进行 pytest 无法找到模块

python - pytest 找不到 pytest.fixture_request

python - 失败 : Database access not allowed, 使用 "django_db"标记,或 "db"或 "transactional_db"装置启用它

java - 启动appium浏览器时出错:- org. openqa.selenium.WebDriverException : ERROR running Appium command: Arguments to path.解析必须是字符串

appium - Appium/Python 的云测试服务?

python - pytest - 将值从一个测试函数传递到测试文件中的另一个

android - 使用 appium 和 python 的 android 应用程序的功能测试

python-3.x - 使用 pytest 禁用在控制台上打印日志输出