pytest使用allure测试报告

🍅 点击文末小卡片,免费获取软件测试全套资料,资料在手,涨薪更快

选用的项目为Selenium自动化测试Pytest框架实战,在这个项目的基础上说allure报告。

allure安装

首先安装python的allure-pytest包

pip install allure-pytest

然后安装allure的command命令行程序

MacOS直接使用homebrew工具执行 brew install allure 即可安装,不用配置下载包和配置环境

在GitHub下载安装程序https://github.com/allure-framework/allure2/releases

但是由于GitHub访问太慢,我已经下载好并放在了群文件里面

下载完成后解压放到一个文件夹。我的路径是D:\Program Files\allure-2.13.3

然后配置环境变量: 在系统变量path中添加D:\Program Files\allure-2.13.3\bin,然后确定保存。

打开cmd,输入allure,如果结果显示如下则表示成功了:

C:\Users\hoou>allureUsage: allure [options] [command] [command options]Options:--helpPrint commandline help.-q, --quietSwitch on the quiet mode.Default: false-v, --verboseSwitch on the verbose mode.Default: false--versionPrint commandline version.Default: falseCommands:generate      Generate the reportUsage: generate [options] The directories with allure resultsOptions:-c, --cleanClean Allure report directory before generating a new one.Default: false--configAllure commandline config path. If specified overrides values from--profile and --configDirectory.--configDirectoryAllure commandline configurations directory. By default usesALLURE_HOME directory.--profileAllure commandline configuration profile.-o, --report-dir, --outputThe directory to generate Allure report into.Default: allure-reportserve      Serve the reportUsage: serve [options] The directories with allure resultsOptions:--configAllure commandline config path. If specified overrides values from--profile and --configDirectory.--configDirectoryAllure commandline configurations directory. By default usesALLURE_HOME directory.-h, --hostThis host will be used to start web server for the report.-p, --portThis port will be used to start web server for the report.Default: 0--profileAllure commandline configuration profile.open      Open generated reportUsage: open [options] The report directoryOptions:-h, --hostThis host will be used to start web server for the report.-p, --portThis port will be used to start web server for the report.Default: 0plugin      Generate the reportUsage: plugin [options]Options:--configAllure commandline config path. If specified overrides values from--profile and --configDirectory.--configDirectoryAllure commandline configurations directory. By default usesALLURE_HOME directory.--profileAllure commandline configuration profile.

allure初体验

改造一下之前的测试用例代码

#!/usr/bin/env python3# -*- coding:utf-8 -*-import reimport pytestimport allurefrom utils.logger import logfrom common.readconfig import inifrom page_object.searchpage import SearchPage@allure.feature("测试百度模块")class TestSearch:@pytest.fixture(scope='function', autouse=True)def open_baidu(self, drivers):"""打开百度"""search = SearchPage(drivers)search.get_url(ini.url)@allure.story("搜索selenium结果用例")def test_001(self, drivers):"""搜索"""search = SearchPage(drivers)search.input_search("selenium")search.click_search()result = re.search(r'selenium', search.get_source)log.info(result)assert result@allure.story("测试搜索候选用例")def test_002(self, drivers):"""测试搜索候选"""search = SearchPage(drivers)search.input_search("selenium")log.info(list(search.imagine))assert all(["selenium" in i for i in search.imagine])if __name__ == '__main__':pytest.main(['TestCase/test_search.py', '--alluredir', './allure'])os.system('allure serve allure')

然后运行一下:

注意:如果你使用的是pycharm编辑器,请跳过该运行方式,直接使用.bat或.sh的方式运行

***------------------------------- generated html file: file://C:\Users\hoou\PycharmProjects\web-demotest\report.html -------------------------------- Results (12.97s):2 passedGenerating report to temp directory...Report successfully generated to C:\Users\hoou\AppData\Local\Temp\112346119265936111\allure-reportStarting web server...2020-06-18 22:52:44.500:INFO::main: Logging initialized @1958ms to org.eclipse.jetty.util.log.StdErrLogServer started at <http://172.18.47.241:6202/>. Press <Ctrl+C> to exit

命令行会出现如上提示,接着浏览器会自动打开:

点击左下角En即可选择切换为中文。

是不是很清爽很友好,比pytest-html更舒服。

allure装饰器介绍

报告的生成和展示
刚才的两个命令:

生成allure原始报告到report/allure目录下,生成的全部为json或txt文件。

pytest TestCase/test_search.py --alluredir ./allure

在一个临时文件中生成报告并启动浏览器打开

allure serve allure

但是在关闭浏览器之后这个报告就再也打不开了。不建议使用这种。

所以我们必须使用其他的命令,让allure可以指定生成的报告目录。

我们在项目的根目录中创建run_case.py文件,内容如下:

