Python 中使用 unittestreport 之 生成 HTML 报告、失败用例重运行、邮件发送测试报告、推送结果到钉钉、企业微信

  关于 unittestreport 最初在开发的时候,最初只是计划开发一个unittest生成html测试报告的模块,所以起名叫做unittestreport。在开发的过程中结合使用的小伙伴的一些反馈,所以慢慢的扩展了更多的功能进去。之前在写unittestreport的时候,也陆续写了几遍关于unittestreport相关功能的使用,每次都是一个特定的功能,这边给出一遍系统的使用文档来给大家介绍一下unittestreport的功能。

关于 unittestreport 是什么?  官方地址:https://pypi.org/project/unittestreport/

  • unittestreport是基于unittest开发的的一个功能扩展库,为unittest提供了一些常用的扩展功能:
  • HTML测试报告生成
  • 测试用例失败重运行
  • 发送测试结果及报告到邮箱
  • unittest数据驱动
  • 测试结果钉钉通知

一、安装 unittestreport (report译:瑞泡特)

  在 https://pypi.org/  中搜索 unittestreport  就可以查看 官方文档

使用文档:https://unittestreport.readthedocs.io/en/latest/

  

在 cmd 中使用 pip 安装:

  

二.使用 TestRunner 模块生成 HTML 报告

# 加载测试用例的方法:discover(迪斯卡瓦)方法
import unittest
from unittestreport import TestRunner

# 手机测试用例,使用绝对路径加载测试用例,使用 r 进行转码
one_suite = unittest.defaultTestLoader.discover(r"D:\zj_danyuan\Python_0715_unittest")

# 执行用例
# 1.需要创建执行器对象,使用 unittest 当中的 TestRunner(译:泰斯特.软那儿)
"""
:param suites: 测试套件
:param filename: 报告文件名
:param report_dir:报告文件的路径
:param title:测试套件标题
:param templates: 可以通过参数值1或者2,指定报告的样式模板,目前只有两个模板
:param tester:测试者
"""
one_runner = TestRunner(one_suite,
                        filename="python.html",
                        report_dir=r"D:\zj_danyuan\Python_0715_unittest\logs",
                        title="演示用例运行产生的测试报告",
                        tester="守护",
                        desc="第一个报告",
                        templates=1
                        )
# 2.运行套件
one_runner.run()

执行测试用例

  

 使用浏览器打开测试报告

  

 

三、Unittestreport 之 DataDrivenTest (DDT)中数据驱动使用

  关于数据驱动这边就不给大家做过多的介绍了,数据驱动的目的是将测试数据和用例逻辑进行分离,提高代码的重用率,以及用例的维护,关于数据驱动本,unittestreport.dataDriver模块中实现了三个使用方法,支持使用列表(可迭代对象)、json文件、yaml文件来生成测试用例,接来分别给大家介绍一下使用方法:

1、使用介绍

from unittestreport.dataDriver 

import ddt, list_data,json_data,yaml_data
  • 第一步:使用ddt装饰测试用例类

  • 第二步:根据使用的数据选择对应的方法进行驱动

2、使用案例

import unittest
from unittestreport import ddt, list_data, json_data, yaml_data

"""
判断五组数据是否相等
"""
test_cases = [
    (11, 11),
    (11, 12),
    (14, 14),
    (17, 17),
    (19, 19),
]

@ddt
class TestDome(unittest.TestCase):
    @list_data(test_cases)
    def test_demo(self, case):
        a, b = case
        self.assertEqual(a, b)

 

示例1、用例保存在可迭代对象中(如列表):使用LIST_DATA

from unittestreport import ddt, list_data
@ddt
class TestClass(unittest.TestCase):
    cases = [{'title': '用例1', 'data': '用例参数', 'expected': '预期结果'}, 
             {'title': '用例2', 'data': '用例参数', 'expected': '预期结果'},
             {'title': '用例3', 'data': '用例参数', 'expected': '预期结果'}]
    @list_data(cases)
    def test_case(self, data):
        pass

 

示例2、用例保存在JSON文件中:使用JSON_DATA

from unittestreport import ddt,json_data

@ddt
class TestClass(unittest.TestCase):
    @json_data(apitest)
    def test_case(self, data):
        pass

json文件中的数据格式

  • cases.json文件
[
  {
    "title": "用例1",
    "data": "用例参数",
    "expected": "预期结果"
  },
  {
    "title": "用例2",
    "data": "用例参数",
    "expected": "预期结果"
  },
  {
    "title": "用例3",
    "data": "用例参数",
    "expected": "预期结果"
  }
]

 

