request_util.py 11 KB

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