解決自動化接口測試的數據依賴

本篇博客是延續上一篇博客(https://blog.csdn.net/guozhiguo86/article/details/100090828)把其中涉及到的怎樣解決數據依賴的問題,單獨拎出來做講解。

模板釋義

在excel模板中涉及到數據依賴的列如下圖所示:

如上圖所示,一共有:rely_case_id、rely_data、request_rely_file及request_data 這四列。

  1. rely_case_id:表示當前case所依賴的數據所在的case id
  2. rely_data:表示當前case所依賴的case的數據所對應的響應結果的字段(可能一些同學不明白,爲什麼這裏不是直接寫依賴的數據,因爲接口所依賴的數據往往都是動態。至少我做自動化測試的這幾年,沒見過一次是靜態數據依賴,如果是靜態的,就不會讓這麼多的同學煩惱怎樣解決)
  3. request_rely_file:請求數據中要替換的數據所對應的字段值
  4. request_data:請求數據key(需要說一下,該列保存的都是key。所有的請求數據都保存在json文件中。通過key來獲取對應的具體的請求參數數據值)

解決思路

  1. 通過rely_case_id的值,來執行所依賴的case,並獲取相應的響應結果
  2. 將獲取的響應結果轉爲json/dict
  3. 通過jsonpath_rw 來截取rely_data 所對應的具體數據,並返回
  4. 當獲取到所依賴的數據後,此時獲取具體的請求數據
  5. 再將請求數據要替換的數據,替換爲所依賴的數據即可
  6. 此時正常執行該用例即可。

具體代碼

import sys
 
sys.path.append("../../")
from script.case.opera_api_case_excel import OperaApiCaseData
from script.method.run_method import RunMethod
from script.case.get_api_case_excel_data import GetCaseExcelData
from jsonpath_rw import parse
import json
 
import traceback
 
 
class RelyData():
    """
    解決case間的數據依賴  \n
    1:獲取所依賴case所在行的所有數據  \n
    2:運行所依賴的case,並返回該case的請求結果  \n
    3:從請求的結果中獲取所依賴的字段的值(使用jsonpath-rw)  \n
    """
 
    def __init__(self, rely_case_id, excel_path, sheet_name):
        """
        傳入所依賴的case id 以及excel表的路徑和sheet表的名稱  \n
        :param rely_case_id: 所依賴的case id
        """
        self.case_id = rely_case_id
        self.excel_path = excel_path
        self.sheet_name = sheet_name
        self.opera_excel = OperaApiCaseData(self.excel_path, self.sheet_name)
        self.run_method = RunMethod()
        self.excel_data = GetCaseExcelData(self.excel_path, self.sheet_name)
 
    # def get_rely_case_row_data(self):
    #     """
    #     獲取依賴的case所在行的數據  \n
    #     :return: 返回所依賴的case 所在的行的數據 List類型
    #     """
    #     row_data = self.opera_excel.get_case_row_data(self.case_id)
    #     return row_data
 
    def run_rely_case(self,json_file_path):
        """
        執行所依賴的case,並將運行的結果返回  \n
        :param json_file_path: request請求對應的json文件路徑,如'../../data/request/105_web_login.json'
        :return: 返回執行所依賴的case的運行結果
        """
 
        run_method = RunMethod()
        row_num = self.opera_excel.get_rely_case_row_num(self.case_id)
        print("所依賴的case id 爲:",self.case_id)
        print("所依賴的case 所在的行號爲:",row_num)
        request_data = self.excel_data.get_request_data(row_num,json_file_path)
        print("run_rely_case  request_data",request_data)
        header = self.excel_data.get_is_header(row_num)
        url = self.excel_data.get_url(row_num)
        method = self.excel_data.get_method(row_num)
        res = run_method.run_main(method, url, request_data, header)
        print('run_rely_case res',res)
        # 將響應的結果json處理爲str 並返回
        return json.dumps(res.json(), ensure_ascii=False, sort_keys=True, indent=2)
 
    def get_rely_data(self, row,json_file_path):
        """
        執行所依賴的case,並從返回的響應數據中獲取目標數據  \n
        # response_data = {                         \n
        #   "reason": "成功",                        \n
        #   "status": 1                             \n
        # }                                          \n
        # rely_data = "staus"                       \n
        response_data = {                           \n
          "reason": "成功",                          \n
          "status": {"username":"123456",            \n
                     "pass":"12345stwetqw6"}         \n
        }                                            \n
        rely_data = "status.pass"                    \n
        如上面所示,想要查找status下的pass的值,在excel表中的rely_data 就應該寫爲status.pass  \n
        如果想要獲取status的值,就應該爲 status           \n
        :param row: 有依賴case的行號
        :param json_file_path: request 請求所對應的json路徑,含文件名,如'../../data/request/XXXX.json'
        :return: 返回查找到的數據
        """
        # 獲取 rely data 單元格的值
        rely_data = self.excel_data.get_rely_data(row)
        # 判斷是否爲空
        if rely_data == None or rely_data == "":
            return None
        else:
            try:
                # 獲取所依賴的case的返回結果
                response_data = self.run_rely_case(json_file_path)
 
                # 把返回回來的字符串轉化爲json/dict 類型
                response_data = json.loads(response_data)
 
                jsonpath_expr = parse(rely_data)
                find_data = jsonpath_expr.find(response_data)
                return ([match.value for match in find_data][0])
            except Exception as msg:
                # print(msg)
                # print((traceback.print_exc()))
 
                # 輸出完整的異常錯誤信息
                print('traceback.format_exc():', traceback.format_exc())
                return None
 if rely_case_id != None:
        self.rely_data = RelyData(rely_case_id, self.excel_path, self.sheet_name)
        # 執行所依賴的case,並獲取所依賴的響應數據
        rely_response_data = self.rely_data.get_rely_data(i,json_file_path=self.sheet_req_json_file)
        # print(rely_response_data)
        # 獲取依賴的字段
        rely_file = self.excel_wb.get_request_rely_file(i)
        # 更新請求數據
        param_data[rely_file] = rely_response_data
        # print(param_data)

注: 這上面的代碼不支持多層依賴,嵌套依賴。

下一章節將就講解 怎樣解決多層依賴和嵌套依賴(需要用到遞歸)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章