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 main_subtree_filter_by_keyword(company_id, filter_, keyword):
    result_list = []
    if filter_ == '用例编号':
        result_list = ApiCompanyInfoManager.query_api_project_subtree_by_testcase_id(
            company_id, testcase_id=keyword)
    elif filter_ == '接口url':
        result_list = ApiCompanyInfoManager.query_api_project_subtree_like_intf_url(
            company_id, intf_url=keyword)
    elif filter_ == '接口中文名':
        result_list = ApiCompanyInfoManager.query_api_project_subtree_like_intf_desc(
            company_id, intf_desc=keyword)

    print(len(result_list))
    return result_list_to_subtree(result_list)
Exemple #5
0
def download_xmind_api():
    from atp.api.mysql_manager import ApiCompanyInfoManager as acim, ApiTestcaseTagRelationManager as attrm
    project_id = 1
    xmind_dic = {}
    res = acim.query_api_subtree_for_xmind(project_id)
    for row in res:
        print(row)
        if row[0] not in xmind_dic:
            xmind_dic[row[0]] = {}
        if row[1] and row[1] not in xmind_dic[row[0]]:
            xmind_dic[row[0]][row[1]] = {}
        if row[2] and row[2] not in xmind_dic[row[0]][row[1]]:
            xmind_dic[row[0]][row[1]][row[2]] = {}
        if row[3] and row[3] not in xmind_dic[row[0]][row[1]][row[2]]:
            xmind_dic[row[0]][row[1]][row[2]][row[3]] = {}
        if row[4]:
            tag_objs = attrm.query_tag_info_by_testcase(row[4])
            tag_name_list = [t_obj[1]
                             for t_obj in tag_objs] if tag_objs else []
            tag = '异常场景' if '异常场景' in tag_name_list else '正常场景'
            if tag not in xmind_dic[row[0]][row[1]][row[2]][row[3]]:
                xmind_dic[row[0]][row[1]][row[2]][row[3]].update({tag: {}})

            expect = row[6] if row[6] else ''
            xmind_dic[row[0]][row[1]][row[2]][row[3]][tag].update(
                {row[5]: {
                     '预期': {
                         expect: {}
                     }
                 }})

    print(json_dumps(xmind_dic))
    from atp.api.xmind_parser import export_xmind_api
    filename = export_xmind_api(xmind_dic)
Exemple #6
0
 def __init__(self):
     self.data = get_request_json()
     # self.pim = ProjectInfoManager()
     # self.sim = SystemInfoManager()
     # self.mim = ModuleInfoManager()
     self.acim = ApiCompanyInfoManager()
     self.attrm = ApiTestcaseTagRelationManager()
     # self.tsim = TestsuiteInfoManager()
     # self.tcim = TestcaseInfoManager()
     self.btim = BaseTestcaseInfoManager()
     self.bsim = BaseSystemInfoManager()
     self.bpim = BaseProjectInfoManager()
     self.bmim = BaseModuleInfoManager()
     self.username = redis.get_username(request.headers.get('X-Token'))
     self.header_func = [
         "编号", "模块", "用例标题", "前置条件", "操作步骤", "预期结果", "执行结果", "备注"
     ]  # 业务用例excel表格标题
Exemple #7
0
def subtree_filter_by_keyword(company_id, filter_, keyword):
    result_list = []
    if filter_ == '用例编号':
        result_list = ApiCompanyInfoManager.query_api_project_subtree_by_testcase_id(
            company_id, testcase_id=keyword)
    elif filter_ == 'testcaseName':
        result_list = ApiCompanyInfoManager.query_api_project_subtree_like_testcase_name(
            company_id, testcase_name=keyword)
    elif filter_ == 'testcaseCreator':
        result_list = ApiCompanyInfoManager.query_api_project_subtree_like_testcase_creator(
            company_id, testcase_creator=keyword)
    elif filter_ == '接口url':
        result_list = ApiCompanyInfoManager.query_api_project_subtree_like_intf_url(
            company_id, intf_url=keyword)
    elif filter_ == '接口中文名':
        result_list = ApiCompanyInfoManager.query_api_project_subtree_like_intf_desc(
            company_id, intf_desc=keyword)
    # print(len(result_list))
    if not result_list:
        result_list = subtree_filter_by_keyword_not_belong_project(
            company_id, filter_, keyword)
    return result_list_to_subtree(result_list)
