pytest添加运行失败截图和使用自定义的css

1|0pytest添加运行失败截图


在conftest.py中,定义截图的方法,失败时自动截图,并将截图保存到html页面中

from common.base_driver import BaseDriver import pytest driver = None #失败自动截图,展示到html报告中 @pytest.mark.hookwrapper def pytest_runtest_makereport(item): 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="data:image/png;base64,%s" alt="screenshot" style="width:600px;height:300px;" ' \ 'onclick="window.open(this.src)" align="right"/></div>' % screen_img extra.append(pytest_html.extras.html(html)) report.extra = extra #截图保存为base_64,展示在html中 def _capture_screenshot(): return driver.get_screenshot_as_base64() #定义公共的fixture @pytest.fixture def common_driver(): global driver driver = BaseDriver().base_driver() yield driver driver.close_app() driver.quit() #定义含有toast弹框的fixture @pytest.fixture def common_toast_driver(): global driver driver = BaseDriver().base_driver(automationName="UIAutomator2") yield driver driver.close_app() driver.quit()

注意的是fixture修饰的方法中,不要忘了global driver

运行之后显示测试报告的图片是宽度和高度过大,导致图片比较难看,因此我们需要优化下

2|0自定义css


在html_reports目录下定义一个assets目录,在目录下将pytest-html插件源码中的style.css拷贝到assets下

使用F12查看报告的图片的位置,是在class="extra"下的img目录中

修改style.css,为了让这个样式优先级最高,加入!import

.extra div div img { width: 300px!important; height: 500px!important; }

修改main.py,使用--css, style.css路径--self-contained-html(这个表示将我们定义的css样式合并到html页面中)

import pytest import time from common.conf_dir import html_reports_dir cur_time = time.strftime("%Y-%m-%d_%H-%M-%S") pytest.main([ #"--reruns=1", #"--reruns-delay=10", "-m", "fail", "--junitxml", f"{html_reports_dir}/autotest_report_{cur_time}.xml", "--html", f"{html_reports_dir}/autotest_report_{cur_time}.html", "--css", f"{html_reports_dir}/assets/style.css", "--self-contained-html"] )

3|0最终效果


这次报告看起来美观多了~

4|0参考文章


《pytest文档8-html报告报错截图+失败重跑》
《pytest 之 pytest-html生成html报告》


__EOF__

本文作者cnhkzyy
本文链接https://www.cnblogs.com/my_captain/p/12728012.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   cnhkzyy  阅读(588)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示