Exemple #1
0
 def __init__(self):
     self.data = get_request_json()
     self.username = redis.get_username(request.headers.get('X-Token'))
     self.acim = ApiCompanyInfoManager()
     self.asim = ApiSystemInfoManager()
     self.aiim = ApiIntfInfoManager()
     self.apsrm = ApiProjectSystemRelationManager()
Exemple #2
0
 def __init__(self):
     self.data = get_request_json()
     self.username = redis.get_username(request.headers.get('X-Token'))
     self.acim = ApiCompanyInfoManager()
     self.asim = ApiSystemInfoManager()
     self.aiim = ApiIntfInfoManager()
     self.atim = ApiTestcaseInfoManager()
     self.apirm = ApiProjectIntfRelationManager()
     self.aidrm = ApiIntfDefaultRequestManager()
Exemple #3
0
    def __init__(self):
        self.apv = ApiPublicVariableInfoManager()
        self.atim = ApiTestcaseInfoManager()
        self.asim = ApiSystemInfoManager()
        self.apim = ApiProjectInfoManager()
        self.acim = ApiCompanyInfoManager()
        self.aiim = ApiIntfInfoManager()
        self.atmm = ApiTestcaseMainManager()
        self.atsm = ApiTestcaseSubManager()
        self.custom = read_custom()

        self.data = get_request_json()
        self.username = redis.get_username(request.headers.get('X-Token'))
Exemple #4
0
def update_git_url_to_api_system():
    """
    将git url更新到系统表api_system_info
    :return:
    """
    # 从gitlab上获取所有工程git url
    git = GitlabAPI()
    all_projects = git.get_all_projects()
    for project in all_projects:
        git_url = project
        git_system_name = project.split("/")[1].strip(".git")
        system_obj = asim.get_system(system_name=git_system_name)
        if system_obj:
            system_id = system_obj.id
            asim.update_system(system_id, git_url=git_url)
            print("系统 " + git_system_name + "更新git url " + git_url + " 成功")
Exemple #5
0
    def get_statistics(self):
        try:
            company_id = self.data.pop('companyId')
        except KeyError:
            return make_response({"code": "100", "desc": CODE_DESC_MAP["100"]})

        data_dic = {'intfTotalNum': 0}
        res = ApiTestcaseInfoManager.count_intf_in_company_id(company_id)
        for row in res:
            data_dic['intfTotalNum'] += row[1]
            if row[0] == 'HTTP':
                data_dic['intfHttpNum'] = row[1]
            elif row[0] == 'DUBBO':
                data_dic['intfDubboNum'] = row[1]
            elif row[0] == 'MQ':
                data_dic['intfMqNum'] = row[1]
        res = ApiSystemInfoManager.count_system_with_intf_in_company_id(company_id)
        data_dic['systemTotalNum'] = res[0]

        res = ApiTestcaseInfoManager.get_testcase_id_in_company_id(company_id)
        testcase_id_list = [row[0] for row in res]
        data_dic['caseTotalNum'] = len(testcase_id_list)
        can_auto_tag_id = 12
        res = ApiTestcaseInfoManager.count_testcase_in_tag_id(testcase_id_list, can_auto_tag_id)
        data_dic['caseAutoNum'] = res[0]

        return make_response({"code": "000", "data": data_dic})
Exemple #6
0
def add_memo(summary):
    """增加一些备注,并且记录生成的公共变量"""

    details = summary['details']
    for detail_dic in details:
        # 每条用例
        in_out = detail_dic.pop('in_out', None)
        # 全链路用例增加信息
        if detail_dic['is_main']:
            case_id = 'M' + str(detail_dic['case_id'])
            if 'testcase_main_id' not in summary:
                # summary['testcase_main_id'] = detail_dic['case_id']
                testcase_main_obj = ApiTestcaseMainManager.get_testcase_main(id=detail_dic['case_id'])
                # summary['testcase_main_name'] = testcase_main_obj.testcase_name
                p_obj = ApiProductLineManager.get_product_line(id=testcase_main_obj.api_product_line_id)
                summary['product_line_id'] = p_obj.id
                summary['product_line_name'] = get_full_product_line_name(p_obj)
        # 接口用例增加信息
        else:
            case_id = str(detail_dic['case_id'])
            if 'intf_id' not in summary:
                summary['intf_id'] = detail_dic['intf_id']
                intf_obj = ApiIntfInfoManager.get_intf(id=detail_dic['intf_id'])
                summary['intf_name'] = '{0}-{1}'.format(intf_obj.intf_desc, intf_obj.intf_name)
                system_obj = ApiSystemInfoManager.get_system(id=intf_obj.api_system_id)
                summary['system_id'] = system_obj.id
                summary['system_name'] = system_obj.system_name
        # 记录随机生成的数据,方便追溯和定时清理数据
        if in_out:
            record_keys = ['MOBILE_NO', 'ID_NO', 'BANK_CARD_NO_CREDIT', 'BANK_CARD_NO_DEBIT']
            mobile_no, id_no, bank_card_no_credit, bank_card_no_debit = '', '', '', ''
            is_found = False
            for var, var_value in in_out['in'].items():
                for key in record_keys:
                    if key == var:
                        is_found = True
                        if var == 'MOBILE_NO':
                            mobile_no = var_value
                        elif var == 'ID_NO':
                            id_no = var_value
                        elif var == 'BANK_CARD_NO_CREDIT':
                            bank_card_no_credit = var_value
                        elif var == 'BANK_CARD_NO_DEBIT':
                            bank_card_no_debit = var_value
                        break
            if is_found:
                GenerateDataRecordManager.insert_record(
                    case_id=case_id, mobile_no=mobile_no, id_no=id_no, bank_card_no_credit=bank_card_no_credit,
                    bank_card_no_debit=bank_card_no_debit)

    return summary
Exemple #7
0
 def __init__(self):
     self.data = get_request_json()
     self.username = redis.get_username(request.headers.get('X-Token'))
     self.acim = ApiCompanyInfoManager()
     self.asim = ApiSystemInfoManager()
     self.aiim = ApiIntfInfoManager()
     self.atim = ApiTestcaseInfoManager()
     self.atrm = ApiTestcaseRequestManager()
     self.attrm = ApiTestcaseTagRelationManager()
     self.ttm = TestcaseTagManager()
     self.atmm = ApiTestcaseMainManager()
     self.chain_list = []
     self.chain_no = 0
     if self.username:
         self.data["userName"] = self.username
Exemple #8
0
 def __init__(self):
     self.data = get_request_json()
     self.username = redis.get_username(request.headers.get('X-Token'))
     self.acim = ApiCompanyInfoManager()
     self.asim = ApiSystemInfoManager()
     self.all_sub_objs = None
