pytest使用allure测试报告

【Pytest】使用Allure测试报告 简介:Allure非常适合作为自动化测试报告,这里总结下Pytest使用的Allure测试报告的用法 环境准备 所需环境 ide使用PyCharm python 3.7 pytest 5.3.2 allure-pytest 2.8.13 allure-pytest 安装 在已经安装python3和pytest的前提下,打开PyCharm,进入Project Interpreter,点击“... 阅读详情

 

前言

最近通过群友了解到了allure这个报告,开始还不以为然,但还是逃不过真香定律。

经过试用之后,发现这个报告真的很好,很适合自动化测试结果的展示。下面说说我的探索历程吧。

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

allure安装

  • 首先安装python的allure-pytest包
pip install allure-pytest
  • 然后安装allure的command命令行程序

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

但是由于GitHub访问太慢,我已经下载好并放在了群文件里面,请右上角扫描二维码加QQ群下载。

下载完成后解压放到一个文件夹。我的路径是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 os
import re
import pytest
import allure
from tools.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', './report/allure'])
    os.system('allure serve report/allure')

然后运行一下:

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


***


------------------------------- generated html file: file://C:\Users\hoou\PycharmProjects\web-demotest\report\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

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

QQ截图20200618225326.png

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

QQ截图20200618225554.png

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

allure装饰器介绍

image

报告的生成和展示

刚才的两个命令:

  • 生成allure原始报告到report/allure目录下,生成的全部为json或txt文件。
pytest TestCase/test_search.py --alluredir ./report/allure
  • 在一个临时文件中生成报告并启动浏览器打开
allure serve report/allure

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

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

我们在项目根目录新建一个文件:

  • Windows系统创建run_win.bat文件。

  • MacOS或Linux系统run_mac.sh文件。

输入以下内容

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

allure generate allure-results -c -o allure-report

allure open allure-report

命令释义:

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

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

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

QQ截图20200618233119.png

可以看到运行成功了。

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

QQ截图20200618233214.png

allure发生错误截图

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

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

+++

# 截图目录
SCREENSHOT_DIR = os.path.join(BASE_DIR, 'screen_capture')

+++

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

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import os
import base64
import pytest
import allure
from py._xmlgen import html
from selenium import webdriver
from config.conf import SCREENSHOT_DIR
from tools.times import datetime_strftime
from common.inspect import inspect_element
driver = None


@pytest.fixture(scope='session', autouse=True)
def drivers(request):
    global driver
    if driver is None:
        driver = webdriver.Chrome()
        driver.maximize_window()
    inspect_element()

    def fn():
        driver.quit()

    request.addfinalizer(fn)
    return driver


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    当测试失败的时候,自动截图,展示到html报告中
    :param 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):
            screen_img = _capture_screenshot()
            if screen_img:
                html = '<div><img src="https://img-blog.csdnimg.cn/2022010706154076295.png" 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
        report.description = str(item.function.__doc__)
        report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")


@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.insert(1, html.th('用例名称'))
    cells.insert(2, html.th('Test_nodeid'))
    cells.pop(2)


@pytest.mark.optionalhook
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)


@pytest.mark.optionalhook
def pytest_html_results_table_html(report, data):
    if report.passed:
        del data[:]
        data.append(html.div('通过的用例未捕获日志输出.', class_='empty log'))


def _capture_screenshot():
    '''
    截图保存为base64
    '''
    now_time = datetime_strftime("%Y%m%d%H%M%S")
    if not os.path.exists(SCREENSHOT_DIR):
        os.makedirs(SCREENSHOT_DIR)
    screen_path = os.path.join(SCREENSHOT_DIR, "{}.png".format(now_time))
    driver.save_screenshot(screen_path)
    allure.attach.file(screen_path, "测试失败截图...{}".format(
        now_time), allure.attachment_type.PNG)
    with open(screen_path, 'rb') as f:
        imagebase64 = base64.b64encode(f.read())
    return imagebase64.decode()

来看看我们修改了什么:

1、首先我们修改了_capture_screenshot函数

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

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

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

2、接着我们修改了hook函数pytest_runtest_makereport

更新了原来的判断逻辑。

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

修改test_002测试用例

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

