Appium 自動化測試框架:關鍵字驅動+數據驅動


本框架工程的 github 地址:https://github.com/juno3550/AppAutoTest

1. 關鍵字驅動框架簡介

2. 框架結構說明

3. 框架代碼實現

 

 

1. 關鍵字驅動框架簡介

原理及特點

  1. 關鍵字驅動測試是數據驅動測試的一種改進類型,它也被稱為表格驅動測試或者基於動作字的測試。
  2. 主要關鍵字包括三類:被操作對象(Item)、操作行為(Operation)和操作值(Value),用面向對象形式可將其表現為 Item.Operation(Value)
  3. 將測試邏輯按照這些關鍵字進行分解,形成數據文件。
  4. 用關鍵字的形式將測試邏輯封裝在數據文件中,測試工具只要能夠解釋這些關鍵字即可對其應用自動化。

優勢

  1. 執行人員可以不需要太多的技術:一旦框架建立,手工測試人員和非技術人員都可以很容易的編寫自動化測試腳本。
  2. 簡單易懂:它存在 Excel 表格中,沒有編碼,測試腳本容易閱讀和理解。關鍵字和操作行為這樣的手工測試用例,使它變得更容易編寫和維護。
  3. 早期介入:可以在應用未提交測試之前,就可以建立關鍵字驅動測試用例對象庫,從而減少后期工作。使用需求和其它相關文檔進行收集信息,關鍵字數據表可以建立手工測試程序。
  4. 代碼的重用性:用關鍵字的形式將測試用例及數據進行組裝並解釋執行,提高代碼的可重用性。

 

2. 框架結構說明

框架結構

整個測試框架分為四層,通過分層的方式,測試代碼更容易理解,維護起來較為方便。

第一層是“測試工具層”:

  • util 包:用於實現測試過程中調用的工具類方法,例如讀取配置文件、頁面元素的操作方法、操作 Excel 文件、生成測試報告、發送郵件等。
  • conf 包:配置文件及全局變量。
  • log 目錄:日志輸出文件。
  • exception_pic 目錄:失敗用例的截圖保存目錄。

第二層是“服務層”:相當於對測試對象的一個業務封裝。對於接口測試,是對遠程方法的一個實現;對於 UI 測試,是對頁面元素或操作的一個封裝

  • action 包:封裝具體的頁面動作,如點擊、輸入文本等。

第三層是“測試用例邏輯層”:該層主要是將服務層封裝好的各個業務對象,組織成測試邏輯,進行校驗

  • bussiness_process 包:基於關鍵字的形式,實現單條、多條用例的測試腳本邏輯。
  • test_data 目錄:Excel 數據文件,包含用例步驟、被操作對象、操作動作、操作值、測試結果等。

第四層是“測試場景層”:將測試用例組織成測試場景,實現各種級別 cases 的管理,如冒煙,回歸等測試場景

  • main.py:本框架工程的運行主入口。

框架特點

  1. 基於關鍵字測試框架,即使不懂開發技術的測試人員也可以實施自動化測試,便於在整個測試團隊中推廣和使用自動化測試技術,降低自動化測試實施的技術門檻。
  2. 使用外部測試數據文件,使用Excel管理測試用例的集合和每個測試用例的所有執行步驟,實現在一個文件中完成測試用例的維護工作。
  3. 通過定義關鍵字、操作元素的定位方式和定位表達式和操作值,就可以實現每個測試步驟的執行,可以更加靈活地實現自動化測試的需求。
  4. 基於關鍵字的方式,可以進行任意關鍵字的擴展,以滿足更加復雜的自動化測試需求。
  5. 實現定位表達式和測試代碼的分離,實現定位表達式直接在數據文件中進行維護。
  6. 框架提供日志功能,方便調試和監控自動化測試程序的執行。

 

3. 框架代碼實現

action 包

action 包為框架第二層“服務層”,相當於對測試對象的一個業務封裝。對於接口測試,是對遠程方法的一個實現;對於 UI 測試,是對頁面元素或操作的一個封裝。

page_action.py

本模塊基於關鍵字格式,封裝了頁面操作的常用函數,如打開 APP、點擊、輸入文本等。

 1 import traceback
 2 import os
 3 import time
 4 from appium import webdriver
 5 from util.get_desired_caps import get_desired_caps
 6 from util.datetime_util import *
 7 from util.find_element_util import *
 8 from util.global_var import *
 9 from util.log_util import *