Exemple #9
0
class ApiCompany(Resource):
    def __init__(self):
        self.data = get_request_json()
        self.username = redis.get_username(request.headers.get('X-Token'))
        self.acim = ApiCompanyInfoManager()
        self.asim = ApiSystemInfoManager()
        self.all_sub_objs = None

    @timer
    def post(self, action):
        if action == 'add':
            return self.add_company()

        elif action == 'edit':
            return self.edit_company()

        elif action == 'delete':
            return self.delete_company()

        elif action == 'list':
            return self.company_list()

        elif action == 'subtree':
            return self.subtree()

        elif action == 'projectSubtree':
            return self.project_subtree()

        elif action == 'productLineSubtree':
            return self.product_line_subtree()

        elif action == 'intfCaseSubtree':
            return self.intf_case_subtree()

        elif action == 'getFilterConditions':
            return make_response({
                "code": "000",
                "conditions": subtree_filter_conditions
            })

        elif action == 'subtreeFilter':
            return self.api_subtree_filter()

        elif action == 'mainSubtreeFilter':
            return self.api_main_subtree_filter()

        else:
            return make_response({
                "code":
                "100",
                "desc":
                "url错误,不存在的接口动作<{action}>".format(action=action)
            })

    @master_check
    def add_company(self):
        try:
            company_name = self.data.pop('companyName')
            simple_desc = self.data.pop('simpleDesc', None)
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        company_name = str(company_name).strip()

        # 判断公司名是否已存在,存在无法添加
        if self.acim.get_company(company_name=company_name):
            return make_response({
                "code": "201",
                "desc": "公司名称\"{}\"已存在".format(company_name)
            })

        self.acim.insert_company(company_name=company_name,
                                 simple_desc=simple_desc,
                                 creator=self.username)
        return make_response({
            "code": "000",
            "desc": "公司\"{}\"增加成功".format(company_name)
        })

    @master_check
    def edit_company(self):
        try:
            company_id = self.data.pop('companyId')
            company_name = self.data.pop('companyName')
            simple_desc = self.data.pop('simpleDesc', None)
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        if not self.acim.get_company(id=company_id):
            return make_response({
                "code":
                "202",
                "desc":
                "公司id\"{}\"不存在, 请刷新后重试".format(company_id)
            })
        elif self.acim.get_company(company_name=company_name):
            return make_response({
                "code":
                "201",
                "desc":
                "公司名称\"{}\"已存在, 无法修改".format(company_name)
            })

        self.acim.update_company(company_id,
                                 company_name=company_name,
                                 simple_desc=simple_desc,
                                 last_modifier=self.username)
        return make_response({
            "code": "000",
            "desc": "公司\"{}\"修改成功".format(company_name)
        })

    @login_check
    def company_list(self):
        res_list = []
        objs = self.acim.get_companies()
        for obj in objs:
            res_list.append({
                'companyId': obj.id,
                'companyName': obj.company_name,
                'simpleDesc': obj.simple_desc,
                'creator': obj.creator,
                'last_modifier': obj.last_modifier
            })
        return make_response({"code": "000", "companyList": res_list})

    @master_check
    def delete_company(self):
        try:
            company_id = self.data.pop('companyId')
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        if not self.acim.get_company(id=company_id):
            return make_response({
                "code":
                "202",
                "desc":
                "公司id\"{}\"不存在, 请刷新后重试".format(company_id)
            })

        system_objs = self.asim.get_systems(api_company_id=company_id)
        if system_objs:
            return make_response({
                "code":
                "300",
                "desc":
                "公司下已配置{}个工程,无法直接删除公司".format(len(system_objs))
            })

        self.acim.delete_company(company_id)
        return make_response({"code": "000", "desc": "公司删除成功"})

    @login_check
    def subtree(self):
        """根据公司id查询配置在该公司下的系统-接口"""
        try:
            company_id = self.data.pop('companyId')
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        subtree = []
        index_id = 1

        result_list = self.acim.query_api_subtree(company_id)
        # logger.info('result_list:{}'.format(json.dumps(result_list)))

        system_id_exist_list = []
        intf_id_exist_list = []
        for row in result_list:
            if row[0] not in system_id_exist_list and row[2] is None:
                system_id_exist_list.append(row[0])
                subtree.append({
                    'id': index_id,
                    'label': row[1],
                    'systemId': row[0],
                    'gitSshURL': row[4],
                    'children': []
                })
                index_id += 1
            elif row[0] not in system_id_exist_list and row[
                    2] not in intf_id_exist_list:
                system_id_exist_list.append(row[0])
                intf_id_exist_list.append(row[2])
                subtree.append({
                    'id':
                    index_id,
                    'label':
                    row[1],
                    'systemId':
                    row[0],
                    'gitSshURL':
                    row[4],
                    'children': [{
                        'id': index_id + 1,
                        'label': row[3],
                        'intfId': row[2]
                    }]
                })
                index_id += 2
            elif row[0] in system_id_exist_list and row[
                    2] not in intf_id_exist_list:
                intf_id_exist_list.append(row[2])
                for system in subtree:
                    if row[0] == system['systemId']:
                        system['children'].append({
                            'id': index_id,
                            'label': row[3],
                            'intfId': row[2]
                        })
                        break
                index_id += 1

        return make_response({"code": "000", "data": subtree})

    @login_check
    def project_subtree(self):
        """根据公司id查询配置在该公司下的项目-系统-接口-用例"""
        try:
            company_id = self.data.pop('companyId')
            recent_days = int(self.data.pop('recentDays', 0))
        except (KeyError, ValueError):
            return make_response({"code": "100", "desc": "入参校验失败"})

        if recent_days:
            today_date = datetime.date(datetime.now())
            start_day = today_date + timedelta(days=-int(recent_days))
            result_list = self.acim.query_api_project_subtree(
                company_id, start_day=start_day)
        else:
            result_list = self.acim.query_api_project_subtree(company_id)

        # logger.info('result_list:{}'.format(json.dumps(result_list)))
        patch_result_list = self.acim.query_api_project_subtree_patch(
            company_id)
        subtree = result_list_to_subtree(result_list, patch_result_list)

        return make_response({"code": "000", "data": subtree})

    @login_check
    def product_line_subtree_old(self):
        """根据公司id查询配置在该公司下的产品线-全链路用例"""
        try:
            company_id = self.data.pop('companyId')
        except KeyError:
            return make_response({"code": "100", "desc": CODE_DESC_MAP["100"]})

        subtree = []
        index_id = 0

        result_list = self.acim.query_api_product_line_subtree(company_id)
        logger.debug(result_list)

        result_dic = db_result_to_map(result_list)
        logger.debug(result_dic)
        for p_k, p_dic in result_dic.items():
            p_name = p_dic.pop('name')
            index_id += 1
            p_tree = {
                'id': index_id,
                'label': p_name,
                'productLineId': p_k,
                'children': []
            }
            for t_k, t_dic in p_dic.items():
                t_name = t_dic.pop('name')
                index_id += 1
                t_tree = {
                    'id': index_id,
                    'label': t_name,
                    'testcaseId': t_k,
                    'children': []
                }
                p_tree['children'].append(t_tree)
            subtree.append(p_tree)

        return make_response({"code": "000", "data": subtree})

    @login_check
    def product_line_subtree(self):
        """根据公司id查询配置在该公司下的产品线-目录-目录-...-全链路用例"""
        try:
            company_id = self.data.pop('companyId')
            with_sub = self.data.pop('withSub', None)
            tag_id_list = self.data.pop('tagIdList', None)
            without_testcase = self.data.pop('withoutTestcase', None)
        except KeyError:
            return make_response({"code": "100", "desc": CODE_DESC_MAP["100"]})

        if not (isinstance(tag_id_list, list) and len(tag_id_list) in [1, 2]):
            tag_id_list = None

        self.all_sub_objs = ApiTestcaseSubManager.get_testcase_subs()

        subtree = []
        index = 0

        pl_objs = ApiProductLineManager.get_product_lines(
            api_company_id=company_id)
        for pl_obj in pl_objs:
            index += 1
            top_tree = {
                'id': index,
                'label': pl_obj.product_line_name,
                'productLineId': pl_obj.id,
                'children': []
            }
            index = get_under_node(pl_obj.id, top_tree['children'], index,
                                   with_sub, tag_id_list, without_testcase,
                                   self.all_sub_objs)
            subtree.append(top_tree)

        if tag_id_list:
            # 过滤去除没有用例的节点
            remove_no_case_node(subtree)

        return make_response({"code": "000", "data": subtree})

    @login_check
    def intf_case_subtree(self):
        """根据公司id查询配置在该公司下的工程-接口-用例"""
        try:
            company_id = self.data.pop('companyId')
        except KeyError:
            return make_response({"code": "100", "desc": CODE_DESC_MAP["100"]})

        subtree = []
        index_id = 0

        result_list = self.acim.query_api_intf_case_subtree(company_id)

        result_dic = db_result_to_map(result_list)
        for s_k, s_dic in result_dic.items():
            p_name = s_dic.pop('name')
            index_id += 1
            s_tree = {
                'id': index_id,
                'label': p_name,
                'value': s_k,
                'children': []
            }
            for i_k, i_dic in s_dic.items():
                t_name = i_dic.pop('name')
                index_id += 1
                i_tree = {'id': index_id, 'label': t_name, 'value': i_k}
                for t_k, t_dic in i_dic.items():
                    t_name = t_dic.pop('name')
                    index_id += 1
                    t_tree = {'id': index_id, 'label': t_name, 'value': t_k}
                    if 'children' not in i_tree:
                        i_tree['children'] = []
                    i_tree['children'].append(t_tree)
                s_tree['children'].append(i_tree)
            subtree.append(s_tree)

        return make_response({"code": "000", "data": subtree})

    @login_check
    def api_subtree_filter(self):
        try:
            company_id = self.data.pop('companyId')
            filter_ = self.data.pop('filter')
            keyword = self.data.pop('keyword').strip()
            if not keyword:
                raise ValueError
            if filter_ not in subtree_filter_conditions:
                raise ValueError
        except (KeyError, ValueError):
            return make_response({"code": "100", "desc": CODE_DESC_MAP["100"]})

        subtree = subtree_filter_by_keyword(company_id, filter_, keyword)

        return make_response({"code": "000", "data": subtree})

    @login_check
    def api_main_subtree_filter(self):
        try:
            company_id = self.data.pop('companyId')
            filter_ = self.data.pop('filter')
            keyword = self.data.pop('keyword').strip()
            if not keyword:
                raise ValueError
            if filter_ not in subtree_filter_conditions:
                raise ValueError
        except (KeyError, ValueError):
            return make_response({"code": "100", "desc": CODE_DESC_MAP["100"]})

        subtree = main_subtree_filter_by_keyword(company_id, filter_, keyword)

        return make_response({"code": "000", "data": subtree})