#!/usr/bin/env python3# -*- coding:utf-8 -*-import sysimport subprocessWIN = sys.platform.startswith('win')def main():"""主函数"""steps = ["venv\\Script\\activate" if WIN else "source venv/bin/activate","pytest --alluredir allure-results --clean-alluredir","allure generate allure-results -c -o allure-report","allure open allure-report"]for step in steps:subprocess.run("call " + step if WIN else step, shell=True)if __name__ == "__main__":main()

命令释义:

1、使用pytest生成原始报告,里面大多数是一些原始的json数据,加入--clean-alluredir参数清除allure-results历史数据。

pytest --alluredir allure-results --clean-alluredir

--clean-alluredir 清除allure-results历史数据

2、使用generate命令导出HTML报告到新的目录

allure generate allure-results -o allure-report

-c 在生成报告之前先清理之前的报告目录

-o 指定生成报告的文件夹

3、使用open命令在浏览器中打开HTML报告

allure open allure-report

好了我们运行一下该文件。

Results (12.85s):2 passedReport successfully generated to c:\Users\hoou\PycharmProjects\web-demotest\allure-reportStarting web server...2020-06-18 23:30:24.122:INFO::main: Logging initialized @260ms to org.eclipse.jetty.util.log.StdErrLogServer started at <http://172.18.47.241:7932/>. Press <Ctrl+C> to exit

可以看到运行成功了。

在项目中的allure-report文件夹也生成了相应的报告。

allure发生错误截图

上面的用例全是运行成功的,没有错误和失败的,那么发生了错误怎么样在allure报告中生成错误截图呢,我们一起来看看。

首先我们先在config/conf.py文件中添加一个截图目录和截图文件的配置。

+++class ConfigManager(object):...@propertydef screen_path(self):"""截图目录"""screenshot_dir = os.path.join(self.BASE_DIR, 'screen_capture')if not os.path.exists(screenshot_dir):os.makedirs(screenshot_dir)now_time = dt_strftime("%Y%m%d%H%M%S")screen_file = os.path.join(screenshot_dir, "{}.png".format(now_time))return now_time, screen_file...+++

然后我们修改项目目录中的conftest.py:

#!/usr/bin/env python3# -*- coding:utf-8 -*-import base64import pytestimport allurefrom py.xml import htmlfrom selenium import webdriverfrom config.conf import cmfrom common.readconfig import inifrom utils.times import timestampfrom utils.send_mail import send_reportdriver = None@pytest.fixture(scope='session', autouse=True)def drivers(request):global driverif driver is None:driver = webdriver.Chrome()driver.maximize_window()def fn():driver.quit()request.addfinalizer(fn)return driver@pytest.hookimpl(hookwrapper=True)def pytest_runtest_makereport(item):"""当测试失败的时候,自动截图,展示到html报告中:param item:"""pytest_html = item.config.pluginmanager.getplugin('html')outcome = yieldreport = outcome.get_result()report.description = str(item.function.__doc__)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):screen_img = _capture_screenshot()if screen_img:html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:1024px;height:768px;" ' \'onclick="window.open(this.src)" align="right"/></div>' % screen_imgextra.append(pytest_html.extras.html(html))report.extra = extradef pytest_html_results_table_header(cells):cells.insert(1, html.th('用例名称'))cells.insert(2, html.th('Test_nodeid'))cells.pop(2)def pytest_html_results_table_row(report, cells):cells.insert(1, html.td(report.description))cells.insert(2, html.td(report.nodeid))cells.pop(2)def pytest_html_results_table_html(report, data):if report.passed:del data[:]data.append(html.div('通过的用例未捕获日志输出.', class_='empty log'))def pytest_html_report_title(report):report.title = "pytest示例项目测试报告"def pytest_configure(config):config._metadata.clear()config._metadata['测试项目'] = "测试百度官网搜索"config._metadata['测试地址'] = ini.urldef pytest_html_results_summary(prefix, summary, postfix):# prefix.clear() # 清空summary中的内容prefix.extend([html.p("所属部门: XX公司测试部")])prefix.extend([html.p("测试执行人: 随风挥手")])def pytest_terminal_summary(terminalreporter, exitstatus, config):"""收集测试结果"""result = {"total": terminalreporter._numcollected,'passed': len(terminalreporter.stats.get('passed', [])),'failed': len(terminalreporter.stats.get('failed', [])),'error': len(terminalreporter.stats.get('error', [])),'skipped': len(terminalreporter.stats.get('skipped', [])),# terminalreporter._sessionstarttime 会话开始时间'total times': timestamp() - terminalreporter._sessionstarttime}print(result)if result['failed'] or result['error']:send_report()def _capture_screenshot():"""截图保存为base64"""now_time, screen_file = cm.screen_pathdriver.save_screenshot(screen_file)allure.attach.file(screen_file,"失败截图{}".format(now_time),allure.attachment_type.PNG)with open(screen_file, 'rb') as f:imagebase64 = base64.b64encode(f.read())return imagebase64.decode()

