How to add screenshots to html reports generated by pytest-html plugin using selenium and pytest?

2.2k views Asked by At

I am trying to add screenshots of failed tests to html reports generated by pytest-html plugin,pytest libraries.I followed this How do I include screenshot in python pytest html report. However i always ended up with the below error.

Error occuring:

feature_request = item.funcargs['request']
KeyError: 'request'

conftest.py

import pytest
from datetime import datetime
from selenium import webdriver
import pytest_html

@pytest.hookimpl(hookwrapper=True)
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.getfixturevalue('browser')
        driver.save_screenshot('Screenshots/scr' + timestamp + '.png')
        extra.append(pytest_html.extras.image('Screenshots/scr' + timestamp + '.png'))
        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('Screenshots/scr.png'))
            extra.append(pytest_html.extras.html('<div>Additional HTML</div>'))
        report.extra = extra

@pytest.fixture(scope='session')
def setup():
    print('Starting')
    url = 'https://www.google.com/'
    driver = webdriver.Firefox()
    driver.get(url)
    return driver
    

test_google.py

class Test_One():
    def test_login(setup):
        print('Opend google')
        assert False

Whats wrong with my code ? how can i append screenshot on failed test cases ?

1

There are 1 answers

0
Yogi Galvez On

you should have a fixture with request argument on your conftest.py, specifically your driver.

@pytest.fixture(scope='session')
def setup(request):
then use driver = feature_request.getfixturevalue('setup') #referencing your def setup