Exemple #10
0
class ApiSystem(Resource):
    def __init__(self):
        self.data = get_request_json()
        self.username = redis.get_username(request.headers.get('X-Token'))
        self.acim = ApiCompanyInfoManager()
        self.asim = ApiSystemInfoManager()
        self.aiim = ApiIntfInfoManager()
        self.apsrm = ApiProjectSystemRelationManager()

    @timer
    def post(self, action):
        if action == 'add':
            return self.add_system()

        elif action == 'edit':
            return self.edit_system()

        elif action == 'delete':
            return self.delete_system()

        elif action == 'queryByCompanyId':
            return self.query_by_company_id()

        elif action == 'getGitBranchNamesBySystemId':
            return self.get_git_branch_names_by_system_id()

        else:
            return make_response({
                "code":
                "100",
                "desc":
                "url错误,不存在的接口动作<{action}>".format(action=action)
            })

    @master_check
    def add_system(self):
        try:
            company_id = self.data.pop('companyId')
            system_name = self.data.pop('systemName')
            git_ssh_url = self.data.pop('gitSshURL')
            simple_desc = self.data.pop('simpleDesc', None)
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        system_name = str(system_name).strip()
        git_ssh_url = str(git_ssh_url).strip()

        if not self.acim.get_company(id=company_id):
            return make_response({
                "code": "201",
                "desc": "公司id\"{}\"不存在".format(company_id)
            })

        if self.asim.get_system(system_name=system_name,
                                api_company_id=company_id):
            return make_response({
                "code":
                "201",
                "desc":
                "公司下存在相同工程名称\"{}\", 无法新增".format(system_name)
            })

        self.asim.insert_system(system_name=system_name,
                                simple_desc=simple_desc,
                                api_company_id=company_id,
                                git_url=git_ssh_url,
                                creator=self.username)
        return make_response({
            "code": "000",
            "desc": "工程\"{}\"增加成功".format(system_name)
        })

    @master_check
    def edit_system(self):
        try:
            system_id = self.data.pop('systemId')
            system_name = self.data.pop('systemName')
            git_ssh_url = self.data.pop('gitSshURL')
            simple_desc = self.data.pop('simpleDesc', None)
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        system_obj = self.asim.get_system(id=system_id)
        if not system_obj:
            return make_response({
                "code":
                "202",
                "desc":
                "工程id\"{}\"不存在, 请刷新后重试".format(system_id)
            })

        exist_system_obj = self.asim.get_system(
            system_name=system_name, api_company_id=system_obj.api_company_id)
        if exist_system_obj and exist_system_obj.id != int(system_id):
            return make_response({
                "code":
                "201",
                "desc":
                "公司下存在相同工程名称\"{}\", 无法修改".format(system_name)
            })

        self.asim.update_system(system_id,
                                system_name=system_name,
                                git_url=git_ssh_url,
                                simple_desc=simple_desc,
                                last_modifier=self.username)
        return make_response({
            "code": "000",
            "desc": "工程\"{}\"修改成功".format(system_name)
        })

    @master_check
    def delete_system(self):
        try:
            system_id = self.data.pop('systemId')
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        if not self.asim.get_system(id=system_id):
            return make_response({
                "code":
                "202",
                "desc":
                "工程id\"{}\"不存在, 请刷新后重试".format(system_id)
            })

        intf_objs = self.aiim.get_intfs(api_system_id=system_id)
        if intf_objs:
            return make_response({
                "code":
                "300",
                "desc":
                "工程下已配置{}个接口,无法直接删除".format(len(intf_objs))
            })

        self.asim.delete_system(system_id)
        return make_response({"code": "000", "desc": "工程删除成功"})

    # @login_check
    def query_by_company_id(self):
        try:
            company_id = self.data.pop('companyId')
            project_id = self.data.pop('projectId', None)
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        all_system_objs = self.asim.get_systems(api_company_id=company_id)
        all_system_list = []
        for obj in all_system_objs:
            all_system_list.append({
                'systemId': obj.id,
                'label': obj.system_name,
                'gitUrl': obj.git_url
            })

        include_system_list = []
        system_list = []
        if project_id:
            relation_objs = self.apsrm.get_relations(api_project_id=project_id)
            for system_dic in all_system_list:
                is_include = False
                for relation_obj in relation_objs:
                    if relation_obj.api_system_id == system_dic['systemId']:
                        include_system_list.append({
                            'systemId':
                            system_dic['systemId'],
                            'label':
                            system_dic['label'],
                        })
                        is_include = True
                        break
                if not is_include:
                    system_list.append({
                        'systemId': system_dic['systemId'],
                        'label': system_dic['label'],
                    })
            return make_response({
                "code": "000",
                "systemList": system_list,
                "includeSystemList": include_system_list
            })
        else:
            return make_response({
                "code": "000",
                "allSystemList": all_system_list
            })

    def get_git_branch_names_by_system_id(self):
        try:
            git_url = self.data.pop('gitUrl')
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        git_userspace_name = git_url.split(":")[1].strip('.git')

        try:
            git = GitlabAPI()
            git_branches_list = git.get_project_branches(git_userspace_name)
            return make_response({
                "code": "000",
                "data": {
                    "gitUrl": git_url,
                    "gitBranchList": git_branches_list
                }
            })
        except:
            return make_response({"code": "999", "desc": "系统内部错误"})