来看看我们修改了什么:

我们修改了_capture_screenshot函数

在里面我们使用了webdriver截图生成文件,并使用allure.attach.file方法将文件添加到了allure测试报告中。

并且我们还返回了图片的base64编码,这样可以让pytest-html的错误截图和allure都能生效。

运行一次得到两份报告,一份是简单的一份是好看内容丰富的。

现在我们在测试用例中构建一个预期的错误测试一个我们的这个代码。

修改test_002测试用例

        assert not all(["selenium" in i for i in search.imagine])

运行一下:

可以看到allure报告中已经有了这个错误的信息。

再来看看pytest-html中生成的报告:

可以看到两份生成的报告都附带了错误的截图,真是鱼和熊掌可以兼得呢。

好了,到这里可以说allure的报告就先到这里了,以后发现allure其他的精彩之处我再来分享。

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于做【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!凡事要趁早,特别是技术行业,一定要提升技术功底。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/97459.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/97459.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PortSwigger靶场之SQL injection with filter bypass via XML encoding通关秘籍

一、题目分析该实验室的库存查询功能存在 SQL 注入漏洞。查询结果为这些信息会出现在应用程序的响应中&#xff0c;因此您可以利用“联合”攻击来从其他表中获取数据。该数据库中有一个“用户”表&#xff0c;该表包含了已注册用户的用户名和密码。要解决&#xff0c;需进行一次…

Cocos游戏中自定义按钮组件(BtnEventComponent)的详细分析与实现

概述在Cocos游戏开发中&#xff0c;按钮交互是用户界面中最基础且重要的组成部分。原生的Cocos Button组件虽然功能完善&#xff0c;但在复杂的游戏场景中往往无法满足多样化的交互需求。本文将详细分析一个功能强大的按钮组件BtnEventComponent&#xff0c;它提供了多种交互模…

终于完成William F. Egan所著的Practical RF System Design的中文版学习资料

终于完成William F. Egan所著的Practical RF System Design的中文版学习资料 该文档聚焦RF系统的分析与设计。书中先介绍系统设计流程、书籍结构及工具&#xff08;如电子表格、测试与仿真&#xff09;&#xff0c;接着围绕RF系统关键参数展开&#xff1a;讲解增益计算&#xf…

嵌入式Linux驱动开发:蜂鸣器驱动

嵌入式Linux驱动开发&#xff1a;蜂鸣器驱动 1. 引言 本文档详细记录了基于i.MX6ULL处理器的蜂鸣器驱动开发过程。内容涵盖驱动的理论基础、代码实现、设备树配置以及用户空间应用程序的编写。本文档严格遵循用户提供的代码和文档&#xff0c;确保理论与实践的紧密结合。本文档…

Qt中的锁和条件变量和信号量

Qt中的锁和条件变量和信号量 C11中引入智能指针用来解决锁忘记释放的问题 代码如下&#xff1a; void Thread::run() {for(int i0;i<50000;i){QMutexLocker locker(&mutex);//mutex.lock();num;//mutex.unlock();} }大括号结束的时候&#xff0c;生命周期踩结束&#xf…

智能电视MaxHub恢复系统

公司的MaxHub智能电视又出故障了。 去年硬件故障返厂&#xff0c;花了8600多元。 这次看上去是软件故障。开机后蓝屏报错。 按回车键&#xff0c;电视重启。 反复折腾几次&#xff0c;自行修复执行完毕&#xff0c;终于可以进入系统了。 只不过进入windows10后&#xff0c;图…

TensorFlow 面试题及详细答案 120道(71-80)-- 性能优化与调试

《前后端面试题》专栏集合了前后端各个知识模块的面试题,包括html,javascript,css,vue,react,java,Openlayers,leaflet,cesium,mapboxGL,threejs,nodejs,mangoDB,SQL,Linux… 。 前后端面试题-专栏总目录 文章目录 一、本文面试题目录 71. 如何优化TensorFlow模…

数据结构 第三轮

以看严蔚敏老师的教材为主&#xff0c;辅以其他辅导书&#xff1a;王道&#xff0c;新编数据结构&#xff0c;学校讲义 线性结构&#xff1a;线性表、串、队列、栈、数组和广义表 树形结构、网状结构&#xff1a;图 查找、排序 动态内存管理和文件 绪论 8-29 数据&#xf…

[新启航]新启航激光频率梳 “光量子透视”:2μm 精度破除遮挡,完成 130mm 深孔 3D 建模

摘要&#xff1a;本文介绍新启航激光频率梳的 “光量子透视” 技术&#xff0c;该技术凭借独特的光量子特性与测量原理&#xff0c;以 2μm 精度破除深孔遮挡&#xff0c;成功完成 130mm 深孔的 3D 建模&#xff0c;为深孔三维形态的精确获取提供了创新解决方案&#xff0c;推动…