示例3、用例保存在YAML文件中:使用YAML_DATA

from unittestreport import ddt,yaml_data

@ddt
class TestClass(unittest.TestCase):
    @yaml_data("C:/xxxx/xxx/cases.yaml")
    def test_case(self, data):
        pass

yaml文件中的数据展示

  • cases.yaml文件
- title: 用例1
  data: 用例参数
  expected: 预期结果

- title: 用例2
  data: 用例参数
  expected: 预期结果

- title: 用例4
  data: 用例参数
  expected: 预期结果

 

2、注意点:

  • 关于使用ddt的时候进行数据驱动,指定测试报告中的用例描述:

  • 测试报告中的用例描述默认使用的是用例方法的文档字符串注释,

  • 如果要给每一条用例添加用例描述,需要在用例数据中添加 title 或者 desc 字段,字段对应的数据会自动设置为测试报告中用例的描述

 

四、测试用例失败重运行

关于 unittest 重运行机制,unittestreport 中提供了两种方式

方式一: RERUN 装饰器

  • 使用案例:使用 rerun 装饰失败需要重运行的用例,该用例失败后会自动重运行
from unittestreport import rerun

class TestClass(unittest.TestCase):
    @rerun(count=4, interval=2)
    def test_case_01(self):
        a = 100
        b = 99
        assert a == b

用例运行

runner = TestRunner(test_suite)
runner.run()

参数说明:

  • count:用来指定用例失败重运行的次数
  • interval:指定每次重运行的时间间隔,默认三秒

  

 

方式二:TESTRUNNER.RERUN方法

  • 使用案例:所有的用例失败,只要有失败的用例,会自动重运行该用例

  • 用例正常编写即可
  • 运行是使用 TestRunner.rerun_run 方法运行
runner = TestRunner(suite=suite)
runner.rerun_run(count=3, interval=2)

参数说明:

  • count:用来指定用例失败重运行的次数
  • interval:指定每次重运行的时间间隔

 

五、Unittestreport 多线程执行测试用例

  unittestreport 的 TestRunner 模块当中的 run 方法

注意:

  • 1、确保际个线程任务测试类)在执行的时候不会出现资源竞争(对全局依赖的数据进行修改)
  • 2、确保用例类执行没有先后顺序的依赖关系
from unittestreport import TestRunner
        def run(self, thread_count=1):
        """
        支持多线程执行
        注意点:如果多个测试类共用某一个全局变量,由于资源竞争可能会出现错误
        :param thread_count:线程数量,默认位1
        :return:测试运行结果
        """
        # 将测试套件按照用例类进行拆分
        suites = self.__classification_suite()
        with ThreadPoolExecutor(max_workers=thread_count) as ts:
            for i in suites:
                res = TestResult()
                self.result.append(res)
                ts.submit(i.run, result=res).add_done_callback(res.stopTestRun)
            ts.shutdown(wait=True)
        res = self.__get_reports()
        return res 

 

用例示例:

  一共有20个测试用例,如果不适用多线程 需要20秒

import unittest
import time
from unittestreport import ddt, list_data, json_data, yaml_data, rerun


@ddt
class TestDome(unittest.TestCase):

    @list_data(range(10))
    def test_demo(self, case):
        print(case)
        time.sleep(1)


@ddt
class TestDome1(unittest.TestCase):

    @list_data(range(10))
    def test_demo(self, case):
        print(case)
        time.sleep(1)

运行文件:

# 加载测试用例的方法:discover(迪斯卡瓦)方法
import unittest
from unittestreport import TestRunner

# 收集测试用例,使用绝对路径加载测试用例,使用 r 进行转码
one_suite = unittest.defaultTestLoader.discover(r"D:\zj_danyuan\Python_lianxi\repo1")

# 执行用例1.需要创建执行器对象,使用 unittest 当中的 TestRunner(译:泰斯特.软那儿)
one_runner = TestRunner(one_suite,
                        filename="python.html",
                        report_dir=r"D:\zj_danyuan\Python_lianxi\repo1",
                        title="演示用例运行产生的测试报告",
                        tester="守护",
                        desc="第一个报告",
                        templates=1
                        )
# 2.多线程运行
one_runner.run(thread_count=2)

使用多线程运行 后为 10秒

  

  

 