10 
11 
12 DRIVER = ""
13 
14 
15 # 打開APP,獲取webdriver對象
16 def open_app():
17     global DRIVER
18     desired_caps = get_desired_caps()
19     DRIVER = webdriver.Remote(APPIUM_SERVER, desired_caps)
20 
21 
22 # 設定開始活動頁
23 def open_start_activity(app_name, start_activity_name):
24     global DRIVER
25     DRIVER.start_activity(app_name, start_activity_name)
26 
27 
28 # 退出APP
29 def quit_app():
30     global DRIVER
31     DRIVER.quit()
32 
33 
34 # 在頁面輸入框中輸入數據
35 def input_string(location_type, locator_expression, input_content):
36     global DRIVER
37     find_element(DRIVER, location_type, locator_expression).send_keys(input_content)
38 
39 
40 # 清除輸入框默認內容
41 def clear(location_type, locator_expression):
42     global DRIVER
43     find_element(DRIVER, location_type, locator_expression).clear()
44 
45 
46 # 點擊頁面元素
47 def click(location_type, locator_expression):
48     global DRIVER
49     find_element(DRIVER, location_type, locator_expression).click()
50 
51 
52 # 斷言界面源碼是否存在某關鍵字或關鍵字符串
53 def assert_string_in_pagesource(assert_string):
54     global DRIVER
55     try:
56         assert assert_string in DRIVER.page_source, "%s not found in page source!" % assert_string
57         info("斷言成功【關鍵字:{}】".format(assert_string))
58     except:
59         error("斷言失敗【關鍵字:{}】".format(assert_string))
60         raise
61 
62 
63 # 強制等待
64 def sleep(sleep_seconds):
65     time.sleep(int(sleep_seconds))
66 
67 
68 # 批量斷言
69 def assert_app_list(location_type, locator_expression, assert_string):
70     global DRIVER
71     assert_string_list = assert_string.split(",")
72     elements = find_element(DRIVER, location_type, locator_expression)
73     for element in elements[:3]:
74         assert element.text in assert_string_list
75 
76 
77 # 截圖函數
78 def take_screenshot():
79     global DRIVER
80     # 創建當前日期目錄
81     dir = os.path.join(EXCEPION_PIC_PATH, get_chinese_date())
82     if not os.path.exists(dir):
83         os.makedirs(dir)
84     # 以當前時間為文件名
85     file_name = get_chinese_time()
86     file_path = os.path.join(dir, file_name+".png")
87     try:
88         DRIVER.get_screenshot_as_file(file_path)
89         # 返回截圖文件的絕對路徑
90         return file_path
91     except:
92         print("截圖發生異常【{}】".format(file_path))
93         traceback.print_exc()
94         return file_path

 

business_process 包

business_process 包是框架第三層“測試用例邏輯層”,該層主要是將服務層封裝好的各個業務對象,組織成測試邏輯,進行校驗。

case_process.py

  • 測試用例文件的一行數據,拼接其中的操作動作、操作對象、操作值等關鍵字,形成與 page_action.py 中的函數相對應的字符串,並通過 eval() 轉成表達式以執行用例。
  • 記錄該用例的測試結果,如測試執行結果、測試執行時間等。
  • 如需數據驅動的用例集,則獲取數據驅動的數據源集合,循環將每組數據傳遞給用例步驟。
  • 如果遇到需要參數化的值 ${變量名},則根據數據驅動的數據源,根據變量名進行參數化。
 1 import traceback
 2 import re
 3 from util.global_var import *
 4 from util.log_util import *
 5 from util.datetime_util import *
 6 from util.excel_util import Excel
 7 from action.page_action import *
 8 
 9 
10 # 執行單條測試用例(對應excel測試數據文件中的一行測試用例數據)
11 def execute_case(excel_file_path, case_data, test_data_source=None):
12     # 用例數據格式校驗
13     if not isinstance(case_data, (list, tuple)):
14         error("測試用例數據格式有誤!測試數據應為列表或元組類型!【%s】" % case_data)
15         case_data[CASESTEP_EXCEPTION_INFO_COL_NO] = "測試用例數據格式有誤!應為列表或元組類型!【%s】" % case_data
16         case_data[CASESTEP_TEST_RESULT_COL_NO] = "Fail"
17     # 該用例無需執行
18     if case_data[CASESTEP_IS_EXECUTE_COL_NO].lower() == "n":
19         info("測試用例步驟【%s】無需執行" % case_data[CASESTEP_NAME_COL_NO])
20         return
21     # excel對象初始化
22     if isinstance(excel_file_path, Excel):
23         excel = excel_file_path
24     else:
25         excel = Excel(excel_file_path)
26     # 獲取各關鍵字
27     operation_action = case_data[CASESTEP_ACTION_COL_NO]  # 操作動作(即函數名)
28     locate_method = case_data[CASESTEP_LOCATE_METHOD_COL_NO]  # 定位方式
29     locate_expression = case_data[CASESTEP_LOCATE_EXPRESSION_COL_NO]  # 定位表達式
30     operation_value = case_data[CASESTEP_OPERATION_VALUE_COL_NO]  # 操作值
31     # 由於數據驅動,需要進行參數化的值
32     if test_data_source:
33         if re.search(r"\$\{\w+\}", str(operation_value)):
34             # 取出需要參數化的值
35             key = re.search(r"\$\{(\w+)\}", str(operation_value)).group(1)
36             operation_value = re.sub(r"\$\{\w+\}", test_data_source[key], str(operation_value))
37             # 將參數化后的值回寫excel測試結果中,便於回溯
38             case_data[CASESTEP_OPERATION_VALUE_COL_NO] = operation_value
39     # 拼接關鍵字函數
40     if locate_method and locate_expression:
41         if operation_value:
42             func = "%s('%s', '%s', '%s')" % (operation_action, locate_method, locate_expression, operation_value)
43         else:
44             func = "%s('%s', '%s')" % (operation_action, locate_method, locate_expression)
45     else:
46         if operation_value:
47             func = "%s('%s')" % (operation_action, operation_value)
48         else:
49             func = "%s()" % operation_action
50     # 執行用例
51     try:
52         eval(func)
53         info("測試用例步驟執行成功:【{}】 {}".format(case_data[CASESTEP_NAME_COL_NO], func))
54         case_data[CASESTEP_TEST_RESULT_COL_NO] = "Pass"
55     except:
56         info("測試用例步驟執行失敗:【{}】 {}".format(case_data[CASESTEP_NAME_COL_NO], func))
57         case_data[CASESTEP_TEST_RESULT_COL_NO] = "Fail"
58         error(traceback.format_exc())
59         # 進行截圖
60         case_data[CASESTEP_EXCEPTION_PIC_DIR_COL_NO] = take_screenshot()
61         # 異常信息記錄
62         case_data[CASESTEP_EXCEPTION_INFO_COL_NO] = traceback.format_exc()
63     # 測試時間記錄
64     case_data[CASESTEP_TEST_TIME_COL_NO] = get_english_datetime()
65     return case_data
66 
67 
68 if __name__ == "__main__":
69     excel = Excel(TEST_DATA_FILE_PATH)
70     excel.get_sheet("登錄")
71     all_data = excel.get_all_row_data()
72     for data in all_data[1:]:
73         execute_case(excel, data)

 

