request_util.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import json
  2. import re
  3. import traceback
  4. import jsonpath
  5. import requests
  6. from common.database_util import DatabaseUtil
  7. from common.encrypt import genRat
  8. from common.log_util import error_log, logs
  9. from common.yaml_util import write_yaml, read_config_yaml, write_yaml_out_time_url
  10. from random1111 import DubugTalk
  11. class RequestUtil:
  12. def __init__(self, two_node):
  13. self.base_url = read_config_yaml("base", two_node)
  14. # 定义一个全局变量,类变量,通过类名调用
  15. sess = requests.session()
  16. def send_request(self, name, method, url, **kwargs):
  17. try:
  18. # 请求方式处理
  19. method = str(method).lower()
  20. # 基础路径拼接以及替换
  21. url_old = self.replace_value(url)
  22. url = self.base_url + self.replace_value(url)
  23. # 参数替换
  24. for key, value in kwargs.items():
  25. if key in ['params', 'data', 'json', 'headers']:
  26. kwargs[key] = self.replace_value(value)
  27. if key == 'headers':
  28. kwargs['headers']["Mi"]= DubugTalk().genRat(url_old)
  29. elif key == 'files':
  30. for file_key, file_path in value.items():
  31. value[file_key] = open(file_path, 'rb')
  32. # 输出日志
  33. logs("请求名称:%s" % name)
  34. logs("请求方式:%s" % method)
  35. logs("请求路径:%s" % url)
  36. if "headers" in kwargs.keys():
  37. logs("请求头:%s" % kwargs["headers"])
  38. if "params" in kwargs.keys():
  39. logs("请求params参数:%s" % kwargs["params"])
  40. elif "data" in kwargs.keys():
  41. logs("请求data参数:%s" % kwargs["data"])
  42. elif "json" in kwargs.keys():
  43. logs("请求json参数:%s" % kwargs["json"])
  44. if "files" in kwargs.keys():
  45. logs("文件上传:%s" % kwargs["files"])
  46. # 请求
  47. res = RequestUtil.sess.request(method, url, **kwargs)
  48. logs("实际结果: %s" % res)
  49. return res
  50. except Exception as e:
  51. error_log("发送请求send_request异常:%s" % str(traceback.format_exc()))
  52. # 替换值的方法
  53. # 问题1:(替换url,params,data,json,headers)
  54. # 问题2:(string,float,int,dict)
  55. def replace_value(self, data):
  56. if data:
  57. # 保存数据类型
  58. data_type = type(data)
  59. # 判断数据类型
  60. if isinstance(data, dict) or isinstance(data, list):
  61. str_data = json.dumps(data)
  62. else:
  63. str_data = str(data)
  64. # 替换
  65. for cs in range(1, str_data.count('${') + 1):
  66. if "${" in str_data and "}" in str_data:
  67. start_index = str_data.index("${")
  68. end_index = str_data.index("}", start_index)
  69. old_index = str_data[start_index:end_index + 1]
  70. # 反射,通过类的对象和方法,字符串调用方法
  71. function_name = old_index[2:old_index.index('(')]
  72. args_value = old_index[old_index.index("(") + 1:old_index.index(")")]
  73. new_index = ""
  74. if args_value != "":
  75. args_value2 = args_value.split(',')
  76. new_index = getattr(DubugTalk(), function_name)(*args_value2)
  77. else:
  78. new_index = getattr(DubugTalk(), function_name)()
  79. if isinstance(new_index, int) or isinstance(new_index, float):
  80. str_data = str_data.replace('"' + old_index + '"', str(new_index))
  81. else:
  82. str_data = str_data.replace(old_index, str(new_index))
  83. # 还原数据类型
  84. if isinstance(data, dict) or isinstance(data, list):
  85. data = json.loads(str_data)
  86. else:
  87. data = data_type(str_data)
  88. return data
  89. # def replace_headers(self, data):
  90. # 规范yaml文件
  91. def standard_yaml(self, arg_names):
  92. try:
  93. logs("--------接口测试开始--------")
  94. arg_names_keys = arg_names.keys()
  95. # 判断一级关键字是否存在:name,request,validate
  96. if "name" in arg_names_keys and "request" in arg_names_keys and "validate" in arg_names_keys:
  97. # 判断requests下面是否包含method,url
  98. request_keys = arg_names['request'].keys()
  99. if "method" in request_keys and "url" in request_keys:
  100. logs("yaml框架检查基本通过")
  101. # pop返回该值,并删除
  102. name = arg_names.pop("name")
  103. method = arg_names['request'].pop("method")
  104. url = arg_names['request'].pop("url")
  105. # 发送请求
  106. res = self.send_request(name, method, url, **arg_names['request'])
  107. # 获取接口的请求时间
  108. res_time = round(res.elapsed.total_seconds() * 1000, 2)
  109. act_time = read_config_yaml("request", "request_out_time")
  110. print("act_time============", act_time)
  111. print("res_time============", res_time)
  112. # 判断响应时间
  113. if res_time >= act_time:
  114. # warring_log(
  115. # "接口实际请求时间{res_time}毫秒,请求时间大于{act_time}毫秒,请关注".format(res_time=res_time,
  116. # act_time=act_time))
  117. # # 超时发送钉钉推送
  118. # dingtalk_send_warning(res)
  119. write_yaml_out_time_url({name: res.url})
  120. # print(res.json())
  121. return_text = res.text
  122. # print(return_text)
  123. return_json = ""
  124. return_code = res.status_code
  125. # 提取值并写入extract.yaml文件里面
  126. try:
  127. return_json = res.json()
  128. except Exception as e:
  129. error_log("返回结果不是json格式,不能用这种方法")
  130. if "extract" in arg_names_keys:
  131. for key, value in arg_names['extract'].items():
  132. if "(.*?)" in value or "(.+?)" in value: # 正则
  133. # print("-------"+ value)
  134. zz_value = re.search(value, return_text)
  135. if zz_value:
  136. extract_value = {key: zz_value.group(1)}
  137. write_yaml(extract_value)
  138. else: # jsonpath
  139. # print("+++++"+value)
  140. js_value = jsonpath.jsonpath(return_json, value)
  141. if js_value:
  142. extract_value = {key: js_value[0]}
  143. write_yaml(extract_value)
  144. # 断言结果
  145. self.assert_result(arg_names['validate'], return_json, return_code)
  146. else:
  147. error_log("request下面是否包含method,url")
  148. else:
  149. error_log("一级关键字必须包括:name, request, validate")
  150. except Exception as e:
  151. error_log("规范yaml文件standard_yaml异常:%s" % str(traceback.format_exc()))
  152. # 断言方法
  153. def assert_result(self, yq_result, sj_result, return_code):
  154. try:
  155. logs("预期结果:%s" % yq_result)
  156. logs("实际结果:%s" % sj_result)
  157. # logs("实际结果:%s" % json.loads(json.dumps(sj_result).replace(r"\\", "\\")))
  158. for yq in yq_result:
  159. for key, value in yq.items():
  160. # print(key, value)
  161. if key == "equals":
  162. self.assert_equals(value, sj_result, return_code)
  163. elif key == "contains":
  164. # self.assert_contains(value, json.loads(json.dumps(sj_result).replace(r"\\", "\\")))
  165. self.assert_contains(value, sj_result)
  166. elif key == 'db_equals':
  167. self.database_assert(value, sj_result)
  168. else:
  169. error_log("框架暂时不支持此框架断言")
  170. logs("接口测试成功")
  171. logs("------接口测试结束————————\n")
  172. except Exception as e:
  173. logs("接口测试失败!!!")
  174. logs("------接口测试结束————————")
  175. error_log("断言assert_result异常:%s" % str(traceback.format_exc()))
  176. # 相等断言
  177. def assert_equals(self, value, sj_result, return_code):
  178. for assert_key, assert_value in value.items():
  179. # print(assert_value)
  180. if assert_key == "status_code":
  181. if assert_value != return_code:
  182. error_log("断言失败:状态码不等于%s" % assert_value)
  183. else:
  184. lists = jsonpath.jsonpath(sj_result, '$..%s' % assert_key)
  185. if lists:
  186. if assert_value not in lists:
  187. error_log("断言失败:" + assert_key + "不等于" + str(assert_value))
  188. else:
  189. error_log("断言失败:返回中的结果不存在:" + assert_key)
  190. # 包含断言
  191. def assert_contains(self, value, sj_result):
  192. if str(value).replace("{", "").replace("}", "") not in str(sj_result):
  193. error_log("断言失败:返回结果中不包含" + str(value))
  194. # 数据库断言
  195. def database_assert(self, value, sj_result):
  196. for sql, key in value.items():
  197. if key not in sj_result:
  198. error_log("数据库断言失败:返回结果中不包含" + str(key))
  199. else:
  200. res = None
  201. try:
  202. res = DatabaseUtil().execute_sql(sql)
  203. except:
  204. error_log("数据库断言失败:SQL查询异常:%s" % str(traceback.format_exc()))
  205. if res is None:
  206. error_log("数据库断言失败:SQL语句有语法错误或者查询结果为空")
  207. else:
  208. res_new = []
  209. for i in res:
  210. for k in i:
  211. res_new.append(k)
  212. if str(sj_result[key]) in res_new:
  213. logs("数据库断言成功:数据库查询结果" + str(res) + ",返回结果:" + str(sj_result[key]))
  214. else:
  215. error_log("数据库断言失败:SQL查询出的结果不等于接口返回结果")