MongoDB /redis/mysql 界面化的数据查看页面App

MongoDB、Redis 和 MySQL 都有界面化的数据查看工具&#xff0c;以下是相关介绍&#xff1a; MongoDB 输入MongoDB的账号密码即可读取数据&#xff0c;可访问数据。 MongoDB Compass&#xff1a;这是 MongoDB 官方提供的 GUI 管理工具&#xff0c;支持 Windows、Mac 和 Linux 等…

Spring Boot 实战:接入 DeepSeek API 实现问卷文本优化

本文结合 Spring Boot 项目&#xff0c;介绍如何接入 DeepSeek API&#xff0c;自动优化问卷文本&#xff0c;并给出完整示例代码及详细注释。一、项目目标 目标是实现一个 REST 接口&#xff0c;将原始问卷文本提交给 DeepSeek API&#xff0c;然后返回优化后的文本给前端。 接…

opencv实现轮廓绘制和选择

前面学习了opencv中图像的一些处理&#xff0c;但对于opencv我们更多的还是对图像做出一些判断和识别&#xff0c;所以下面开始学习图像的识别。 原图&#xff1a; 一 图像轮廓的识别 import cv2 pencv2.imread(pen.png,0) ret,new_pencv2.threshold(pen,120,255,cv2.THRESH_…

【Linux】Docker洞察:掌握docker inspect命令与Go模板技巧

&#x1f468;‍&#x1f393;博主简介 &#x1f3c5;CSDN博客专家   &#x1f3c5;云计算领域优质创作者   &#x1f3c5;华为云开发者社区专家博主   &#x1f3c5;阿里云开发者社区专家博主 &#x1f48a;交流社区&#xff1a;运维交流社区 欢迎大家的加入&#xff01…

知料觅得-新一代AI搜索引擎

本文转载自&#xff1a;知料觅得-新一代AI搜索引擎 - Hello123工具导航 ** 一、&#x1f50d; 初识知料觅得&#xff1a;你的 AI 搜索新伙伴 知料觅得是一款融合了前沿人工智能技术的智能搜索引擎&#xff0c;它旨在彻底改变我们获取信息的方式。不同于传统搜索引擎只给你一堆…

高性能网络转发中的哈希表技术选型与实践

引言 在现代网络编程中,处理大量并发连接是一个常见而重要的挑战。特别是在中间件、代理服务器和负载均衡器等场景中,如何高效地管理数万个并发连接并实现数据转发,对系统性能有着至关重要的影响。本文将围绕一个具体的网络转发场景,深入探讨三种不同的哈希表实现(hsearc…

【CF】Day136——Codeforces Round 1046 (Div. 2) CD (动态规划 | 数学)

C. Against the Difference题目&#xff1a;思路&#xff1a;简单DP不难发现我们贪心是没法贪的&#xff0c;因此考虑DP我们令 dp[i] 为 前 i 个元素能构造出的最长整齐子序列的长度&#xff0c;不难发现一个很简单的转移&#xff0c;即直接继承 dp[i] dp[i-1]&#xff0c;那么…

如何评价 Kimi 开源的推理平台 Mooncake?对行业有什么影响?

2月26日&#xff0c;Mooncake的论文获得「计算机存储顶会 FAST 2025」Best Paper&#xff0c;这也是国内连续第三年拿到FAST Best Paper。同时&#xff0c;Mooncake 团队宣布和 vLLM 团队已经合作制定了一个多阶段路线图。这次整合将为 vLLM 引入 P/D&#xff08;Prefill/Decod…

Java中不太常见的语法-总结

简介 读源码时&#xff0c;或者看同事写的代码&#xff0c;经常看到一些不太常见的语法&#xff0c;这里做一个总结 不太常见的语法 成员变量的默认值 案例&#xff1a; public class Person2 {private String name "张三";private Integer age;public String getNa…

Easytier异地组网与移动光猫GS220-s

Easytier异地组网与Nginx反向代理_--relay-network-whitelis easytier-CSDN博客 上一篇文章介绍了Easytier实现异地组网&#xff0c;基于Windows应用&#xff0c;本篇将探讨如何将Easytier写入光猫GS220-s中&#xff0c;实现更方便的家庭组网。 一、Telnet移动光猫GS220-s 1…

卫星信号和无线信号的设备厂商

以下是一些与卫星信号相关的公司&#xff1a;中国卫通集团股份有限公司&#xff1a;中国航天科技集团有限公司从事卫星运营服务业的核心专业子公司&#xff0c;是中国唯一拥有通信卫星资源且自主可控的卫星通信运营企业。运营管理着多颗在轨民商用通信广播卫星&#xff0c;覆盖…