data_source_process.py

本模塊實現了獲取數據驅動所需的數據源集合。

  • 根據數據源 sheet 名,獲取該 sheet 所有行數據,每行數據作為一組測試數據。
  • 每行數據作為一個字典,存儲在一個列表中。如 [{"登錄用戶名": "xxx", "登錄密碼": "xxx", ...}, {...}, ...]
 1 from util.excel_util import Excel
 2 from util.global_var import *
 3 from util.log_util import *
 4 
 5 
 6 # 數據驅動
 7 # 每行數據作為一個字典,存儲在一個列表中。如[{"登錄用戶名": "xxx", "登錄密碼": "xxx", ...}, {...}, ...]
 8 def get_test_data(excel_file_path, sheet_name):
 9     # excel對象初始化
10     if isinstance(excel_file_path, Excel):
11         excel = excel_file_path
12     else:
13         excel = Excel(excel_file_path)
14     # 校驗sheet名
15     if not excel.get_sheet(sheet_name):
16         error("sheet【】不存在,停止執行!" % sheet_name)
17         return
18     result_list = []
19     all_row_data = excel.get_all_row_data()
20     if len(all_row_data) <= 1:
21         error("sheet【】數據不大於1行,停止執行!" % sheet_name)
22         return
23     # 將參數化的測試數據存入全局字典
24     head_line_data = all_row_data[0]
25     for data in all_row_data[1:]:
26         if data[-1].lower() == "n":
27             continue
28         row_dict = {}
29         for i in range(len(data[:-1])):
30             row_dict[head_line_data[i]] = data[i]
31         result_list.append(row_dict)
32     return result_list
33 
34 
35 if __name__ == "__main__":
36     from util.global_var import *
37     print(get_test_data(TEST_DATA_FILE_PATH, "搜索詞"))
38     # [{'搜索詞': 'python', '斷言詞': 'python'}, {'搜索詞': 'mysql', '斷言詞': 'mysql5.6'}]

 

main_process.py

本模塊基於 case_process.py 和 data_source_process.py,實現關鍵字驅動+數據驅動的測試用例集的執行。

  • suite_process():執行具體的測試用例步驟 sheet(如“登錄” sheet、“搜索” sheet 等)
  • main_suite_process():執行“測試用例”主 sheet 的用例集。每行用例集對應一個用例步驟 sheet 和數據源 sheet。
  1 from util.excel_util import *
  2 from util.datetime_util import *
  3 from util.log_util import *
  4 from util.global_var import *
  5 from bussiness_process.case_process import execute_case
  6 from bussiness_process.data_source_process import get_test_data
  7 
  8 
  9 # 執行具體的測試用例步驟sheet
 10 def suite_process(excel_file_path, sheet_name, test_data_source=None):
 11     """
 12     :param excel_file_path: excel文件絕對路徑或excel對象
 13     :param sheet_name: 測試步驟sheet名
 14     :param test_data_source: 數據驅動的數據源,默認沒有
 15     :return:
 16     """
 17     # 記錄測試結果統計
 18     global TOTAL_CASE
 19     global PASS_CASE
 20     global FAIL_CASE
 21     # 整個用例sheet的測試結果,默認為全部通過
 22     suite_test_result = True
 23     # excel對象初始化
 24     if isinstance(excel_file_path, Excel):
 25         excel = excel_file_path
 26     else:
 27         excel = Excel(excel_file_path)
 28     if not excel.get_sheet(sheet_name):
 29         error("sheet【】不存在,停止執行!" % sheet_name)
 30         return
 31     # 獲取測試用例sheet的全部行數據
 32     all_row_data = excel.get_all_row_data()
 33     if len(all_row_data) <= 1:
 34         error("sheet【】數據不大於1行,停止執行!" % sheet_name)
 35         return
 36     # 標題行數據
 37     head_line_data = all_row_data[0]
 38     # 切換到測試結果明細sheet,准備寫入測試結果
 39     if not excel.get_sheet("測試結果明細"):
 40         error("【測試結果明細】sheet不存在,停止執行!")
 41         return
 42     excel.write_row_data(head_line_data, None, True, "green")
 43     # 執行每行的測試用例
 44     for row_data in all_row_data[1:]:
 45         result_data = execute_case(excel, row_data, test_data_source)
 46         # 無需執行的測試步驟,跳過
 47         if result_data is None:
 48             continue
 49         TOTAL_CASE += 1
 50         if result_data[CASESTEP_TEST_RESULT_COL_NO].lower() == "fail":
 51             suite_test_result = False
 52             FAIL_CASE += 1
 53         else:
 54             PASS_CASE += 1
 55         excel.write_row_data(result_data)
 56     # 切換到測試結果統計sheet,寫入統計數據
 57     if not excel.get_sheet("測試結果統計"):
 58         error("【測試結果統計】sheet不存在,停止執行!")
 59         return
 60     excel.insert_row_data(1, [TOTAL_CASE, PASS_CASE, FAIL_CASE])
 61     return excel, suite_test_result
 62 
 63 
 64 # 執行【測試用例】主sheet的用例集
 65 def main_suite_process(excel_file_path, sheet_name):
 66     # 初始化excel對象
 67     excel = Excel(excel_file_path)
 68     if not excel:
 69         error("excel數據文件【%s】不存在!" % excel_file_path)
 70         return
 71     if not excel.get_sheet(sheet_name):
 72         error("sheet名稱【%s】不存在!" % sheet_name)
 73         return
 74     # 獲取所有行數據
 75     all_row_datas = excel.get_all_row_data()
 76     if len(all_row_datas) <= 1:
 77         error("sheet【%s】數據不大於1行,停止執行!" % sheet_name)
 78         return
 79     # 標題行數據
 80     head_line_data = all_row_datas[0]
 81     for row_data in all_row_datas[1:]:
 82         # 跳過不需要執行的測試用例集
 83         if row_data[TESTCASE_IS_EXECUTE_COL_NO].lower() == "n":
 84             info("#" * 50 + " 測試用例集【%s】無需執行!" % row_data[TESTCASE_CASE_NAME_COL_NO] + "#" * 50 + "\n")
 85             continue
 86         # 記錄本用例集的測試時間
 87         row_data[TESTCASE_TEST_TIME_COL_NO] = get_english_datetime()
 88         # 校驗用例步驟sheet名是否存在
 89         if row_data[TESTCASE_CASE_STEP_SHEET_NAME_COL_NO] not in excel.get_all_sheet():
 90             error("#" * 50 + " 用例步驟集【%s】不存在! " % row_data[TESTCASE_CASE_STEP_SHEET_NAME_COL_NO] + "#" * 50 + "\n")
 91             row_data[TESTCASE_TEST_RESULT_COL_NO] = "Fail"
 92             excel.write_row_data(head_line_data, None, True, "red")
 93             excel.write_row_data(row_data)
 94             continue
 95         # 判斷本測試用例集是否進行數據驅動
 96         if row_data[TESTCASE_DATA_SOURCE_SHEET_NAME_COL_NO]:
 97             # 校驗測試數據集sheet名是否存在
 98             if row_data[TESTCASE_DATA_SOURCE_SHEET_NAME_COL_NO] not in excel.get_all_sheet():
 99                 error("#" * 50 + " 測試數據集【%s】不存在! " % row_data[TESTCASE_DATA_SOURCE_SHEET_NAME_COL_NO] + "#" * 50 + "\n")
