在使用unittest框架时,我们常常需要下载一个HTMLRunnerCN.py用来生成HTML格式的报告,那么我们能不能自己实现一个呢?

HTMLRunner是模仿unittest自带的TextTestRunner()实现的,我们先来看看TextTestRunner()的运行流程。

TextTestRunner使用方法

import unittest

suite = unittest.defaultTestLoader.discover("./")

with open("report.txt", "w") as f:   # 将运行结果保存为txt文件
unittest.TextTestRunner().run(suite)

运行流程

  1. TextTestRunner 内部实现了一个TextTestResult(继承自unittest.TestResult类)来记录测试结果
  2. TextTestRunner().run()实际调用suite(result) suite.run(result) (result用来记录结果)
  3. suite.run(result)会遍历suite中的用例,依次调用case(result)case.run(result)
  4. case.run(result)时,首先会调用result.testRun+=1然后执行用例方法testMethod(), 如果用例失败、出错、跳过则用例会分别调用result.addSuccess(),result.addFailure()等方法,在对应的result.failures,result.errors列表中添加用例信息,默认成功用例result中不处理
  5. 运行完返回result(测试结果对象)

unittest.TextTestRunner和网上的HTMLRunner都是基于stream流去写的文件,每执行一条用例,把对应的结果和信息写到流中,最后输出成文件,这种方法需要很多的细节控制,比较复杂。

我们可以采用解析执行完返回result结果,通过Jinjia2模板引擎渲染,将数据渲染到模板里,形成报告文件。

Jinjia2是一个三方包,可以将模板代码中的{{变量名}}等占位符将变量值渲染进去,支持循环和if判断。安装方法pip install jinjia2

实现步骤

  1. 首先我们要写个模板
