pytest使用allure测试报告

最近通过群友了解到了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>allure
 
Usage: allure [options] [command] [command options]
 
  Options:
 
    --help
 
      Print commandline help.
 
    -q, --quiet
 
      Switch on the quiet mode.
 
      Default: false
 
    -v, --verbose
 
      Switch on the verbose mode.
 
      Default: false
 
    --version
 
      Print commandline version.
 
      Default: false
 
  Commands:
 
    generate      Generate the report
 
      Usage: generate [options] The directories with allure results
 
        Options:
 
          -c, --clean
 
            Clean Allure report directory before generating a new one.
 
            Default: false
 
          --config
 
            Allure commandline config path. If specified overrides values from
 
            --profile and --configDirectory.
 
          --configDirectory
 
            Allure commandline configurations directory. By default uses
 
            ALLURE_HOME directory.
 
          --profile
 
            Allure commandline configuration profile.
 
          -o, --report-dir, --output
 
            The directory to generate Allure report into.
 
            Default: allure-report
 
 
 
    serve      Serve the report
 
      Usage: serve [options] The directories with allure results
 
        Options:
 
          --config
 
            Allure commandline config path. If specified overrides values from
 
            --profile and --configDirectory.
 
          --configDirectory
 
            Allure commandline configurations directory. By default uses
 
            ALLURE_HOME directory.
 
          -h, --host
 
            This host will be used to start web server for the report.
 
          -p, --port
 
            This port will be used to start web server for the report.
 
            Default: 0
 
          --profile
 
            Allure commandline configuration profile.
 
 
 
    open      Open generated report
 
      Usage: open [options] The report directory
 
        Options:
 
          -h, --host
 
            This host will be used to start web server for the report.
 
          -p, --port
 
            This port will be used to start web server for the report.
 
            Default: 0
 
 
 
    plugin      Generate the report
 
      Usage: plugin [options]
 
        Options:
 
          --config
 
            Allure commandline config path. If specified overrides values from
 
            --profile and --configDirectory.
 
          --configDirectory
 
            Allure commandline configurations directory. By default uses
 
            ALLURE_HOME directory.
 
          --profile
 
            Allure commandline configuration profile.

 allure初体验

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

#!/usr/bin/env python3
 
# -*- coding:utf-8 -*-
 
import re
 
import pytest
 
import allure
 
from utils.logger import log
 
from common.readconfig import ini
 
from 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 passed
 
Generating report to temp directory...
 
Report successfully generated to C:\Users\hoou\AppData\Local\Temp\112346119265936111\allure-report
 
Starting web server...
 
2020-06-18 22:52:44.500:INFO::main: Logging initialized @1958ms to org.eclipse.jetty.util.log.StdErrLog
 
Server 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 sys
 
import subprocess
 
 
 
WIN = 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 passed
 
Report successfully generated to c:\Users\hoou\PycharmProjects\web-demotest\allure-report
 
Starting web server...
 
2020-06-18 23:30:24.122:INFO::main: Logging initialized @260ms to org.eclipse.jetty.util.log.StdErrLog
 
Server started at <http://172.18.47.241:7932/>. Press <Ctrl+C> to exit

可以看到运行成功了。

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

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

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

+++
 
 
 
class ConfigManager(object):
 
 
 
		...
 
    
 
    @property
 
    def 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 base64
 
import pytest
 
import allure
 
from py.xml import html
 
from selenium import webdriver
 
 
 
from config.conf import cm
 
from common.readconfig import ini
 
from utils.times import timestamp
 
from utils.send_mail import send_report
 
 
 
driver = None
 
 
 
 
 
@pytest.fixture(scope='session', autouse=True)
 
def drivers(request):
 
    global driver
 
    if 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 = yield
 
    report = 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_img
 
                extra.append(pytest_html.extras.html(html))
 
        report.extra = extra
 
 
 
 
 
def 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.url
 
 
 
 
 