运行一下:

QQ截图20200618234740.png

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

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

QQ截图20200618234916.png

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

转载于:https://www.cnblogs.com/wxhou/p/13160922.html

如何使用Jenkins+pytest+allure生成测试报告 如何使用jenkins+pytest+allure生成漂亮的测试报告 阅读详情

相关推荐

Pytest教程:简单了解Pytest+Allure生成测试报告的使用

在软件测试领域,Pytest 是一个非常流行的 Python 测试框架,它简单、灵活且功能强大。Allure 是一个轻量级且富有表现力的测试报告工具,能够展示丰富的测试信息。将 Pytest 与 Allure 结合使用,可以生成详细且美观的测试报告,有助于提高软件质量和测试效率。

旦莫的博客 1729

conftest在pytest框架里面的使用及实现失败截图的功能

它位于测试文件或测试目录的顶级位置,并在运行测试时自动加载。可以使用pytest提供的钩子函数和Selenium的截图功能,使用钩子函数和Allure API将失败的截图添加到Allure报告中。夹具是一个自定义夹具,它可以在测试函数中作为参数使用,用于模拟登录操作并返回登录后的页面对象或其他需要的数据。中的代码可以根据测试需求进行扩展或修改。上述示例只是一种常见的用法,具体的实现取决于你的测试框架和需求。是钩子函数,它们可以在每个测试用例运行之前和之后执行自定义的代码。

weixin_42789071的博客 619

别再浪费HDRI了!D5渲染器环境光设置避坑指南(附天空球调试参数)

本文深入解析D5渲染器中HDRI环境光的高阶调试技巧,揭示90%渲染师常犯的错误认知。通过参数联动黄金法则、特殊材质应对方案及动态场景优化策略,帮助用户精准控制光子能量分布,实现建筑玻璃反射云层过渡等专业级效果。附赠天空球调试参数和商业项目验证案例,助您彻底释放HDRI潜力。

weixin_29216049的博客 495

微信小程序自动化测试pytest版-失败截图

在这里我给大家分享一些自动化测试的学习资源,希望能给你前进的路上带来帮助。

伤心的辣条 520

一文了解ECU软件刷写的2种方法:Bootloader刷写和调试器刷写

分为刷写前、刷写中和刷写后三个阶段,如下示意:下面我们来详细了解一下Bootloader收到外部请求后开始刷写的三个阶段1)刷写前进行刷写的准备,一是确保刷写阶段总线通信的稳定性,二是避免刷写阶段出现非预期的故障,三是读取车辆数据供刷写前的一些检查等,如下所示:首先进行会话控制,通过功能寻址方式进入扩展会话模式,为后面的信息访问及其他指令做准备;然后检查刷写的前提条件,通过物理寻址方式发送历程控制请求。比如车确实处于静止状态,供电电压稳定等条件下才允许刷写;

menghuyouyou的博客 5783

DreamerV3实战:如何用世界模型在Minecraft中自动挖钻石(附完整训练流程)

本文详细介绍了如何使用DreamerV3世界模型在Minecraft中训练AI智能体自动完成挖钻石的复杂任务。文章深入分析了该任务对强化学习的挑战,提供了从环境配置、模型训练到结果评估的完整实战流程,并分享了关键的调优技巧与问题解决方案,展示了基于模型的强化学习在解决稀疏奖励问题上的强大能力。

weixin_29050271的博客 192

pytest(3): 收集测试结果pytest_runtest_makereport

pytest_runtest_makereport 先看下相关的源码,在_pytest/runner.py下,可以导入之后,点进去查看 from _pytest import runner # 对应源码 def pytest_runtest_makereport(item, call): """ return a :py:class:`_pytest.runner.TestReport` object for the given :py:class:`pytest.Item` and

Python开发分享的博客 2572

5种超实用方法:快速获取Windows文件夹下所有文件名(含CMD/PowerShell脚本)

本文详细介绍了5种快速获取Windows文件夹下所有文件名的实用方法,包括图形界面操作、Excel数据导入、CMD命令和PowerShell脚本。特别提供了高效的CMD和PowerShell脚本示例,帮助用户轻松实现文件名的批量获取与管理,大幅提升工作效率。

