Python+unittest自动化测试多线程执行合并测试报告
主要解决思路就是利用 runner.run(all_case)执行结束后会返回测试结果,拿到测试结果后,再重新整合测试报告。同时利用threadpool.makeRequests(run_case, lst)构建多线程执行,但是这里多线程执行指的的是多个py文件里面的测试用例是并发的,但是单个py里面的测试用例执行还是按照字母顺序执行的。
import datetime
import platform
import sys
import os
import time
import unittest
# 解决bat执行的路径问题
import threadpool as threadpool
from HTMLTestRunner import MergeResult, HTMLTestRunner
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)
print(rootPath)
sys.path.append(rootPath)
current_path = os.getcwd()
current_path = r"E:\study"
allcase = r"E:\study\test_case"
if platform.platform().startswith("Linux"):
current_path = "M_site_selenium"
allcase = "M_site_selenium/case"
def create_suite():
# 不要太多其他的
discover = unittest.defaultTestLoader.discover(allcase, pattern='test*.py', top_level_dir=None)
return discover
# 所以case 结果result,存入list
all_result = []
def run_case(all_case, report_path, nth=0):
"""执行所有的用例, 并把结果写入测试报告"""
retry_count = 2
fp_temp = open(report_path, "wb")
runner = HTMLTestRunner(stream=fp_temp, verbosity=3, retry=retry_count,
description=u'测试用例结果' + report_path)
# 调用add_case函数返回值
res = runner.run(all_case)
# 每个结果result 存在集合中,完事时候,集中输出html
all_result.append(res)
fp_temp.close()
if __name__ == "__main__":
# 按目录获取到的cases
allcasenames = create_suite()
# 保存的.html 结果目录
if not os.path.isdir(current_path + "/report/rp2"):
os.mkdir(current_path + "/report/rp2")
time_stamp = int(time.time())
count = 0
start_time = datetime.datetime.now()
# 3线程数
task_pool = threadpool.ThreadPool(3)
lst = []
for i, j in zip(allcasenames, range(len(list(allcasenames)))):
file_path = current_path + '/report/rp2/index' + str(time_stamp) + str(count) + ".html"
count += 1
# 禁止文件路转义
file_path = file_path.replace("\r", r"\r").replace('\n', r'\n')
print("文件路径:" + file_path)
# thread_pool 多参数写法
lst.append((, None))
rqs = threadpool.makeRequests(run_case, lst)
#等待运行结束
task_pool.wait()
end_time = datetime.datetime.now()
file_path_main = current_path + '/report/rp2/index' + str(time_stamp) + str(10000000) + ".html"
fp = open(file_path_main, "wb")
# 自定义生成html的class,目前是集合在HTMLTestRunner ,好像不能独立出来,用了很多HTMLTestRunner的自带方法
merge_html = MergeResult(fp=fp, result_list=all_result, start_time=start_time, end_time=end_time)
merge_html.make_html()
fp.close()
print(file_path_main)
print(len(all_result))HTMLTestRunner插件下载地址:解压后放到工程目录即可
支持分享
页:
[1]