pytest集成失败图片到html中并添加用例描述

import pytest
from selenium import webdriver
from py._xmlgen import html

_driver = None
# 测试失败时添加截图和测试用例描述(用例的注释信息)

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """当测试失败的时候,自动截图,展示到html报告中"""
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_")+".png"
            screen_img = _capture_screenshot()
            if file_name:
                html = '<div><img src="https://img-blog.csdnimg.cn/2022010711192613967.png" alt="screenshot" style="width:600px;height:300px;" ' \
                       'οnclick="window.open(this.src)" align="right"/></div>' % screen_img
                extra.append(pytest_html.extras.html(html))
        report.extra = extra

def _capture_screenshot():
    '''截图保存为base64'''
    return _driver.get_screenshot_as_base64()

@pytest.fixture(scope='module')
def driver():
    global _driver
    print('------------open browser------------')
    _driver = webdriver.Firefox()

    yield _driver
    print('------------close browser------------')
    _driver.quit()

注意这个模块from py._xmlgen import html,网上看到大多数是使用 from py.xml import html,使用这个模块时会报错,所以换成现在这个模块了(估计和python版本有关系,用的3,3估计没有这个模块了)。

正常情况下,html报告是没有描述信息这一项的,所以我们只能通过添加代码来实现了(描述信息就是用例函数上方的注释信息)。通过官方的文档说明,我们知道是可以添加和删除报告的table表的
我们在上面的代码 report.extra = extra 后面添加这样一行代码

report.description = str(item.function.__doc__)

并在文件中添加这两个方法

@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.insert(1, html.th('Description'))

@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    cells.insert(1, html.td(report.description))

规则是在test_method下面用注释。
描述内容在用例下面直接用

‘’’ 描述 ‘’’

表示,报告中就会展示了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值