Exemple #11
0
def get_testcase_chain(testcase_id,
                       case_type,
                       chain_list=None,
                       with_intf_system_name=None,
                       with_extract=None,
                       only_first=False,
                       main_case_flow_id=None,
                       childless=False):
    """
    根据testcase_id获取调用链, 包含接口用例和全链路用例
    return example:
    [
        {
            "preCaseId": 1,
            "preCaseName": "指定手机获取验证码",
            "preCaseType": "接口用例",
            "preIntfName": "接口描述-/url/api"
        },
        {
            "preCaseId": 27,
            "preCaseName": "新户申请钱包",
            "preCaseType": "全链路用例"
        },
        {
            "preCaseId": 2,
            "preCaseName": "登录",
            "preCaseType": "接口用例"
        }
    ]
    """
    if not chain_list:
        chain_list = []

    # 调用链最大长度保护
    if len(chain_list) >= 100:
        return chain_list

    if case_type == 1:
        tc_obj = ApiTestcaseInfoManager.get_testcase(id=testcase_id)
        if tc_obj:
            if with_intf_system_name:
                intf_obj = ApiIntfInfoManager.get_intf(id=tc_obj.api_intf_id)
                system_obj = ApiSystemInfoManager.get_system(
                    id=intf_obj.api_system_id)
                chain_row_dic = {
                    "preCaseName":
                    '{0}__{1}'.format(tc_obj.testcase_name,
                                      tc_obj.expect_result),
                    "preCaseId":
                    tc_obj.id,
                    "preCaseType":
                    get_desc_by_case_type(case_type),
                    "preIntfName":
                    '{0}-{1}'.format(intf_obj.intf_desc, intf_obj.intf_name),
                    "preSystemName":
                    system_obj.system_name
                }
                if with_extract:
                    # 解析出用例中提取变量
                    extract_v_names = get_extract_v_names(testcase_id)
                    public_v_names = get_public_v_names(tc_obj)
                    chain_row_dic.update({
                        "extract_v_names": extract_v_names,
                        "public_v_names": public_v_names
                    })
                chain_list.insert(0, chain_row_dic)
            else:
                chain_row_dic = {
                    "preCaseName":
                    '{0}__{1}'.format(tc_obj.testcase_name,
                                      tc_obj.expect_result),
                    "preCaseId":
                    tc_obj.id,
                    "preCaseType":
                    get_desc_by_case_type(case_type),
                }
                if with_extract:
                    # 解析出用例中提取变量
                    extract_v_names = get_extract_v_names(testcase_id)
                    public_v_names = get_public_v_names(tc_obj)
                    chain_row_dic.update({
                        "extract_v_names": extract_v_names,
                        "public_v_names": public_v_names
                    })
                chain_list.insert(0, chain_row_dic)
            if childless:
                chain_list[0]['hasChildren'] = False
                return chain_list
            setup_case_list = json.loads(
                tc_obj.setup_case_list) if tc_obj.setup_case_list else []
            setup_case_list.reverse()
            if setup_case_list:
                if only_first:
                    chain_list[0]['hasChildren'] = True
                    return chain_list
                else:
                    # 继续递归查询前置
                    for setup_case_str in setup_case_list:
                        setup_case_type, setup_case_id, option = parse_setup_case_str(
                            setup_case_str)
                        kwargs = {
                            'chain_list': chain_list,
                            'with_intf_system_name': with_intf_system_name,
                            'with_extract': with_extract
                        }
                        if setup_case_type == 1:
                            if option == 'self':
                                kwargs['childless'] = True
                        elif setup_case_type == 2:
                            kwargs['main_case_flow_id'] = option
                        chain_list = get_testcase_chain(
                            setup_case_id, setup_case_type, **kwargs)
                        # setup_case_type, setup_case_id, setup_case_flow_id = parse_setup_case_str(setup_case_str)
                        # chain_list = get_testcase_chain(
                        #     setup_case_id, setup_case_type, chain_list=chain_list,
                        #     with_intf_system_name=with_intf_system_name, with_extract=with_extract,
                        #     main_case_flow_id=setup_case_flow_id
                        # )
            else:
                if only_first:
                    chain_list[0]['hasChildren'] = False
                    return chain_list
        return chain_list

    elif case_type == 2:
        tm_obj = ApiTestcaseMainManager.get_testcase_main(id=testcase_id)
        if tm_obj:
            chain_list.insert(
                0, {
                    "preCaseName":
                    '{0}__{1}'.format(tm_obj.testcase_name,
                                      tm_obj.expect_result),
                    "preCaseId":
                    tm_obj.id,
                    "preCaseType":
                    get_desc_by_case_type(case_type),
                    "preIntfName":
                    '',
                    "preSystemName":
                    '',
                    "customFlowId":
                    None,
                    "customFlowName":
                    ''
                })
            if only_first:
                chain_list[0]['hasChildren'] = False
            if main_case_flow_id:
                flow_obj = ApiTestcaseMainCustomFlowManager.get_flow(
                    id=main_case_flow_id)
                if flow_obj:
                    chain_list[0]['customFlowName'] = flow_obj.flow_name
                    chain_list[0]['customFlowId'] = flow_obj.id
        return chain_list
Exemple #12
0
    def get_all_pv_id_list(self,
                           target_pv_id_list,
                           testcase_id_list=None,
                           testcase_main_id_list=None):
        if testcase_id_list:
            for testcase_id in testcase_id_list:
                obj = self.atim.get_testcase(id=testcase_id)
                include_list = json_loads(obj.include)
                public_variables_list = []
                for include in include_list:
                    if 'public_variables' in include:
                        public_variables_list = include['public_variables']
                # public_variables_list = include_list[0]['public_variables']
                # setup_cases_list = include_list[1]['setup_cases']

                for public_variable_id in public_variables_list:
                    if public_variable_id not in target_pv_id_list:
                        target_pv_id_list.append(public_variable_id)

                if obj.setup_case_list:
                    setup_case_list = json_loads(obj.setup_case_list)
                    for setup_case_str in setup_case_list:
                        case_type, case_id, case_flow_id = parse_setup_case_str(
                            setup_case_str)
                        if case_type == 1:
                            testcase_id_list = [case_id]
                            target_pv_id_list = self.get_all_pv_id_list(
                                target_pv_id_list,
                                testcase_id_list=testcase_id_list)
                        elif case_type == 2:
                            testcase_main_id_list = [case_id]
                            target_pv_id_list = self.get_all_pv_id_list(
                                target_pv_id_list,
                                testcase_main_id_list=testcase_main_id_list)
        elif testcase_main_id_list:
            exist_main_teardown_var_name = set()  # 已加载的全链路独立后置中的公共变量名称集合
            for testcase_id in testcase_main_id_list:
                tm_obj = self.atmm.get_testcase_main(id=testcase_id)
                sub_list = json_loads(tm_obj.sub_list)
                for sub_id in sub_list:
                    ts_obj = self.atsm.get_testcase_sub(id=sub_id)
                    include_list = json_loads(ts_obj.include)
                    public_variables_list = include_list[0]['public_variables']

                    for public_variable_id in public_variables_list:
                        if public_variable_id not in target_pv_id_list:
                            target_pv_id_list.append(public_variable_id)

                    # 处理全链路用例独立后置步骤中的公共变量
                    if tm_obj.main_teardown_hooks:
                        variable_regexp = r"\$([\w_]+)"
                        main_teardown_variables = re.findall(
                            variable_regexp, str(tm_obj.main_teardown_hooks))
                        for target in main_teardown_variables:
                            if target in exist_main_teardown_var_name:
                                continue
                            intf_id = ts_obj.api_intf_id
                            intf_obj = ApiIntfInfoManager.get_intf(id=intf_id)
                            system_id = intf_obj.api_system_id
                            s_var_obj = ApiPublicVariableInfoManager.get_variable(
                                variable_name=target, api_system_id=system_id)

                            if s_var_obj:
                                target_pv_id_list.append(s_var_obj.id)
                            else:
                                company_id = ApiSystemInfoManager.get_system(
                                    id=system_id).api_company_id
                                c_var_obj = ApiPublicVariableInfoManager.get_variable(
                                    variable_name=target,
                                    api_company_id=company_id)
                                if c_var_obj:
                                    target_pv_id_list.append(c_var_obj.id)
                            exist_main_teardown_var_name.add(target)

        return target_pv_id_list