100                 row_data[TESTCASE_TEST_RESULT_COL_NO] = "Fail"
101                 excel.write_row_data(head_line_data, None, True, "red")
102                 excel.write_row_data(row_data)
103                 continue
104             # 獲取測試數據集
105             test_data_source = get_test_data(excel, row_data[TESTCASE_DATA_SOURCE_SHEET_NAME_COL_NO])
106             # 每條數據進行一次本用例集的測試
107             for data_source in test_data_source:
108                 info("-" * 50 + " 測試用例集【%s】開始執行!" % row_data[TESTCASE_CASE_NAME_COL_NO] + "-" * 50)
109                 excel, test_result_flag = suite_process(excel, row_data[TESTCASE_CASE_STEP_SHEET_NAME_COL_NO], data_source)
110                 # 記錄本用例集的測試結果
111                 if test_result_flag:
112                     info("#" * 50 + " 測試用例集【%s】執行成功! " % row_data[TESTCASE_CASE_NAME_COL_NO] + "#" * 50 + "\n")
113                     row_data[TESTCASE_TEST_RESULT_COL_NO] = "Pass"
114                 else:
115                     error("#" * 50 + " 測試用例集【%s】執行失敗! " % row_data[TESTCASE_CASE_NAME_COL_NO] + "#" * 50 + "\n")
116                     row_data[TESTCASE_TEST_RESULT_COL_NO] = "Fail"
117                 # 全部測試步驟結果寫入后,最后寫入本用例集的標題行和測試結果行數據
118                 # 切換到“測試結果明細”sheet,以寫入測試執行結果
119                 excel.get_sheet("測試結果明細")
120                 excel.write_row_data(head_line_data, None, True, "red")
121                 excel.write_row_data(row_data)
122         # 本用例集無需數據驅動
123         else:
124             info("-" * 50 + " 測試用例集【%s】開始執行!" % row_data[TESTCASE_CASE_NAME_COL_NO] + "-" * 50)
125             excel, test_result_flag = suite_process(excel, row_data[TESTCASE_CASE_STEP_SHEET_NAME_COL_NO])
126             # 記錄本用例集的測試結果
127             if test_result_flag:
128                 info("#" * 50 + " 測試用例集【%s】執行成功! " % row_data[TESTCASE_CASE_NAME_COL_NO] + "#" * 50 + "\n")
129                 row_data[TESTCASE_TEST_RESULT_COL_NO] = "Pass"
130             else:
131                 error("#" * 50 + " 測試用例集【%s】執行失敗! " % row_data[TESTCASE_CASE_NAME_COL_NO] + "#" * 50 + "\n")
132                 row_data[TESTCASE_TEST_RESULT_COL_NO] = "Fail"
133             # 全部測試步驟結果寫入后,最后寫入本用例集的標題行和測試結果行數據
134             # 切換到“測試結果明細”sheet,以寫入測試執行結果
135             excel.get_sheet("測試結果明細")
136             excel.write_row_data(head_line_data, None, True, "red")
137             excel.write_row_data(row_data)
138     return excel
139 
140 
141 if __name__ == "__main__":
142     from util.report_util import create_excel_report_and_send_email
143     # excel, _ = suite_process(TEST_DATA_FILE_PATH, "進入主頁")
144     # excel, _ = suite_process(excel, "登錄")
145     excel = main_suite_process(TEST_DATA_FILE_PATH, "測試用例")
146     create_excel_report_and_send_email(excel, "182230124@qq.com", "app自動化測試", "請查收附件:app自動化測試報告")

 

