def test_request(self): session = HttpSession(self.url) for interface_ in self.if_dict_list: for interface in interface_: if isinstance(interface['body'], dict): for k, v in interface['body'].items(): if '$' in str(v): interface['body'][k] = self.extract_dict[v[1:]] if interface['method'] in ["post", "put"]: if interface['data_type'] == 'json': res = session.request(method=interface['method'], url=interface['url'], json=interface['body'], headers=interface['header']) elif interface['data_type'] == 'data': res = session.request(method=interface['method'], url=interface['url'], data=interface['body'], headers=interface['header']) elif interface['method'] in ["get", "delete"]: if interface['is_sign']: if interface['sign_type'] == 4: res = session.request( method=interface['method'], url=interface['url'], params={'data': interface['body']}, headers=interface['header']) else: res = session.request(method=interface['method'], url=interface['url'], params=interface['body'], headers=interface['header']) if interface['extract']: self.extract_dict = get_extract(interface['extract'], res.text) log.info(res.text)
def step(step_content, sign_type, private_key, env_url, begin_time=0, locust=False, env_id=''): global step_json, extract_dict, s if_id = step_content["if_id"] interface = sql.execute_sql( 'select bi.url, bi.method, bi.data_type, bi.is_sign, bi.is_header from base_interface as bi where bi.if_id = {};' .format(if_id), dict_type=True) var_list = extract_variables(step_content) # 检查是否存在变量 if var_list and not locust: for var_name in var_list: var_value = get_param(var_name, step_content) if var_value is None: var_value = get_param(var_name, step_json) if var_value is None: var_value = extract_dict[var_name] step_content = json.loads( replace_var(step_content, var_name, var_value)) else: extract = step_content['extract'] if_dict = { "url": interface['url'], "header": step_content["header"], "body": step_content["body"] } set_headers = sql.execute_sql( 'select be.set_headers from base_environment as be where be.env_id="{}";' .format(env_id), dict_type=True, num=1) headers = set_headers['set_headers'] make = False if set_headers: for k, v in eval(headers)['header'].items(): if k and v: if '$' not in v: make = True if make: if_dict['header'] = eval(headers)['header'] if interface['data_type'] == 'sql': for k, v in if_dict['body'].items(): if 'select' in v: if_dict['body'][k] = SqL(job=True).execute_sql(v) # 签名 if interface['is_sign']: if sign_type == 1: # md5加密 if_dict["body"] = user_sign_api(if_dict["body"], private_key) elif sign_type == 2: # 不签名 pass elif sign_type == 3: # 用户认证 pass elif sign_type == 4: # AES算法加密 if_dict["body"] = encryptAES( json.dumps(if_dict['body']).encode('utf-8'), private_key.encode('utf-8')).decode('utf-8') else: if 'true' in step_content['body']: if_dict["body"] = True elif 'false' in step_content['body']: if_dict['body'] = False if '[' in json.dumps(if_dict["body"]): # body参数是list的情况 for k, v in if_dict['body'].items(): if_dict["body"][k] = eval(v) if not locust: if_dict["url"] = env_url + interface['url'] else: if_dict["url"] = interface['url'] if_dict["if_id"] = if_id if_dict["url"], if_dict["body"] = format_url(if_dict["url"], if_dict["body"]) if_dict["if_name"] = step_content["if_name"] if_dict["method"] = interface['method'] if_dict["data_type"] = interface['data_type'] if_dict["is_sign"] = interface['is_sign'] if_dict["sign_type"] = sign_type if locust: if_dict['extract'] = extract return if_dict, env_url try: if interface['is_sign']: if sign_type == 4: res = call_interface(s, if_dict["method"], if_dict["url"], if_dict["header"], {'data': if_dict["body"]}, if_dict["data_type"]) else: res = call_interface(s, if_dict["method"], if_dict["url"], if_dict["header"], if_dict["body"], if_dict["data_type"]) if_dict["res_status_code"] = res.status_code # if_dict["res_content"] = res.text if_dict["res_content"] = eval( res.text.replace('false', 'False').replace('null', 'None').replace( 'true', 'True')) # 查看报告时转码错误的问题 if interface['is_header']: # 补充默认headers中的变量 if headers: for k, v in eval(headers)['header'].items(): if k == 'token': eval(headers )['header'][k] = if_dict["res_content"]['data'] now_time = datetime.now() sql.execute_sql( 'update base_environment as be set be.env_id = {}, update_time = {};' .format(env_id, now_time)) except requests.RequestException as e: if_dict["result"] = "Error" if_dict["msg"] = str(e) return if_dict if step_content["extract"]: extract_dict = get_extract(step_content["extract"], if_dict["res_content"]) if step_content["validators"]: if_dict["result"], if_dict["msg"], if_dict[ 'checkpoint'] = validators_result(step_content["validators"], if_dict["res_content"]) if 'fail' in if_dict['result']: if_dict['result'] = 'fail' else: if_dict['result'] = 'pass' else: if_dict["result"] = "pass" if_dict["msg"] = {} end_time = time.clock() interface_totalTime = str(end_time - begin_time) + 's' if_dict['interface_totalTime'] = interface_totalTime return if_dict
def step(self, step_content): """ 处理各种情况的参数,并请求接口 :param step_content: :return: """ if_id = step_content["if_id"] try: interface = Interface.objects.get(if_id=if_id) except Interface.DoesNotExist as e: return e # 接口不存在 if self.run_mode == '0': var_list = extract_variables(step_content) if var_list: # 检查是否存在变量 for var_name in var_list: var_value = get_param(var_name, step_content) if var_value is None: var_value = get_param(var_name, self.step_json) if var_value is None: for extract_dict in self.extract_list: # 把变量替换为提取的参数 if var_name in extract_dict.keys(): var_value = extract_dict[var_name] step_content = json.loads( replace_var(step_content, var_name, var_value)) if_dict = { "url": interface.url, "header": step_content["header"], "body": step_content["body"], "if_id": if_id, "if_name": step_content["if_name"], "method": interface.method, "data_type": interface.data_type, "parameters": step_content.get("parameters", []) } # 跳过不执行 if interface.skip: if_dict["skip"] = interface.skip elif step_content["skip"]: if_dict["skip"] = step_content["skip"] else: if_dict["skip"] = "" if_dict['body'] = format_body( if_dict['body']) # body参数中存在list或者dict,或者dict本身就是list if if_dict['body'] == 'error': if_dict = eval_set_error(if_dict) return if_dict if self.run_mode == '0': if_dict['body'] = http_random( if_dict['body']) # 默认参数化和httpruner参数化保持基本一致 if if_dict['body'] == 'error' or if_dict[ "parameters"]: # TODO:parameters参数化默认执行未做 if_dict = parameters_error(if_dict) return if_dict if_dict['header'] = random_params(if_dict['header']) # random参数化 if_dict['body'] = random_params(if_dict['body']) if if_dict['header'] == 'error' or if_dict[ 'body'] == 'error': # 参数化异常 if_dict = parametric_set_error(if_dict) return if_dict # if self.run_mode == '0': # 补全header set_headers = Environment.objects.get(env_id=self.env_id).set_headers if set_headers and not interface.is_header: # 把设置的header赋值到if_dict中 headers = eval(set_headers)['header'] # for k, v in headers.items(): # if '$' not in v: # self.make = True # if self.make: if "$" not in headers.values(): if self.headers: self.headers.update(if_dict["header"]) if_dict['header'] = self.headers else: headers.update(if_dict['header']) if_dict['header'] = headers # hmac加密 random_str = ranstr(10) hmac = hmac_sign(random_str) if_dict['header']['x-qqw-request-nonce'] = random_str if_dict['header']['x-qqw-request-sign'] = hmac if_dict['header']['x-qqw-token-customer'] = '721037' # if interface.data_type == 'sql': # for k, v in if_dict['body'].items(): # if 'select' in v: # if_dict['body'][k] = self.sql.execute_sql(v) # if not if_dict['body'][k]: # if_dict = sql_query_error(if_dict, v) # return if_dict if interface.is_sign: # 接口存在签名时,处理参数 if self.sign_type == "md5加密": # md5加密 if_dict["body"] = user_sign_api(if_dict["body"], self.private_key) elif self.sign_type == "无": # 不签名 pass elif self.sign_type == "用户认证": # 用户认证 self.user_auth = auth_user() elif self.sign_type == "AES算法": # AES算法加密 if len(self.private_key) in [16, 24, 32]: if_dict["body"] = encryptAES( json.dumps(if_dict['body']).encode('utf-8'), self.private_key.encode('utf-8')).decode('utf-8') else: if_dict = AES_length_error(if_dict) # AES密钥设置异常 return if_dict else: if 'true' in step_content['body']: if_dict["body"] = True elif 'false' in step_content['body']: if_dict['body'] = False if interface.data_type == 'file': # 图片上传类型接口 if_dict["body"] = { "file": ("login-bg.jpg", open("/var/static/static/img/login-bg.jpg", "rb"), "image/jpeg", {}) } if interface.set_mock == '1': # 使用mock接口 if settings.DEBUG: if_dict['url'] = 'http://localhost:8000/mocks' + interface.url else: if_dict[ 'url'] = 'http://www.easytest.xyz/mocks' + interface.url else: if_dict["url"] = self.env_url + interface.url if_dict["url"], if_dict["body"] = format_url(if_dict["url"], if_dict["body"]) if self.run_mode == '1': if_dict['extract'] = step_content['extract'] if_dict['validators'] = step_content['validators'] return if_dict else: # if not interface.set_mock: # 请求接口或者模拟接口返回值 if if_dict["skip"]: if_dict = skip_error(if_dict) return if_dict try: if interface.is_sign: if self.sign_type == "AES算法": res = call_interface(self.s, if_dict["method"], if_dict["url"], if_dict["header"], {'data': if_dict["body"]}, if_dict["data_type"]) else: res = call_interface(self.s, if_dict["method"], if_dict["url"], if_dict["header"], if_dict["body"], if_dict["data_type"], self.user_auth) else: res = call_interface(self.s, if_dict["method"], if_dict["url"], if_dict["header"], if_dict["body"], if_dict["data_type"]) if_dict["res_status_code"] = res.status_code try: if_dict["res_content"] = eval( res.text.replace('false', 'False').replace( 'null', 'None').replace('true', 'True')) # 查看报告时转码错误的问题 if isinstance(if_dict["res_content"], dict): if_dict["res_content"].update( {"res_status_code": res.status_code}) elif isinstance(if_dict["res_content"], list): res_content = {} res_content.update({ "res_status_code": res.status_code, "data": if_dict["res_content"] }) if_dict["res_content"] = res_content elif isinstance(if_dict["res_content"], (str, int)): if_dict["res_content"] = { "res_status_code": res.status_code, "data": res.text } if isinstance(if_dict['res_content'], dict): if '系统异常' in if_dict['res_content'].values(): if_dict = response_value_error(if_dict, make=True) return if_dict except SyntaxError as e: if_dict["res_content"] = { "res_status_code": res.status_code, "data": res.text } # 返回值无法eval的情况 except requests.RequestException as e: if_dict = request_api_error(if_dict, e) # 接口请求异常 return if_dict if not isinstance(if_dict["res_content"], str): if interface.is_header: # 补充默认headers中的变量 set_headers = Environment.objects.get( env_id=self.env_id).set_headers if set_headers: self.headers = eval(set_headers)['header'] from lib.public import httprunner_extract if self.headers: for k, v in self.headers.items(): v = extract_variables(v) if v: self.headers[k] = httprunner_extract( if_dict["res_content"], v) if step_content["extract"]: # 提取接口中的变量 extract_dict = get_extract(step_content["extract"], if_dict["res_content"], interface.url) if 'error' in extract_dict.keys(): if_dict = index_error(if_dict, extract_dict) return if_dict else: self.extract_list.append(extract_dict) if step_content["validators"]: # 判断接口返回值 validators = str_number(step_content["validators"]) if_dict["result"], if_dict["msg"], if_dict[ 'checkpoint'] = validators_result(validators, if_dict) if 'error' in if_dict['result']: if_dict['result'] = 'error' elif 'fail' in if_dict['result']: if_dict['result'] = 'fail' else: if_dict['result'] = 'pass' else: if_dict = checkpoint_no_error(if_dict) if interface.data_type == 'file': if_dict["body"] = {'file': '上传图片'} end_time = time.clock() interface_totalTime = str(end_time - self.begin_time)[:6] + ' s' # 接口执行时间 if_dict['interface_totalTime'] = interface_totalTime return if_dict
def step(self, step_content): """ 处理各种情况的参数,并请求接口 :param step_content: :return: """ if_id = step_content["if_id"] try: interface = Interface.objects.get(if_id=if_id) except Interface.DoesNotExist as e: return e # 接口不存在 if self.run_mode == '0': var_list = extract_variables(step_content) if var_list: # 检查是否存在变量 for var_name in var_list: var_value = get_param(var_name, step_content) if var_value is None: var_value = get_param(var_name, self.step_json) if var_value is None: for extract_dict in self.extract_list: # 把变量替换为提取的参数 if var_name in extract_dict.keys(): var_value = extract_dict[var_name] step_content = json.loads( replace_var(step_content, var_name, var_value)) if_dict = { "url": interface.url, "header": step_content["header"], "body": step_content["body"], "if_id": if_id, "if_name": step_content["if_name"], "method": interface.method, "data_type": interface.data_type } if_dict['body'] = format_body( if_dict['body']) # body参数中存在list或者dict,或者dict本身就是list if if_dict['body'] == 'error': if_dict = eval_set_error(if_dict) return if_dict if self.run_mode == '0': if_dict['header'] = random_params(if_dict['header']) # random参数化 if_dict['body'] = random_params(if_dict['body']) if if_dict['header'] == 'error' or if_dict['body'] == 'error': # 参数化异常 if_dict = parametric_set_error(if_dict) return if_dict if self.run_mode == '0': # 补全header set_headers = Environment.objects.get( env_id=self.env_id).set_headers if set_headers: # 把设置的header赋值到if_dict中 headers = eval(set_headers)['header'] for k, v in headers.items(): if '$' not in v: self.make = True if self.make: if_dict['header'] = headers # if interface.data_type == 'sql': # for k, v in if_dict['body'].items(): # if 'select' in v: # if_dict['body'][k] = self.sql.execute_sql(v) # if not if_dict['body'][k]: # if_dict = sql_query_error(if_dict, v) # return if_dict if interface.is_sign: # 接口存在签名时,处理参数 if self.sign_type == 1: # md5加密 if_dict["body"] = user_sign_api(if_dict["body"], self.private_key) elif self.sign_type == 2: # 不签名 pass elif self.sign_type == 3: # 用户认证 self.user_auth = auth_user() elif self.sign_type == 4: # AES算法加密 if len(self.private_key) in [16, 24, 32]: if_dict["body"] = encryptAES( json.dumps(if_dict['body']).encode('utf-8'), self.private_key.encode('utf-8')).decode('utf-8') else: if_dict = AES_length_error(if_dict) # AES密钥设置异常 return if_dict else: if 'true' in step_content['body']: if_dict["body"] = True elif 'false' in step_content['body']: if_dict['body'] = False if interface.data_type == 'file': # 图片上传类型接口 if_dict["body"] = { "file": ("login-bg.jpg", open("/var/static/static/img/login-bg.jpg", "rb"), "image/jpeg", {}) } if self.run_mode == '0': if interface.set_mock == '1': # 使用mock接口 if_dict[ 'url'] = 'http://www.easytest.xyz/mocks' + interface.url if_dict['base_url'] = 'http://www.easytest.xyz/mocks' else: if_dict["url"] = self.env_url + interface.url elif self.run_mode == '1': if interface.set_mock == '1': if_dict['base_url'] = 'http://www.easytest.xyz/mocks' else: if_dict['base_url'] = self.env_url if_dict['path'] = interface.url if_dict["url"], if_dict["body"] = format_url(if_dict["url"], if_dict["body"]) if self.run_mode == '1': if_dict['extract'] = step_content['extract'] if_dict['validators'] = step_content['validators'] return if_dict else: # if not interface.set_mock: # 请求接口或者模拟接口返回值 try: if interface.is_sign: if self.sign_type == 4: res = call_interface(self.s, if_dict["method"], if_dict["url"], if_dict["header"], {'data': if_dict["body"]}, if_dict["data_type"]) else: res = call_interface(self.s, if_dict["method"], if_dict["url"], if_dict["header"], if_dict["body"], if_dict["data_type"], self.user_auth) else: res = call_interface(self.s, if_dict["method"], if_dict["url"], if_dict["header"], if_dict["body"], if_dict["data_type"]) if_dict["res_status_code"] = res.status_code try: if_dict["res_content"] = eval( res.text.replace('false', 'False').replace( 'null', 'None').replace('true', 'True')) # 查看报告时转码错误的问题 if isinstance(if_dict["res_content"], dict): if_dict["res_content"].update( {"res_status_code": res.status_code}) elif isinstance(if_dict["res_content"], list): res_content = {} res_content.update({ "res_status_code": res.status_code, "data": if_dict["res_content"] }) if_dict["res_content"] = res_content elif isinstance(if_dict["res_content"], (str, int)): if_dict["res_content"] = { "res_status_code": res.status_code, "data": res.text } if isinstance(if_dict['res_content'], dict): if '系统异常' in if_dict['res_content'].values(): if_dict = response_value_error(if_dict, make=True) return if_dict except SyntaxError as e: # if_dict = response_value_error(if_dict, e) # 解析返回值异常 if_dict["res_content"] = { "res_status_code": res.status_code, "data": res.text } # 返回值无法eval的情况 # return if_dict except requests.RequestException as e: if_dict = request_api_error(if_dict, e) # 接口请求异常 return if_dict # else: # if_dict["res_content"] = \ # eval(interface.set_mock.replace('false', 'False').replace('null', 'None').replace('true', 'True'))[ # 'mock'] # 模拟接口返回值 # if_dict["result"] = "fail" # if_dict['fail'] = ErrorCode.mock_fail if not isinstance(if_dict["res_content"], str): if interface.is_header and self.make: # 补充默认headers中的变量 set_headers = Environment.objects.get( env_id=self.env_id).set_headers headers = eval(set_headers)['header'] if headers: for k, v in headers.items(): if k == 'token': if 'error' in if_dict.keys(): headers[k] = '' else: headers[k] = if_dict["res_content"]['data'] now_time = datetime.datetime.now() Environment.objects.filter( env_id=self.env_id).update( set_headers={'header': headers}, update_time=now_time) if step_content["extract"]: # 提取接口中的变量 extract_dict = get_extract(step_content["extract"], if_dict["res_content"], interface.url) if 'error' in extract_dict.keys(): if_dict = index_error(if_dict, extract_dict) return if_dict else: self.extract_list.append(extract_dict) if step_content["validators"]: # 判断接口返回值 if_dict["result"], if_dict["msg"], if_dict[ 'checkpoint'] = validators_result( step_content["validators"], if_dict) if 'error' in if_dict['result']: if_dict['result'] = 'error' elif 'fail' in if_dict['result']: if_dict['result'] = 'fail' else: if_dict['result'] = 'pass' else: if_dict = checkpoint_no_error(if_dict) if interface.data_type == 'file': if_dict["body"] = {'file': '上传图片'} end_time = time.clock() interface_totalTime = str(end_time - self.begin_time)[:6] + ' s' # 接口执行时间 if_dict['interface_totalTime'] = interface_totalTime return if_dict
def send_requests(s, data_dict): """封装requests请求""" if not isinstance(data_dict, dict): # 判断传入参数类型 raise TypeError('{} 参数不是字典类型'.format(send_requests.__name__)) else: method = data_dict["method"] # 获取请求方式 url = data_dict["url"] # 获取请求地址 data_type = data_dict["data_type"] # 请求参数类型 test_name = data_dict['if_name'] # 测试用例中文名称 headers = replace_params(data_dict['headers'], data_dict) body = replace_params(data_dict['body'], data_dict, params_type=1) if '[' in json.dumps(body): # body参数是list的情况 for k, v in body.items(): body[k] = eval(v) url, body = format_url(url, body) extract = data_dict['extract'] checkpoint = data_dict["checkpoint"] if_id = data_dict['if_id'] log.info("*******正在执行用例:----- {} {} ----**********".format( if_id, test_name)) log.info("请求方式: {}, 请求url: {}".format(method, url)) log.info("请求头部:{}".format(headers)) log.info("{} 请求,参数类型为:{} ,参数内容为 {}".format(method, data_type, body)) res = {} # 接受返回数据 try: # 构造请求 r = call_interface(s, method, url, headers, body, data_type) log.info("页面返回信息:%s" % r.content.decode("utf-8")) # 信息存储到res字典中 res['if_id'] = if_id res['test_name'] = test_name res["status_code"] = str(r.status_code) # 状态码转成str res["text"] = r.content.decode("utf-8") if extract: extract_dict = get_extract(extract, res["text"]) write_data(extract_dict, res_path) res["times"] = str(r.elapsed.total_seconds()) # 接口请求时间转str if res["status_code"] != "200": # 判断返回code是否正常 res["error"] = res["text"] else: res["error"] = "" text = json.loads(res["text"]) result = '' log.info("检查点:%s" % checkpoint) for inspect in checkpoint: if inspect['expect'] == str(text[inspect['check']]): result += "pass\t" else: result += 'fail\t' res['result'] = result log.info("用例测试结果: {}---->{}".format(test_name, res["result"])) res["msg"] = "" return res except Exception as msg: log.error('请求出现异常! {}'.format(msg)) res["msg"] = str(msg) # 出现异常,保存错误信息 res["result"] = "error" # 结果保存错误 return res