Python自动化测试生成HTML测试报告
HTMLTestRunner是Python标准库unittest单元测试框架的一个扩展,他生成易于使用的HTML测试报告。
Ubuntu放置位置:输入Python3 命令进入Python交互模式,通过import sys 以及sys.path可以查看本机Python的安装目录
[email protected]:/home/ranxf# python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.p
sys.path sys.platform sys.ps2
sys.path_hooks sys.prefix
sys.path_importer_cache sys.ps1
>>> sys.path
[‘‘, ‘/usr/lib/python35.zip‘, ‘/usr/lib/python3.5‘, ‘/usr/lib/python3.5/plat-x86_64-linux-gnu‘, ‘/usr/lib/python3.5/lib-dynload‘, ‘/usr/local/lib/python3.5/dist-packages‘, ‘/usr/lib/python3/dist-packages‘]
以root身份将HTMLTestRunner.py文件复制到/usr/local/lib/python3.5/dist-packages目录下。
[email protected]:/usr/local/lib/python3.5/dist-packages# ls
selenium selenium-3.7.0.dist-info
[email protected]:/usr/local/lib/python3.5/dist-packages# cp /home/ranxf/下载/HTMLTestRunner.py .
[email protected]:/usr/local/lib/python3.5/dist-packages# ls
HTMLTestRunner.py selenium selenium-3.7.0.dist-info
在交互模式导入模块,如果没有报错,则说明添加成功:
[email protected]:/usr/local/lib/python3.5/dist-packages# python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import HTMLTestRunner
>>>
实例:遍历在该路径(/home/ranxf/python_web_unittest-master/test_case)下以test开头的所有用例。
import unittest, time
from HTMLTestRunner import HTMLTestRunner
# 定义测试用例的目录为当前目录
# test_dir = ‘./test_case‘
# discover = unittest.defaultTestLoader.discover(test_dir, pattern=‘test*.py‘)
if __name__ == ‘__main__‘:
test_dir = ‘/home/ranxf/python_web_unittest-master/test_case‘
test_report = ‘/home/ranxf/python_web_unittest-master/report‘
discover = unittest.defaultTestLoader.discover(test_dir, pattern=‘test*.py‘)
# 按照一定格式获取当前时间
now = time.strftime("%Y-%m-%d %H_%M_%S")
# 定义报告存放路径
# filename = ‘./‘ + now + ‘ result.html‘
filename = test_report + ‘/‘ + now + ‘result.html‘
fp = open(filename, ‘wb‘)
# 定义测试报告
runner = HTMLTestRunner(stream=fp,
title=‘web测试报告‘,
description=‘用例执行情况: ‘)
runner.run(discover)
fp.close()
测试项目目录结构如下:
[email protected]:/home/ranxf/python_web_unittest-master# tree . ├── report ├── runtest.py └── test_case ├── test_baidu.py └── test_youdao.py
report:放置HTML报告的目录;
runtest.py:遍历测试用例的主程序;
test_case:用例放置目录
运行后的目录结构:
[email protected]:/home/ranxf/python_web_unittest-master# tree
.
├── report
│ └── 2017-12-26 15_56_59result.html
├── runtest.py
└── test_case
├── test_baidu.py
└── test_youdao.py