util 包

util 包屬於第一層的測試工具層:用於實現測試過程中調用的工具類方法,例如讀取配置文件、頁面元素的操作方法、操作 Excel 文件、生成測試報告、發送郵件等。

global_var.py

本模塊用於定義測試過程中所需的全局變量。

 1 import os
 2 
 3 
 4 PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 5 
 6 # APP配置信息路徑
 7 INI_FILE_PATH = os.path.join(PROJECT_DIR, "conf", "desired_caps_config.ini")
 8 
 9 # 異常截圖路徑
10 EXCEPION_PIC_PATH = os.path.join(PROJECT_DIR, "exception_pic")
11 
12 # 日志配置文件路徑
13 LOG_CONF_FILE_PATH = os.path.join(PROJECT_DIR, "conf", "logger.conf")
14 
15 # 測試數據文件路徑
16 TEST_DATA_FILE_PATH = os.path.join(PROJECT_DIR, "test_data", "test_case.xlsx")
17 
18 # 測試報告存放路徑
19 TEST_REPORT_FILE_DIR = os.path.join(PROJECT_DIR, "test_report")
20 
21 # Appium server地址
22 APPIUM_SERVER = 'http://localhost:4723/wd/hub'
23 
24 # 測試數據文件中,測試用例sheet中部分列對應的數字序號
25 TESTCASE_CASE_NAME_COL_NO = 0
26 TESTCASE_FRAMEWORK_TYPE_COL_NO = 1
27 TESTCASE_CASE_STEP_SHEET_NAME_COL_NO = 2
28 TESTCASE_DATA_SOURCE_SHEET_NAME_COL_NO = 3
29 TESTCASE_IS_EXECUTE_COL_NO = 4
30 TESTCASE_TEST_TIME_COL_NO = 5
31 TESTCASE_TEST_RESULT_COL_NO = 6
32 
33 # 用例步驟sheet中,部分列對應的數字序號
34 CASESTEP_NAME_COL_NO = 0
35 CASESTEP_ACTION_COL_NO = 1
36 CASESTEP_LOCATE_METHOD_COL_NO = 2
37 CASESTEP_LOCATE_EXPRESSION_COL_NO = 3
38 CASESTEP_OPERATION_VALUE_COL_NO = 4
39 CASESTEP_IS_EXECUTE_COL_NO = 5
40 CASESTEP_TEST_TIME_COL_NO = 6
41 CASESTEP_TEST_RESULT_COL_NO = 7
42 CASESTEP_EXCEPTION_INFO_COL_NO = 8
43 CASESTEP_EXCEPTION_PIC_DIR_COL_NO = 9
44 
45 # 數據源sheet中,是否執行列對應的數字編號
46 DATASOURCE_DATA = 0
47 DATASOURCE_KEYWORD = 1
48 DATASOURCE_IS_EXECUTE = 2
49 DATASOURCE_TEST_TIME = 3
50 DATASOURCE_TEST_RESULT = 4
51 
52 # 測試執行結果統計
53 TOTAL_CASE = 0
54 PASS_CASE = 0
55 FAIL_CASE = 0
56 
57 
58 if __name__ == "__main__":
59     print(PROJECT_DIR)

 

find_element_util.py

本模塊封裝了基於顯式等待的界面元素定位方法。

 1 from selenium.webdriver.support.ui import WebDriverWait
 2 
 3 
 4 # 顯式等待一個元素
 5 def find_element(driver, locate_method, locate_exp):
 6     # 顯式等待對象(最多等10秒,每0.2秒判斷一次等待的條件)
 7     return WebDriverWait(driver, 10, 0.2).until(lambda x: x.find_element(locate_method, locate_exp))
 8 
 9 # 顯式等待一組元素
10 def find_elements(driver, locate_method, locate_exp):
11     # 顯式等待對象(最多等10秒,每0.2秒判斷一次等待的條件)
12     return WebDriverWait(driver, 10, 0.2).until(lambda x: x.find_elements(locate_method, locate_exp))

 

excel_util.py

