Esempio n. 1
0
    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
Esempio n. 2
0
    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