Exemple #13
0
class ApiPublicVariable(Resource):
    def __init__(self):
        self.apv = ApiPublicVariableInfoManager()
        self.atim = ApiTestcaseInfoManager()
        self.asim = ApiSystemInfoManager()
        self.apim = ApiProjectInfoManager()
        self.acim = ApiCompanyInfoManager()
        self.aiim = ApiIntfInfoManager()
        self.atmm = ApiTestcaseMainManager()
        self.atsm = ApiTestcaseSubManager()
        self.custom = read_custom()

        self.data = get_request_json()
        self.username = redis.get_username(request.headers.get('X-Token'))

    @timer
    @login_check
    def get(self, action):
        if action == 'list':
            page = request.args.get('page', 1, type=int)
            num = request.args.get('num', 10, type=int)
            keywords = request.args.get('keywords', None, type=str)
            variable_objs = self.apv.public_variable_paginate(
                page, num, keywords=keywords)
            total = variable_objs.total
            data = []
            for variable in variable_objs.items:
                if variable.api_system_id:
                    system_obj = self.asim.get_system(
                        id=variable.api_system_id)
                    company_obj = self.acim.get_company(
                        id=system_obj.api_company_id)
                    company_id = system_obj.api_company_id
                    system_id = variable.api_system_id
                    company_name = company_obj.company_name
                    system_name = system_obj.system_name
                elif variable.api_company_id:
                    company_obj = self.acim.get_company(
                        id=variable.api_company_id)
                    company_id = variable.api_company_id
                    company_name = company_obj.company_name
                    system_id = None
                    system_name = None
                else:
                    company_id = None
                    system_id = None
                    company_name = None
                    system_name = None
                variable_dict = {}
                variable_value = variable.value
                # 变量类型-files
                if variable.type == 'files':
                    if isinstance(variable_value, str):
                        '''windows下文件路径 C:\\users: \\json解析报错,先替换成\\\\'''
                        try:
                            variable_value = json.loads(
                                variable_value.replace('\\', '\\\\'))
                            variable_value = json.loads(
                                json.dumps(variable_value).replace(
                                    '\\\\', '\\'))
                        except TypeError:
                            variable_value = json.loads(variable_value)
                    variable_dict["name"] = variable.variable_name
                    variable_dict["type"] = "files"
                    variable_dict["type_desc"] = "文件"
                    variable_dict["value"] = variable_value

                # 自定义变量-db
                elif variable_value.startswith("${variable_db_operation("):
                    variable_dict["name"] = variable.variable_name
                    variable_dict["type"] = "db"
                    variable_dict["type_desc"] = "数据库操作"
                    variable_dict["value"] = variable_value.replace(
                        "${variable_db_operation(", "",
                        1).replace("||$DB_CONNECT)}", "", 1)

                # 变量类型-function
                elif variable_value.startswith(
                        '${') and variable_value.endswith('}'):
                    func_name = variable_value.split('${')[-1].split('(')[0]
                    if 'variable_db_operation' == func_name:
                        continue
                    # args_list = variable_value.split('(')[-1].split(')')[0].split(',')
                    args_list = variable_value[:-2].split('(',
                                                          1)[-1].split('||')
                    args_dict = {}
                    for func in self.custom["functions"]:
                        if func["name"] == func_name:
                            for a, p in zip(args_list, func["parameters"]):
                                args_dict[p] = a
                            break

                    variable_dict["name"] = variable.variable_name
                    variable_dict["type"] = "function"
                    variable_dict["type_desc"] = "特定函数生成"
                    variable_dict["value"] = func_name
                    variable_dict["args"] = args_dict

                # 变量类型-constant
                else:
                    variable_dict["name"] = variable.variable_name
                    variable_dict["type"] = "constant"
                    variable_dict["type_desc"] = "key-value"
                    variable_dict["value"] = variable_value
                    variable_dict[
                        "saveAs"] = variable.save_as if variable.save_as else 'str'

                variable_dict.update({
                    "variable_id":
                    variable.id,
                    "simple_Desc":
                    variable.simple_desc,
                    "creator":
                    username_to_nickname(variable.creator),
                    "system_id":
                    system_id,
                    "company_id":
                    company_id,
                    "company_name":
                    company_name,
                    "system_name":
                    system_name
                })
                data.append(variable_dict)
            return make_response({"code": "000", "total": total, "desc": data})

    @timer
    def post(self, action):
        if action == 'addVariable':
            return self.add_variable()

        elif action == "delete":
            return self.delete_variable()

        elif action == "edit":
            return self.edit_variable()

        elif action == "detail":
            return self.detail()

        elif action == "querySupportPubVariables":
            return self.query_support_pub_variables()

        elif action == "queryPubVariablesByTestcaseList":
            return self.query_pub_variables_by_testcase_list()

        else:
            return make_response({
                "code":
                "100",
                "desc":
                "url错误,不存在的接口动作<{action}>".format(action=action)
            })

    @developer_check
    def add_variable(self):
        """
            input:
            {
                "variableName":1,
                "type":"function",
                "value":"123",
                "simpleDesc":"s",
                "systemId":"1",
                "companyId":"1",
                "saveAs": "str",
            }
            """
        try:
            system_id = self.data.pop("systemId", None)
            company_id = self.data.pop("companyId", None)
            variable_name = self.data.pop("variableName")
            variable_type = self.data.pop("variableType")
            value = self.data.pop("value")
            args = self.data.pop("args", None)
            simple_desc = self.data.pop("simpleDesc", None)
            save_as = self.data.pop("saveAs", "str")
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        if system_id:
            if self.apv.get_variable(variable_name=variable_name,
                                     api_system_id=system_id):
                return make_response({
                    "code":
                    "201",
                    "desc":
                    "变量名{}已经存在,请重新添加".format(variable_name)
                })
        elif company_id:
            if self.apv.get_variable(variable_name=variable_name,
                                     api_company_id=company_id):
                return make_response({
                    "code":
                    "202",
                    "desc":
                    "变量名{}已经存在,请重新添加".format(variable_name)
                })
        else:
            return make_response({
                "code": "300",
                "desc": "systemId/companyId二选一必填"
            })

        if variable_type == 'files' and isinstance(value, list):
            value_str = json.dumps(value)
        elif variable_type == 'function':
            value_str = transfer_function_variable_to_expression(value, args)
        else:
            value_str = value
        self.apv.insert_variable(api_company_id=company_id,
                                 api_system_id=system_id,
                                 variable_name=variable_name,
                                 type=variable_type,
                                 value=value_str,
                                 simple_desc=simple_desc,
                                 creator=self.username,
                                 save_as=save_as)
        return make_response({
            "code": "000",
            "desc": "变量{}新增成功".format(variable_name)
        })

    @developer_check
    def delete_variable(self):
        """根据变量名称(唯一)删除变量
            input:
            {
              "variable_name":"test",
              "systemId":"1"
            }
        """
        try:
            variable_id = int(self.data.pop("variableId"))
            # id_=data.pop("id")
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        pv_obj = self.apv.get_variable(id=variable_id)
        if not pv_obj:
            return make_response({
                "code": "000",
                "desc": "变量id{}不存在,请刷新后重试".format(variable_id)
            })

        include_list = self.atim.query_all_testcases_include()
        for row in include_list:
            if not row[0]:
                continue
            include = json_loads(row[0])
            if 'public_variables' in include[0]:
                if variable_id in include[0]['public_variables']:
                    return make_response({
                        "code": "200",
                        "desc": "存在用例引用公共变量,无法直接删除"
                    })

        self.apv.delete_variable(pv_obj.id)
        return make_response({"code": "000", "desc": "变量删除成功"})

    @developer_check
    def edit_variable(self):
        """
            根据变量id或者变量名称编辑变量
            input:
                {
                 "variable_name:"
                }
            """
        try:
            id_ = self.data.pop('id')
            variable_name = self.data.pop("variableName")
            value = self.data.pop("value", None)
            variable_type = self.data.pop("variableType", None)
            simple_desc = self.data.pop("simpleDesc", None)
            system_id = self.data.pop("systemId", None)
            company_id = self.data.pop("companyId", None)
            args = self.data.pop("args", None)
            save_as = self.data.pop("saveAs", "str")
        except KeyError:
            return make_response({"code": "100", "desc": "传参错误"})

        # 变量名称唯一:如果想修改的变量名称,在作用域内被其它变量已使用,不能修改
        if system_id:
            if not self.asim.get_system(id=system_id):
                return make_response({"code": "101", "desc": "systemId不存在"})
            if self.apv.whether_variable_name_canbeupdated(
                    variable_name, id_, system_id):
                return make_response({
                    "code":
                    "102",
                    "desc":
                    "变量名{}已存在,请重新修改".format(variable_name)
                })
        elif company_id:
            if not self.acim.get_company(id=company_id):
                return make_response({"code": "101", "desc": "companyId不存在"})
            if self.apv.whether_variable_name_canbeupdated_in_company_id(
                    variable_name, id_, company_id):
                return make_response({
                    "code":
                    "102",
                    "desc":
                    "变量名{}已存在,请重新修改".format(variable_name)
                })
        else:
            return make_response({
                "code": "201",
                "desc": "systemId/companyId二选一必填"
            })

        if variable_type == 'files' and isinstance(value, list):
            value_str = json.dumps(value)
        elif variable_type == 'function':
            value_str = transfer_function_variable_to_expression(value, args)
        else:
            value_str = value
        self.apv.update_variable(id_,
                                 variable_name=variable_name,
                                 value=value_str,
                                 type=variable_type,
                                 simple_desc=simple_desc,
                                 api_system_id=system_id,
                                 api_company_id=company_id,
                                 save_as=save_as)
        return make_response({
            "code": "000",
            "desc": "变量{}已修改".format(variable_name)
        })

    @login_check
    def detail(self):
        """根据变量名称,获取变量详情 ----未找到使用场景"""
        try:
            system_id = self.data.pop("systemId")
            variable_name = self.data.pop("variableName")
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})
        variable = self.apv.get_variable(api_system_id=system_id,
                                         variable_name=variable_name)
        if not variable:
            return make_response({
                "code": "200",
                "desc": "该系统下的变量名{}不存在".format(variable_name)
            })
        id_ = variable.id
        variable_name = variable.variable_name
        value = variable.value
        simple_desc = variable.simple_desc
        variable_type = variable.type
        if variable.system_id:
            system_obj = self.asim.get_system(id=variable.system_id)
            company_obj = self.acim.get_company(id=system_obj.api_company_id)
            company_name = company_obj.company_name
            system_name = system_obj.system_name
        else:
            company_name = None
            system_name = None
        return make_response({
            "code": "000",
            "data": {
                "id": id_,
                "company_name": company_name,
                "system_name": system_name,
                "variable_name": variable_name,
                "value": value,
                "type": variable_type,
                "simpleDesc": simple_desc
            }
        })

    @login_check
    def query_support_pub_variables(self):
        """获取某一类型下的变量列表
            input: {variable_type:"constant"}
            output:{
                   "code": "000",
                   "desc": {
                       "constant": [
                           {
                               "id": 7,
                               "simpleDesc": "ssd",
                               "value": "dfssfds",
                               "variable_name": "hejianhao05"
                           },
                           {
                               "id": 11,
                               "simpleDesc": "gdfg",
                               "value": "dfgdf",
                               "variable_name": "dgfdfgfdg"
                           },
                           {
                               "id": 16,
                               "simpleDesc": null,
                               "value": "select * from fromfrormrmf",
                               "variable_name": "hjhdf"
                           }
                       ]
                   }
               }"""

        objs = self.apv.get_variables()
        desc_dic = {"constant": [], "db": [], "function": [], "files": []}
        for obj in objs:
            for desc_key in desc_dic.keys():
                if obj.type == desc_key:
                    desc_dic[desc_key].append({
                        "id": obj.id,
                        "variable_name": obj.variable_name,
                        "value": obj.value,
                        "simpleDesc": obj.simple_desc
                    })
                    break
        return make_response({"code": "000", "desc": desc_dic})

    @login_check
    def query_pub_variables_by_testcase_list(self):
        """
        根据testcase_id_list查询当前用例以及所有前置用例引用的公共变量信息
        url:/atp/apiPublicVariable/queryPubVariablesByTestcaseList
        input:{"testcaseList":["666", "999"]}
        output:{
            "code": "000",
            "pubVariablesList": [
                {
                    "id": "",
                    "name": "",
                    "value": "",
                    "type": "",
                    "optionValues": ["" , ""]
                },
                {
                    "id": "",
                    "name": "",
                    "value": "",
                    "type": "",
                    "optionValues": []
                }
            ]
        }
        """
        try:
            testcase_id_list = self.data.pop("testcaseList", None)
            testcase_main_id_list = self.data.pop("testcaseMainList", None)
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        if not testcase_id_list and not testcase_main_id_list:
            return make_response({"code": "100", "desc": "入参校验失败"})

        target_pv_id_list = self.get_all_pv_id_list(
            [],
            testcase_id_list=testcase_id_list,
            testcase_main_id_list=testcase_main_id_list)
        print(target_pv_id_list)
        pv_objs = self.apv.get_variables_in_id_list(target_pv_id_list)

        data_list = []
        for pv_obj in pv_objs:
            """
            from
            pv_obj.value : "12|| wudi || sad2s||"
            to
            pv_value_list : ['12', 'wudi', 'sad2s']
            """
            '''如果是文件类型的变量,暂不支持可选值'''
            if pv_obj.type == 'files':
                continue
            elif pv_obj.type == 'function':
                pv_value_list = []
                default_value = str(pv_obj.value).strip()
            else:
                pv_value_list = [
                    v.strip()
                    for v in str(pv_obj.value).strip('##').split('##')
                ]
                default_value = pv_value_list.pop(0)

            tmp_dic = {
                "id": pv_obj.id,
                "name": pv_obj.variable_name,
                "value": default_value,
                "type": pv_obj.type,
                "optionValues": pv_value_list
            }
            data_list.append(tmp_dic)

        return make_response({"code": "000", "pubVariablesList": data_list})

    def get_all_pv_id_list(self,
                           target_pv_id_list,
                           testcase_id_list=None,
                           testcase_main_id_list=None):
        if testcase_id_list:
            for testcase_id in testcase_id_list:
                obj = self.atim.get_testcase(id=testcase_id)
                include_list = json_loads(obj.include)
                public_variables_list = []
                for include in include_list:
                    if 'public_variables' in include:
                        public_variables_list = include['public_variables']
                # public_variables_list = include_list[0]['public_variables']
                # setup_cases_list = include_list[1]['setup_cases']

                for public_variable_id in public_variables_list:
                    if public_variable_id not in target_pv_id_list:
                        target_pv_id_list.append(public_variable_id)

                if obj.setup_case_list:
                    setup_case_list = json_loads(obj.setup_case_list)
                    for setup_case_str in setup_case_list:
                        case_type, case_id, case_flow_id = parse_setup_case_str(
                            setup_case_str)
                        if case_type == 1:
                            testcase_id_list = [case_id]
                            target_pv_id_list = self.get_all_pv_id_list(
                                target_pv_id_list,
                                testcase_id_list=testcase_id_list)
                        elif case_type == 2:
                            testcase_main_id_list = [case_id]
                            target_pv_id_list = self.get_all_pv_id_list(
                                target_pv_id_list,
                                testcase_main_id_list=testcase_main_id_list)
        elif testcase_main_id_list:
            exist_main_teardown_var_name = set()  # 已加载的全链路独立后置中的公共变量名称集合
            for testcase_id in testcase_main_id_list:
                tm_obj = self.atmm.get_testcase_main(id=testcase_id)
                sub_list = json_loads(tm_obj.sub_list)
                for sub_id in sub_list:
                    ts_obj = self.atsm.get_testcase_sub(id=sub_id)
                    include_list = json_loads(ts_obj.include)
                    public_variables_list = include_list[0]['public_variables']

                    for public_variable_id in public_variables_list:
                        if public_variable_id not in target_pv_id_list:
                            target_pv_id_list.append(public_variable_id)

                    # 处理全链路用例独立后置步骤中的公共变量
                    if tm_obj.main_teardown_hooks:
                        variable_regexp = r"\$([\w_]+)"
                        main_teardown_variables = re.findall(
                            variable_regexp, str(tm_obj.main_teardown_hooks))
                        for target in main_teardown_variables:
                            if target in exist_main_teardown_var_name:
                                continue
                            intf_id = ts_obj.api_intf_id
                            intf_obj = ApiIntfInfoManager.get_intf(id=intf_id)
                            system_id = intf_obj.api_system_id
                            s_var_obj = ApiPublicVariableInfoManager.get_variable(
                                variable_name=target, api_system_id=system_id)

                            if s_var_obj:
                                target_pv_id_list.append(s_var_obj.id)
                            else:
                                company_id = ApiSystemInfoManager.get_system(
                                    id=system_id).api_company_id
                                c_var_obj = ApiPublicVariableInfoManager.get_variable(
                                    variable_name=target,
                                    api_company_id=company_id)
                                if c_var_obj:
                                    target_pv_id_list.append(c_var_obj.id)
                            exist_main_teardown_var_name.add(target)

        return target_pv_id_list