本模塊封裝了對 excel 的讀寫操作(openpyxl 版本:3.0.4)。

  1 import os
  2 from openpyxl import load_workbook
  3 from openpyxl.styles import PatternFill, Font, Side, Border
  4 from util.datetime_util import *
  5 from util.global_var import *
  6 from util.log_util import *
  7 
  8 
  9 # 支持excel讀寫操作的工具類
 10 class Excel:
 11 
 12     # 初始化讀取excel文件
 13     def __init__(self, file_path):
 14         if not os.path.exists(file_path):
 15             return
 16         self.wb = load_workbook(file_path)
 17         # 初始化默認sheet
 18         self.ws = self.wb.active
 19         self.data_file_path = file_path
 20         # 初始化顏色字典,供設置樣式用
 21         self.color_dict = {"red": "FFFF3030", "green": "FF008B00"}
 22 
 23     def get_all_sheet(self):
 24         return self.wb.get_sheet_names()
 25 
 26     # 打開指定sheet
 27     def get_sheet(self, sheet_name):
 28         if sheet_name not in self.get_all_sheet():
 29             print("sheet名稱【%s】不存在!" % sheet_name)
 30             return
 31         self.ws = self.wb.get_sheet_by_name(sheet_name)
 32         return True
 33 
 34     # 獲取最大行號
 35     def get_max_row_no(self):
 36         # openpyxl的API的行、列索引默認都從1開始
 37         return self.ws.max_row
 38 
 39     # 獲取最大列號
 40     def get_max_col_no(self):
 41         return self.ws.max_column
 42 
 43     # 獲取所有行數據
 44     def get_all_row_data(self, head_line=True):
 45         # 是否需要標題行數據的標識,默認需要
 46         if head_line:
 47             min_row = 1  # 行號從1開始,即1為標題行
 48         else:
 49             min_row = 2
 50         result = []
 51         # min_row=None:默認獲取標題行數據
 52         for row in self.ws.iter_rows(min_row=min_row, max_row=self.get_max_row_no(), max_col=self.get_max_col_no()):
 53             result.append([cell.value for cell in row])
 54         return result
 55 
 56     # 獲取指定行數據
 57     def get_row_data(self, row_num):
 58         # 0 為標題行
 59         return [cell.value for cell in self.ws[row_num+1]]
 60 
 61     # 獲取指定列數據
 62     def get_col_data(self, col_num):
 63         # 索引從0開始
 64         return [cell.value for cell in tuple(self.ws.columns)[col_num]]
 65 
 66     # 追加行數據且可以設置樣式
 67     def write_row_data(self, data, font_color=None, border=True, fill_color=None):
 68         if not isinstance(data, (list, tuple)):
 69             print("寫入數據失敗:數據不為列表或元組類型!【%s】" % data)
 70         self.ws.append(data)
 71         # 設置字體顏色
 72         if font_color:
 73             if font_color.lower() in self.color_dict.keys():
 74                 font_color = self.color_dict[font_color]
 75         # 設置單元格填充顏色
 76         if fill_color:
 77             if fill_color.lower() in self.color_dict.keys():
 78                 fill_color = self.color_dict[fill_color]
 79         # 設置單元格邊框
 80         if border:
 81             bd = Side(style="thin", color="000000")
 82         # 記錄數據長度(否則會默認與之前行最長數據行的長度相同,導致樣式超過了該行實際長度)
 83         count = 0
 84         for cell in self.ws[self.get_max_row_no()]:
 85             # 設置完該行的實際數據長度樣式后,則退出
 86             if count > len(data) - 1:
 87                 break
 88             if font_color:
 89                 cell.font = Font(color=font_color)
 90             # 如果沒有設置字體顏色,則默認給執行結果添加字體顏色
 91             else:
 92                 if cell.value is not None and isinstance(cell.value, str):
 93                     if cell.value.lower() == "pass" or cell.value == "成功":
 94                         cell.font = Font(color=self.color_dict["green"])
 95                     elif cell.value.lower() == "fail" or cell.value == "失敗":
 96                         cell.font = Font(color=self.color_dict["red"])
 97             if border:
 98                 cell.border = Border(left=bd, right=bd, top=bd, bottom=bd)
 99             if fill_color:
100                 cell.fill = PatternFill(fill_type="solid", fgColor=fill_color)
101             count += 1
102 
103     # 指定行插入數據(行索引從0開始)
104     def insert_row_data(self, row_no, data, font_color=None, border=True, fill_color=None):
105         if not isinstance(data, (list, tuple)):
106             print("寫入數據失敗:數據不為列表或元組類型!【%s】" % data)
107         for idx, cell in enumerate(self.ws[row_no+1]):  # 此處行索引從1開始
108             cell.value = data[idx]
109 
110     # 生成寫入了測試結果的excel數據文件
111     def save(self, save_file_name, timestamp):
112         save_dir = os.path.join(TEST_REPORT_FILE_DIR, get_chinese_date())
113         if not os.path.exists(save_dir):
114             os.mkdir(save_dir)
115         save_file = os.path.join(save_dir, save_file_name + "_" + timestamp + ".xlsx")
116         self.wb.save(save_file)
117         info("生成測試結果文件:%s" % save_file)
118         return save_file
119 
120 
121 if __name__ == "__main__":
122     from util.global_var import *
123     from util.datetime_util import *
124     excel = Excel(TEST_DATA_FILE_PATH)
125     excel.get_sheet("測試結果統計")
126     # print(excel.get_all_row_data())
127     # excel.write_row_data(["4", None, "嘻哈"], "green", True, "red")
128     excel.insert_row_data(1, [1,2,3])
129     excel.save(get_timestamp())

 

ini_reader.py

本模塊封裝了對 ini 配置文件的讀取操作。

 1 import os
 2 import configparser
 3 
 4 
 5 # 讀取ini文件的工具類
 6 class IniParser:
 7 
 8     # 初始化打開ini文件
 9     def __init__(self, file_path):
10         if not os.path.exists(file_path):
11             print("ini文件【%s】不存在!" % file_path)
12             return
13         self.cf = configparser.ConfigParser()
14         self.cf.read(file_path, encoding="utf-8")
15 
16     # 獲取所有分組
17     def get_sections(self):
18         return self.cf.sections()
19 
20     # 獲取指定分組的所有鍵
21     def get_options(self, section):
22         return self.cf.options(section)  # 注意,獲取的鍵會自動轉小寫
23 
24     # 獲取指定分組的所有鍵值對
25     def get_items(self, section):
26         return dict(self.cf.items(section))  # 注意,獲取的鍵會自動轉小寫
27 
28     # 獲取指定分組指定鍵的值
29     def get_value(self, section, option):
30         return self.cf.get(section, option)
31 
32 
33 if __name__ == "__main__":
34     from util.global_var import *
35     p = IniParser(INI_FILE_PATH)
36     print(p.get_sections())
37     print(p.get_options("desired_caps"))
38     print(p.get_items("desired_caps"))
39     print(p.get_value("desired_caps", "deviceName"))

 

