前言
假設執行一條腳本(.py)用例一分鍾,那么100個腳本需要100分鍾,當你的用例達到一千條時需要1000分鍾,也就是16個多小時。。。
那么如何並行運行多個.py的腳本,節省時間呢?這就用到多線程了,理論上開2個線程時間節省一半,開5個線程,時間就縮短五倍了。
項目結構
1.項目結構跟之前的設計是一樣的:
- case test開頭的.py用例腳本
- common 放公共模塊,如HTMLTestRunner
- report 放生成的html報告
- run_all.py 用於執行全部腳本
2.case文件夾里面用例參考
# coding:utf-8
import unittest
from selenium import webdriver
import time
class Test1(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Firefox()
def setUp(self):
self.driver.get("http://www.cnblogs.com/yoyoketang/")
def test_01(self):
time.sleep(3)
t = self.driver.title
print t
# 隨便寫的用例,沒寫斷言
def test_02(self):
time.sleep(3)
t = self.driver.title
print t
h = self.driver.window_handles
print h
# 隨便寫的用例,沒寫斷言
@classmethod
def tearDownClass(cls):
cls.driver.quit()
if __name__ == "__main__":
unittest.main()
多線程執行
1.多線程設計思路:
- 先寫一個run的函數
- 保證for循環能跑的通
- 在run函數上加個裝飾器 @threads(n),n是線程數
2.run_all參考代碼
# coding=utf-8
import unittest
from common import HTMLTestRunner
import os
from tomorrow import threads
# python2需要這三行,python3不需要
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# 獲取路徑
curpath = os.path.dirname(os.path.realpath(__file__))
casepath = os.path.join(curpath, "case")
reportpath = os.path.join(curpath, "report")
def add_case(case_path=casepath, rule="test*.py"):
'''加載所有的測試用例'''
discover = unittest.defaultTestLoader.discover(case_path,
pattern=rule,
top_level_dir=None)
return discover
@threads(3)
def run_case(all_case, report_path=reportpath, nth=0):
'''執行所有的用例, 並把結果寫入測試報告'''
report_abspath = os.path.join(report_path, "result%s.html"%nth)
fp = open(report_abspath, "wb")
runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
title=u'自動化測試報告,測試結果如下:',
description=u'用例執行情況:')
# 調用add_case函數返回值
runner.run(all_case)
fp.close()
if __name__ == "__main__":
# 用例集合
cases = add_case()
# 之前是批量執行,這里改成for循環執行
for i, j in zip(cases, range(len(list(cases)))):
run_case(i, nth=j) # 執行用例,生成報告
3.生成報告,這里生成的報告是多個的,每個.py腳本生成一個html的報告,接下來遇到的難點就是合並報告了
如何把多個html報告合並成一個報告呢?