unittest 统计测试执行case总数,成功数量,失败数量,输出至文件,生成一个简易的html报告带饼图

这是一个Python的单元测试框架的示例代码,主要用于执行测试用例并生成测试报告。其中,通过unittest模块创建主测试类MainTestCase,并加载其他文件中的测试用例,统计用例的执行结果并将结果写入文件,最后生成一个简单的测试报告html页面。

在执行测试时,可以根据需要添加更多的测试文件和测试用例,在自定义CustomTextTestResult类中重写addSuccess和addFailure方法,获取用例的执行结果,并在统计成功和失败的用例数量时进行累加。将用例执行成功和失败的信息分别保存到success_cases和failure_cases列表中,最后将结果写入文件。

在生成测试报告时,利用HTML和CSS语言生成一个表格结构的页面,并将测试结果以文本和图表的形式展示出来。在页面中使用了一些JavaScript代码来计算成功和失败的百分比,并将其以饼状图的形式呈现出来。最终,将html代码写入到文件中,生成测试报告。

main.py

import unittest
import time


class MyTestcase(unittest.TestCase):

    def test_1(self):
        print('main_test_1')
        self.assertEqual(2 - 2, 4)

    def test_2(self):
        print('main_test_2')
        self.assertEqual(2 - 2, 4)

    def test_3(self):
        print('test_3')
        time.sleep(2)
        self.assertEqual(2 + 2, 4)

    def test_4(self):
        print('test_4')
        self.assertEqual(2 - 2, 4)

    def test_5(self):
        print('test_5')
        self.assertEqual(2 + 2, 4)

    def test_6(self):
        print('test_6')
        self.assertEqual(2 + 2, 4)

    def test_7(self):
        print('test_7')
        self.assertEqual(2 + 2, 4)

    def test_8(self):
        print('test_8')
        self.assertEqual(2 + 3, 4)


 Testcase2.py

import unittest

