【第五章】介面關聯 正則表示式-jsonpath模組
阿新 • • 發佈:2021-12-09
這一章節說到的是正則表示式模組跟jsonpthon模組 以及介面引數化的操作
簡單介紹一下正則表示式跟jsonpath模組
re模組是python獨有的匹配字串的模組,該模組中提供的很多功能是基於正則表示式實現的,而正則表示式是對字串進行模糊匹配,提取自己需要的字串部分,他對所有的語言都通用。注意:
- re模組是python獨有的
- 正則表示式所有程式語言都可以使用
- re模組、正則表示式是對字串進行操作
- json_path_demo_06.py
# -*- coding: utf-8 -*- # @Time : 2021/12/9 15:41 # @Author : Limusen# @File : json_path_demo_06 import re import jsonpath """ jsonpath 第三方模組 下載方式 pip install jsonpath """ print("========================json_path=========================") json_data = {"name": "哈利波特", "age": 22, "books": [{"bn": "假如給我三天光明", "p": 32.3}, {"bn": "朝花夕拾", "p": 33.3}]} # jsonpath返回的是列表 需要用下標取值# $ 表示根節點, .表示字典的key []表示列表的下標 value1 = jsonpath.jsonpath(json_data, "$.age")[0] print(value1) value2 = jsonpath.jsonpath(json_data, "$.books[1].bn")[0] print(value2) value3 = jsonpath.jsonpath(json_data, "$.books[1].p")[0] print(value3) print("========================json_path=========================") print("========================re=========================") """ re模組可以參考: https://www.cnblogs.com/shenjianping/p/11647473.html """ # 正則表示式 str_01 = "helloword669582" str_01 = re.findall("hell(.+?)69582", str_01)[0] print(str_01) str1 = "hello123kkkas567" value4 = re.findall("o(\d+)k", str1)[0] print(value4) print("========================re=========================")
- 通過字串的replace方法分割正則提取器的值
- replace_demo_07.py
# -*- coding: utf-8 -*- # @Time : 2021/12/9 15:58 # @Author : Limusen # @File : replace_demo_07 """ 配合re模組進行引數替換 """ import re dict_01 = {"token": "88669952sss"} str1 = '{"access_token":"${token}"}' # 找出我們需要替換的值 variables_list = re.findall("\\${.+?}", str1) print(variables_list) # 取variables_list列表的第一個值,然後通過 從${ 展位為2 }為-1 分割欄位進行替換 \\${.+?} str1 = str1.replace(variables_list[0], dict_01[variables_list[0][2:-1]]) print(str1)
- 在excel裡面我們已經定義好的取值方式可以根據正則jsonpath或者沒有
- 優化request_utils模組底層方法get跟post
- 單獨拿一個接口出來封裝,以免導致之前的程式碼也不能執行
- request_demo_08.py
# -*- coding: utf-8 -*- # @Time : 2021/12/9 16:17 # @Author : Limusen # @File : request_demo_08 import re import json import jsonpath import requests from common.config_utils import local_config class RequestsUtils: def __init__(self): # 封裝好的配置檔案直接拿來用 self.hosts = local_config.get_hosts # 全域性session呼叫 self.session = requests.session() # 臨時變數儲存正則或者jsonpath取到的值 self.temp_variables = {} def get(self, request_info): """ get請求封裝 :param request_info: :return: """ # request_info 是我們封裝好的資料,可以直接拿來用 url = "https://%s%s" % (self.hosts, request_info["請求地址"]) response = self.session.get(url=url, params=json.loads( requests_info['請求引數(get)'] if requests_info['請求引數(get)'] else None), # 頭部資訊有時候可能為空,這裡運用到三元運算子如果為空則設定為None headers=json.loads(request_info["請求頭部資訊"]) if request_info["請求頭部資訊"] else None ) if request_info["取值方式"] == "正則取值": value = re.findall(request_info['取值程式碼'], response.text)[0] self.temp_variables[request_info["取值變數"]] = value elif request_info["取值方式"] == "jsonpath取值": value = jsonpath.jsonpath(response.json(), request_info["取值程式碼"])[0] self.temp_variables[request_info["取值變數"]] = value print(self.temp_variables) # result = { # "code": 0, # "response_code": response.status_code, # "response_reason": response.reason, # "response_headers": response.headers, # "response_body": response.text # } # return result if __name__ == '__main__': requests_info = {'測試用例編號': 'api_case_03', '測試用例名稱': '刪除標籤介面測試', '用例執行': '是', '用例步驟': 'step_01', '介面名稱': '獲取access_token介面', '請求方式': 'get', '請求頭部資訊': '', '請求地址': '/cgi-bin/token', '請求引數(get)': '{"grant_type":"client_credential","appid":"wxb637f8f0d","secret":"501123d2dd0f084"}', '請求引數(post)': '', '取值方式': 'jsonpath取值', '取值程式碼': '$.access_token', '取值變數': 'token', '斷言型別': 'json_key', '期望結果': 'access_token,expires_in'} res = RequestsUtils() res.get(requests_info) # print(res.get(requests_info))
- 咱們要雨露均沾post方法也封裝一下
def __post(self, request_info): """ post請求封裝 :param request_info: :return: """ url = "https://%s%s" % (self.hosts, request_info["請求地址"]) response = self.session.post(url=url, params=json.loads(request_info['請求引數(get)']), # params=json.loads( # requests_info['請求引數(get)'] if requests_info['請求引數(get)'] else None), headers=json.loads(request_info["請求頭部資訊"]) if request_info["請求頭部資訊"] else None, json=json.loads(request_info["請求引數(post)"]) ) if request_info["取值方式"] == "正則取值": value = re.findall(request_info["取值程式碼"], response.text)[0] self.temp_variables[request_info["取值變數"]] = value elif request_info["取值方式"] == "jsonpath取值": value = jsonpath.jsonpath(response.json(), request_info["取值程式碼"])[0] self.temp_variables[request_info["取值變數"]] = value result = { "code": 0, "response_code": response.status_code, "response_reason": response.reason, "response_headers": response.headers, "response_body": response.text } return result
- 接下來封裝請求引數的引數化資訊
# -*- coding: utf-8 -*- # @Time : 2021/12/9 16:17 # @Author : Limusen # @File : request_demo_08 import re import json import jsonpath import requests from common.config_utils import local_config class RequestsUtils: def __init__(self): # 封裝好的配置檔案直接拿來用 self.hosts = local_config.get_hosts # 全域性session呼叫 self.session = requests.session() # 臨時變數儲存正則或者jsonpath取到的值 self.temp_variables = {} def __get(self, request_info): """ get請求封裝 :param request_info: :return: """ # request_info 是我們封裝好的資料,可以直接拿來用 url = "https://%s%s" % (self.hosts, request_info["請求地址"]) variables_list = re.findall('\\${.+?}', request_info["請求引數(get)"]) for variable in variables_list: request_info["請求引數(get)"] = request_info["請求引數(get)"].replace(variable, self.temp_variables[variable[2:-1]]) response = self.session.get(url=url, params=json.loads(request_info["請求引數(get)"]), # params=json.loads( # requests_info['請求引數(get)'] if requests_info['請求引數(get)'] else None), headers=json.loads(request_info["請求頭部資訊"]) if request_info["請求頭部資訊"] else None ) if request_info["取值方式"] == "正則取值": value = re.findall(request_info["取值程式碼"], response.text)[0] self.temp_variables[request_info["取值變數"]] = value elif request_info["取值方式"] == "jsonpath取值": value = jsonpath.jsonpath(response.json(), request_info["取值程式碼"])[0] self.temp_variables[request_info["取值變數"]] = value result = { "code": 0, "response_code": response.status_code, "response_reason": response.reason, "response_headers": response.headers, "response_body": response.text } return result def __post(self, request_info): """ post請求封裝 :param request_info: :return: """ url = "https://%s%s" % (self.hosts, request_info["請求地址"]) variables_list = re.findall('\\${.+?}', request_info["請求引數(get)"]) for variable in variables_list: request_info["請求引數(get)"] = request_info["請求引數(get)"].replace(variable, self.temp_variables[variable[2:-1]]) variables_list = re.findall('\\${.+?}', request_info["請求引數(post)"]) for variable in variables_list: request_info["請求引數(post)"] = request_info["請求引數(post)"].replace(variable, self.temp_variables[variable[2:-1]]) response = self.session.post(url=url, params=json.loads(request_info['請求引數(get)']), # params=json.loads( # requests_info['請求引數(get)'] if requests_info['請求引數(get)'] else None), headers=json.loads(request_info["請求頭部資訊"]) if request_info["請求頭部資訊"] else None, json=json.loads(request_info["請求引數(post)"]) ) if request_info["取值方式"] == "正則取值": value = re.findall(request_info["取值程式碼"], response.text)[0] self.temp_variables[request_info["取值變數"]] = value elif request_info["取值方式"] == "jsonpath取值": value = jsonpath.jsonpath(response.json(), request_info["取值程式碼"])[0] self.temp_variables[request_info["取值變數"]] = value result = { "code": 0, "response_code": response.status_code, "response_reason": response.reason, "response_headers": response.headers, "response_body": response.text } return result def request(self, request_info): """ 封裝方法自動執行post或者get方法 :param request_info: :return: """ request_type = request_info['請求方式'] if request_type == "get": # 私有化方法,其他類均不可呼叫 result = self.__get(request_info) elif request_type == "post": result = self.__post(request_info) else: result = {"code": 1, "error_message": "當前請求方式暫不支援!"} return result def request_steps(self, request_steps): """ 按照列表測試用例順序執行測試用例 :param request_steps: :return: """ for request in request_steps: result = self.request(request) if result['code'] != 0: break return result if __name__ == '__main__': requests_info = [ {'測試用例編號': 'api_case_03', '測試用例名稱': '刪除標籤介面測試', '用例執行': '是', '用例步驟': 'step_01', '介面名稱': '獲取access_token介面', '請求方式': 'get', '請求頭部資訊': '', '請求地址': '/cgi-bin/token', '請求引數(get)': '{"grant_type":"client_credential","appid":"wxb637f897f0bf1f0d","secret":"501123d2d367b109a5cb9a9011d0f084"}', '請求引數(post)': '', '取值方式': 'jsonpath取值', '取值程式碼': '$.access_token', '取值變數': 'token_value', '斷言型別': 'json_key', '期望結果': 'access_token,expires_in'}, {'測試用例編號': 'api_case_03', '測試用例名稱': '刪除標籤介面測試', '用例執行': '是', '用例步驟': 'step_02', '介面名稱': '建立標籤介面', '請求方式': 'post', '請求頭部資訊': '', '請求地址': '/cgi-bin/tags/create', '請求引數(get)': '{"access_token":"${token_value}"}', '請求引數(post)': '{ "tag" : { "name" : "asssqwe" } } ', '取值方式': '無', '取值程式碼': '"id":(.+?),', '取值變數': 'tag_id', '斷言型別': 'none', '期望結果': ''} ] res = RequestsUtils() print(res.request_steps(requests_info))
- 執行通過後放入request_utils.py
# -*- coding: utf-8 -*- # @Time : 2021/12/9 14:37 # @Author : Limusen # @File : request_utils import re import json import jsonpath import requests from common.config_utils import local_config class RequestsUtils: def __init__(self): # 封裝好的配置檔案直接拿來用 self.hosts = local_config.get_hosts # 全域性session呼叫 self.session = requests.session() self.temp_variables = {} def __get(self, request_info): """ get請求封裝 :param request_info: :return: """ # request_info 是我們封裝好的資料,可以直接拿來用 url = "https://%s%s" % (self.hosts, request_info["請求地址"]) variables_list = re.findall('\\${.+?}', request_info["請求引數(get)"]) for variable in variables_list: request_info["請求引數(get)"] = request_info["請求引數(get)"].replace(variable, self.temp_variables[variable[2:-1]]) response = self.session.get(url=url, params=json.loads(request_info["請求引數(get)"]), # params=json.loads( # requests_info['請求引數(get)'] if requests_info['請求引數(get)'] else None), headers=json.loads(request_info["請求頭部資訊"]) if request_info["請求頭部資訊"] else None ) if request_info["取值方式"] == "正則取值": value = re.findall(request_info["取值程式碼"], response.text)[0] self.temp_variables[request_info["取值變數"]] = value elif request_info["取值方式"] == "jsonpath取值": value = jsonpath.jsonpath(response.json(), request_info["取值程式碼"])[0] self.temp_variables[request_info["取值變數"]] = value result = { "code": 0, "response_code": response.status_code, "response_reason": response.reason, "response_headers": response.headers, "response_body": response.text } return result def __post(self, request_info): """ post請求封裝 :param request_info: :return: """ url = "https://%s%s" % (self.hosts, request_info["請求地址"]) variables_list = re.findall('\\${.+?}', request_info["請求引數(get)"]) for variable in variables_list: request_info["請求引數(get)"] = request_info["請求引數(get)"].replace(variable, self.temp_variables[variable[2:-1]]) variables_list = re.findall('\\${.+?}', request_info["請求引數(post)"]) for variable in variables_list: request_info["請求引數(post)"] = request_info["請求引數(post)"].replace(variable, self.temp_variables[variable[2:-1]]) response = self.session.post(url=url, params=json.loads(request_info['請求引數(get)']), # params=json.loads( # requests_info['請求引數(get)'] if requests_info['請求引數(get)'] else None), headers=json.loads(request_info["請求頭部資訊"]) if request_info["請求頭部資訊"] else None, json=json.loads(request_info["請求引數(post)"]) ) if request_info["取值方式"] == "正則取值": value = re.findall(request_info["取值程式碼"], response.text)[0] self.temp_variables[request_info["取值變數"]] = value elif request_info["取值方式"] == "jsonpath取值": value = jsonpath.jsonpath(response.json(), request_info["取值程式碼"])[0] self.temp_variables[request_info["取值變數"]] = value result = { "code": 0, "response_code": response.status_code, "response_reason": response.reason, "response_headers": response.headers, "response_body": response.text } return result def request(self, request_info): """ 封裝方法自動執行post或者get方法 :param request_info: :return: """ request_type = request_info['請求方式'] if request_type == "get": # 私有化方法,其他類均不可呼叫 result = self.__get(request_info) elif request_type == "post": result = self.__post(request_info) else: result = {"code": 1, "error_message": "當前請求方式暫不支援!"} return result def request_steps(self, request_steps): """ 按照列表測試用例順序執行測試用例 :param request_steps: :return: """ for request in request_steps: result = self.request(request) if result['code'] != 0: break return result if __name__ == '__main__': requests_info = {'測試用例編號': 'api_case_03', '測試用例名稱': '刪除標籤介面測試', '用例執行': '是', '用例步驟': 'step_01', '介面名稱': '獲取access_token介面', '請求方式': 'get', '請求頭部資訊': '', '請求地址': '/cgi-bin/token', '請求引數(get)': '{"grant_type":"client_credential","appid":"wxb637f897f0bf1f0d","secret":"501123d2d367b109a5cb9a9011d0f084"}', '請求引數(post)': '', '取值方式': 'jsonpath取值', '取值程式碼': '$.access_token', '取值變數': 'token', '斷言型別': 'json_key', '期望結果': 'access_token,expires_in'} requests_info_post = {'測試用例編號': 'api_case_03', '測試用例名稱': '刪除標籤介面測試', '用例執行': '是', '用例步驟': 'step_02', '介面名稱': '建立標籤介面', '請求方式': 'post', '請求頭部資訊': '', '請求地址': '/cgi-bin/tags/create', '請求引數(get)': '{"access_token":"51_136b9lRBH4SdLbSYI9C_1Sf1OogELivPJPNZ5z1mTzekmp3Yg4XQn8mx-sb3WxxV99NRWAX5CQhVIF6-uY12H_nRDjmEJ7H7oEbz9-qNHWV1g04V2t-29pslCsiuaSxIrkUChv4a2rPwdhnEEMHeADAMUP"}', '請求引數(post)': '{ "tag" : { "name" : "snsnssn" } } ', '取值方式': '正則取值', '取值程式碼': '"id":(.+?),', '取值變數': 'tag_id', '斷言型別': 'none', '期望結果': ''} requests_info_list = [ {'測試用例編號': 'api_case_03', '測試用例名稱': '刪除標籤介面測試', '用例執行': '是', '用例步驟': 'step_01', '介面名稱': '獲取access_token介面', '請求方式': 'get', '請求頭部資訊': '', '請求地址': '/cgi-bin/token', '請求引數(get)': '{"grant_type":"client_credential","appid":"wxb63f0bf1f0d","secret":"501123d29a9011d0f084"}', '請求引數(post)': '', '取值方式': 'jsonpath取值', '取值程式碼': '$.access_token', '取值變數': 'token_value', '斷言型別': 'json_key', '期望結果': 'access_token,expires_in'}, {'測試用例編號': 'api_case_03', '測試用例名稱': '刪除標籤介面測試', '用例執行': '是', '用例步驟': 'step_02', '介面名稱': '建立標籤介面', '請求方式': 'post', '請求頭部資訊': '', '請求地址': '/cgi-bin/tags/create', '請求引數(get)': '{"access_token":"${token_value}"}', '請求引數(post)': '{ "tag" : { "name" : "newtest" } } ', '取值方式': '無', '取值程式碼': '"id":(.+?),', '取值變數': 'tag_id', '斷言型別': 'none', '期望結果': ''} ] res = RequestsUtils() # res.get(requests_info) # res.post(requests_info_post) # print(res.request(requests_info_post)) print(res.request_steps(requests_info_list))
- 現在我們request模組的正則也封裝好了,下一章節我們將講述一下封裝斷言庫