如何使用selenium和pytest将屏幕截图添加到pytest-html插件生成的html报告中?

问题描述

我正在尝试将失败测试的屏幕截图添加到pytest-html插件生成的html报告,pytest库中。我遵循了How do I include screenshot in python pytest html report。但是我总是以以下错误告终。

发生错误

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

我的代码有什么问题?如何在失败的测试用例上附加屏幕截图?

解决方法

您的 conftest.py 上应该有一个带有请求参数的装置,特别是您的驱动程序。

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