自动化测试中的失败截图和存log

如果我们在执行自动化测试的时候,希望能在失败的时候保存现场,方便事后分析。 对于UI自动化,我们希望截图在测试报告中。 对于api自动化,我们希望截取出错的log在测试报告中。 我开始自己蛮干,写了两个出错截图的方法。

def save_screenshot():
    '''
    页面截屏保存截图
    :return:
    '''
    file_name = IMG_PATH + "\\{}.png".format(time.strftime("%Y%m%d%H%M%S", time.localtime()))
    d.screenshot(file_name)
    with open(file_name, mode='rb') as f:
        file = f.read()
    allure.attach(file, allure.attachment_type.PNG)

出错截图,我写了一个装饰器

 
def fail_screenshot(func):
    '''
    失败页面截屏保存截图
    :return:
    '''
 
    def wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except:
            file_name = FAIL_IMG_PATH + "\\{}_{}.png".format(func.__name__,
                                                             time.strftime("%Y%m%d%H%M%S", time.localtime()))
            d.screenshot(file_name)
 
            # with open(file_name, mode='rb') as f:
            #     file = f.read()
            # allure.attach(file, allure.attachment_type.PNG)
 
    return wrapper

似乎能达到我的期望,就是太烦了,每次需要调用或者将装饰器写在函数上。 然后我发现allue里面有一个钩子函数。

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
    :py:class:`_pytest.runner.CallInfo`.
    """

这里item是测试用例,call是测试步骤,具体执行过程如下:

先执行when='setup' 返回setup 的执行结果

然后执行when='call' 返回call 的执行结果

最后执行when='teardown'返回teardown 的执行结果

例如:

# conftest.py 
import pytest
 
 
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    print('------------------------------------')
 
    # 获取钩子方法的调用结果
    out = yield
    print('用例执行结果', out)
 
    # 3. 从钩子方法的调用结果中获取测试报告
    report = out.get_result()
 
    print('测试报告:%s' % report)
    print('步骤:%s' % report.when)
    print('nodeid:%s' % report.nodeid)
    print('description:%s' % str(item.function.__doc__))
    print(('运行结果: %s' % report.outcome))

运行用例的过程会经历三个阶段:setup-call-teardown,每个阶段都会返回的 Result 对象和 TestReport 对象,以及对象属性。

如果setup执行失败了,setup的执行结果的failed,后面的call用例和teardown都不会执行了。

如果setup正常执行,但是测试用例call失败了。那么此时运行的结果就是failed。

如果setup正常执行,测试用例call正常执行,teardown失败了,这种情况,最终统计的结果:1 passed, 1 error in 0.16 seconds

只获取call的时候,我们在写用例的时候,如果保证setup和teardown不报错情况,只关注测试用例本身的运行结果,前面的 pytest_runtest_makereport 钩子方法执行了三次。

可以加个判断:if report.when == "call"

import pytest
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
    :py:class:`_pytest.runner.CallInfo`.
    """
'''
 
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    print('------------------------------------')
 
    # 获取钩子方法的调用结果
    out = yield
    # print('用例执行结果', out)
 
    # 3. 从钩子方法的调用结果中获取测试报告
    report = out.get_result()
    if report.when == "call":
        print('测试报告:%s' % report)
        print('步骤:%s' % report.when)
        print('nodeid:%s' % report.nodeid)
        print('description:%s' % str(item.function.__doc__))
        print(('运行结果: %s' % report.outcome))
 
@pytest.fixture(scope="session", autouse=True)
def fix_a():
    print("setup 前置操作")
    yield
    print("teardown 后置操作")

allure报告集成错误截图 需要使用conftest.py文件,conftest.py需要存在在测试目录中,文件名不能变更,可以根据模块创建层级嵌套。

具体参照pytest的官方文档

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''
    hook pytest失败
    :param item:
    :param call:
    :return:
    '''
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()
    # we only look at actual failing test calls, not setup/teardown
    if rep.when == "call" and rep.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            # let's also access a fixture for the fun of it
            if "tmpdir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(rep.nodeid + extra + "\n")
        # pic_info = adb_screen_shot()
        with allure.step('添加失败截图...'):
            allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)

好了,我们可以用在我们自己的项目里面来了。 我们可以在conftest.py里面定义:

import pytest
from selenium import webdriver
import os
import allure
 
 
 
