使用 HTMLTestRunner 自动生成测试报告

高效程序员

共 1812字,需浏览 4分钟

 ·

2020-09-29 11:05


在做自动化测试时,我们通常希望以可视化的形式来展示测试结果,这时候 HTMLTestRunner 就有很大的用武之地了。它是 Python 标准库中 unittest 模块的一个扩展,可用于生成 HTML 测试报告。



1

配置  HTMLTestRunner


虽然 HTMLTestRunner 很强大,但有个小问题,它是基于 Python2 的,所以无法直接在 Python3 中直接使用(网上下载的很多都用不了)。


那就升级一下吧,由于文件内容过多,所以就不直接贴代码了,点击下面的链接直接下载(已验证通过,可直接使用):


  • 戳我:https://github.com/Waleon/HTMLTestRunner


下载 HTMLTestRunner.py 之后,将其拷贝至 Python 的安装目录下,例如:/usr/local/lib/python3.7/dist-packages/,然后就可以使用了。



2

测试脚本


编写一个简单的示例脚本 - autotest.py,看是否能自动生成测试报告:


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import unittest
import HTMLTestRunner
import time

class TestDemo(unittest.TestCase):
    """测试用例"""

    def setUp(self):
        print('========== begin ==========')

    def test_success(self):
        self.assertEqual(1 + 12)

    def test_fail(self):
        self.assertEqual(1 + 110)

    def test_error(self):
        self.assertEqual(x, 1024)

    def tearDown(self):
        print('========== end ==========')

if __name__ == '__main__':
    # 构造测试集
    suite = unittest.TestSuite()

    # 添加测试用例
    suite.addTest(TestDemo("test_success"))
    suite.addTest(TestDemo("test_fail"))
    suite.addTest(TestDemo("test_error"))

    # 报告路径
    date_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    report_abspath = 'report_' + date_time + '.html'

    # 执行测试
    with open(report_abspath, 'wb'as f:
        runner = HTMLTestRunner.HTMLTestRunner(
            stream=f,
            title='TestDemo unit test',
            description='TestDemo report output by HTMLTestRunner.'
        )
        runner.run(suite)



3

验证一下


执行脚本,进行验证:


$ python3 autotest.py


不出意外,这时会生成一个后缀为 .html 的文件,这就是我们的测试报告,打开来看看:



像标题、描述、日期等基本信息都有,当然执行的用例也少不了,一共有 3 条,一条成功,一条失败,一条错误。


如果要查看对应用例的详细信息,可以点击蓝色的超链接按钮,尤其在有失败和错误的情况下,这个功能非常好用,能帮助我们快速定位问题!


·END·

浏览 54
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报