TPL = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body>
<h2>{{title}}</h2>
<h3>{{description}}</h3>
<br/>
<table border="1">
{% for case in cases %}
<tr>
<td>{{case.name}}</td>
<td>{{case.status}}</td>
<td>{{case.exec_info}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
'''
  • {{title}},{{description}}能将传入的数据中的相应的变量值填充进去
  • {% for case in cases%} ...{% endfor %}遍历cases列表中每一个用例数据,每个生成一个表格行(<tr>...</tr>
  1. 自定义一个Result类

    由于默认的TestResult()将各种状态的用例分散存的,我们可以自定义一个Result类来处理用例成功、失败、出错执行的操作
class Result(unittest.TestResult):
def __init__(self):
super().__init__()
self.cases = [] def addSuccess(self, test):
self.cases.append({"name": test.id(), "status": "pass", "exec_info": ""}) def addError(self, test, exec_info):
self.cases.append({"name": test.id(), "status": "error",
"exec_info": self._exc_info_to_string(exec_info, test)
.replace("\n", "<br/>")}) def addFailure(self, test, exec_info):
self.cases.append({"name": test.id(), "status": "fail",
"exec_info": self._exc_info_to_string(exec_info, test)
.replace("\n", "<br/>")}) def addSkip(self, test, reason):
self.cases.append({"name": test.id(), "status": "skip", "exec_info": reason))
  • addSuccess等方法对应用例成功或其他状态时在result结果中的操作
  • _exec_info_to_string: 默认用例传过来的exec_info是Trackback对象

    ,需要转换为字符串,replace\n转为网页的换行<br/>
  1. 实现我们的HTMLRunner
class HTMLRunner(object):
def __init__(self, output, title="Test Report", description=""):
self.file = output
self.title = title
self.description = description def run(self, suite):
result = Result() # 用于保存测试结果
suite(result) # 执行测试 # 渲染数据到模板
content = Template(TPL).render({"title": self.title,
"description": self.description,
"cases": result.cases})
with open(self.file, "w") as f:
f.write(content) # 写入文件
return result
  1. 使用方法(自己准备几条用例)
suite = unittest.defaultTestLoader.discover("./")

HTMLRunner(output="report.html",
title="测试报告",
description="测试报告描述").run(suite)

生成的测试报告

整体代码

美化格式,增加执行统计信息

import time
import unittest
from jinja2 import Template TPL = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="pt-4">测试报告</h1>
<h6>测试报告描述信息</h6>
<h6>执行: {{run_num}} 通过: {{pass_num}} 失败: {{fail_num}} 出错: {{error_num}} 跳过: {{skipped_num}}</h6>
<h6 class="pb-2">执行时间: {{duration}}s</h6>
<table class="table table-striped">
<thead><tr><th>用例名</th><th>状态</th><th>执行信息</th></tr></thead>
<tbody>
{% for case in cases %}
<tr><td>{{case.name}}</td><td>{{case.status}}</td><td>{{case.exec_info}}</td></tr>
{% endfor %}
</tbody>
</table>
</div> </body>
</html>
''' class Result(unittest.TestResult):
def __init__(self):
super().__init__()
self.success = []
self.cases = [] def addSuccess(self, test):
self.success.append(test)
self.cases.append({"name": test.id(), "status": "pass", "exec_info": ""}) def addError(self, test, exec_info):
self.errors.append((test, exec_info))
self.cases.append({"name": test.id(), "status": "error",
"exec_info": self._exc_info_to_string(exec_info, test)
.replace("\n", "<br/>")}) def addFailure(self, test, exec_info):
self.failures.append((test, exec_info))
self.cases.append({"name": test.id(), "status": "fail",
"exec_info": self._exc_info_to_string(exec_info, test)
.replace("\n", "<br/>")}) def addSkip(self, test, exec_info):
self.skipped.append((test, exec_info))
self.cases.append({"name": test.id(), "status": "skip",
"exec_info": self._exc_info_to_string(exec_info, test)
.replace("\n", "<br/>")}) def addExpectedFailure(self, test, exec_info):
self.success.append(test)
self.cases.append({"name": test.id(), "status": "pass",
"exec_info": self._exc_info_to_string(exec_info, test)
.replace("\n", "<br/>")}) def addUnexpectedSuccess(self, test):
self.failures.append((test, "UnexpectedSuccess"))
self.cases.append({"name": test.id(), "status": "fail", "exec_info": "UnexpectedSuccess"}) class HTMLRunner(object):
def __init__(self, output, title="Test Report", description=""):
self.file = output
self.title = title
self.description = description def run(self, suite):
result = Result() # 用于保存测试结果
start_time = time.time()
suite(result) # 执行测试
duration = round(time.time() - start_time, 6)
print(len(result.success), len(result.failures))
# 渲染数据到模板
content = Template(TPL).render({"title": self.title,
"description": self.description,
"cases": result.cases,
"run_num": result.testsRun,
"pass_num": len(result.success),
"fail_num": len(result.failures),
"skipped_num": len(result.skipped),
"error_num": len(result.errors),
"duration": duration})
with open(self.file, "w") as f:
f.write(content) # 写入文件
return result if __name__ == "__main__":
suite = unittest.defaultTestLoader.discover("./")
HTMLRunner(output="report.html",
title="测试报告",
description="测试报告描述").run(suite)

Python测试交流,欢迎添加作者微信:lockingfree

如何自己实现一个HTMLRunner的更多相关文章

  1. 为什么很多人坚信“富贵险中求”?

    之家哥 2017-11-15 09:12:31 微信QQ微博 下载APP 摘要 网贷之家小编根据舆情频道的相关数据,精心整理的关于<为什么很多人坚信"富贵险中求"?>的 ...

  2. python基础全部知识点整理,超级全(20万字+)

    目录 Python编程语言简介 https://www.cnblogs.com/hany-postq473111315/p/12256134.html Python环境搭建及中文编码 https:// ...

  3. 让HTMLrunner 报告的子列表都 默认展示出来的 方法(方便发送邮件时可以方便查看)

    1.找到生成的测试报告,获取到all元素 2.在HTMLrunner源码,</script> 标签上 加入一个函数 #让所有列表都展示出来window.onload = function ...

  4. Tomcat一个BUG造成CLOSE_WAIT

    之前应该提过,我们线上架构整体重新架设了,应用层面使用的是Spring Boot,前段日子因为一些第三方的原因,略有些匆忙的提前开始线上的内测了.然后运维发现了个问题,服务器的HTTPS端口有大量的C ...

  5. 如何一步一步用DDD设计一个电商网站(九)—— 小心陷入值对象持久化的坑

    阅读目录 前言 场景1的思考 场景2的思考 避坑方式 实践 结语 一.前言 在上一篇中(如何一步一步用DDD设计一个电商网站(八)—— 会员价的集成),有一行注释的代码: public interfa ...

  6. 如何一步一步用DDD设计一个电商网站(八)—— 会员价的集成

    阅读目录 前言 建模 实现 结语 一.前言 前面几篇已经实现了一个基本的购买+售价计算的过程,这次再让售价丰满一些,增加一个会员价的概念.会员价在现在的主流电商中,是一个不大常见的模式,其带来的问题是 ...

  7. SQLSERVER将一个文件组的数据移动到另一个文件组

    SQLSERVER将一个文件组的数据移动到另一个文件组 有经验的大侠可以直接忽视这篇文章~ 这个问题有经验的人都知道怎麽做,因为我们公司的数据量不大没有这个需求,也不知道怎麽做实验 今天求助了QQ群里 ...

  8. 构建一个基本的前端自动化开发环境 —— 基于 Gulp 的前端集成解决方案(四)

    通过前面几节的准备工作,对于 npm / node / gulp 应该已经有了基本的认识,本节主要介绍如何构建一个基本的前端自动化开发环境. 下面将逐步构建一个可以自动编译 sass 文件.压缩 ja ...

  9. 【造轮子】打造一个简单的万能Excel读写工具

    大家工作或者平时是不是经常遇到要读写一些简单格式的Excel? shit!~很蛋疼,因为之前吹牛,就搞了个这东西,还算是挺实用,和大家分享下. 厌烦了每次搞简单类型的Excel读写?不怕~来,喜欢流式 ...

随机推荐

  1. beego 参数配置

    详细配置请参考:https://godoc.org/github.com/astaxie/beego#pkg-constants. App配置 AppName 应用名称,默认是 beego.通过bee ...

  2. element-ui 中 table 鼠标悬停时背景颜色修改

    样式穿透: /deep/ .el-table tbody tr:hover>td { background-color: #颜色 }

  3. 计算两个坐标点的距离(高德or百度)

    /// <summary> /// 获取两个坐标之间的距离 /// </summary> /// <param name="lat1">第一个坐 ...

  4. js 超浓缩 双向绑定

    绑定确实是个有趣的话题. 现在我的绑定器有了不少的功能 1. 附着在Object对象上,一切以对象为中心 2. 与页面元素进行双向绑定 3. 与任意对象绑定,主要是应用在绑定到页面元素的一些属性上,比 ...

  5. js将阿拉伯数字转换成汉字大写

    适用场景:票据,结算凭证等.将任意数字的金额,转换成汉字大写的形式.例如:1234.50 -> 壹仟贰佰叁拾肆圆伍角.壹.贰.叁.肆 直接贴代码,如下: //阿拉伯数字转换成大写汉字 funct ...

  6. 一次解决黑帽SEO的经历

    最近有个朋友跟我说他的网站被黑了,百度快照里显示的是另一个网站,如: 于是查找了些资料,终于找到了问题所在,记录如下: 关于黑帽SEO1.暗链:其实“暗链”就是看不见的网站链接,“暗链”在网站中的链接 ...

  7. 安装笔记, caffe 、 opencv等

    1. 1.1 opencv static linux mkdir build & cd build cmake .. -LH  这句话用来查看编译选项  如果不知道编译啥  可以用这个查看一下 ...

  8. 图片样式加hover特效

    之前有个尴尬的事情发生,我不知道如何将文字放在图片右边,我想了个麻烦且愚蠢的办法,后来才知道只需要将图片居左就可以达到效果.....不说了看下面 需要实现的效果: 很简单, <img src=& ...

  9. vue学习(9)-路由守卫

    全局守卫 你可以使用 router.beforeEach 注册一个全局前置守卫: const router = new VueRouter({ ... })   router.beforeEach(( ...

  10. django inclusion用法

    概述: inclusion主要的是生成html标签, 返回的是一个字典,大分部跟simple_tag类似, simple_tag可返回任意类型的值 定义inclusion from django im ...