Exemple #14
0
    def _add_pv(self, testset, tc_obj, intf_obj, tm_obj=None):
        """
        添加公共变量到config
        """
        # testset增加主用例用例独立后置中的公共变量
        if not self.has_extract_variable_in_main_teardown and tm_obj and tm_obj.main_teardown_hooks:
            variable_regexp = r"\$([\w_]+)"
            # main_teardown_hooks = json_loads(tm_obj.main_teardown_hooks)
            main_teardown_variables = re.findall(variable_regexp, str(tm_obj.main_teardown_hooks))
            for target in main_teardown_variables:
                system_id = intf_obj.api_system_id
                s_var_obj = ApiPublicVariableInfoManager.get_variable(variable_name=target, api_system_id=system_id)

                if s_var_obj:
                    testset["config"]["variables"].append({
                        target: s_var_obj.value.split('##')[0]
                    })
                else:
                    company_id = ApiSystemInfoManager.get_system(id=system_id).api_company_id
                    c_var_obj = ApiPublicVariableInfoManager.get_variable(
                        variable_name=target, api_company_id=company_id)
                    if c_var_obj:
                        testset["config"]["variables"].append({
                            target: c_var_obj.value.split('##')[0]
                        })
            self.has_extract_variable_in_main_teardown = True

        teststep = testset["teststeps"][0]
        include_list = json_loads(tc_obj.include)
        pv_list = None
        for include in include_list:
            if "public_variables" in include:
                pv_list = include["public_variables"]
                break

        """用例存在引用公共变量"""
        if pv_list:
            """存在公共变量临时修改"""
            if self.confirmed_pv_changes:
                for pv_change_dic in self.confirmed_pv_changes:
                    if pv_change_dic['changedValue']:
                        if pv_change_dic['type'] == 'files':
                            continue  # 暂不支持文件类型公共变量临时修改
                        elif pv_change_dic['type'] in ['constant', 'function', 'db']:
                            if int(pv_change_dic['pvId']) in pv_list:
                                pv_list.remove(int(pv_change_dic['pvId']))
                                testset["config"]["variables"].append({
                                    pv_change_dic['name']: pv_change_dic['changedValue']
                                })

                        # if int(pv_change_dic['pvId']) in pv_list:
                        #     if pv_change_dic['type'] == 'files':
                        #         continue  # 暂不支持文件类型公共变量临时修改
                        #     pv_list.remove(int(pv_change_dic['pvId']))
                        #     testset["config"]["variables"].append({
                        #         pv_change_dic['name']: pv_change_dic['changedValue']
                        #     })

            pv_objs = avim.get_variables_in_id_list(pv_list)
            for obj in pv_objs:
                if obj.type == 'files':
                    """特殊处理files类型的公共变量"""
                    file_variable_name = obj.variable_name
                    try:
                        file_path_list = eval(obj.value)
                    except (SyntaxError, NameError):
                        file_path_list = None

                    if not isinstance(file_path_list, list):
                        continue

                    target_key = None
                    for key in teststep['request']['json']:
                        if teststep['request']['json'][key] == '$' + file_variable_name:
                            teststep['request']['files'] = []
                            for i in range(len(file_path_list)):
                                if 'f_name' in teststep['request']['json']:
                                    file_name = teststep['request']['json']['f_name'][i]
                                else:
                                    file_name = str(file_path_list[i]).split('/')[-1]
                                try:
                                    teststep['request']['files'].append(
                                        (key, (file_name, open(file_path_list[i], "rb"), "multipart/form-data"))
                                    )
                                except FileNotFoundError:
                                    # 公共变量指定的文件不存在
                                    pass
                            target_key = key
                            break
                    if target_key:
                        teststep['request']['json'].pop('f_name', 0)
                        teststep['request']['json'].pop(target_key)
                        teststep['request']['data'] = teststep['request']['json']
                        teststep['request'].pop('json')
                elif obj.type == 'function':
                    """处理自定义方法类型的公共变量"""
                    is_exist = False
                    for exist_pv_dic in testset["config"]["variables"]:
                        for key in exist_pv_dic:
                            if key == obj.variable_name:
                                is_exist = True
                        if is_exist:
                            break
                    if not is_exist:
                        variable_string = variable_string_add_param(str(obj.value))
                        testset["config"]["variables"].append({
                            obj.variable_name: variable_string
                        })
                elif obj.type == 'db':
                    """处理db类型的公共变量"""
                    is_exist = False
                    for exist_pv_dic in testset["config"]["variables"]:
                        for key in exist_pv_dic:
                            if key == obj.variable_name:
                                is_exist = True
                        if is_exist:
                            break
                    if not is_exist:
                        testset["config"]["variables"].append({
                            obj.variable_name: [v.strip() for v in str(obj.value).strip('##').split('##')][0]
                        })
                else:
                    """处理key-value类型的公共变量"""
                    is_exist = False
                    for exist_pv_dic in testset["config"]["variables"]:
                        for key in exist_pv_dic:
                            if key == obj.variable_name:
                                is_exist = True
                        if is_exist:
                            break
                    if not is_exist:
                        var_value = [v.strip() for v in str(obj.value).strip('##').split('##')][0]
                        save_as = obj.save_as if obj.save_as else 'str'
                        if save_as in ['num', 'bool', 'list', 'dict']:
                            try:
                                var_value = eval(var_value)
                            except SyntaxError:
                                var_value = var_value
                        testset["config"]["variables"].append({
                            obj.variable_name: var_value
                        })

        return testset