Exemple #8
0
def subtree_filter_by_keyword_not_belong_project(company_id, filter_, keyword):
    # 补充查询
    result_list = []
    if filter_ == '用例编号':
        result_list = ApiCompanyInfoManager.query_api_subtree_by_testcase_id(
            company_id, testcase_id=keyword)
    elif filter_ == '接口url':
        result_list = ApiCompanyInfoManager.query_api_subtree_like_intf_url(
            company_id, intf_url=keyword)
    elif filter_ == '接口中文名':
        result_list = ApiCompanyInfoManager.query_api_subtree_like_intf_desc(
            company_id, intf_desc=keyword)

    if result_list:
        # 补齐特殊的项目id和项目名称
        new_result_list = []
        for row in result_list:
            row = list(row)
            row.insert(0, -1)
            row.insert(1, '未归属到任何项目')
            new_result_list.append(row)
        result_list = new_result_list

    return result_list
Exemple #9
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 #10
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 #11
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 #12
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 #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
class Download(Resource):
    def __init__(self):
        self.data = get_request_json()
        # self.pim = ProjectInfoManager()
        # self.sim = SystemInfoManager()
        # self.mim = ModuleInfoManager()
        self.acim = ApiCompanyInfoManager()
        self.attrm = ApiTestcaseTagRelationManager()
        # self.tsim = TestsuiteInfoManager()
        # self.tcim = TestcaseInfoManager()
        self.btim = BaseTestcaseInfoManager()
        self.bsim = BaseSystemInfoManager()
        self.bpim = BaseProjectInfoManager()
        self.bmim = BaseModuleInfoManager()
        self.username = redis.get_username(request.headers.get('X-Token'))
        self.header_func = [
            "编号", "模块", "用例标题", "前置条件", "操作步骤", "预期结果", "执行结果", "备注"
        ]  # 业务用例excel表格标题

        # if self.username:
        #     self.data["userName"] = self.username

    @timer
    def get(self, action):
        if action.endswith("xmind") or action.endswith("xlsx"):
            return send_from_directory(CONFIG.DOWNLOADS_DIR,
                                       action,
                                       mimetype='application/octet-stream')
        elif action.endswith("zip"):
            filename = 'run.zip'
            logger.info('zip_path', CONFIG.DOWNLOADS_DIR)
            return send_from_directory(CONFIG.DOWNLOADS_DIR,
                                       filename,
                                       mimetype='application/octet-stream')
        elif action == 'recentTestcasesToExcel':
            # print(action)
            from_ = request.args.get('from', type=str)
            # print(from_)
            excel_name = export_by_time(from_)
            return send_from_directory(CONFIG.DOWNLOADS_DIR,
                                       excel_name,
                                       mimetype='application/octet-stream')

    @timer
    def post(self, action):
        if action == 'xmindApi':
            return self.download_xmind_api()

        elif action == 'xmindBase':
            return self.download_xmind_base()

        elif action == 'excel':
            return self.download_excel()

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

    def Multi_layer_module(self, module_id_Subsets, dict):
        '''包含多级模块的递归'''
        for module_id_Subset in module_id_Subsets:
            id_ = module_id_Subset.id  # 二级模块  769
            module_second_name = module_id_Subset.module_name
            dict[module_second_name] = {}
            new_dict = dict[module_second_name]
            module_id_Subsets_tests = self.bmim.get_modules(
                parent_module_id=id_)
            if not module_id_Subsets_tests:
                new_dict["功能"] = {}
                '''获取所有用例'''
                testcases = self.btim.get_all_testcase(module_id=id_)
                for testcase in testcases:
                    case_name = testcase.testcase_name
                    case_detail = json.loads(testcase.detail)
                    new_dict["功能"][case_name] = case_detail
            else:
                self.Multi_layer_module(module_id_Subsets_tests, new_dict)

    @developer_check
    def download_xmind_base(self):
        try:
            system_id = self.data.pop("systemId", None)
            project_id = self.data.pop("projectId", None)

        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})
        xmind_dict = {}
        """处理项目名称和系统名称"""
        project_name = self.bpim.get_project(id=project_id).project_name
        system_name = self.bsim.query_system(id=system_id).system_name

        module_list = self.bmim.get_modules(system_id=system_id)
        xmind_dict[project_name] = {system_name: {}}
        # '''系统下所有的模块'''
        # for module_names  in module_name_list:
        #     module_name=module_names.module_name  #一级模块名称
        #     xmind_dict[project_name][system_name][module_name]={}
        #     module_id = module_names.id           #一级模块id
        #     parent_module_id=module_names.parent_module_id
        #     if not parent_module_id:
        #         module_id_lasts = self.bmim.get_modules(parent_module_id=module_id)
        #         for  module_id_last in  module_id_lasts:
        #              id_= module_id_last.id       #最后一级模块id
        #              last_module_name = module_id_last.module_name  #最后一级模块名称
        #              xmind_dict[project_name][system_name][module_name][last_module_name]={"功能":{}}
        #              '''获取所有用例'''
        #              testcases = self.btim.get_all_testcase(module_id=id_)
        #              for  testcase  in  testcases:
        #                  case_name = testcase.testcase_name
        #                  case_detail = json.loads(testcase.detail)
        #                  xmind_dict[project_name][system_name][module_name][last_module_name]["功能"][case_name]=case_detail
        '''系统下所有的模块'''
        for module in module_list:
            module_first_name = module.module_name
            xmind_dict[project_name][system_name][module_first_name] = {}
            dict = xmind_dict[project_name][system_name][module_first_name]
            module_first_id = module.id
            module_id_Subsets = self.bmim.get_modules(
                parent_module_id=module_first_id)
            self.Multi_layer_module(module_id_Subsets, dict)
        filename = export_xmind_base(xmind_dict)
        return make_response({"code": "000", "desc": filename})

    # @developer_check
    # def download_xmind_api_old(self):
    #     try:
    #         module_id = self.data.pop("moduleId", None)
    #         system_id = self.data.pop("systemId", None)
    #     except KeyError:
    #         return make_response({"code": "100", "desc": "入参校验失败"})
    #
    #     xmind_dic = {}
    #     if module_id:
    #         m_obj = self.mim.query_module_id(module_id)[0]
    #         s_obj = self.sim.query_systeminfo_by_id(m_obj.system_id)
    #         p_obj = self.pim.get_project_info(s_obj.project_id)
    #         xmind_dic[p_obj.project_name] = {
    #             s_obj.system_name: {
    #                 m_obj.module_name: {}
    #             }
    #         }
    #         module_dic = deal_testcase_by_module(module_id)
    #         xmind_dic[p_obj.project_name][s_obj.system_name][m_obj.module_name] = module_dic
    #         filename = export_xmind_api(xmind_dic)
    #         return make_response({"code": "000", "desc": filename})
    #     elif system_id:
    #         s_obj = self.sim.query_systeminfo_by_id(system_id)
    #         p_obj = self.pim.get_project_info(s_obj.project_id)
    #         m_list = self.mim.query_all_module(system_id)
    #         xmind_dic[p_obj.project_name] = {
    #             s_obj.system_name: {}
    #         }
    #         for m_obj in m_list:
    #             module_dic = deal_testcase_by_module(m_obj.id)
    #             xmind_dic[p_obj.project_name][s_obj.system_name][m_obj.module_name] = module_dic
    #         filename = export_xmind_api(xmind_dic)
    #         return make_response({"code": "000", "desc": filename})
    #     else:
    #         return make_response({"code": "200", "desc": "未识别到有效节点导出"})

    @developer_check
    def download_xmind_api(self):
        try:
            project_id = self.data.pop("projectId", None)
            system_id = self.data.pop("systemId", None)
            if not project_id and not system_id:
                raise KeyError
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})

        res_list = []
        if project_id:
            res_list = self.acim.query_api_subtree_for_xmind(project_id)
        elif system_id:
            res = self.acim.query_api_subtree_for_xmind_by_system_id(system_id)
            if res:
                system_name = res[0][0]
                for row in res:
                    temp_row = ['默认_{}'.format(system_name)]
                    temp_row.extend(list(row))
                    res_list.append(temp_row)

        xmind_dic = {}
        for row in res_list:
            if row[0] not in xmind_dic:
                xmind_dic[row[0]] = {}
            if row[1] and row[1] not in xmind_dic[row[0]]:
                xmind_dic[row[0]][row[1]] = {}
            if row[2] and row[2] not in xmind_dic[row[0]][row[1]]:
                xmind_dic[row[0]][row[1]][row[2]] = {}
            if row[3] and row[3] not in xmind_dic[row[0]][row[1]][row[2]]:
                xmind_dic[row[0]][row[1]][row[2]][row[3]] = {}
            if row[4]:
                tag_objs = self.attrm.query_tag_info_by_testcase(row[4])
                tag_name_list = [t_obj[1]
                                 for t_obj in tag_objs] if tag_objs else []
                tag = '异常场景' if '异常场景' in tag_name_list else '正常场景'
                if tag not in xmind_dic[row[0]][row[1]][row[2]][row[3]]:
                    xmind_dic[row[0]][row[1]][row[2]][row[3]].update({tag: {}})

                expect = row[6] if row[6] else ''
                xmind_dic[row[0]][row[1]][row[2]][row[3]][tag].update(
                    {row[5]: {
                         '预期': {
                             expect: {}
                         }
                     }})

        filename = export_xmind_api(xmind_dic)
        return make_response({"code": "000", "desc": filename})

    @developer_check
    def download_excel(self):
        try:
            system_id = self.data.pop("systemId")
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})
        value_list = []
        value_list.append(self.header_func)
        """查询系统名称和项目id"""
        s_obj = self.bsim.query_system(id=system_id)
        if not s_obj:
            return make_response({"code": "100", "desc": "系统不存在"})
        project_id = s_obj.project_id
        system_name = s_obj.system_name
        """处理项目名称"""
        p_obj = self.bpim.get_project(id=project_id)
        if not p_obj:
            return make_response({"code": "100", "desc": "项目不存在"})
        project_name = p_obj.project_name
        """查询系统下模块"""
        parent_module_list = self.bmim.get_modules(system_id=system_id)
        testcase_objs = {}
        for module_obj in parent_module_list:
            module_name = module_obj.module_name
            module_name = remove_spaces(module_name)
            sub_module_list = self.bmim.get_modules(
                parent_module_id=module_obj.id)
            module_list = []
            module_list.append(self.header_func)
            idx = 1
            for sub_module_obj in sub_module_list:
                sub_module_name = sub_module_obj.module_name
                case_objs = self.btim.get_all_testcase(
                    module_id=sub_module_obj.id)
                for case_obj in case_objs:
                    '''处理操作步骤和预期结果'''
                    detail = eval(case_obj.detail)
                    setup_list = []
                    step_list = []
                    expect_list = []
                    remark_list = []
                    actualResult_list = []
                    for i in range(0, len(detail)):
                        setup_list.append(detail[i]["前置条件"])
                        step_list.append(detail[i]["操作步骤"])
                        expect_list.append(detail[i]["预期结果"])
                        remark_list.append(detail[i]["备注"])
                        actualResult_list.append('')
                    """封装写入Excel的数据"""
                    case_list = []
                    case_list.append(idx)
                    case_list.append(sub_module_name)
                    case_list.append(case_obj.testcase_name)
                    case_list.append(setup_list)
                    case_list.append(step_list)
                    case_list.append(expect_list)
                    case_list.append(actualResult_list)
                    case_list.append(remark_list)
                    module_list.append(case_list)
                    idx += 1
            testcase_objs[module_name] = module_list
        ep = ExcelParser(project_name + '_' + system_name)

        file_name = ep.writeExcel(values=testcase_objs)
        return make_response({"code": "000", "desc": file_name})

    @developer_check
    def download_modules_excel(self):
        try:
            system_id = self.data.pop("systemId")
            sub_module_list = self.data.pop("moduleList")
        except KeyError:
            return make_response({"code": "100", "desc": "入参校验失败"})
        value_list = []
        value_list.append(self.header_func)
        """查询系统名称和项目id"""
        s_obj = self.bsim.query_system(id=system_id)
        if not s_obj:
            return make_response({"code": "100", "desc": "系统不存在"})
        project_id = s_obj.project_id
        system_name = s_obj.system_name
        """处理项目名称"""
        p_obj = self.bpim.get_project(id=project_id)
        if not p_obj:
            return make_response({"code": "100", "desc": "项目不存在"})
        project_name = p_obj.project_name
        """查询系统下模块"""

        sub_module_object = {}
        for sub_module_id in sub_module_list:
            parent_module_obj = self.bmim.get_module(id=(self.bmim.get_module(
                id=sub_module_id).parent_module_id))
            if parent_module_obj.id not in sub_module_object.keys():
                sub_module_object[parent_module_obj.id] = [sub_module_id]
            else:
                sub_module_object[parent_module_obj.id].append(sub_module_id)

        testcase_objs = {}
        for module_id, sub_module_id_list in sub_module_object.items():
            module_name = self.bmim.get_module(id=module_id).module_name
            module_name = remove_spaces(module_name)
            sub_module_list = self.bmim.get_modules_by_module_ids(
                sub_module_id_list)
            module_list = []
            module_list.append(self.header_func)
            idx = 1
            for sub_module_obj in sub_module_list:
                sub_module_name = sub_module_obj.module_name
                case_objs = self.btim.get_all_testcase(
                    module_id=sub_module_obj.id)
                for case_obj in case_objs:
                    '''处理操作步骤和预期结果'''
                    detail = eval(case_obj.detail)
                    setup_list = []
                    step_list = []
                    expect_list = []
                    remark_list = []
                    actualResult_list = []
                    for i in range(0, len(detail)):
                        setup_list.append(detail[i]["前置条件"])
                        step_list.append(detail[i]["操作步骤"])
                        expect_list.append(detail[i]["预期结果"])
                        remark_list.append(detail[i]["备注"])
                        actualResult_list.append('')
                    """封装写入Excel的数据"""
                    case_list = []
                    case_list.append(idx)
                    case_list.append(sub_module_name)
                    case_list.append(case_obj.testcase_name)
                    case_list.append(setup_list)
                    case_list.append(step_list)
                    case_list.append(expect_list)
                    case_list.append(actualResult_list)
                    case_list.append(remark_list)
                    module_list.append(case_list)
                    idx += 1
            testcase_objs[module_name] = module_list
        ep = ExcelParser(project_name + '_' + system_name)
        file_name = ep.writeExcel(values=testcase_objs)
        return make_response({"code": "000", "desc": file_name})
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})