def peppleRun(self): params = self.getPeppleVersion() params["serviceName"] = self.serviceName params["method"] = self.queryMethod params["env"] = self.env #增加入参参数化处理 if self.body not in ('', None): self.body = GetParmsValue().get_parms_value(self.body, self.env) params["body"] = self.body print(params, '\n', type(params)) self.headers["pebble-service"] = str(self.serviceName) self.headers["Content-Type"] = 'application/json' response = requests.post(url=pepple_conf[self.env]["pepple_run"], data=json.dumps(params), headers=self.headers) # response = requests.post(url=pepple_conf[self.env]["pepple_exceute"],data=json.dumps(params),headers={'Content-Type':'application/json'}) # print("pepple-resonse: ",json.loads(str(response.content, encoding='utf-8'))) # print(type(json.loads(str(response.content, encoding='utf-8')))) if response.status_code == 200: try: z = json.loads(str(response.content, encoding='utf-8')) z = {"success": True, "data": z} except Exception as e: z = {"success": False, 'data': '%s' % str(e)} else: z = { "success": False, 'data': '接口请求失败,响应状态码为%s' % str(response.status_code) } print("pepple-resonse: ", z) return z
def postinterfaceone(self, rest, data, env, headers, dParam='', isBase64Encode=False, isBase64Decode=False): getparmsvalue = GetParmsValue() rest = getparmsvalue.get_parms_value(rest, env) #dff: 20190628 对d参数进行处理 param = {} if dParam is not None and dParam != '': dParam = getparmsvalue.get_parms_value(dParam, env) param['d'] = dParam # dff: 20190628 将请求d参数编码 encodeParam = parse.urlencode(param) rest = rest + '&' + encodeParam try: if (data != '' and data != None): data = getparmsvalue.get_parms_value(data, env) #20190727-dff;增加入参base64蓄电池处理 if isBase64Encode: data = base64Encode(data) if (headers != ''): if ('{{' in headers): headers = getparmsvalue.get_parms_value(headers, env) headers = ast.literal_eval(headers) r = requests.post(rest, data=data.encode('utf-8'), headers=headers) try: #按照接口返回数据返回,不进行重新排序 r = json.loads(r.text, object_pairs_hook=OrderedDict) z = json.dumps(r, ensure_ascii=False) except: z = r.text else: if (headers != ''): # headers = eval(headers) headers = json.loads(headers) r = requests.post(rest, headers=headers) try: r = json.loads(r.text, object_pairs_hook=OrderedDict) z = json.dumps(r, ensure_ascii=False) except: z = r.text # print(rest,data,z) # dff-20191009: 对出参需要base64解码进行处理 if isBase64Decode: z = base64Decode(z) except Exception as e: logging.info(e) print(e) z = '调用的post 请求方法异常' return z
def postinterfaceone(self, rest, data, env, headers, dParam=''): getparmsvalue = GetParmsValue() rest = getparmsvalue.get_parms_value(rest, env) success = True #dff: 20190701 对d参数进行处理 param = {} if dParam is not None and dParam != '': dParam = getparmsvalue.get_parms_value(dParam, env) param['d'] = dParam # dff: 20190701 将请求d参数编码 encodeParam = parse.urlencode(param) rest = rest + '&' + encodeParam try: if (data != '' and data != None): data = getparmsvalue.get_parms_value(data, env) if (headers != ''): if ('{{' in headers): headers = getparmsvalue.get_parms_value(headers, env) headers = ast.literal_eval(headers) # r = requests.post(rest, data=data_json, headers=headers) r = requests.post(rest, data=data.encode('utf-8'), headers=headers) # 接口运行时间 time = r.elapsed.microseconds / 1000 try: #按照接口返回数据返回,不进行重新排序 r = json.loads(r.text, object_pairs_hook=OrderedDict) z = json.dumps(r, ensure_ascii=False) except: z = r else: if (headers != ''): # headers = eval(headers) headers = json.loads(headers) r = requests.post(rest, headers=headers) # 接口运行时间 time = r.elapsed.microseconds / 1000 try: r = json.loads(r.text, object_pairs_hook=OrderedDict) z = json.dumps(r, ensure_ascii=False) except: z = r except Exception as e: print(e) z = '调用的post 请求方法异常' time = 0 # 返回dict(接口返回值以及接口运行时间) response = {} response['res'] = z response['time'] = time response['success'] = success return response
def checkout(self): glabalvalue = GetParmsValue() verify = _Verify() # 全局变量校验并入库(如果校验的时候不进行入库,那么在保存的时候有要去重新查一下全局路径对应的全局字段值) if (len(self.global_route) != 0): print(self.global_route) res = glabalvalue.get_parms_value_from_key(self.global_route, self.global_name, self.env, self.actual_response,self.user) if (res['success'] == False): return res # else: # print('未设置全局变量') # 校验值路径是否存在 if (self.route not in ('', None)): self.actual_field_list = [] route_list = self.route.split(';') for r in route_list: # 替换参数 if ('{{' in r): getparmsvalue = GetParmsValue() r = getparmsvalue.get_parms_value(self.route, self.env) try: self.actual_field_list.append(self.getmyvalue(self.actual_response, r)) except: return ({"success": False, "msg": "无法获取" + str(r) + "对应的value"}) # else: # print("该接口没有设置校验值路径") # 校验 if ((self.route in ('', None)) and (self.expected_response not in ('', None))): # 校验块内容字段 try: # 替换参数 if ('{{' in self.expected_response): getparmsvalue = GetParmsValue() self.expected_response = getparmsvalue.get_parms_value(self.expected_response, self.env) verify.should_contain(''.join(self.actual_response.split()), ''.join(self.expected_response.split())) print('返回结果中' + self.actual_response + '字段中包含预期返回值 ' + self.expected_response + "全部字段") except Exception as e: print(e) return {"success": False, "msg": "返回结果中不包含预期返回值全部字段,请检查!"} return {"success": True, "msg": "OK"} elif ((self.route not in ('', None)) and (self.expected_response in ('', None))): expected_field_list = self.expected_field.split(';') print('') i = 0 for route, actual_field,check_type in zip(self.route.split(';'), self.actual_field_list,self.types.split(';')): i += 1 # 替换参数 try: if ('{{' in expected_field_list[i - 1]): getparmsvalue = GetParmsValue() expected_field_list[i - 1] = getparmsvalue.get_parms_value(expected_field_list[i - 1], self.env) if(check_type=='equal' or check_type == ''): if (actual_field == expected_field_list[i - 1]): print('接口返回数据中' + str(route) + '校验路径字段值匹配成功为' + actual_field) else: return {"success": False, "msg": '接口返回数据中' + str(route) + '校验路径字段值应该为' + expected_field_list[ i - 1] + ',而不是' + actual_field} elif(check_type=='regex'): actual_field = actual_field.strip('"') if('\\\\'in expected_field_list[i - 1]): # expected_field_new=eval(expected_field_list[i - 1]) expected_field_new=expected_field_list[i - 1].replace('\\\\','\\') regex_result=re.search(expected_field_new,actual_field,re.I|re.M|re.S) else: # A=expected_field_list[i - 1] regex_result=re.search(expected_field_list[i - 1],actual_field,re.I|re.M|re.S) if(regex_result): print('接口返回数据中' + str(route) + '校验路径字段值正则匹配成功为' + actual_field) else: return {"success": False, "msg": '接口返回数据中' + str(route) + '路径的字段值' + actual_field + '匹配正则'+expected_field_list[ i - 1]+'失败'} else: return {"success": False, "msg": "校验类型无法匹配"} except: return {"success": False, "msg": "请检查使用的全局变量"} return {"success": True, "msg": "OK"} elif ((self.route not in ('', None)) and (self.expected_response not in ('', None))): # 校验某些字段 try: # 替换参数 if ('{{' in self.expected_response): getparmsvalue = GetParmsValue() self.expected_response = getparmsvalue.get_parms_value(self.expected_response, self.env) verify.should_contain(''.join(self.actual_response.split()), ''.join(self.expected_response.split())) print('返回结果中' + self.actual_response + '字段中包含预期返回值 ' + self.expected_response + "全部字段") except: return {"success": False, "msg": '返回结果中不包含预期返回值全部字段,' + "请检查!"} expected_field_list = self.expected_field.split(';') i = 0 for route, actual_field,check_type in zip(self.route.split(';'), self.actual_field_list,self.types.split(';')): print("route=" + route) print("actual_field=" + actual_field) i += 1 # 替换参数 try: if ('{{' in expected_field_list[i - 1]): getparmsvalue = GetParmsValue() expected_field_list[i - 1] = getparmsvalue.get_parms_value(expected_field_list[i - 1], self.env) if (check_type == 'equal' or check_type == ''): if (actual_field == expected_field_list[i - 1]): # print('接口返回数据中' + '第' + str(i) + '校验路径字段值匹配成功为' + actual_field) print('接口返回数据中' + str(route) + '校验路径字段值匹配成功为' + actual_field) else: return {"success": False, "msg": '接口返回数据中' + str(route) + '校验路径字段值应该为' + expected_field_list[ i - 1] + ',而不是' + actual_field} elif (check_type == 'regex'): actual_field = actual_field.strip('"') if ('\\\\' in expected_field_list[i - 1]): # expected_field_new=eval(expected_field_list[i - 1]) expected_field_new = expected_field_list[i - 1].replace('\\\\', '\\') # regex_result = re.match(expected_field_new, actual_field) regex_result=re.search(expected_field_new,actual_field,re.I|re.M|re.S) else: # regex_result = re.match(expected_field_list[i - 1], actual_field) regex_result=re.search(expected_field_list[i - 1],actual_field,re.I|re.M|re.S) if (regex_result): print('接口返回数据中' + str(route) + '校验路径字段值正则匹配成功为' + actual_field) else: return {"success": False, "msg": '接口返回数据中' + str(route) + '路径的字段值' + actual_field + '匹配正则'+expected_field_list[ i - 1]+'失败'} else: return {"success": False, "msg": "校验类型无法匹配"} except: return {"success": False, "msg": "请检查使用的全局变量"} return {"success": True, "msg": "OK"}
def checkout(self): glabalvalue = GetParmsValue() verify = _Verify() # 全局变量校验并入库(如果校验的时候不进行入库,那么在保存的时候有要去重新查一下全局路径对应的全局字段值) if (len(self.global_route) != 0): # print(self.global_route) res = glabalvalue.get_parms_value_from_key(self.global_route, self.global_name, self.env, self.actual_response,self.user) if (res['success']==False): self.flag = False self.msg.append(res['msg']) # if(res!=None): # return res # else: # print('未设置全局变量') # 校验值路径是否存在 if (self.route): self.actual_field_list = [] # print(self.route) route_list = self.route.split(';') for r in route_list: # 替换参数 if ('{{' in r): getparmsvalue = GetParmsValue() r = getparmsvalue.get_parms_value(self.route, self.env) try: self.actual_field_list.append(self.getmyvalue(self.actual_response, r)) self.msg.append("全局校验OK~~") except: # print("校验失败,无法获取" + str(self.route) + "对应的value") self.flag = False self.msg.append("校验失败,无法获取" + str(r) + "对应的value") # else: # print("该接口没有设置校验值路径") # 校验 if (self.route in ('', None, []) and self.expected_response): # 校验块内容字段 try: # 替换参数 if ('{{' in self.expected_response): getparmsvalue = GetParmsValue() self.expected_response = getparmsvalue.get_parms_value(self.expected_response, self.env) verify.should_contain(''.join(self.actual_response.split()), ''.join(self.expected_response.split())) # print('返回结果中' + self.actual_response + '字段中包含预期返回值 ' + self.expected_response + "全部字段") self.msg.append("校验OK~~,"+'返回结果中' + self.actual_response + '字段中包含预期返回值 ' + self.expected_response + "全部字段") except Exception as e: self.flag = False # print("校验失败,返回结果中不包含预期返回值全部字段,请检查!") self.msg.append("校验失败,返回结果中不包含预期返回值全部字段,请检查!") elif (self.route and self.expected_response in ('', None, [])): expected_field_list = self.expected_field.split(';') i = 0 for route, actual_field,check_type in zip(self.route.split(';'), self.actual_field_list,self.types.split(';')): i += 1 # 替换参数 try: if ('{{' in expected_field_list[i - 1]): getparmsvalue = GetParmsValue() expected_field_list[i - 1] = getparmsvalue.get_parms_value(expected_field_list[i - 1], self.env) if (check_type == 'equal'): if (actual_field == expected_field_list[i - 1]): # print('接口返回数据中' + str(route) + '校验路径字段值匹配成功为' + actual_field) self.msg.append("校验OK~~,"+'接口返回数据中' + str(route) + '校验路径字段值匹配成功为' + actual_field) else: self.flag = False # print("校验失败,接口返回数据中" + str(route) + '校验路径字段值应该为' + expected_field_list[i - 1] + ',而不是' + actual_field) self.msg.append("校验失败,接口返回数据中" + str(route) + '校验路径字段值应该为' + expected_field_list[ i - 1] + ',而不是' + actual_field) elif (check_type == 'regex'): actual_field = actual_field.strip('"') if ('\\\\' in expected_field_list[i - 1]): # expected_field_new=eval(expected_field_list[i - 1]) expected_field_new = expected_field_list[i - 1].replace('\\\\', '\\') # regex_result = re.match(expected_field_new, actual_field) regex_result=re.search(expected_field_new,actual_field,re.I|re.M|re.S) else: # regex_result = re.match(expected_field_list[i - 1], actual_field) regex_result=re.search(expected_field_list[i - 1],actual_field,re.I|re.M|re.S) if (regex_result): self.msg.append("校验OK~~," + '接口返回数据中' + str(route) + '路径字段值' + actual_field + '匹配正则' + expected_field_list[ i - 1]+'成功') else: self.flag = False self.msg.append("校验失败,接口返回数据中" + str(route) + '路径的字段值'+actual_field+'匹配正则'+expected_field_list[ i - 1]+'匹配失败') else: self.flag = False self.msg.append("校验失败,校验类型无法匹配") except Exception as e: self.flag = False # print(e) self.msg.append(e) elif (self.route and self.expected_response not in ('', None, [])): # 校验某些字段 try: # 替换参数 if ('{{' in self.expected_response): getparmsvalue = GetParmsValue() self.expected_response = getparmsvalue.get_parms_value(self.expected_response, self.env) verify.should_contain(''.join(self.actual_response.split()), ''.join(self.expected_response.split())) # print('返回结果中' + self.actual_response + '字段中包含预期返回值 ' + self.expected_response + "全部字段") self.msg.append("校验OK~~"+'返回结果中' + self.actual_response + '字段中包含预期返回值 ' + self.expected_response + "全部字段") except: self.flag = False # print("校验失败,返回结果中不包含预期返回值全部字段") self.msg.append("校验失败,返回结果中不包含预期返回值全部字段") expected_field_list = self.expected_field.split(';') i = 0 for route, actual_field,check_type in zip(self.route.split(';'), self.actual_field_list,self.types.split(';')): i += 1 # 替换参数 try: if ('{{' in expected_field_list[i - 1]): getparmsvalue = GetParmsValue() expected_field_list[i - 1] = getparmsvalue.get_parms_value(expected_field_list[i - 1], self.env) if (check_type == 'equal'): if (actual_field == expected_field_list[i - 1]): self.msg.append("校验OK~~"+'接口返回数据中' + str(route) + '校验路径字段值匹配成功为' + actual_field) else: self.flag = False self.msg.append("校验失败,接口返回数据中" + str(route) + '校验路径字段值应该为' + expected_field_list[ i - 1] + ',而不是' + actual_field) elif (check_type == 'regex'): actual_field = actual_field.strip('"') if ('\\\\' in expected_field_list[i - 1]): # expected_field_new=eval(expected_field_list[i - 1]) expected_field_new = expected_field_list[i - 1].replace('\\\\', '\\') # regex_result = re.match(expected_field_new, actual_field) regex_result=re.search(expected_field_new,actual_field,re.I|re.M|re.S) else: # regex_result = re.match(expected_field_list[i - 1], actual_field) regex_result=re.search(expected_field_list[i - 1],actual_field,re.I|re.M|re.S) if (regex_result): self.msg.append("校验OK~~," + '接口返回数据中' + str(route) + '路径字段值' + actual_field + '匹配正则' + expected_field_list[ i - 1] + '成功') else: self.flag = False self.msg.append( "校验失败,接口返回数据中" + str(route) + '路径的字段值' + actual_field + '匹配正则'+expected_field_list[ i - 1]+'失败') else: self.flag = False self.msg.append("校验失败,校验类型无法匹配") except Exception as e: self.flag = False # print(e) self.msg.append(e) if (self.flag == False): return {'success':self.flag,'msg':self.msg} else: return {'success': self.flag, 'msg': self.msg}
def batchRunCaseForJenkins(tag): err_list = [] case_total = 0 case_failed = 0 user = "******" getparmsvalue = GetParmsValue() #联表查询,查询出所有需要运行的用例,并按照用例树结构顺序排序 # all_run_cases=db.session.query(Interface_Mall.name,Interface_Mall.request,Interface_Mall.rest,Interface_Mall.request_type, # Interface_Mall.data,Interface_Mall.headers,Interface_Mall.expected_response,Interface_Mall.assert_info, # Interface_Mall.global_var,Interface_Mall.tree_id,Interface_Mall.env,Interface_Mall.dParam,Interface_Mall.isBase64Encode)\ # .outerjoin(Tree_Task,Tree_Task.tree_id==Interface_Mall.tree_id).filter(Interface_Mall.tag==tag).order_by(Tree_Task.parent_id,Tree_Task.tree_order).all() all_run_cases = db.session.query(Interface_Mall).outerjoin( Tree_Task, Tree_Task.tree_id == Interface_Mall.tree_id).filter( Interface_Mall.tag == tag).order_by(Tree_Task.parent_id, Tree_Task.tree_order).all() print(all_run_cases) #根据标签设置env if ('sit' in tag[0].lower()): env = 'sit' elif ('pre' in tag[0].lower()): env = 'pre' elif ('prd' in tag[0].lower()): env = 'prd' else: env = '' #报告 (入库count) report_count = Report.query.filter_by().count() if (report_count != 0): report_one = Report.query.filter_by().order_by( Report.count.desc()).first() run_count = report_one.count + 1 else: run_count = 1 #run_count 入表,占位(防止因为未及时入表被抢用) report_count_pre = Report(case_id=0, count=run_count) db.session.add(report_count_pre) db.session.flush() #循环执行用例 #开始时间 start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) for case_info in all_run_cases: interface = Parameter_Interface() # 使用参数化后方式处理 # 获取入参 env = case_info.env requestmethod = case_info.request id = case_info.tree_id queryMethod = case_info.queryMethod # string转成list headers = json.loads(case_info.headers) # 增加对接口类型rest\tsp分别处理 requestType = case_info.request_type if requestType == 'tsp': tsp_name = case_info.rest tsp_interface = TspSearch(tsp_name, env) tsp_interface = tsp_interface.tsp2interface() print(tsp_interface) if tsp_interface is None: url = tsp_name # 如果未查询到tsp服务接口,则url直接获取为表中存储的tsp服务名,后续接口会执行失败处理 else: tsp_interface = json.loads(tsp_interface) print(tsp_interface["ip"], type(tsp_interface["ip"])) print(tsp_interface["path"], type(tsp_interface["path"])) url = "http://" + str( tsp_interface["ip"]) + tsp_interface["path"] else: url = case_info.rest url = url.strip() inputparam = case_info.data # 增加入参是否需要base64编码处理逻辑 isBase64Encode = case_info.isBase64Encode #dff 20191017:增加出参是否需要base64解码处理 isBase64Decode = case_info.isBase64Decode # 全局变量信息 globalvar = json.loads(case_info.global_var) # 校验字段信息 assertInfo = json.loads(case_info.assert_info) # 获取块信息 expectedcontent = case_info.expected_response #获取d参数 dParam = case_info.dParam # 处理请求头 flag = True dict = {} for i in range(len(headers)): if (headers[i]['key'] != '' or headers[i]['value'] != ''): # flag_assert = True flag = True # dff : 20190705 增加此行,将上面一行屏蔽 break else: flag = False if (flag == True): for i in range(len(headers)): k = headers[i]['key'] v = headers[i]['value'] dict[k] = v headers = str(dict) else: headers = '' # assertInfo不为空数组的时候处理校验信息 格式 route;route expected_response;expected_response if (len(assertInfo) != 0): # 路径 route = [] # 期望值 expeted_field = [] types = [] flag_assert = True for i in range(len(assertInfo)): if (assertInfo[i]['key'] != '' or assertInfo[i]['value'] != ''): flag_assert = True break else: flag_assert = False if (flag_assert == True): for i in range(len(assertInfo)): k = assertInfo[i]['key'] v = assertInfo[i]['value'] check_type = assertInfo[i]['checkType'] if (k != '' or v != ''): route.append(k) expeted_field.append(v) types.append(check_type) route = ';'.join(route) expeted_field = ';'.join(expeted_field) types = ';'.join(types) else: route = '' expeted_field = '' types = '' else: route = '' expeted_field = '' types = '' # 当globalvar不为空的时候处理全局变量 name;name route;route 格式 # 2.全局变量信息不为空 # 2.1全局变量都为空 if (len(globalvar) != 0): # 路径 globalname = [] # 期望值 globalroute = [] flag_global = True for i in range(len(globalvar)): if (globalvar[i]['key'] != '' or globalvar[i]['value'] != ''): flag_global = True break else: flag_global = False if (flag_global == True): for i in range(len(globalvar)): k = globalvar[i]['key'] v = globalvar[i]['value'] if (k != '' or v != ''): globalname.append(k) globalroute.append(v) globalname = ';'.join(globalname) globalroute = ';'.join(globalroute) else: globalname = '' globalroute = '' try: if (url not in ('', None) and url.startswith('http://') == False and url.startswith('https://') == False and requestType != 'pepple'): url = 'http://' + url if (requestmethod in ('get', 'GET')): response = interface.getinterfaceone(url, inputparam, env, headers, dParam, isBase64Encode, isBase64Decode) print(response) elif (requestmethod in ('post', 'POST')): response = interface.postinterfaceone(url, inputparam, env, headers, dParam, isBase64Encode, isBase64Decode) print(response) elif (requestmethod in ('put', 'PUT')): response = interface.putinterfaceone(url, inputparam, env, headers, dParam, isBase64Encode, isBase64Decode) print(response) elif (requestmethod == 'pepple'): response = InterfacePepple(env, url, queryMethod, inputparam).peppleBatchRun() print(response) if (requestmethod in ('get', 'GET', 'post', 'POST', 'put', 'PUT', 'pepple')): for response_item in response: # 记录执行用例总数 case_total += 1 # 接口响应数据 if requestType == 'tsp': # 20190722-dff: tsp类型接口,对响应数据进行base64转码处理 # response = base64Decode(response) res = base64Decode(response_item['res']) else: res = response_item['res'] # 运行时间 run_time = response_item['time'] # get/post运行结果 success = response_item['success'] url = response_item['url'] data = response_item['data'] if (globalname == [] and globalroute == [] and route == [] and expeted_field == [] and expectedcontent == ''): print('无需校验') bacth_checkout = '' # 20190705 dff新增,如果无校验信息,此字段默认为空 else: checkOut = BatchCheck(env, res, globalname, globalroute, route, expeted_field, types, expectedcontent, user) result = checkOut.checkout() if (result['success'] == False): err_list.append(id) # 记录失败用例id if (len(result['msg']) != 0): bacth_checkout = (';\n').join(result['msg'][0:]) else: bacth_checkout = '' if (success == False or result['success'] == False): success = False case_failed += 1 # 记录失败用例数 print("到此失败个数为:" + str(case_failed)) # 入参 if (headers != ''): inparams = headers + ';' + str(data) else: inparams = data # 最终校验结论整合 report_info = Report( case_id=id, runtime=run_time, result=success, rest=url, inparams=inparams, outparams=str(res), checkout=bacth_checkout, count=run_count, tag=tag, ) db.session.add(report_info) db.session.commit() else: print('请求方式不正确') except Exception as e: print('ERROR:' + str(e)) if (err_list): print("运行用例共:%d个;成功:%d;失败:%d" % (case_total, case_total - case_failed, case_failed)) else: print("运行完成,共执行了用例:%d个。" % case_total) #结束时间 end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) #成功率 Success = round((case_total - case_failed) / case_total, 2) * 100 # 删除占位记录 report_pre_delete = Report.query.filter( and_( Report.count == run_count, Report.case_id == 0, )).first() db.session.delete(report_pre_delete) # 这里是传送的消息 header = {"Content-Type": "application/json", "charset": "utf-8"} data = { "msgtype": "link", "link": { "text": ">>成功率:" + str(Success) + "% ,用例总数:" + str(case_total) + "\n" + ">>成功数:" + str(case_total - case_failed) + ",失败数:" + str(case_failed) + "\n" + ">>查看更多...", "title": "Automatic(" + tag + ")\n", "picUrl": "http://m.tuniucdn.com/fb2/t1/G5/M00/A1/8B/Cii-slq7dASIL3m5AAB17eM2eHsAAE2fgPygjoAAHYF06_w400_h300_c1_t0.jpeg", "messageUrl": "http://pandora.tuniu.org/automation/report/" + str(run_count) } } message_json = json.dumps(data) if (case_failed == 0): build_result = 1 webhook = "https://oapi.dingtalk.com/robot/send?access_token=9d28e85a48392be9cc2fb1579c7e213f6db1d0810d1efe0c7bf13d4456763acf" else: build_result = 0 webhook = ding_url # 发送钉钉信息 msg = requests.post(url=webhook, data=message_json, headers=header) # 打印返回值 print(msg.text) try: module_name = tag[:tag.rfind('-')].replace('-', '_') group_info = db.session.query(Modules_list.systemChinese).filter( Modules_list.module_name == module_name).first() # 组name:例如 订单 group_name = group_info[0] #第几周 week_for_year = datetime.datetime.now().isocalendar() week = week_for_year[1] - 44 #数据入jenkins_case_build 表 build_case_info = Jenkins_Case_Build(group_name=group_name, report_num=run_count, tag=tag, env=env, build_result=build_result, success_case_count=case_total - case_failed, fail_case_count=case_failed, start_time=start_time, end_time=end_time, week=week) db.session.add(build_case_info) db.session.commit() print("恭喜你,入jenkins_case_build表成功~~") except Exception as e: print(e) print("呜呜呜,入jenkins_case_build表失败!!")
class InterfacePepple(): def __init__(self, env='sit', serviceName='', queryMethod='', body=''): ''' :param env: 测试环境,前台界面录入 :param serviceName: pepple服务名称,前台界面录入 :param queryMethod: pepple服务查询方法,前台界面录入 :param body: pepple服务接口入参,前台界面录入 :return: 完成登录pepple,获取登录后的cookies,并添加到公共headers中,方便下面接口调用 ''' self.env = env self.serviceName = serviceName self.queryMethod = queryMethod self.body = body.replace('\n', '').replace('\t', '') self.tmp_params = {"env": self.env} formData = { "username": pepple_conf["username"], "password": pepple_conf["password"] } req = requests.post(url=pepple_conf[self.env]['pepple_login'], data=formData, headers={}) cookies = requests.utils.dict_from_cookiejar( req.cookies) #获取登录后生成的cookies #将cookies转成str,以便添加到headers中供下方接口使用 cookies_str = '' for i in cookies.items(): cookies_str = cookies_str + ';' + '='.join(i) self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36', 'cookie': cookies_str } def getPeppleProvider(self): params = {"service": self.serviceName, "limit": 10, "page": 0} print(params) # cookies_str = self.peppleLogin() req_provider = requests.get( url=pepple_conf[self.env]['pepple_provider'], params=params, headers=self.headers) # print("333333---:",req_provider.content) try: req_provider = json.loads( str(req_provider.content, encoding='utf-8')) print("444---:", req_provider) ip = req_provider["list"][0]["providerConfig"]["protocolConfig"][ "host"] port = req_provider["list"][0]["providerConfig"]["protocolConfig"][ "port"] address = str(ip) + ":" + str(port) name = req_provider["list"][0]["applicationConfig"]["name"] pepple_sys = name.split(":")[0] pepple_mod = name.split(":")[1] self.tmp_params["sys"] = pepple_sys self.tmp_params["mod"] = pepple_mod self.tmp_params["address"] = address except Exception as e: print('服务提供者信息获取异常,异常信息如下:\n%s' % str(e)) return self.tmp_params def getPeppleVersion(self): self.tmp_params = self.getPeppleProvider() params = { "service": self.serviceName, "sys": self.tmp_params["sys"], "mod": self.tmp_params["mod"], "page": 1, "limit": 10 } req_Version = requests.get(url=pepple_conf[self.env]["pepple_version"], params=params, headers=self.headers) try: req_Version = json.loads(str(req_Version.content, encoding='utf-8')) self.tmp_params["version"] = req_Version["list"][0]["versions"][-1] except Exception as e: print('获取服务的版本信息出错,异常信息如下:\n%s' % str(e)) # print(self.tmp_params) return self.tmp_params def getPeppleMethod(self): params = self.getPeppleVersion() get_params = { "service": self.serviceName, "sys": params["sys"], "mod": params["mod"], "version": params["version"], "page": 1, "limit": 10 } response = requests.get(url=pepple_conf[self.env]["pepple_method"], params=get_params, headers=self.headers) try: response = json.loads(str(response.content, encoding='utf-8')) except Exception as e: print('获取查询方法失败,异常信息为:\n%s' % str(e)) response = None # print("query-methods: ",str(response.content, encoding='utf-8')) # print(type(json.loads(str(response.content, encoding='utf-8')))) return response def getPeppleParams(self, method): params = self.getPeppleVersion() get_params = { "service": self.serviceName, "sys": params["sys"], "mod": params["mod"], "version": params["version"], "method": method } print('获取params 请求的参数:', get_params) response = requests.get(url=pepple_conf[self.env]["pepple_params"], params=get_params, headers=self.headers) try: response = json.loads(eval(str(response.content, encoding='utf-8'))) except Exception as e: print('获取请求入参失败,异常信息为:\n%s' % str(e)) response = None # print("method-params : ",eval(str(response.content, encoding='utf-8'))) # print(type(json.loads(eval(str(response.content, encoding='utf-8'))))) return response def peppleRun(self): params = self.getPeppleVersion() params["serviceName"] = self.serviceName params["method"] = self.queryMethod params["env"] = self.env #增加入参参数化处理 if self.body not in ('', None): self.body = GetParmsValue().get_parms_value(self.body, self.env) params["body"] = self.body print(params, '\n', type(params)) self.headers["pebble-service"] = str(self.serviceName) self.headers["Content-Type"] = 'application/json' response = requests.post(url=pepple_conf[self.env]["pepple_run"], data=json.dumps(params), headers=self.headers) # response = requests.post(url=pepple_conf[self.env]["pepple_exceute"],data=json.dumps(params),headers={'Content-Type':'application/json'}) # print("pepple-resonse: ",json.loads(str(response.content, encoding='utf-8'))) # print(type(json.loads(str(response.content, encoding='utf-8')))) if response.status_code == 200: try: z = json.loads(str(response.content, encoding='utf-8')) z = {"success": True, "data": z} except Exception as e: z = {"success": False, 'data': '%s' % str(e)} else: z = { "success": False, 'data': '接口请求失败,响应状态码为%s' % str(response.status_code) } print("pepple-resonse: ", z) return z def peppleBatchRun(self): params = self.getPeppleVersion() params["serviceName"] = self.serviceName params["method"] = self.queryMethod params["env"] = self.env #增加入参参数化批量处理 body_list = [] response_list = [] self.headers["pebble-service"] = str(self.serviceName) self.headers["Content-Type"] = 'application/json' # print('the self.body is : ',self.body) if self.body not in ('', None): body_first, body_params_list = GetParmsValue( ).get_params_values_list(self.body, self.env) if body_params_list not in ('', [], {}, None): body_list = GetParmsValue().set_params_list( self.body, body_params_list) # print('the body list is : ',body_params_list,'\n', self.body, '\n', body_list) if len(body_list) > 0: for body_item in body_list: params["body"] = body_item print(params, '\n', type(params)) time = 0 response = {} try: r = requests.post(url=pepple_conf[self.env]["pepple_run"], data=json.dumps(params), headers=self.headers) #接口运行时间 time = r.elapsed.microseconds / 1000 try: r = json.loads(r.content) z = json.dumps(r, ensure_ascii=False) success = True except: z, success = r.status_code, False if r.status_code != 200 else r.text response['res'] = z response['success'] = success except Exception as e: response['res'] = str(e) response['success'] = False response['time'] = time response['url'] = self.serviceName response['data'] = body_item.encode('utf-8') response_list.append(response) else: params['body'] = body_first time = 0 response = {} try: r = requests.post(url=pepple_conf[self.env]["pepple_run"], data=json.dumps(params), headers=self.headers) #接口运行时间 time = r.elapsed.microseconds / 1000 try: r = json.loads(r.content) z = json.dumps(r, ensure_ascii=False) success = True except: z, success = r.status_code, False if r.status_code != 200 else r.text response['res'] = z response['success'] = success except Exception as e: response['res'] = str(e) response['success'] = False response['time'] = time response['url'] = self.serviceName response['data'] = self.body.encode('utf-8') response_list.append(response) print("pepple-response_list: ", response_list) return response_list
def peppleBatchRun(self): params = self.getPeppleVersion() params["serviceName"] = self.serviceName params["method"] = self.queryMethod params["env"] = self.env #增加入参参数化批量处理 body_list = [] response_list = [] self.headers["pebble-service"] = str(self.serviceName) self.headers["Content-Type"] = 'application/json' # print('the self.body is : ',self.body) if self.body not in ('', None): body_first, body_params_list = GetParmsValue( ).get_params_values_list(self.body, self.env) if body_params_list not in ('', [], {}, None): body_list = GetParmsValue().set_params_list( self.body, body_params_list) # print('the body list is : ',body_params_list,'\n', self.body, '\n', body_list) if len(body_list) > 0: for body_item in body_list: params["body"] = body_item print(params, '\n', type(params)) time = 0 response = {} try: r = requests.post(url=pepple_conf[self.env]["pepple_run"], data=json.dumps(params), headers=self.headers) #接口运行时间 time = r.elapsed.microseconds / 1000 try: r = json.loads(r.content) z = json.dumps(r, ensure_ascii=False) success = True except: z, success = r.status_code, False if r.status_code != 200 else r.text response['res'] = z response['success'] = success except Exception as e: response['res'] = str(e) response['success'] = False response['time'] = time response['url'] = self.serviceName response['data'] = body_item.encode('utf-8') response_list.append(response) else: params['body'] = body_first time = 0 response = {} try: r = requests.post(url=pepple_conf[self.env]["pepple_run"], data=json.dumps(params), headers=self.headers) #接口运行时间 time = r.elapsed.microseconds / 1000 try: r = json.loads(r.content) z = json.dumps(r, ensure_ascii=False) success = True except: z, success = r.status_code, False if r.status_code != 200 else r.text response['res'] = z response['success'] = success except Exception as e: response['res'] = str(e) response['success'] = False response['time'] = time response['url'] = self.serviceName response['data'] = self.body.encode('utf-8') response_list.append(response) print("pepple-response_list: ", response_list) return response_list