在Jenkins代理上运行测试时如何使用Selenium捕获屏幕截图

时间:2018-06-21 21:48:52

标签: python selenium jenkins selenium-webdriver pytest

现在,我正在使用pytest和硒在Jenkins上运行测试。当我在本地运行以下代码时,它会在每次测试后创建一个屏幕截图,效果很好。

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    if 'selenium' not in item.fixturenames or 'selenium' not in item.funcargs:
        return

    driver = item.funcargs['selenium']
    extra = getattr(report, 'extra', [])
    if report.when == 'call' or report.when == "setup":
        extra.append(pytest_html.extras.url(driver.current_url, name = "Go To URL Tested"))
        if not report.skipped:
            report_directory = os.path.dirname(item.config.option.htmlpath)
            file_name = f"{item.originalname}.png"
            screenshot_was_saved = driver.get_screenshot_as_file(f"{report_directory}\\{file_name}")
            if file_name:
                report.screenshot = html.a(html.img(src = file_name, onclick = "window.open(this.src)", align = "right", style = "max-height: 150px;"), href = "#")
        report.extra = extra

但是,当我在Jenkins的构建管道中运行相同的代码时,不会创建图像。从get_screenshot_as_file方法返回的值是False。没有异常返回并且测试通过。 Jenkins代理有权写入文件,因为已创建要转储到HTML报表的目录。报告的index.html也会被创建。除了图像,其他所有内容都在那里。

有人有这样的经历吗?我什至尝试以无头模式运行chrome驱动程序,但这没有什么不同。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这对我有用

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    """
    Extends the PyTest Plugin to take and embed screenshots in html report, whenever test fails.
    :param item:
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call':
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            report_directory = os.path.dirname(item.config.option.htmlpath)
            file_name = str(int(round(time.time() * 1000))) + ".png"
            # full_path = os.path.join("C:\Screenshots", file_name)
            full_path = os.path.join(report_directory, file_name)
            if item.funcargs.get('driver'):
                print(f"[INFO] screenshot: {full_path}")
                item.funcargs['driver'].get_screenshot_as_file(full_path)
                if file_name:
                    html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
                           'onclick="window.open(this.src)" align="right"/></div>' % file_name
                    extra.append(pytest_html.extras.html(html))
        report.extra = extra