多测师是一家拥有先进的教学理念,强大的师资团队,业内好评甚多的接口自动化测试培训机构!

17727591462

联系电话

您现在所在位置:接口自动化测试培训 > 新闻资讯

Python+unittest自动化测试多线程执行合并测试报告

更新时间:2022-07-12 09:12:13 作者:多测师 浏览:22

  主要解决思路就是利用 runner.run(all_case)执行结束后会返回测试结果,拿到测试结果后,再重新整合测试报告。同时利用threadpool.makeRequests(run_case, lst)构建多线程执行,但是这里多线程执行指的的是多个py文件里面的测试用例是并发的,但是单个py里面的测试用例执行还是按照字母顺序执行的。

Python+unittest自动化测试多线程执行合并测试报告

  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)[0]

  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(([i, file_path, j], None))

  rqs = threadpool.makeRequests(run_case, lst)

  # 等待运行结束

  [task_pool.putRequest(req) for req in rqs]

  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))

  以上内容为大家介绍了Python+unittest自动化测试多线程执行合并测试报告,本文由多测师亲自撰写,希望对大家有所帮助。了解更多自动化测试相关知识:https://www.aichudan.com/xwzx/

联系电话

17727591462

返回顶部