email_util.py

本模塊封裝了郵件發送功能。(示例代碼中的用戶名/密碼已隱藏)

 1 import yagmail
 2 import traceback
 3 from util.log_util import *
 4 
 5 
 6 def send_mail(attachments_report_name, receiver, subject, content):
 7     try:
 8         # 連接郵箱服務器
 9         # 注意:若使用QQ郵箱,則password為授權碼而非郵箱密碼;使用其它郵箱則為郵箱密碼
10         # encoding設置為GBK,否則中文附件名會亂碼
11         yag = yagmail.SMTP(user="*****@163.com", password="*****", host="smtp.163.com", encoding='GBK')
12 
13         # 收件人、標題、正文、附件(若多個收件人或多個附件,則可使用列表)
14         yag.send(to=receiver, subject=subject, contents=content, attachments=attachments_report_name)
15 
16         # 可簡寫:yag.send("****@163.com", subject, contents, report)
17 
18         info("測試報告郵件發送成功!【郵件標題:%s】【郵件附件:%s】【收件人:%s】" % (subject, attachments_report_name, receiver))
19     except:
20         error("測試報告郵件發送失敗!【郵件標題:%s】【郵件附件:%s】【收件人:%s】" % (subject, attachments_report_name, receiver))
21         error(traceback.format_exc())
22 
23 
24 if __name__ == "__main__":
25    send_mail("e:\\code.txt", "182230124@qq.com", "測試郵件", "正文")
26    

 

datetime_util.py

本模塊實現了獲取各種格式的當前日期時間。

 1 import time
 2 
 3 
 4 # 返回中文格式的日期:xxxx年xx月xx日
 5 def get_chinese_date():
 6     year = time.localtime().tm_year
 7     if len(str(year)) == 1:
 8         year = "0" + str(year)
 9     month = time.localtime().tm_mon
10     if len(str(month)) == 1:
11         month = "0" + str(month)
12     day = time.localtime().tm_mday
13     if len(str(day)) == 1:
14         day = "0" + str(day)
15     return "{}年{}月{}日".format(year, month, day)
16 
17 
18 # 返回英文格式的日期:xxxx/xx/xx
19 def get_english_date():
20     year = time.localtime().tm_year
21     if len(str(year)) == 1:
22         year = "0" + str(year)
23     month = time.localtime().tm_mon
24     if len(str(month)) == 1:
25         month = "0" + str(month)
26     day = time.localtime().tm_mday
27     if len(str(day)) == 1:
28         day = "0" + str(day)
29     return "{}/{}/{}".format(year, month, day)
30 
31 
32 # 返回中文格式的時間:xx時xx分xx秒
33 def get_chinese_time():
34     hour = time.localtime().tm_hour
35     if len(str(hour)) == 1:
36         hour = "0" + str(hour)
37     minute = time.localtime().tm_min
38     if len(str(minute)) == 1:
39         minute = "0" + str(minute)
40     second = time.localtime().tm_sec
41     if len(str(second)) == 1:
42         second = "0" + str(second)
43     return "{}時{}分{}秒".format(hour, minute, second)
44 
45 
46 # 返回英文格式的時間:xx:xx:xx
47 def get_english_time():
48     hour = time.localtime().tm_hour
49     if len(str(hour)) == 1:
50         hour = "0" + str(hour)
51     minute = time.localtime().tm_min
52     if len(str(minute)) == 1:
53         minute = "0" + str(minute)
54     second = time.localtime().tm_sec
55     if len(str(second)) == 1:
56         second = "0" + str(second)
57     return "{}:{}:{}".format(hour, minute, second)
58 
59 
60 # 返回中文格式的日期時間
61 def get_chinese_datetime():
62     return get_chinese_date() + " " + get_chinese_time()
63 
64 
65 # 返回英文格式的日期時間
66 def get_english_datetime():
67     return get_english_date() + " " + get_english_time()
68 
69 
70 # 返回時間戳
71 def get_timestamp():
72     year = time.localtime().tm_year
73     if len(str(year)) == 1:
74         year = "0" + str(year)
75     month = time.localtime().tm_mon
76     if len(str(month)) == 1:
77         month = "0" + str(month)
78     day = time.localtime().tm_mday
79     if len(str(day)) == 1:
80         day = "0" + str(day)
81     hour = time.localtime().tm_hour
82     if len(str(hour)) == 1:
83         hour = "0" + str(hour)
84     minute = time.localtime().tm_min
85     if len(str(minute)) == 1:
86         minute = "0" + str(minute)
87     second = time.localtime().tm_sec
88     if len(str(second)) == 1:
89         second = "0" + str(second)
90     return "{}{}{}_{}{}{}".format(year, month, day, hour, minute, second)
91 
92 
93 if __name__ == "__main__":
94     print(get_chinese_datetime())
95     print(get_english_datetime())

 

get_desired_caps.py