六、邮件发送测试报告

  unittestreport内部实现了发生测试结果到邮箱的方法,执行完测试用例之后调用发送测试报告的方法即可。发邮件的方法介绍:TestRunner类中实现了send_email方法,可以方便用户,快速发送邮件。

send_email 方法:

    def send_email(self, host, port, user, password, to_addrs, is_file=True):
        """
        发生报告为附件到邮箱
        :param host: str类型,(smtp服务器地址)
        :param port: int类型,(smtp服务器地址端口)
        :param user: str类型,(邮箱账号)
        :param password: str类型(邮箱密码)
        :param to_addrs: str(单个收件人) or list(多个收件人)收件人列表,
        :return:
        """
        sm = SendEmail(host=host, port=port, user=user, password=password)
        if is_file:
            filename = self.email_conent["file"]
        else:
            filename = None
        content = self.email_conent["content"]

        sm.send_email(subject=self.title, content=content, filename=filename, to_addrs=to_addrs)

 

使用案例:

runner = TestRunner(suite)
runner.run()
runner.send_email(host="smtp.qq.com",
                  port=465,
                  user="musen_nmb@qq.com",
                  password="algmmzptupjccbab",
                  to_addrs="3247119728@qq.com")

参数介绍

  • host: smtp服务器地址
  • port:端口
  • user:邮箱账号
  • password:smtp服务授权码
  • to_addrs:收件人邮箱地址(一个收件人传字符串,多个收件人传列表)

收到的邮件样式

  

 

六、推送测试结果到钉钉

关于把测试结果推送到钉钉群,unittestreport里面进行了封装。执行完用例之后,调用TestRunner对象的dingtalk_notice方法即可。

参数介绍:

  关于dingtalk_notice这个方法的参数如下,大家可以根据使用需求来进行选择。

  • url: 钉钉机器人的Webhook地址
  • key: (非必传:str类型)如果钉钉机器人安全设置了关键字,则需要传入对应的关键字
  • secret:(非必传:str类型)如果钉钉机器人安全设置了签名,则需要传入对应的密钥
  • atMobiles: (非必传,list类型)发送通知钉钉中要@人的手机号列表,如:[137xxx,188xxx]
  • isatall: 是否@所有人,默认为False,设为True则会@所有人
  • except_info:是否发送未通过用例的详细信息,默认为False,设为True则会发送失败用例的详细信息

案例代码:

import unittest
from unittestreport import TestRunner

# 收集用例到套件
suite = unittest.defaultTestLoader.discover(CASE_DIR)
runner = TestRunner(suite)
# 执行用例
runner.run()

url = "https://oapi.dingtalk.com/robot/send?access_token=6e2a63c2b9d870ee878335b5ce6d5d10bb1218b8e64a4e2b55f96a6d116aaf5"
# 发送钉钉通知  
runner.dingtalk_notice(url=url, key='钉钉安全设置的关键字',secret='钉钉安全设置签名的秘钥')

# 备注:关于钉钉群机器人的创建大家可以去看钉钉开放平台上的教程,关键字和秘钥,
# 根据创建钉钉机器人时设置的去添加,没有设置就不需要传这个参数。

url 获取方式:

  • 百度搜索 “钉钉开放平台”

  

钉钉收到样式:

  

 

七、推送测试结果到企业微信

  目前也有不少的公司使用企业微信办公,自动化跑完之后,测试结果需要推送到企业微信群,所以把这个功能做了一下集成(其实大家自己去些也没多少代码)。执行完用例之后,调用TestRunner对象的weixin_notice 方法即可将测试结果推送到企业微信群。

参数介绍

  • CHATID: 企业微信群ID
  • ACCESS_TOKEN:调用企业微信API接口的凭证
  • CORPID:企业ID
  • CORPSECRET:应用的凭证密钥

案例代码

import unittest
from tests.test_case import TestClass
from unittestreport import TestRunner
# 加载用例
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestClass)
runner = TestRunner(suite=suite)
# 运行用例
runner.run()

# 推送测试结果到企业微信
# 方式一:
runner.weixin_notice(chatid="企业微信群id", access_token="调用企业微信API接口的凭证")
# 方式二:
runner.weixin_notice(chatid="企业微信群id",corpid='企业ID', corpsecret='应用的凭证密钥')

 

 

*******请大家尊重原创,如要转载,请注明出处:转载自:https://www.cnblogs.com/shouhu/,谢谢!!******* 

posted @ 2021-03-02 19:50  守护往昔  阅读(1496)  评论(1编辑  收藏  举报