標籤:擷取路徑 tde assm code 技術分享 set elf encoding 假設
前言
假設執行一條指令碼(.py)用例一分鐘,那麼100個指令碼需要100分鐘,當你的用例達到一千條時需要1000分鐘,也就是16個多小時。。。
那麼如何並行運行多個.py的指令碼,節省時間呢?這就用到多線程了,理論上開2個線程時間節省一半,開5個線程,時間就縮短五倍了。
項目結構
1.項目結構跟之前的設計是一樣的:
- case test開頭的.py用例指令碼
- common 放公用模組,如HTMLTestRunner
- report 放產生的html報告
- run_all.py 用於執行全部指令碼
2.case檔案夾裡面用例參考
# coding:utf-8import unittestfrom selenium import webdriverimport timeclass 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-8import unittestfrom common import HTMLTestRunnerimport osfrom tomorrow import threads# python2需要這三行,python3不需要import sysreload(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報告合并成一個報告呢?
selenium+python自動化90-unittest多線程執行用例