如何在python pytest html报告中包含屏幕截图

时间:2018-05-25 17:59:32

标签: python-2.7 selenium-webdriver pytest

当我在浏览器中点击以下网址" https://192.168.xx.xxx/Test/ScreenCapture" 我在浏览器中获得了测试设备屏幕的屏幕截图。

如何在我的pytest html测试报告中添加屏幕截图。 目前我使用下面的代码捕获指定的测试目录中的屏幕截图。

url = 'https://192.168.xx.xxx/Test/ScreenCapture'
driver.get(url)    driver.save_screenshot('/home/tests/screen.png')

我用以下命令运行我的pytest: py.test --html = report.html --self-contained-html screentest.py

2 个答案:

答案 0 :(得分:3)

从文档https://pypi.org/project/pytest-html/:您可以通过创建“额外”来为HTML报告添加详细信息

extra.image(image, mime_type='image/gif', extension='gif')

你需要勾拳。再次来自doc:

import pytest
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])
    if report.when == 'call':
        # always add url to report
        extra.append(pytest_html.extras.url('http://www.example.com/'))
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            # only add additional html on failure
            extra.append(pytest_html.extras.html('<div>Additional HTML</div>'))
        report.extra = extra

答案 1 :(得分:1)

我找到了一个自己找到解决方案的人(@ Vic152),这是原始帖子:https://github.com/pytest-dev/pytest-html/issues/186 关键是调用item.funcargs['request']以获取当前的测试请求上下文。

注意:如果像我一样使用Pytest 3.0+,请用getfuncargvalue()替换getfixturevalue()

我将代码复制到这里:

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):

    timestamp = datetime.now().strftime('%H-%M-%S')

    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])
    if report.when == 'call':

        feature_request = item.funcargs['request']

        driver = feature_request.getfuncargvalue('browser')
        driver.save_screenshot('D:/report/scr'+timestamp+'.png')

        extra.append(pytest_html.extras.image('D:/report/scr'+timestamp+'.png'))

        # always add url to report
        extra.append(pytest_html.extras.url('http://www.example.com/'))
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            # only add additional html on failure
            extra.append(pytest_html.extras.image('D:/report/scr.png'))
            extra.append(pytest_html.extras.html('<div>Additional HTML</div>'))
        report.extra = extra