request_util.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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_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 = 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. write_yaml_out_time_url({name: res.url})
  116. # print(res.json())
  117. return_text = res.text
  118. # print(return_text)
  119. return_json = ""
  120. return_code = res.status_code
  121. # 提取值并写入extract.yaml文件里面
  122. try:
  123. return_json = res.json()
  124. except Exception as e:
  125. error_log("返回结果不是json格式,不能用这种方法")
  126. if "extract" in arg_names_keys:
  127. for key, value in arg_names['extract'].items():
  128. if "(.*?)" in value or "(.+?)" in value: # 正则
  129. # print("-------"+ value)
  130. zz_value = re.search(value, return_text)
  131. if zz_value:
  132. extract_value = {key: zz_value.group(1)}
  133. write_yaml(extract_value)
  134. else: # jsonpath
  135. # print("+++++"+value)
  136. js_value = jsonpath.jsonpath(return_json, value)
  137. if js_value:
  138. extract_value = {key: js_value[0]}
  139. write_yaml(extract_value)
  140. # 断言结果
  141. self.assert_result(arg_names['validate'], return_json, return_code)
  142. else:
  143. error_log("request下面是否包含method,url")
  144. else:
  145. error_log("一级关键字必须包括:name, request, validate")
  146. except Exception as e:
  147. error_log("规范yaml文件standard_yaml异常:%s" % str(traceback.format_exc()))
  148. # 断言方法
  149. def assert_result(self, yq_result, sj_result, return_code):
  150. try:
  151. logs("预期结果:%s" % yq_result)
  152. logs("实际结果:%s" % sj_result)
  153. # logs("实际结果:%s" % json.loads(json.dumps(sj_result).replace(r"\\", "\\")))
  154. for yq in yq_result:
  155. for key, value in yq.items():
  156. # print(key, value)
  157. if key == "equals":
  158. self.assert_equals(value, sj_result, return_code)
  159. elif key == "contains":
  160. # self.assert_contains(value, json.loads(json.dumps(sj_result).replace(r"\\", "\\")))
  161. self.assert_contains(value, sj_result)
  162. elif key == 'db_equals':
  163. self.database_assert(value, sj_result)
  164. else:
  165. error_log("框架暂时不支持此框架断言")
  166. logs("接口测试成功")
  167. logs("------接口测试结束————————\n")
  168. except Exception as e:
  169. logs("接口测试失败!!!")
  170. logs("------接口测试结束————————")
  171. error_log("断言assert_result异常:%s" % str(traceback.format_exc()))
  172. # 相等断言
  173. def assert_equals(self, value, sj_result, return_code):
  174. for assert_key, assert_value in value.items():
  175. # print(assert_value)
  176. if assert_key == "status_code":
  177. if assert_value != return_code:
  178. error_log("断言失败:状态码不等于%s" % assert_value)
  179. else:
  180. lists = jsonpath.jsonpath(sj_result, '$..%s' % assert_key)
  181. if lists:
  182. if assert_value not in lists:
  183. error_log("断言失败:" + assert_key + "不等于" + str(assert_value))
  184. else:
  185. error_log("断言失败:返回中的结果不存在:" + assert_key)
  186. # 包含断言
  187. def assert_contains(self, value, sj_result):
  188. if str(value).replace("{", "").replace("}", "") not in str(sj_result):
  189. error_log("断言失败:返回结果中不包含" + str(value))
  190. # 数据库断言
  191. def database_assert(self, value, sj_result):
  192. for sql, key in value.items():
  193. if key not in sj_result:
  194. error_log("数据库断言失败:返回结果中不包含" + str(key))
  195. else:
  196. res = None
  197. try:
  198. res = DatabaseUtil().execute_sql(sql)
  199. except:
  200. error_log("数据库断言失败:SQL查询异常:%s" % str(traceback.format_exc()))
  201. if res is None:
  202. error_log("数据库断言失败:SQL语句有语法错误或者查询结果为空")
  203. else:
  204. res_new = []
  205. for i in res:
  206. for k in i:
  207. res_new.append(k)
  208. if str(sj_result[key]) in res_new:
  209. logs("数据库断言成功:数据库查询结果" + str(res) + ",返回结果:" + str(sj_result[key]))
  210. else:
  211. error_log("数据库断言失败:SQL查询出的结果不等于接口返回结果")