1. 程式人生 > 實用技巧 >Python3+Selenium Web自動化測試案例分享⑺——執行用例入口及結果展示

Python3+Selenium Web自動化測試案例分享⑺——執行用例入口及結果展示

本章節主要講解caselist.txt、config.ini、Main.py檔案,以及展示測試報告、日誌等。

一、caselist.txt

caselist存放需要執行的case名稱(TestCase目錄),不需要執行的時候就在case名稱前加上"#"號註釋掉,這樣可以選擇性的執行用例。

二、config.ini

config檔案存放一些配置檔案,格式如下:

三、Main.py

這是測試執行控制的方法,也是執行測試用例的入口,生成HTML視覺化的測試報告。

# _*_ coding:utf-8 _*_
import unittest, os, time
from Public import
getPathInfo, readConfig, HTMLTestRunnerCN_py3,log #from tomorrow import threads nowtime = time.strftime("%Y%m%d%H%M%S") #定義當前時間變數 log_info =log.logger #定義log變數 class All_Test(object): def __init__(self): global report_path path
=getPathInfo.get_Path() report_path = os.path.join(path, 'Report') #測試報告存放路徑 if not os.path.exists(report_path): #判斷報告路徑是否存在 os.mkdir(report_path) #建立報告檔案 self.caselist_path = os.path.join(path, "caselist.txt
") #配置執行哪些測試檔案的配置檔案路徑 self.casepath = os.path.join(path, "TestCase") #測試用例路徑 self.caselist = [] #定義一個空列表 def get_caselist(self): ''' 讀取caselist.txt檔案中的用例名稱,並新增到caselist元素組 ''' fb = open(self.caselist_path) #開啟檔案 for value in fb.readlines(): #遍歷fb所有資料 if value != '' and not value.startswith('#'): #如果data非空且不以#開頭 self.caselist.append(value.replace('\n', '')) #讀取每行資料會將換行轉換為\n,去掉每行資料中的\n fb.close() #關閉檔案 return self.caselist #返回caselist def add_case(self): ''' 新增測試用例 ''' self.get_caselist() #獲得testcase列表 suite = unittest.TestSuite() #建立測試套件 suite_module = [] #定義一個列表 for case in self.caselist: discover = unittest.defaultTestLoader.discover(self.casepath, pattern=case + '.py',top_level_dir=None) # 載入測試用例 suite_module.append(discover) #將測試用例新增到列表中 if len(suite_module) > 0: #判斷suite_module是否存在元素,列表才能判斷長度,suite不能判斷 for i in suite_module: #如果存在,迴圈取出元素組內容,命名為suite for j in i: suite.addTest(j) #取出suite_module,使用addTest新增到測試集 return suite #返回測試集 else: return None #@threads(6) def run_case(self): '''執行所有的用例, 並把結果寫入測試報告''' log_info.info("######################### TEST START #########################") try: all_case = self.add_case() #呼叫add_case獲取suite if all_case != None: test_name = readConfig.Read_Config().get_info('Report', 'test_name') #獲取測試人員姓名 report_title = readConfig.Read_Config().get_info('Report', 'report_title') #獲取測試報告名稱 fp = open(report_path + '\\' + report_title + nowtime + '.html','wb') #定義一個檔案物件,給後面的HTMLTestRunner生成測試報告用,注意開啟方式必須是wb runner = HTMLTestRunnerCN_py3.HTMLTestRunner(stream=fp, title=report_title, description="用例測試情況",tester=test_name) #生成HTML報告 runner.run(all_case) #執行用例 fp.close() else: log_info.info('---測試套件為空---') except Exception as e: log_info.error(str(e)) finally: log_info.info("######################### TEST END #########################") if __name__ == '__main__': result=All_Test() result.run_case() #執行用例

四、測試報告

斷言失敗的會截圖顯示在報告中。

五、日誌