opencv7vision的博客 450

Pytest实现用例失败截图并且在测试报告中可以查看

Pytest+Selenium是UI自动化常用得框架,结合Allure可以给出优美得测试报告,失败的case可以查看错误日志,但是对于UI自动化来说,最直观的还是可以通过截图来查看失败原因,更方便测试人员定位问题。

a598975589的博客 2333

Android GNSS 可视卫星星空图/卫星天顶图 原理及画法介绍

目录1 概念介绍2 绘制步骤2.1 获取卫星信息2.2 绘制底图 效果图: 1 概念介绍 首先介绍一下方位角和高度角的概念: 方位角:是从某点的指北(地理北极)方向线起,依顺时针方向到目标方向线之间的水平夹角。 高度角:从一点至观测目标的方向线与水平面间的夹角。 卫星天顶图 即是根据每一颗卫星的方位角和高度角将其画在以观测位置为中心的天顶图上。 天顶图其底图为由外向内的三个圆和四条直线。三个圆由外向内依次代表高度角0°、30°、60°,中心点代表90°;四条直线分别表示正北-正南、东北-西南、正东

x1471898145的博客 1万+

《MySQL高级篇》十四、多版本并发控制

《MySQL高级篇》十四、多版本并发控制

LXYDSF的博客 3992

pytest使用allure测试报告详解

PS:这里分享一套软件测试的自学教程合集。对于在测试行业发展的小伙伴们来说应该会很有帮助。除了基础入门的资源,博主也收集不少进阶自动化的资源,从理论到实战,知行合一才能真正的掌握。全套内容已经打包到网盘,内容总量接近500个G。【点击文末小卡片免费领取】这些资料,对于做【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!凡事要趁早,特别是技术行业,一定要提升技术功底。

huace3852的博客 705

如何解除Uniaccess管控??

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断与性能调优」方法论,助你稳步进阶、放大技术价值 。

**My Coding Family** 2385

Allure的安装,在Pytest中的简单使用以及生成测试报告

Allure Report — Open-source HTML test automation report toolInstall from an archiveMake sure Java version 8 or above installed, and its directory is specified in the environment variable.我们需要在系统环境变量中配置java JDK设置JAVA_HOME环境变量并且JDK版本是8或者8以上如果不会配置可以看一下这一篇(里面

. 2333

鸿蒙开发之hdc命令行

hdc(HarmonyOS Device Connector)是HarmonyOS为开发人员提供的用于调试的命令行工具,通过该工具可以在windows/linux/mac系统上与真实设备进行交互。

xiangzhihong8的专栏 5828

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Pytest使用allure测试报告

报告的生成和展示刚才的两个命令:生成allure原始报告到report/allure目录下,生成的全部为json或txt文件。

hlsxjh的博客 1165

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

allure测试报告以及结合pytest使用

allure是一个轻量级,灵活的,支持多语言的测试报告工具,本文带你走进allure的世界。

Flora's Zone 2923

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

mac使用allure_Pytest 可视化测试报告之 Allure

点击上方蓝字关注我们 Pytest报告生成生成兼容Junit风格的报告Junit风格xml报告:pytest—junitxml=path生成HTML风格报告Pytest-html报告:pytest—html=report.htmlAllure2报告pytest—alluredir=/tmp/my_allure_results这篇文章主要讲解如何使用Allure来生成漂亮的测试报告。执行步骤如下:...

weixin_39834281的博客 235

python+pytest+allure测试报告的使用

如果你需要使用allure报告的话,还得安装一个java的jdk环境,如果不会装java的jdk环境的,可以自己百度如何装,网上教程很多。6.想确定装好没有,可以在cmd终端里面输入命令:allure --version 如果弹出allure的版本号表示安装成功。5.点击环境变量,在系统变量里面找到Path双击,在里面新建一个目录把前面复制的allure的bin目录加进去点击确定即可。这个命令的意思就是,会用相对路径下面的report文件夹里面的内容生成一个allure的测试报告。

weixin_70786982的博客 1505
上一篇: 如何解决github访问速度慢的问题
下一篇: Jenkins持续集成allure报告
michaelbin2012
博客等级 码龄14年 21粉丝 19原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值