_driver = None
 
 
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''
    获取每个用例状态的钩子函数
    :param item:
    :param call:
    :return:
    '''
    # 获取钩子方法的调用结果
    outcome = yield
    rep = outcome.get_result()
    # 仅仅获取用例call 执行结果是失败的情况, 不包含 setup/teardown
    if rep.when == "call" and rep.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            # let's also access a fixture for the fun of it
            if "tmpdir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
            f.write(rep.nodeid + extra + "\n")
        # 添加allure报告截图
        if hasattr(_driver, "get_screenshot_as_png"):
            with allure.step('添加失败截图...'):
                allure.attach(_driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)
 
 
@pytest.fixture(scope='session')
def browser():
    global _driver
    if _driver is None:
        _driver =webdriver.Chrome()
    yield _driver
    print("1111111111")
    _driver.quit()

然后写一个测试用例,如在某度上搜一个关键词。

 
@allure.feature('self study')
class TestLesson():
    @allure.story('user course page')
    @allure.description('be course')
    def test_be_ge_course(self,browser):
        url = 'http://www.baidu.com'
        browser.get(url)
        time.sleep(2)
        browser.find_element_by_id('kw').send_keys("python")
 
        with allure.step('查找元素...'):
            browser.find_element_by_id('su').click()
            time.sleep(2)
 
        assert browser.title == 'python'

这是一个失败的用例,所以执行错误会截图。

这样你的报告就看起来高大上了。 截图还可以直接用allure.attach allure.attach(挺有用的) 作用:allure报告还支持显示许多不同类型的附件,可以补充测试结果;自己想输出啥就输出啥,挺好的

语法:allure.attach(body, name, attachment_type, extension) 
 
参数列表
body:要显示的内容(附件)
name:附件名字
attachment_type:附件类型,是 allure.attachment_type 里面的其中一种
extension:附件的扩展名(比较少用)

allure.attach.file(source, name, attachment_type, extension) source:文件路径,相当于传一个文件

其他参数和上面的一致:

TEXT = ("text/plain", "txt")
   CSV = ("text/csv", "csv")
   TSV = ("text/tab-separated-values", "tsv")
   URI_LIST = ("text/uri-list", "uri")
 
   HTML = ("text/html", "html")
   XML = ("application/xml", "xml")
   JSON = ("application/json", "json")
   YAML = ("application/yaml", "yaml")
   PCAP = ("application/vnd.tcpdump.pcap", "pcap")
 
   PNG = ("image/png", "png")
   JPG = ("image/jpg", "jpg")
   SVG = ("image/svg-xml", "svg")
   GIF = ("image/gif", "gif")
   BMP = ("image/bmp", "bmp")
   TIFF = ("image/tiff", "tiff")
 
   MP4 = ("video/mp4", "mp4")
   OGG = ("video/ogg", "ogg")
   WEBM = ("video/webm", "webm")
 
   PDF = ("application/pdf", "pdf")

根据需要,在报告里将更多的信息展现出来。 这周末啥也没干,主要就搞明白了这个。

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

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你! 

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

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

相关文章

Essential Math for AI:高效的人工智能数学原理晋级读物

今天给大家介绍一本人工智能数学原理书籍:Essential Math for AI。作者是Hala Nelson,一位应用数学领域的美女博士,James Madison University (JMU) 大学的助理教授。 关注微信公众号:人工智能大讲堂,后台回复【ema】获…

【Android】Debug时禁用主线程ANR限制

ANR全称Application Not Response,指主线程超过5s无响应,应用会自动退出 由于这个线程,如果我们给主线程加了断点,就会触发ANR,导致调试时应用退出 这样调试起来会非常麻烦,其实对于Debug应用&#xff0c…

JVM虚拟机-虚拟机性能监控、故障处理工具

1基础故障处理工具 jps(JVM Process Status Tool)是:虚拟机进程状况工具 作用:可以列出正在运行的虚拟机进程,并显示虚拟机执行主类(Main Class,main()函数所在的类)名称以及这些进…

人工智能基础——python:Pandas与数据处理

人工智能的学习之路非常漫长,不少人因为学习路线不对或者学习内容不够专业而举步难行。不过别担心,我为大家整理了一份600多G的学习资源,基本上涵盖了人工智能学习的所有内容。点击下方链接,0元进群领取学习资源,让你的学习之路更加顺畅!记得…

CSS基础:你必须要知道的行高属性 line-height

作者:WangMin 格言:努力做好自己喜欢的每一件事 CSDN原创文章 博客地址 👉 WangMin 对于初学CSS的同学来说,会有很多属性相关的疑问,行高属性 line-height一定是其中一个,因为它是CSS中非常重要的一个属性,这个属性改变…

AlphaControls控件TsRadioGroup的使用

通常使用AlphaControls控件中的TsRadioGroup时,往往使用默认值,会造成TsRadioGroup标题被TsRadioGroup的ITEMs占用,严重影响美观: 解决方案,通过对TsRadioGroup的ContentVOffset属性,设置为10。即可立即改善…

【ARFoundation学习笔记】点云与参考点

写在前面的话 本系列笔记旨在记录作者在学习Unity中的AR开发过程中需要记录的问题和知识点。主要目的是为了加深记忆。其中难免出现纰漏,更多详细内容请阅读原文以及官方文档。 汪老师博客 文章目录 点云新建点云 参考点参考点的工作原理何时使用参考点使用参考点…

【高等数学】导数的应用

导数的应用 1、洛必达法则1.1、引例1.2、内容1.3、证明1.4、洛必达的应用总结 1.5、注意 2、泰勒公式2.1、解决的问题2.2、引例2.3、内容2.3.1、带Peano余项的泰勒公式2.3.2、带Lagrange余项的泰勒公式2.3.3、麦克劳林公式2.3.4、几个初等函数的麦克劳林公式 2.4、证明2.5、泰勒…

SpringBoot 监控

概述 SpringBoot自带监控功能Actuator&#xff0c;可以帮助实现对程序内部运行情况监控&#xff0c;比如监控状况、Bean加载情况、配置属性、日志信息等。 使用步骤 导入依赖坐标 <dependency><groupId>org.springframework.boot</groupId><artifactI…

Vuex模块概念

一、核心概念 - module 1.目标 掌握核心概念 module 模块的创建 2.问题 由于使用单一状态树&#xff0c;应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时&#xff0c;store 对象就有可能变得相当臃肿。 这句话的意思是&#xff0c;如果把所有的状态都放在s…

智慧城市建设解决方案分享【完整】

文章目录 第1章 前言第2章 智慧城市建设的背景2.1 智慧城市的发展现状2.2 智慧城市的发展趋势 第3章 智慧城市“十二五”规划要点3.1 国民经济和社会发展“十二五”规划要点3.2 “十二五”信息化发展规划要点 第4章 大数据&#xff1a;智慧城市的智慧引擎4.1 大数据技术—智慧城…

公司如何实现多套环境的自动化测试?

实战练习 分别准备两套测试环境&#xff0c;都对其发起 get 请求&#xff0c;传入参数 name&#xff0c;对应值为 hogwarts&#xff0c;并断言其响应值。 测试环境1&#xff1a;http://httpbin.org/get 测试环境2&#xff1a;https://httpbin.ceshiren.com/get <strong>…

浙大恩特客户资源管理系统任意文件上传漏洞复现

0x01 产品简介 浙大恩特客户资源管理系统是一款针对企业客户资源管理的软件产品。该系统旨在帮助企业高效地管理和利用客户资源&#xff0c;提升销售和市场营销的效果。 0x02 漏洞概述 浙大恩特客户资源管理系统中fileupload.jsp接口处存在文件上传漏洞&#xff0c;未经身份认…

Postman小白安装和注册入门教程

近期在复习Postman的基础知识&#xff0c;在小破站上跟着百里老师系统复习了一遍&#xff0c;也做了一些笔记&#xff0c;希望可以给大家一点点启发。 一&#xff09;安装 访问官网https://www.getpostman.com/downloads/&#xff0c;直接下载安装。 二&#xff09;注册和登录…

基本数据类型小题两道

根据公式计算A地区教师任教年薪&#xff0c;统计键盘输入的字符串中数字个数&#xff0c;按字典序输出。 (笔记模板由python脚本于2023年11月10日 18:05:18创建&#xff0c;本篇笔记适合熟悉python列表、元、字符串等基本数据类型的coder翻阅) 【学习的细节是欢悦的历程】 Pyth…

Hololens开发笔记

1、关闭阴影 2、将相机渲染改为后向。因为默认是Forward&#xff0c;当在场景里面想使用点光源时&#xff0c;运行起来三角面会翻倍&#xff0c;影响软件运行流畅度。 3、第三人称同步相关。开启Host/Sever/Client前&#xff0c;需要将所有挂有NetworkObject/NetworkTransfor…

C语言之文件操作(详解版)

不知不觉我们已经学到C语言的文件操作部分了&#xff0c;这部分内容其实很有意思&#xff0c;因为它可以直接把我们代码中的数据写入硬盘&#xff0c;而不是我们关掉这个程序&#xff0c;代码就没有了&#xff0c;让我们开始学习吧&#xff01; 目录 1.为什么使用文件 2.什么…

7个学习自动化测试小技巧希望能帮助到你

一、编程语言 当我开始担任手动测试人员时&#xff0c;我不喜欢编码。但是&#xff0c;当我逐渐进入自动化领域时&#xff0c;对我来说很清楚&#xff0c;如果没有对编程语言的一些基本了解&#xff0c;就无法编写逻辑自动化测试脚本。 对编程有一点了解&#xff0c;不仅可以…

创建Vue3工程

一、使用Vue-cil创建工程 先全局安装Vue脚手架&#xff1a; npm install -g vue/cli 安装完成后输入如下命令就可以查看到Vue的版本&#xff1a; vue -V 版本尽量在4.5及以上 。 输入如下指定常见Vue项目&#xff1a; vue create 项目名称 注意&#xff1a;项目名中不要有大写…

OpenCV校准棋盘集合

棋盘格可以与相机校准工具一起使用&#xff0c;例如ROS的camera_calibration包。您可以通过单击下面的任何链接免费下载 PDF 格式的各种棋盘&#xff0c;没有水印或广告。此外&#xff0c;还添加了基于 JavaScript 的棋盘生成器&#xff0c;允许您生成自定义尺寸。 提示&#…