def 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_path
 
    driver.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其他的精彩之处我再来分享。

最后:下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

 

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

物料做出库的时候提交,提示 【即时成本为0】

【财务会计】——【出库核算】——【材料出库核算】

HarmonyOS学习--TypeScript语言学习(二)

本章目录如下&#xff1a; 一、基础类型 二、运算符 三、变量声明 四、类型断言 五、类型推断 TypeScript支持一些基础的数据类型&#xff0c;如布尔型、数组、字符串等&#xff0c;下文举例几个较为常用的数据类型&#xff0c;我们来了解下他们的基本使用。 关于let 我们…

MYSQL数据库中运行SQL文件报错

报错显示 当使用mysql数据库运行SQL文件报错时 [Err] 1273 - Unknown collation: utf8mb4_0900_ai_ci 报错原因 版本高低问题&#xff0c;一个是5.7版本&#xff0c;一个是8.0版本生成转储文件的数据库版本为8.0,要导入sql文件的数据库版本为5.7,因为是高版本导入到低版本&a…

首次超越1000量子比特大关!量子前哨详解IBM突破性进展

&#xff08;图片来源&#xff1a;网络&#xff09; 本周&#xff0c;IBM在其年度量子峰会上宣布&#xff0c;公司已在量子计算领域取得重要突破。其中包括备受期待的1121量子比特Condor QPU&#xff0c;以及一个较小的133量子比特Heron QPU&#xff0c;这些QPU能够与其他QPU组…

0-1背包问题