Exemple #15
0
class ApiIntf(Resource):
    def __init__(self):
        self.data = get_request_json()
        self.username = redis.get_username(request.headers.get('X-Token'))
        self.acim = ApiCompanyInfoManager()
        self.asim = ApiSystemInfoManager()
        self.aiim = ApiIntfInfoManager()
        self.atim = ApiTestcaseInfoManager()
        self.apirm = ApiProjectIntfRelationManager()
        self.aidrm = ApiIntfDefaultRequestManager()

    @timer
    def post(self, action):
        if action == 'add':
            return self.add_intf()

        elif action == 'edit':
            return self.edit_intf()

        elif action == 'delete':
            return self.delete_intf()

        elif action == 'detail':
            return self.intf_detail()

        elif action == 'queryBySystemId':
            return self.query_by_system_id()

        else:
            return make_response({"code": "100", "desc": "url错误,不存在的接口动作<{action}>".format(action=action)})

    @developer_check
    def add_intf(self):
        try:
            system_id = self.data.pop('systemId')
            intf_desc = self.data.pop('intfNameInChinese')
            intf_type = self.data.pop('type')
            intf_info = self.data.pop('info')
            request_dic = self.data.pop('request', {})
            request_detail_dic = self.data.pop('requestDetail', [])
            intf_relation = self.data.pop('intfRelation')
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        intf_desc = str(intf_desc).strip()

        if not self.asim.get_system(id=system_id):
            return make_response({"code": "201", "desc": "工程id\"{}\"不存在".format(system_id)})

        if intf_type != 'MQ':
            if intf_type == 'HTTP':
                intf_info['apiUrl'] = intf_info['apiUrl'].strip()
                intf_name = intf_info['apiUrl']
            elif intf_type == 'DUBBO':
                intf_info['dubboService'] = intf_info['dubboService'].strip()
                intf_info['dubboMethod'] = intf_info['dubboMethod'].strip()
                intf_name = '{0}.{1}'.format(intf_info['dubboService'], intf_info['dubboMethod'])

            company_id = self.asim.get_system(id=system_id).api_company_id
            system_id_list = [row.id for row in self.asim.get_systems(api_company_id=company_id)]
            intf_name_list = [row.intf_name for row in self.aiim.get_intfs_in_system_id_list(system_id_list)]
            if intf_name in intf_name_list:
                company_name = self.acim.get_company(id=company_id).company_name
                return make_response({"code": "201", "desc": "\"{0}\"公司下存在相同接口\"{1}\", 请使用已存在的接口".format(
                    company_name, intf_name)})

        else:
            intf_info['topic'] = intf_info['topic'].strip()
            intf_info['tag'] = intf_info['tag'].strip()
            intf_name = '{0}.{1}'.format(intf_info['topic'], intf_info['tag'])
            obj = self.aiim.get_intf(intf_name=intf_name, api_system_id=system_id)
            if obj:
                return make_response({"code": "201", "desc": "工程下存在相同MQ接口\"{}\", 请使用已存在的MQ接口".format(intf_name)})

        # 增加依赖接口列表属性
        if intf_relation:
            intf_relation = [i[1] for i in intf_relation]
            self.aiim.insert_intf(intf_name=intf_name, intf_desc=intf_desc, api_system_id=system_id,
                                  intf_type=intf_type, intf_info=json_dumps(intf_info), creator=self.username,
                                  intf_relation=json_dumps(intf_relation))
        else:
            self.aiim.insert_intf(intf_name=intf_name, intf_desc=intf_desc, api_system_id=system_id,
                                  intf_type=intf_type, intf_info=json_dumps(intf_info), creator=self.username)
        intf_obj = self.aiim.get_intf(intf_name=intf_name, intf_desc=intf_desc, api_system_id=system_id,
                                      intf_type=intf_type, intf_info=json_dumps(intf_info), creator=self.username)
        self.aidrm.insert_request(api_intf_id=intf_obj.id, request=json_dumps(request_dic),
                                  request_detail=json_dumps(request_detail_dic))
        return make_response({"code": "000", "desc": "接口\"{}\"增加成功".format(intf_name)})

    @developer_with_limit_check
    def edit_intf(self):
        try:
            intf_id = self.data.pop('intfId')
            intf_desc = self.data.pop('intfNameInChinese')
            intf_type = self.data.pop('type')
            intf_info = self.data.pop('info')
            request_dic = self.data.pop('request', {})
            request_detail_dic = self.data.pop('requestDetail', [])
            intf_relation = self.data.pop('intfRelation')
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        intf_obj = self.aiim.get_intf(id=intf_id)
        if not intf_obj:
            return make_response({"code": "202", "desc": "接口id\"{}\"不存在, 请刷新后重试".format(intf_id)})

        if intf_type != 'MQ':
            header_variables = []
            if intf_type == 'HTTP':
                intf_info['apiUrl'] = intf_info['apiUrl'].strip()
                intf_name = intf_info['apiUrl']
                header = intf_info['headers']
                variable_regexp = r"\$([\w_]+)"
                header_variables = re.findall(variable_regexp, header)
            elif intf_type == 'DUBBO':
                intf_info['dubboService'] = intf_info['dubboService'].strip()
                intf_info['dubboMethod'] = intf_info['dubboMethod'].strip()
                intf_name = '{0}.{1}'.format(intf_info['dubboService'], intf_info['dubboMethod'])

            company_id = self.asim.get_system(id=intf_obj.api_system_id).api_company_id
            system_id_list = [row.id for row in self.asim.get_systems(api_company_id=company_id)]
            for obj in self.aiim.get_intfs_in_system_id_list(system_id_list):
                if obj.intf_name == intf_name and int(obj.id) != int(intf_id):
                    company_name = self.acim.get_company(id=company_id).company_name
                    return make_response({"code": "201", "desc": "\"{0}\"公司下存在相同接口\"{1}\", 无法将当前接口修改为\"{1}\"".format(
                        company_name, intf_name)})

        else:
            intf_info['topic'] = intf_info['topic'].strip()
            intf_info['tag'] = intf_info['tag'].strip()
            intf_name = '{0}.{1}'.format(intf_info['topic'], intf_info['tag'])

            obj = self.aiim.get_intf(intf_name=intf_name, api_system_id=intf_obj.api_system_id)
            if obj and obj.id != intf_id:
                return make_response({"code": "201", "desc": "工程下存在相同MQ接口\"{}\", 请使用已存在的MQ接口".format(intf_name)})

        if intf_relation:
            intf_relation = [i[1] for i in intf_relation]
            self.aiim.update_intf(intf_id, intf_name=intf_name, intf_desc=intf_desc, intf_type=intf_type,
                                  intf_info=json_dumps(intf_info), last_modifier=self.username,
                                  intf_relation=json_dumps(intf_relation))
        else:
            self.aiim.update_intf(intf_id, intf_name=intf_name, intf_desc=intf_desc, intf_type=intf_type,
                                  intf_info=json_dumps(intf_info), last_modifier=self.username)
        self.aidrm.update_request_by_intf_id(intf_id, request=json_dumps(request_dic),
                                             request_detail=json_dumps(request_detail_dic))

        # 保存接口headers中的公共变量到接口下的所有用例
        if intf_type == 'HTTP' and header_variables:
            to_add_pv_id_list = []
            pv_objs = ApiPublicVariableInfoManager.get_variables(api_company_id=company_id)
            for pv_obj in pv_objs:
                for header_variable in header_variables:
                    if header_variable == pv_obj.variable_name:
                        to_add_pv_id_list.append(pv_obj.id)
                        break
            # 如果存在需添加的公共变量id
            if to_add_pv_id_list:
                tc_objs = ApiTestcaseInfoManager.get_testcases(api_intf_id=intf_id)
                for tc_obj in tc_objs:
                    try:
                        pv_id_list = json_loads(tc_obj.include)[0]['public_variables']
                    except (json.decoder.JSONDecodeError, IndexError, KeyError):
                        pv_id_list = []
                    merge_pv_id_list = pv_id_list + to_add_pv_id_list
                    merge_pv_id_list = list(set(merge_pv_id_list))
                    if set(merge_pv_id_list) != set(pv_id_list):
                        include = json_dumps([{"public_variables": merge_pv_id_list}])
                        ApiTestcaseInfoManager.update_testcase(id_=tc_obj.id, include=include)
                ts_objs = ApiTestcaseSubManager.get_testcase_subs(api_intf_id=intf_id)
                for ts_obj in ts_objs:
                    try:
                        pv_id_list = json_loads(ts_obj.include)[0]['public_variables']
                    except (json.decoder.JSONDecodeError, IndexError, KeyError):
                        pv_id_list = []
                    merge_pv_id_list = pv_id_list + to_add_pv_id_list
                    merge_pv_id_list = list(set(merge_pv_id_list))
                    if set(merge_pv_id_list) != set(pv_id_list):
                        include = json_dumps([{"public_variables": merge_pv_id_list}])
                        ApiTestcaseSubManager.update_testcase_sub(id_=ts_obj.id, include=include)

        return make_response({"code": "000", "desc": "接口\"{}\"修改成功".format(intf_name)})

    @developer_with_limit_check
    def delete_intf(self):
        try:
            intf_id = self.data.pop('intfId')
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        if not self.aiim.get_intf(id=intf_id):
            return make_response({"code": "202", "desc": "接口id\"{}\"不存在, 请刷新后重试".format(intf_id)})

        testcase_objs = self.atim.get_testcases(api_intf_id=intf_id)
        if testcase_objs:
            return make_response({"code": "300", "desc": "接口下已编写{}个用例,无法直接删除".format(len(testcase_objs))})

        self.aiim.delete_intf(intf_id)
        self.aidrm.delete_request_by_intf_id(intf_id)
        relation_objs = self.apirm.get_relations(api_intf_id=intf_id)
        for relation_obj in relation_objs:
            self.apirm.delete_relation(relation_obj.id)
        return make_response({"code": "000", "desc": "接口删除成功"})

    @login_check
    def intf_detail(self):
        try:
            intf_id = self.data.pop('intfId')
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        intf_obj = self.aiim.get_intf(id=intf_id)
        if not intf_obj:
            return make_response({"code": "202", "desc": "接口id\"{}\"不存在, 请刷新后重试".format(intf_id)})

        try:
            info = json.loads(intf_obj.intf_info)
        except json.decoder.JSONDecodeError:
            return make_response({"code": "301", "desc": "intf_info字段解析异常"})

        intf_r_obj = self.aidrm.get_request(api_intf_id=intf_id)
        if intf_r_obj:
            request_dic = json.loads(intf_r_obj.request)
            request_detail_dic = json.loads(intf_r_obj.request_detail)
        else:
            request_dic = {}
            request_detail_dic = []

        # 处理依赖列表数据
        if intf_obj.intf_relation:
            relation_intf_objs = self.aiim.get_intfs_in_id_list(json.loads(intf_obj.intf_relation))
            intf_relation = [[i.api_system_id, i.id] for i in relation_intf_objs]
        else:
            intf_relation = []
        data = {
            'intfChineseName': intf_obj.intf_desc,
            'type': intf_obj.intf_type,
            'systemId': intf_obj.api_system_id,
            'info': info,
            'request': request_dic,
            'requestDetail': request_detail_dic,
            'intfRelation': intf_relation
        }
        return make_response({"code": "000", "data": data})

    @login_check
    def query_by_system_id(self):
        try:
            system_id = self.data.pop('systemId')
            project_id = self.data.pop('projectId', None)
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        all_intf_objs = self.aiim.get_intfs(api_system_id=system_id)
        # print(len(all_intf_objs))
        all_intf_list = []
        for obj in all_intf_objs:
            all_intf_list.append(
                {
                    'intfId': obj.id,
                    'label': obj.intf_name,
                }
            )

        include_intf_list = []
        intf_list = []
        if project_id:
            relation_objs = self.apirm.get_relations(api_project_id=project_id)
            for intf_dic in all_intf_list:
                is_include = False
                for relation_obj in relation_objs:
                    if relation_obj.api_intf_id == intf_dic['intfId']:
                        include_intf_list.append(
                            {
                                'intfId': intf_dic['intfId'],
                                'label': intf_dic['label'],
                            }
                        )
                        is_include = True
                        break
                if not is_include:
                    intf_list.append(
                        {
                            'intfId': intf_dic['intfId'],
                            'label': intf_dic['label'],
                        }
                    )
            return make_response({"code": "000", "intfList": intf_list, "includeIntfList": include_intf_list})
        else:
            return make_response({"code": "000", "intfList": all_intf_list, "includeIntfList": include_intf_list})