2
votes

When I hit the below url in browser "https://192.168.xx.xxx/Test/ScreenCapture" I get the screenshot of the device screen under test in the browser.

How do I add the screenshot in my pytest html test report. Currently I am using below code which captures screen shot in the test directory specified.

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

I am running my pytest with below command : py.test --html=report.html --self-contained-html screentest.py

2

2 Answers

3
votes

From the documentation https://pypi.org/project/pytest-html/: You can add details to the HTML reports by creating an ‘extra’

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

You need to make a hook. Again from 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
votes

I found one who found a solution by himself(@Vic152), here's the original post:https://github.com/pytest-dev/pytest-html/issues/186 The key is to call item.funcargs['request'] to get current test request context.

Note: if you use Pytest 3.0+ like me, replace getfuncargvalue() with getfixturevalue()

I copy the code here:

@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