class TestcaseGo(unittest.TestCase):

    def test_1(self):
        print('TestcaseGo_test_1')
        self.assertEqual(2 - 2, 4)

    def test_2(self):
        print('TestcaseGo_test_2')
        self.assertEqual(2 - 2, 4)

    def test_3(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_4(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_5(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_6(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_7(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_8(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_9(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_10(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_11(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)


    def test_12(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_13(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_14(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_15(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_16(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_17(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_18(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_19(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_20(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_21(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_22(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_23(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

    def test_24(self):
        print('TestcaseGo_test_3')
        self.assertEqual(2 + 2, 4)

 run.py

import unittest
import datetime


# 创建主测试类
class MainTestCase(unittest.TestCase):
    pass


if __name__ == '__main__':

    # 统计测试用例执行开始时间
    today1 = datetime.date.today()
    current_time1 = datetime.datetime.now().time()
    # print("执行开始时间:" + str(today1) +" "+ str(current_time1))

    # 创建测试加载器
    loader = unittest.TestLoader()

    # 加载其他Python文件中的测试用例并添加到主测试类中
    test_cases = [
        loader.loadTestsFromName('main.MyTestcase'),
        loader.loadTestsFromName('Testcase2.TestcaseGo')
        # 添加更多的测试文件和测试用例
    ]
    suite = unittest.TestSuite(test_cases)
    suite.addTests(loader.loadTestsFromTestCase(MainTestCase))

    # 计算总用例数量
    total_count = suite.countTestCases()

    # 定义全局的成功、失败和总数计数变量
    success_count = 0
    failure_count = 0

    # 保存执行成功的用例和执行失败的用例
    success_cases = []
    failure_cases = []


    # 重写run()方法,获取用例的执行结果
    class CustomTextTestResult(unittest.TextTestResult):
        def addSuccess(self, test):
            global success_count
            success_count += 1
            success_cases.append(str(test))
            super().addSuccess(test)

        def addFailure(self, test, err):
            global failure_count
            failure_count += 1
            failure_cases.append(str(test))
            super().addFailure(test, err)


    # 创建测试运行器并运行测试
    runner = unittest.TextTestRunner(verbosity=2, resultclass=CustomTextTestResult)
    result = runner.run(suite)

    #  将结果写入文件,指定编码格式为UTF-8
    with open("test_result.txt", "w", encoding="utf-8") as file:
        file.write(f"成功的用例数量: {success_count}\n")
        file.write(f"失败的用例数量: {failure_count}\n")
        file.write(f"总用例数量: {total_count}\n")

        file.write("\n执行成功的用例:\n")
        for case in success_cases:
            file.write(case + "\n")

        file.write("\n执行失败的用例:\n")
        for case in failure_cases:
            file.write(case + "\n")

    print("测试结果已写入文件 test_result.txt")


    # print(total_count)
    # print(success_count)
    # print(failure_count)
    # print(success_cases)
    # print(failure_cases)

    # 生成一个简单的测试报告html页面
    def html_report(today1, current_time1, total_count, success_count, failure_count, success_cases, failure_cases):

        # 用例总数量、成功数量、失败数量、百分比
        Success_Rate = (success_count / total_count) * 100
        failure_Rate = (failure_count / total_count) * 100
        # print(int(Success_Rate))
        # print(int(failure_Rate))
        Success_Rate_text = str(int(Success_Rate)) + '%'
        failure_Rate_text = str(int(failure_Rate)) + '%'
        # print(Success_Rate_text)
        # print(failure_Rate_text)
        Success_Rate_text_b = '{'+str(Success_Rate)+'}%'

        # 拼接元素
        # text_content1 = "\n".join(success_cases)
        # text_content2 = "\n".join(failure_cases)

        test_cases_with_br = [f"{case}<br/>" for case in success_cases]
        # 将带有<br>标签的元素连接成一个字符串
        text_content1 = "".join(test_cases_with_br)

        test_cases_with_br = [f"{case}<br/>" for case in failure_cases]
        # 将带有<br>标签的元素连接成一个字符串
        text_content2 = "".join(test_cases_with_br)

        text_content1 = text_content1
        text_content2 = text_content2

        # 统计测试用例执行时间
        today2 = datetime.date.today()
        current_time2 = datetime.datetime.now().time()
        # print("执行结束时间:" + str(today2) + str(current_time2))
        time_diff = datetime.datetime.combine(datetime.date.min, current_time2) - datetime.datetime.combine(
            datetime.date.min, current_time1)
        strat_time = str(today1) + " " + str(current_time1)
        over_time = str(today2) + " " + str(current_time2)

        # 测试报告html源码
        report = """
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <title>表格示例</title>

            <style>


                """ \
                 + \
                 """
               .status-labels {
                    display: flex;
                    justify-content: space-between;
                    margin-bottom: 10px;
                }

                .status-label {
                    display: flex;
                    align-items: center;
                    text-align: center;
                    flex-direction: column;
                }

                .status-color {
                    width: 20px;
                    height: 20px;
                    margin-right: 5px;
                    align-items: center;
                }

                .pie-chart {
                    width: 200px;
                    height: 200px;
                    border-radius: 50%;
                    background: linear-gradient(to right, green 50%, red 0);
                    transform: rotate(-90deg);
                    margin: 20px auto;
                } 

                """ + """
                th, td {{
                    text-align: center;
                    padding: 10px;
                    vertical-align: top;
                }}

                table {{
                    margin-left: auto;
                    margin-right: auto;
                    border-collapse: collapse;
                    margin: auto;
                }}

            </style>

            </head>
            <body>

                <br/>
                <br/>

                <table border="1">
                    <thead>
                        <th>成功的用例数量</th>
                        <th>成功的用例占比</th>
				        <th>失败的用例数量</th>
				        <th>失败的用例占比</th>
				        <th>总用例数量</th>
                    </thead>
                    <tbody>
                        <tr>
                            <td>{success_count}</td>
                            <td>{Success_Rate_text}</td>
                            <td>{failure_count}</td>
                            <td>{failure_Rate_text}</td>
                            <td>{total_count}</td>
                        </tr>
                    </tbody>
                </table>

                <br/>
                <table border="1">
                    <thead>
                        <tr>
                            <th>执行开始时间</th>
                            <th>执行结束时间</th>
                            <th>执行总耗时</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>{strat_time}</td>
                            <td>{over_time}</td>
                            <td>{time_diff}</td>
                        </tr>
                    </tbody>
                </table>


                <br/>
                <br/>


                <table  id="my-table">
                     <thead>
                            <tr>
                                <th><div class="status-color" style="background-color: #336699;"></div></th>
                                <th>成功</th>
                                <th><div class="status-color" style="background-color: #bf242a;"></div></th>
                                <th>失败</th>
                            </tr>
                        </thead>
                        <tbody>

                    </tbody>

                    </table>
                <div class="pie-chart"></div>

                <br/>
                <table border="1">
                    <thead>
                        <tr>
                            <th>执行成功的用例</th>
                            <th>执行失败的用例</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>{text_content1}</td>
                            <td>{text_content2}</td>
                        </tr>
                    </tbody>
                </table>

                <br/>
                <br/>
            """.format(time_diff=time_diff, strat_time=strat_time, over_time=over_time, total_count=total_count,
                       success_count=success_count, Success_Rate_text=Success_Rate_text, failure_count=failure_count,
                       failure_Rate_text=failure_Rate_text, text_content1=text_content1, text_content2=text_content2) \
                 + \
                 """

                <script>

                    // 获取饼图元素
                    var pieChart = document.querySelector('.pie-chart');

                    // 设置饼图的背景渐变色
                    pieChart.style.background = `conic-gradient(#336699 ${Success_Rate_text}, #bf242a 0)`;
                </script>


            """.format(Success_Rate_text=Success_Rate_text_b) + """
            </body>
            </html>
        """
        # ${successPercentage}%
        # $81%
        print(report)

        with open("html_result.html", "w", encoding="utf-8") as file:
            file.write(report)

        print("测试报告生成成功!")


    html_report(today1, current_time1, total_count, success_count, failure_count, success_cases, failure_cases)
    # html_report(total_count, success_count, failure_count, success_cases, failure_cases)

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

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

相关文章

记录一次校园CTF--wp

一.第一题简单nc 这题直接nc 地址端口即可得到flags没有套路 二.第二题pwn:ezstack 这是一题栈溢出题目&#xff0c;查看保护&#xff1a; 没有开启PIE&#xff0c;运行下查看效果&#xff1a; 题目是一个文字购物游戏。 接着扔进IDA中分析&#xff1a; 在主函数中我们找到…

macOS电池续航工具:Endurance中文

Endurance for Mac是一款强大而实用的电池管理和优化软件&#xff0c;专为MacBook设计。通过智能调整系统设置和管理后台应用&#xff0c;它能有效延长电池续航时间&#xff0c;提升工作和娱乐效率&#xff0c;成为你在各种场合下的得力助手。 Endurance for Mac软件的功能特色…

cordova Xcode打包ios以及发布流程(ionic3适用)

第一步 1、申请iOS证书 2、导入证书到钥匙串 第二步 1、xcode配置iOS证书 1.1用Xcode打开你的项目&#xff08;我的Xcode版本是新版&#xff09; 修改如下图 回到基本信息设置界面&#xff0c;Bundie 这项填写&#xff0c;最先创建的那个appid&#xff0c;跟创建iOS描述文件时选…

MySQL基础架构详解

概述 我们学习东西&#xff0c;都不应该是先去了解细节&#xff0c;而是应该窥其全貌&#xff0c;这样才能从高纬度去理解问题&#xff0c;同样我们学习mysql也是一样的&#xff0c;我们应该先了解整个mysql架构&#xff0c;及来龙去脉&#xff0c;才能更好的掌握它。下面我们开…

Mybatis-Plus使用Wrapper自定义SQL

文章目录 准备工作Mybatis-Plus使用Wrapper自定义SQL注意事项目录结构如下所示domain层Controller层Service层ServiceImplMapper层UserMapper.xml 结果如下所示&#xff1a;单表查询条件构造器单表查询&#xff0c;Mybatis-Plus使用Wrapper自定义SQL联表查询不用&#xff0c;My…

qt6:无法使用setFontColor

问题描述 跟着C开发指南视频学习&#xff0c;但是发现无论是直接使用ui设计&#xff0c;还是纯代码都无法实现变更字体颜色的功能。图中显示&#xff0c;点击颜色控件后&#xff0c;文本框的文字加粗、下划线、斜体等才能设置&#xff0c;但是无法变更颜色。 此文提醒qt sty…

基于驾驶训练算法的无人机航迹规划-附代码

基于驾驶训练算法的无人机航迹规划 文章目录 基于驾驶训练算法的无人机航迹规划1.驾驶训练搜索算法2.无人机飞行环境建模3.无人机航迹规划建模4.实验结果4.1地图创建4.2 航迹规划 5.参考文献6.Matlab代码 摘要&#xff1a;本文主要介绍利用驾驶训练算法来优化无人机航迹规划。 …

『MySQL快速上手』-③-库的操作

文章目录 1.创建数据库2.创建数据库案例3.字符集和校验规则3.2 校验规则对数据库的影响3.2.1 进行查询3.2.2 进行排序 4.字符集和检验规则的作用5.操纵数据库5.1 查看数据库5.2 显示创建语句5.3 修改数据库5.4 数据库删除 6.备份与恢复6.1 备份6.2 还原6.3 注意事项 7.查看数据…

[量化投资-学习笔记007]Python+TDengine从零开始搭建量化分析平台-布林带

布林带&#xff08;Bollinger Bands&#xff09;也称为布林通道、保力加通道&#xff0c;是由约翰布林格&#xff08;John Bollinger&#xff09;发明的技术分析指标。布林通道通常被用来确认资产价格波动范围。 布林通道是由三条平滑的曲线组成的趋势线图表&#xff0c;中线为…

js原型链

什么叫原型链 原型链是js中的核心&#xff0c;原型链将各个属性链接起来&#xff0c;在原型链上面定义&#xff0c;原型链上的其他属性能够使用&#xff0c;原型链就是保证继承 原型链区分 原型链分为显式原型和隐式原型 显式原型&#xff1a;只有函数和构建函数才有显式原型…

CCF CSP认证 历年题目自练Day44

题目一 试题编号&#xff1a; 201612-3 试题名称&#xff1a; 权限查询 时间限制&#xff1a; 1.0s 内存限制&#xff1a; 256.0MB 问题描述&#xff1a; 问题描述   授权 (authorization) 是各类业务系统不可缺少的组成部分&#xff0c;系统用户通过授权机制获得系统中各个…

[ACTF2020 新生赛]BackupFile 1

题目环境&#xff1a; 好好好&#xff0c;让找源文件是吧&#xff1f;咱们二话不说直接扫它后台 使用dirsearch工具扫描网站后台&#xff08;博主有这个工具的压缩包&#xff0c;可以私聊我领取&#xff09;python dirsearch.py -u http://0d418151-ebaf-4f26-86b2-5363ed16530…

01-基于IDEA,Spring官网,阿里云官网,手动四种方式创建SpringBoot工程

快速上手SpringBoot SpringBoot技术由Pivotal团队研发制作&#xff0c;功能的话简单概括就是加速Spring程序初始搭建过程和Spring程序的开发过程的开发 最基本的Spring程序至少有一个配置文件或配置类用来描述Spring的配置信息现在企业级开发使用Spring大部分情况下是做web开…

基于机器学习的 ICU 脑血管疾病死亡风险智能预测系统

温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长 Wechat / QQ 名片 :) 1. 项目简介 重症患者或重大手术后的患者在重症监护室&#xff08;ICU&#xff09;内通过多种生命支持系统以维持生理功能。患者在ICU 内会被频繁持续的记录生命体征和实验室测量等多种数据。由于高频…

为什么有了MAC地址,还需要IP地址?

解释 搞懂这个问题&#xff0c;首先需要了解交换机的功能 交换机内部有一张MAC地址映射表&#xff0c;记录着MAC地址和端口的对应关系。 如果A要给B发送一个数据包&#xff0c;构造如下格式的数据结构&#xff1a; 到达交换机时&#xff0c;交换机内部通过自己维护的 MAC 地…

b2b.ccb.com:443 需要你的凭据

忙活了一天&#xff0c;晚上回来准备查一下公户的最近的账单。因为昨天晚上熬夜重新做了电脑系统&#xff0c;就下载了建设银行的E路护航&#xff0c;一切安装就绪&#xff0c;准备进入企业网银时&#xff0c;被这些垃圾搞的系统及软件恶心到了&#xff0c;在此记录一下&#x…

Flutter利用GridView创建网格布局实现优美布局

文章目录 简介使用详解导入依赖项创建一个基本的 GridView一些参数说明使用GridView.count来构造 其他控制总结 简介 GridView 是 Flutter 中用于创建网格布局的强大小部件。它允许你在行和列中排列子小部件&#xff0c;非常适合显示大量项目&#xff0c;例如图像、文本、卡片…

js树形数组遍历练习,扁平化、格式化、获取节点父级

1.树形数组扁平化 数组扁平化的方式很多&#xff0c;这里主要是用递归处理&#xff0c;除此之外还有正则、扩展运算符等等 const list [{name:1,id:1,children:[{name:11,id:11,children:[{name:111,id:111}]},{name:12},]},{name:2,id:2,children:[{name:21,id:21,children:…

数据结构-栈和队列(一)

目录 1.栈 1.1 栈的概念及结构 1.2 栈的实现 初始化栈&#xff1a; 入栈&#xff1a; 判空函数&#xff1a; 出栈&#xff1a; 获取栈顶元素&#xff1a; 获取栈中有效元素的个数&#xff1a; 销毁栈&#xff1a; 完整代码&#xff1a; 测试&#xff1a; 2. 队列 …

在 Python 中使用 Selenium 按文本查找元素

我们将通过示例介绍在Python中使用selenium通过文本查找元素的方法。 在 Python 中使用 Selenium 按文本查找元素 软件测试是检查应用程序是否满足用户需求的技术。 该技术有助于使应用程序成为无错误的应用程序。 软件测试可以手动完成&#xff0c;也可以通过某些软件完成。…