Python实现多线程自动化


前言

假设执行一条脚本(.py)用例一分钟,那么60个脚本需要1个小时,当你的用例达到一千条时需要1000分钟,也就是16个多小时。。。
那么如何并行运行多个.py的脚本,节省时间呢?这就用到多线程了,理论上开2个线程时间节省一半,开6个线程,时间就缩短倍了。

项目结构

一.项目结构跟之前的设计是一样的:

case test开头的.py用例脚本

common 放公共模块,如HTMLTestRunner

report 放生成的html报告

run_all.py 用于执行全部脚本

二.case文件夹里面用例参考

# coding=utf-8

import unittest

import requests

import time

 

class Test(unittest.TestCase):

 

    def setUp(self):

        self.s = requests.session()

 

    def tearDown(self):

        self.s.close()

 

    def test_1(self):

        '''获取参数'''

        headers = {             

            }

 

        globals()["id"] = headers

 

        self.assertTrue(headers)

 

    def test_2(self):

        '''获取自定义搜索规则描述'''

        url = "

        b = globals()["id"]

        print(b)

        print(url)

        r = requests.get(url, headers=globals()["id"])

        time.sleep(2)

        print(r.status_code)

        print(r.text)

        '''断言、返回值等于200就判断正确'''

        assert

 

    if __name__ == '__main__'

 

三、多线程执行

1.多线程设计思路:

先写一个run的函数

保证for循环能跑的通

run函数上加个装饰器 @threads(n),n是线程数

2.run_all参考代码

 

# coding:utf-8
from test_hotel_project.common import HTMLTestRunner_cn

import unittest

import os

import time

curdir = os.path.dirname(os.path.realpath(__file__))
print(curdir)
start_dir = os.path.join(curdir, "case")
print(start_dir)
discover = unittest.defaultTestLoader.discover(start_dir,
pattern="H5*.py")
print(discover)


# report_path = "D:\\xuexi13\\testproject\\report\\result.html"

report_path = os.path.join(curdir, "report", "result.html")
print(report_path)

fp = open(report_path, "wb")
runner = HTMLTestRunner_cn.HTMLTestRunner(stream=fp,
title="测试报告的title",
description="测试报告的描述,当前时间",
retry=1)
runner.run(discover)
fp.close()