二维版: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;public class Main {static int N 1010;static int[][] dp new int[N][N]; //dp[i][j] 只选前i件物品,体积 < j的最优解static int[] w new int[N]; //存储价…

Unity渲染Stats分析

文章目录 前言一、Stats二、我们主要看渲染状态分析1、FPS2、其他状态信息3、DrawCall4、Batch5、Setpass Call6、在Unity中弱化了DrawCall的概念&#xff0c;我们主要看 Batch 和 Setpass Call 三、使用 Batching&#xff08;合批&#xff09; 降低 Batch &#xff08;渲染批次…

【C++】:set和map

朋友们、伙计们&#xff0c;我们又见面了&#xff0c;本期来给大家解读一下有关多态的知识点&#xff0c;如果看完之后对你有一定的启发&#xff0c;那么请留下你的三连&#xff0c;祝大家心想事成&#xff01; C 语 言 专 栏&#xff1a;C语言&#xff1a;从入门到精通 数据结…

k8s 安装部署

一&#xff0c;准备3台机器&#xff0c;安装docker&#xff0c;kubelet、kubeadm、kubectl firewall-cmd --state 使用下面命令改hostname的值&#xff1a;(改为k8s-master01)另外两台改为相应的名字。 172.188.32.43 hostnamectl set-hostname k8s-master01 172.188.32.4…

【用unity实现100个游戏之18】从零开始制作一个类CSGO/CS2、CF第一人称FPS射击游戏——基础篇1(附项目源码)

文章目录 本节最终效果前言搭建环境玩家移动控制摄像机跟随和视角人物奔跑实现跳跃斜坡顿挫感人物卡墙问题源码完结 本节最终效果 前言 生存和射击游戏一直是我的最爱&#xff0c;说起3D最普遍的应该就是射击系统了&#xff0c;你可以在任何情况下加入射击功能&#xff0c;所以…

PWM控制器电路D9741,定时闩锁、短路保护电路,输出基准电压(2.5V) 采用SOP16封装形式

D9741是一块脉宽调制方三用于也收路像机和笔记本电的等设备上的直流转换器。在便携式的仪器设备上。 主要特点&#xff1a;● 高精度基准电路 ● 定时闩锁、短路保护电路 ● 低电压输入时误操作保护电路 ● 输出基准电…

2023年美赛获奖结果分析(附中英文版赛题)

023年美国大学生数学建模竞赛&#xff08;MCM/ICM&#xff09;成绩已经公布&#xff0c;现在就请跟随着忠哥一起通过Python 进行大数据分析吧&#xff01; 美赛成绩分析 2023年美国大学生数学建模竞赛MCM参赛队伍总数为11296支&#xff0c;ICM参赛队伍总数为9562支&#xff0…

智慧校园:TSINGSEE青犀智能视频监控系统,AI助力优化校园管理

随着科技的飞速发展和信息化社会的到来&#xff0c;智慧校园已经成为教育领域的一种新型发展模式。智慧校园的需求和发展趋势日益显现&#xff0c;其建设已成为当今教育信息化发展的重要方向。 TSINGSEE青犀结合高可靠、高性能的云计算、人工智能、大数据、物联网等技术&#…

css实现最简单的3d透视效果,通过旋转可以直观感受到

css的3d效果还是非常复杂的&#xff0c;我今天简单学习了一下入门&#xff0c;实现了一个超级简单的效果&#xff0c;帮助我自己理解这个3d的过程&#xff0c;实现的效果动画如下&#xff1a;可以通过调整父元素旋转的角度&#xff0c;更加直观的感受这个3d效果&#xff1a; 实…

Android中在google Map 上绘制历史路径

很多的App都会有这种需求&#xff0c;需要把自己的轨迹绘制在地图上来加标一段行踪&#xff0c;使得自己的行程展现出来&#xff0c;通过地图的展示&#xff0c;自己的行程也就一目了然了。 这里利用Google Map 把自己的行程展现出来&#xff0c;注意这里用到了上一章的基础&a…

男士化妆品市场分析:全球市场规模将达到786亿美元

男士化妆品是针对男性肤质特点而研制的化妆品。男士化妆护肤品基本上集中在洗发水、香水、须后水、剃须膏、洁面乳、面霜、爽肤水以及润唇膏几类,。男性和女性化妆品 需求的发展都历经了3个阶段&#xff1a;清洁、护理和美容。中国市场上男士护理品在过去很长一段时期都集中在基…

java封装类Number

1、概念 在实际开发过程中&#xff0c;我们经常会遇到需要使用对象&#xff0c;而不是内置数据类型的情形。为了解决这个问题&#xff0c;Java 语言为每一个内置数据类型提供了对应的包装类。 所有的包装类&#xff08;Integer、Long、Byte、Double、Float、Short&…

1. Appflowy 之 Bloc和freezed,理解Bloc和模式匹配

Talk is cheap, Show me the code Bloc是什么&#xff1f; Bloc 全称Business Logic Component, 核心思想是将界面和业务逻辑分离&#xff0c;并通过单项数据流的方式来管理状态。 Flutter 提供了StatelessWidget 处理无状态的UI&#xff0c;StatefulWidget处理有状态的数据&…

对String类的深入理解

String类&#xff1a; String类相信大家对这个类并不陌生&#xff0c;这就是我们熟悉的字符串类型&#xff0c;但是我们一开始只知道它是用来定义字符串的&#xff0c;并不知道它的底层原理&#xff0c;这里我们就来简单的分析一下String的底层原理&#xff0c;首先我们来看一下…

机器学习实验一:线性回归

系列文章目录 机器学习实验一&#xff1a;线性回归机器学习实验二&#xff1a;决策树模型机器学习实验三&#xff1a;支持向量机模型机器学习实验四&#xff1a;贝叶斯分类器机器学习实验五&#xff1a;集成学习机器学习实验六&#xff1a;聚类 文章目录 系列文章目录一、实验…

Vue学习计划-Vue2--Vue核心(二)Vue代理方式

Vue data中的两种方式 对象式 data:{}函数式 data(){return {} }示例&#xff1a; <body><div id"app">{{ name }} {{ age}} {{$options}}<input type"text" v-model"value"></div><script>let vm new Vue({el: …
最新文章