本模塊實現了獲取 ini 配置文件中的 Appium 創建 Session 的配置信息。

 1 from util.ini_reader import IniParser
 2 from util.global_var import INI_FILE_PATH
 3 
 4 
 5 def get_desired_caps():
 6     pcf = IniParser(INI_FILE_PATH)
 7     items = pcf.get_items("desired_caps")  # 獲取的鍵會自動轉成小寫
 8     desired_caps = {
 9         "platformName": items.get("platformname"),
10         "platformVersion": items.get("platformversion"),
11         "deviceName": items.get("devicename"),
12         "appPackage": items.get("apppackage"),
13         "appActivity": items.get("appactivity"),
14         "unicodeKeyboard": items.get("unicodekeyboard"),
15         "autoAcceptAlerts": items.get("autoacceptalerts"),
16         "resetKeyboard": items.get("resetkeyboard"),
17         "noReset": items.get("noreset"),
18         "newCommandTimeout": items.get("newcommandtimeout")
19     }
20     return desired_caps
21 
22 
23 if __name__ == "__main__":
24     from util.global_var import *
25     print(get_desired_caps())

 

log_util.py

封裝了日志打印輸出、級別設定等功能。

 1 import logging
 2 import logging.config
 3 from util.global_var import *
 4 
 5 
 6 # 日志配置文件:多個logger,每個logger指定不同的handler
 7 # handler:設定了日志輸出行的格式
 8 #          以及設定寫日志到文件(是否回滾)?還是到屏幕
 9 #          還定了打印日志的級別
10 logging.config.fileConfig(LOG_CONF_FILE_PATH)
11 logger = logging.getLogger("example01")
12 
13 
14 def debug(message):
15     logging.debug(message)
16 
17 
18 def info(message):
19     logging.info(message)
20 
21 
22 def warning(message):
23     logging.warning(message)
24 
25 
26 def error(message):
27     logging.error(message)
28 
29 
30 if __name__ == "__main__":
31     debug("hi")
32     info("gloryroad")
33     warning("hello")
34     error("這是一個error日志")

 

report_util.py

生成測試結果文件並發送郵件。

 1 from util.email_util import send_mail
 2 from util.log_util import *
 3 from util.datetime_util import *
 4 
 5 
 6 # 生成測試報告並發送郵件
 7 def create_excel_report_and_send_email(excel_obj, receiver, subject, content):
 8     """
 9     :param excel_obj: excel對象用於保存文件
10     :param timestamp: 用於文件命名的時間戳
11     :return: 返回excel測試報告文件名
12     """
13     time_stamp = get_timestamp()
14     report_path = excel_obj.save(subject, time_stamp)
15     send_mail(report_path, receiver, subject+"_"+time_stamp, content)

 

conf 目錄

conf 目錄屬於第一層測試工具層,用於存儲各配置文件。

desired_caps_config.ini

本配置文件存儲了 Appium 創建 Session 的配置信息。

[desired_caps]
platformName=Android
platformVersion=6
deviceName=3DN6T16B26001805
appPackage=com.xsteach.appedu
appActivity=com.xsteach.appedu.StartActivity
unicodeKeyboard=True
autoAcceptAlerts=True
resetKeyboard=True
noReset=True
newCommandTimeout=6000

 

logger.conf

本配置文件用於日志功能的具體配置。

###############################################
[loggers]
keys=root,example01,example02
[logger_root]
level=DEBUG
handlers=hand01,hand02

[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0

[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0

###############################################
[handlers]
keys=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level=INFO
formatter=form01
args=(sys.stderr,)

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('E:\\pycharm_project_dir\\AppAutoTest\\log\\app_test.log', 'a')

[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form01
args=('E:\\pycharm_project_dir\\AppAutoTest\\log\\app_test.log', 'a', 10*1024*1024, 5)

###############################################
[formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s [%(levelname)s] %(message)s
datefmt=%Y-%m-%d %H:%M:%S

[formatter_form02]
format=%(name)-12s: [%(levelname)-8s] %(message)s
datefmt=%Y-%m-%d %H:%M:%S

 

test_data 目錄

test_data 目錄用於存放測試數據文件(Excel),存儲了用例步驟、用例執行關鍵字、數據源等測試數據。

 

 

main.py

本模塊是本框架的運行主入口,屬於第四層“測試場景層”,將測試用例組織成測試場景,實現各種級別 cases 的管理,如冒煙,回歸等測試場景。

  • 基於 business_process/main_process.py 中的模塊用例 sheet 執行函數或主 sheet 執行函數,組裝測試場景。
  • 可直接用代碼組裝測試場景,也可根據 excel 數據文件的用例集合和用例步驟的維護來設定測試場景。
  • 完成測試執行后生成測試結果文件並發送郵件。
 1 from bussiness_process.main_process import *
 2 from util.report_util import *
 3 
 4 
 5 # 組裝測試場景
 6 # 冒煙測試
 7 def smoke_test(report_name):
 8     excel, _ = suite_process(TEST_DATA_FILE_PATH, "進入主頁")
 9     excel, _ = suite_process(excel, "登錄")
10     excel, _ = suite_process(excel, "退出")
11     # 生成測試報告並發送郵件
12     create_excel_report_and_send_email(excel, ['itsjuno@163.com', '182230124@qq.com'], report_name, "請查收附件:app自動化測試報告")
13 
14 
15 # 全量測試:執行主sheet的用例集
16 def suite_test(report_name):
17     excel = main_suite_process(TEST_DATA_FILE_PATH, "測試用例集")
18     create_excel_report_and_send_email(excel, ['itsjuno@163.com', '182230124@qq.com'], report_name, "請查收附件:app自動化測試報告")
19 
20 
21 if __name__ == "__main__":
22     # smoke_test("APP自動化測試報告_冒煙測試")
23     suite_test("APP自動化測試報告_全量測試")

 

test_report 目錄

本目錄用於存放測試結果文件。

 

exception_pic 目錄

本目錄用於存放失敗用例的截圖。

 

log 目錄

本目錄用於存放日志輸出文件(日志內容同時也會輸出到控制台)。

log/app_test.log:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM