Python3测试框架unittest搭配自动化测试报告工具HTMLTestRunner

news/2025/2/12 15:26:21/文章来源:https://www.cnblogs.com/lansling09/p/18706144

最近接触到Python的测试框架unittest, 浅浅的学习了一下。
unittest和HTMLTestRunner搭配,可以完成自动化测试的功能并生成自动化测试报告。

一. 简介

  1. Python内置的unittest模块,用于编写和执行单元测试。
    HTMLTestRunner 是一个用于生成自动化测试报告的工具,扩展了 unittest 模块。它可以生成详细的 HTML 测试报告,包含测试结果、用例数、成功率等信息。
    HTMLTestRunner非内置模块,需要另外安装。安装方式如下: pip install HTMLTestRunner-Python3

  2. unittest一些很重要的概念:
    test fixture
    A test fixture represents the preparation needed to perform one or more tests, and any associated cleanup actions.
    This may involve, for example, creating temporary or proxy databases, directories, or starting a server process.

    test case
    A test case is the individual unit of testing. It checks for a specific response to a particular set of inputs.
    unittest provides a base class, TestCase, which may be used to create new test cases.

    test suite
    A test suite is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.

    test runner
    A test runner is a component which orchestrates the execution of tests and provides the outcome to the user.
    The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests.

  3. A testcase is created by subclassing unittest.TestCase. The three individual tests are defined with methods whose names start with the letters test.
    This naming convention informs the test runner about which methods represent tests.

  4. assert
    The TestCase class provides several assert methods to check for and report failures.
    The following table lists the most commonly used methods (see the tables below for more assert methods):



二. 代码
代码示例运行环境:
win10 + Python3.11.5 + IDIE

代码示例

点击查看代码
unittest_sample.py:import unittest
from HTMLTestRunner import HTMLTestRunner
import timeclass Student(object):def __init__(self, age, weight):self.__age = ageself.__weight = weightdef getAge(self):return self.__agedef getWeight(self):return self.__weightdef setAge(self, age):self.__age = agereturn Truedef setWeight(self, weight):self.__weight = weightreturn Trueclass Calculator(object):@classmethoddef add(cls, num1, num2):return num1 + num2@classmethoddef sub(cls, num1, num2):return num2 - num1@classmethoddef mul(cls, num1, num2):return num1 * num2@classmethoddef div(cls, num1, num2):return num2 / num1def getTestReportNameWithTimestamp():now_time = time.strftime('%Y%m%d%H%M%S')testReportName = './result_' + now_time + '.html'return testReportNameclass TestStudent(unittest.TestCase):@classmethoddef setUpClass(cls):print('TestStudent setUpClass ...')cls.stu = Student(10, 20)@classmethoddef tearDownClass(cls):print('TestStudent tearDownClass ...')def setUp(self):print('TestStudent setUp ...')def tearDown(self):print('TestStudent tearDown ...')def test_get_age(self):''' verify age '''print('testcase get age')self.assertEqual(self.stu.getAge(), 10)def test_get_weight(self):''' verify weight '''print('testcase get weight')self.assertEqual(self.stu.getWeight(), 20)def test_set_age(self):''' verify change age '''print('testcase set age')self.stu.setAge(20)self.assertEqual(self.stu.getAge(), 20)def test_set_weight(self):''' verify change weight '''print('testcase get weight')self.stu.setWeight(100)self.assertTrue(self.stu.getWeight(), 100)class TestCalculator(unittest.TestCase):@classmethoddef setUpClass(cls):print('TestCalculator setUpClass')@classmethoddef tearDownClass(cls):print('TestCalculator tearDownClass')def setUp(self):print('TestCalculator setUp')def tearDown(self):print('TestCalculator tearDown')def test_add(self):self.assertEqual(Calculator.add(1, 2), 3)def test_sub(self):self.assertEqual(Calculator.sub(3, 5), 2)def test_mul(self):self.assertEqual(Calculator.mul(2, 8), 16)def test_div(self):self.assertEqual(Calculator.div(5, 100), 20)def run_unittest():unittest.main()def run_suite_addTest():suite_obj = unittest.TestSuite()suite_obj.addTest(TestStudent("test_get_age"))suite_obj.addTest(TestStudent("test_get_weight"))suite_obj.addTest(TestStudent("test_set_age"))suite_obj.addTest(TestStudent("test_set_weight"))testReportName = getTestReportNameWithTimestamp()with open(testReportName, 'wb') as fp:runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='Test Student', description='TestCase List')runner.run(suite_obj)def run_suite_addTests():map_obj = map(TestStudent, ['test_get_age', 'test_get_weight', 'test_set_age', 'test_set_weight', 'test_aget_weight'])suite_obj = unittest.TestSuite()suite_obj.addTests(map_obj)testReportName = getTestReportNameWithTimestamp()with open(testReportName, 'wb') as fp:runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='Test Student', description='TestCase List')runner.run(suite_obj)def run_testloader():suite = unittest.TestSuite()testCaseSuite1 = unittest.TestLoader().loadTestsFromTestCase(TestStudent)suite.addTests(testCaseSuite1)testCaseSuite2 = unittest.TestLoader().loadTestsFromTestCase(TestCalculator)suite.addTests(testCaseSuite2)testReportName = getTestReportNameWithTimestamp()with open(testReportName, 'wb') as fp:runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='Test Result Report', description='TestCase List')runner.run(suite)if __name__ == '__main__':run_testloader()

执行后生成的自动化测试报告如下:

参考 https://docs.python.org/3/library/unittest.html

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

毕业设计目前进度

毕业设计进度:基于VoIP的音频音协算法设计与实现 1、学习了MATLAB的使用并动手实践界面认识 变量命名 运算和程序结构 矩阵操作 绘制二维三维图形等 绘制波形图(或数据曲线图)通过学习matlab的使用,为编写代码和运行并检测音频质量打下基础,同时也学会了建立坐标轴并绘制图…

使用LM Studio部署DeepSeek 1.5B模型

下载LM Studio: https://installers.lmstudio.ai/win32/x64/0.3.9-6/LM-Studio-0.3.9-6-x64.exe 安装LM Studio: 略 打开LM Studio 设置语言启用内置代理,用于下载模型,否则大概率在Model Search中看不到模型信息,无法下载模型模型下载,两种方式: 第一种,通过LM Studio…

React—05—脚手架

使用npm全局下载create-react-app, 建议node>16。npm install create-react-app -g; 然后创建项目即可。create-react-app 项目名称 但是现在create-react-app有问题,有些库依赖的react18但是这个脚手架创建的默认是react19,而官方还没解决这个问题,建议用vite创建一…

2.9 CW 练时记录

前言 新的类型, 跟考试放的差不多的策略就行了 后面就是找时间复习, 然后找一下状态就好了 \(\rm{F}\) 看到这是个 \(\rm{C}\) 题, 先做这个 思路给定 \(p_{i, c}\) 表示位置 \(i\) 是字符 \(c\) 的概率, 确定 \(\displaystyle\sum_{c = 1}^{t} p_{i, c} = 1\) 一个有效的信息被…

SMU2025寒假训练周报2

这周状态其实不太好,很多时候心急总是卡简单题,中档题也有些难a,希望尽快调整 一.个人训练赛2 1. Linova and Kingdom 题目链接:Problem - C - Codeforces 每加一个点总体贡献就可能发生变化,那我们就处理每个点的贡献,将他的深度减去他孩子的总个数就是贡献,最后排序取…

无需服务器个性化域名重定向到其他网站

1. 准备工作 1. 申请个人域名免费方式:从 ClouDNS.net上创建账号申请即可,右上角可以选择中文。如果实在不会操作,可以参考:教你免费注册一个ClouDNS永久域名(保姆级教程) ,还可以自行搜索或问大模型或留言。 付费方式:从 主流域名注册商注册,国外:namesilo 比较便宜,…

在GitHub上部署个人静态网站

在GitHub上部署个人静态网站 首先将网站设置文件上传到github的一个新建仓库,并公开仓库(会员可不用公开)找到settings(设置)-page(页面)选项并进入 选择分支(root)并save等待一段时间(5分钟左右),重新进入该仓库的pages 已经生成网址点击网址或者Visit site进入网站…

使用nvm管理node版本

1、下载安装 NVM:https://github.com/coreybutler/nvm-windows2、下载完成后,解压缩nvm-setup.zip文件到您想要安装 NVM 的目录,双击nvm-setup.exe进行安装 3、配置环境变量,将安装目录添加到path环境变量PS C:\Users> nvm -v 1.2.24、查看可用的 Node.js 版本: 5、选择…

Cursor从0到1:让每个人都会编程

Cursor 可谓是最近最火的 AI 代码类应用之一。它结合了传统编辑器的功能(如 VS Code 的体验)与 AI 驱动的智能编程能力,旨在提升开发效率和代码质量。一、关于Cursor 1.1 简介 Cursor 是一款基于人工智能(AI)的现代化代码编辑器,专为开发者设计。它结合了传统编辑器的功能…

销售就是推销自己

销售的本质是顾客用钱买满足自己需求的卖方提供的产品。销售员就承担着桥梁的角色。渠道那么多,销售人员那么多,顾客为什么要通过你来买? 优秀的销售人员(商人)有下面几个特点。 1.自信 如果你相信你会成功,成功便会发生;如果你相信你会失败,失败便会找上门。无论如何我…

Snipaste - 截屏软件

qq截屏闪退,故更改软件————下载https://www.snipaste.com/download.html选择对应版本 下载后双击即可(默认F1截屏) 参考: https://blog.csdn.net/m0_64979660/article/details/142353087

红蓝对抗之系统密码提取

mimikatz mimikatz工具从内存中提取明文密码,HASH值,PIN密码和票据,利用zerologon漏洞(通过NetLogon/MS-NRPC协议与AD域控建立安全通道时,可利用该漏洞将AD域控的计算机账号密码设置为空。 mimikatz 需要管理员或 SYSTEM 权限,通常使用 DEBUG 权限执行某些操作,与 LSASS…