def user_status_put(): # 初始化返回内容 response_json = { "code": 200, "msg": "", "data": {} } # 取出传入参数值 requestvalue_userid = flask.request.json["user_id"] requestvalue_status = flask.request.json["status"] # 4.校验所操作的账户是否存在 # 5.校验所操作的账户所属角色是否是超级管理员 try: ur_data = mysqlpool.session.query( model_mysql_userinfo, model_mysql_userinfo.userId, model_mysql_userinfo.userStatus, model_mysql_roleinfo.roleIsAdmin ).join( model_mysql_roleinfo, model_mysql_roleinfo.roleId == model_mysql_userinfo.userRoleId, isouter=True ).filter( model_mysql_userinfo.userId == requestvalue_userid ).first() except Exception as e: logmsg = "数据库中账号数据读取失败,失败原因:" + repr(e) api_logger.error(logmsg) return route.error_msgs[500]['msg_db_error'] else: if ur_data and ur_data.roleIsAdmin in [0, None]: pass elif ur_data and ur_data.roleIsAdmin == 1: return route.error_msgs[201]['msg_user_is_admin'] elif ur_data and ur_data.userStatus in [-2, 0]: return route.error_msgs[201]['msg_user_cannot_operate'] else: return route.error_msgs[201]['msg_no_user'] # 6.修改mysql账户状态 try: u_data = model_mysql_userinfo.query.filter( model_mysql_userinfo.userId == requestvalue_userid ).first() logmsg = "数据库中账号数据读取成功" api_logger.debug(logmsg) except Exception as e: logmsg = "数据库中账号数据读取失败,失败原因:" + repr(e) api_logger.error(logmsg) return route.error_msgs[500]['msg_db_error'] else: u_data.userStatus = requestvalue_status mysqlpool.session.commit() # 返回成功信息 response_json["msg"] = "操作成功" # 最后返回内容 return response_json
def key_project_delete(): # 初始化返回内容 response_json = {"code": 200, "msg": "数据删除成功", "data": None} # 取出入参 project_user_id = flask.request.headers['UserId'] project_id = flask.request.args['id'] # 判断项目是否存在 try: mysql_project_info = model_mysql_project.query.filter( model_mysql_project.id == project_id, model_mysql_project.userId == project_user_id, model_mysql_project.status == 1).first() api_logger.debug("账户基础信息读取成功") except Exception as e: api_logger.error("账户基础信息读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_project_info is None: return route.error_msgs[201]['msg_no_project'] else: mysql_project_info.status = -1 mysqlpool.session.commit() # 最后返回内容 return response_json
def wrapper(*args, **kwargs): # 首先检查必传参数Mail/Token if 'UserId' not in flask.request.headers: return error_msgs[302]['msg_request_params_incomplete'] user_id = flask.request.headers['UserId'] # 尝试从mysql中查询 try: api_logger.debug("准备查询账户数据") uinfo_mysql = model_mysql_userinfo.query.filter_by( userId=user_id).first() api_logger.debug("账户数据查询成功") except Exception as e: api_logger.error("账户数据查询失败,失败原因:" + repr(e)) return error_msgs[500]['msg_db_error'] else: # 如果mysql中未查询到 if uinfo_mysql is None: return error_msgs[201]['msg_no_user'] # 如果mysql中查询到了 else: # 判断账户状态 if uinfo_mysql.userStatus == 0: return error_msgs[201]['msg_need_register'] elif uinfo_mysql.userStatus == -1: return error_msgs[201]['msg_user_forbidden'] elif uinfo_mysql.userStatus != 1: return error_msgs[201]['msg_status_error'] # 检查通过,执行应用逻辑 return func(*args, **kwargs)
def wrapper(*args, **kwargs): request_url = flask.request.url api_logger.debug("URL:" + request_url + ".准备检查请求格式") try: request_parameters = flask.request.json except Exception as e: api_logger.error("URL:" + request_url + "格式检查失败,原因:" + repr(e)) return error_msgs[301]['msg_request_body_not_json'] else: if not request_parameters: return error_msgs[301]['msg_request_body_not_json'] # 检查必传项目 for key in keys: # 如果缺少必传项 if key[0] not in request_parameters: return error_msgs[302]['msg_request_params_incomplete'] else: value = request_parameters[key[0]] # 先检查类型 if type(value) is not key[1]: return error_msgs[301]['msg_value_type_error'] # 如果非布尔型,则检查长度 if key[1] is not bool: # 如果有最小值但没最大值 if key[2] and not key[3]: if key[1] is str or key[1] is list: # 如果比最小值还小 if len(value) < key[2]: return error_msgs[301][ 'msg_value_type_error'] elif key[1] is int: # 如果比最小值还小 if value < key[2]: return error_msgs[301][ 'msg_value_type_error'] # 如果有最小以及最大值 elif key[2] and key[3]: if key[1] is str or key[1] is list: # 如果比最小值还小或者比最大值还大 if len(value) < key[2] or len(value) > key[3]: return error_msgs[301][ 'msg_value_type_error'] elif key[1] is int: # 如果比最小值还小或者比最大值还大 if value < key[2] or value > key[3]: return error_msgs[301][ 'msg_value_type_error'] # 如果有没有最小值但有最大值 elif not key[2] and key[3]: if key[1] is str or key[1] is list: # 如果比最大值还大 if len(value) > key[3]: return error_msgs[301][ 'msg_value_type_error'] elif key[1] is int: # 如果比最大值还大 if value > key[3]: return error_msgs[301][ 'msg_value_type_error'] return func(*args, **kwargs)
def get_snap_table_data(plan_id): # 于redis中尝试读取计划的快照缓存 cache_table_bytes = modle_redis_apitestplanworktable.query_table( plan_id=plan_id) # 如果缓存中没有,就去mysql读取并且同步至redis # 这里类型错误,数组为空 if cache_table_bytes is None: # 读取mysql中对应plan的最新snap try: mysql_snap_data = model_mysql_tablesnap.query.filter( and_(model_mysql_tablesnap.planId == plan_id, # model_mysql_tablesnap.status == 1 )).order_by( model_mysql_tablesnap.id.desc()).limit(1).first() api_logger.debug("model_mysql_tablesnap数据读取成功") except Exception as e: api_logger.error("model_mysql_tablesnap数据读取失败,失败原因:" + repr(e)) return False, None else: if mysql_snap_data: # 如果查询到了,则同步至redis redis_set_flag = True redis_set_flag = modle_redis_apitestplanworktable.set_table( plan_id, mysql_snap_data.table) redis_set_flag = modle_redis_apitestplanworktable.set_time( plan_id) if redis_set_flag: return True, mysql_snap_data.table else: return False, None else: # 如果无记录,说明是新测试计划,此时需要在mysql中新增空记录,然后一并同步至redis # 新增status为1的snap,内容为空 new_blank_snap = model_mysql_tablesnap( status=1, planId=plan_id, snapAddTime=datetime.datetime.now(), table="[]") try: mysqlpool.session.add(new_blank_snap) mysqlpool.session.commit() except Exception as e: api_logger.error("new_blank_snap数据写入失败,失败原因:" + repr(e)) return False, None else: # 然后再讲空数据同步至redis redis_set_flag = True redis_set_flag = modle_redis_apitestplanworktable.set_table( plan_id, new_blank_snap.table) redis_set_flag = modle_redis_apitestplanworktable.set_time( plan_id) if redis_set_flag: return True, new_blank_snap.table else: return False, None # 如果有 else: return True, cache_table_bytes.decode("utf8")
def get_task_init_logs(task_id, query_offset=0, query_limit=200): """ 至mongodb中获取re_task_id对应的初始化日志条目,并将条目组装为单个字符串 顺序获取 每次获取N条,并记录下当前获取的条目数 循环请求时仅返回批次数据,之前返回的不再返回,保证接口每批次返回数据较小 :param task_id: 测试任务id :param query_offset: 分页查询偏移量 :param query_limit: 分页查询行数 :return: True/False-方法执行结果 initLog/None-测试任务初始化日志 count/None-数据总数 """ try: log_query = mongodb_tasklog_pool['task%s_init' % task_id].find({}, { "_id": 0, "log": 1 }).skip(query_offset).limit(query_limit) except Exception as e: api_logger.error("测试任务:%s初始化日志数据读取失败,失败原因:%s" % (task_id, repr(e))) return False, None, -1 else: api_logger.debug("测试任务:%s初始化日志数据读取成功" % task_id) log_list = [lq['log'] for lq in list(log_query)] return True, log_list, log_query.count()
def role_delete(): # 初始化返回内容 response_json = {"code": 200, "msg": "", "data": {}} # 取出传入参数值 requestvalue_roleid = int(flask.request.args["role_id"]) # 5.尝试按照id删除角色以及角色的权限信息 # 先删除mysql中roleInfo的信息 try: ri_mysql = model_mysql_roleinfo.query.filter_by( roleId=requestvalue_roleid).all() logmsg = "数据库中账号信息读取成功" api_logger.error(logmsg) except Exception as e: logmsg = "数据库中账号信息读取失败,失败原因:" + repr(e) api_logger.error(logmsg) return route.error_msgs[500]['msg_db_error'] else: # 删 [mysqlpool.session.delete(rim) for rim in ri_mysql] mysqlpool.session.commit() # 然后删除mysql中rolePermission的信息 try: rp_mysql = model_mysql_rolepermission.query.filter_by( roleId=requestvalue_roleid).all() logmsg = "数据库中角色权限信息读取成功" api_logger.error(logmsg) except Exception as e: logmsg = "数据库中角色权限信息读取失败,失败原因:" + repr(e) api_logger.error(logmsg) return route.error_msgs[500]['msg_db_error'] else: # 删 [mysqlpool.session.delete(rpm) for rpm in rp_mysql] mysqlpool.session.commit() # 删除redis中rolePermission的信息 deleteflag = model_redis_rolepermission.delete(role_id=requestvalue_roleid) if deleteflag is True: logmsg = "缓存中角色权限信息删除成功" api_logger.debug(logmsg) else: logmsg = "缓存中角色权限信息删除失败" api_logger.error(logmsg) # 删除redis中apiAuth的信息 deleteflag = model_redis_apiauth.delete(role_id=requestvalue_roleid) if deleteflag is True: logmsg = "缓存中角色权限信息删除成功" api_logger.debug(logmsg) else: logmsg = "缓存中角色权限信息删除失败" api_logger.error(logmsg) # 8.返回成功信息 response_json["msg"] = "操作成功" # 最后返回内容 return response_json
def role_info_list_get(): # 初始化返回内容 response_json = { "code": 200, "msg": "", "data": { "total": 0, "role_list": {} } } # 取出传入参数值 page_num = int(flask.request.args['page_num']) per_page = int(flask.request.args['per_page']) # 查询角色,包括id/name/canmanage # 根据角色id,查询角色下关联的账户,判断角色是否可删除 try: rinfo_mysql = mysqlpool.session.query( model_mysql_roleinfo, model_mysql_roleinfo.roleId, model_mysql_roleinfo.roleName, model_mysql_roleinfo.roleIsAdmin).limit( # (requestvalue_num - 1) * requestvalue_per, per_page).offset((page_num - 1) * per_page).all() except Exception as e: logmsg = "数据库中角色列表读取失败,失败原因:" + repr(e) api_logger.error(logmsg) return route.error_msgs[500]['msg_db_error'] else: # 构造role_list for r in rinfo_mysql: rsome = { "id": r.roleId, "name": r.roleName, "can_manage": True if r.roleIsAdmin == 0 else False } response_json["data"]["role_list"][r.roleId] = rsome try: total_mysql = mysqlpool.session.query( func.count( model_mysql_roleinfo.roleId).label(name="roleNum")).first() logmsg = "数据库中角色总数读取成功" api_logger.debug(logmsg) except Exception as e: logmsg = "数据库中角色总数读取失败,失败原因:" + repr(e) api_logger.error(logmsg) return route.error_msgs[500]['msg_db_error'] else: # 构造total response_json["data"]["total"] = total_mysql.roleNum # 8.返回成功信息 response_json["msg"] = "操作成功" # 最后返回内容 return response_json
def key_catalogues_post(): # 初始化返回内容 response_json = {"code": 200, "msg": "目录归档成功", "data": None} # 取出必传入参 request_user_id = flask.request.headers['UserId'] subject_name = flask.request.json['subjectName'] subject_logo_path = flask.request.json['subjectLogoPath'] subject_description = flask.request.json['subjectDescription'] subject_open_level = flask.request.json['subjectOpenLevel'] # 判断user_id是否存在 try: mysql_userinfo = model_mysql_subject.query.filter( model_mysql_subject.userId == request_user_id).first() api_logger.debug("账户基础信息读取成功") except Exception as e: api_logger.error("账户基础信息读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_userinfo is None: return route.error_msgs[201]['msg_no_user'] # 查询项目名称是否存在 try: mysql_subject = model_mysql_subject.query.filter( model_mysql_subject.subjectName == subject_name).first() except Exception as e: api_logger.error("测试计划类型读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_subject is None: pass else: return route.error_msgs[201]['msg_exit_subject'] #获取当前id """ 插入项目计划数据 """ new_subject_info = model_mysql_subject( userId=request_user_id, subjectName=subject_name, subjectLogoPath=subject_logo_path, subjectOpenLevel=subject_open_level, subjectDescription=subject_description if subject_description else None, subjectStatus=1, ) mysqlpool.session.add(new_subject_info) mysqlpool.session.commit() # 最后返回内容 return response_json
def check_parameter(action, *keys): if type(action) is str: try: api_logger.debug("准备检查参数格式") json_action = json.loads(action) except Exception as e: api_logger.warn("不能转为json格式,原因:" + repr(e)) return False else: # 检查必传项目 for key in keys: # 如果缺少必传项 if key[0] not in json_action: return False else: value = json_action[key[0]] # 先检查类型 if type(value) is not key[1]: return False # 如果非布尔型,则检查长度 if key[1] is not bool: # 如果有最小值但没最大值 if key[2] and not key[3]: if key[1] is str or key[1] is list: # 如果比最小值还小 if len(value) < key[2]: return False elif key[1] is int: # 如果比最小值还小 if value < key[2]: return False # 如果有最小以及最大值 elif key[2] and key[3]: if key[1] is str or key[1] is list: # 如果比最小值还小或者比最大值还大 if len(value) < key[2] or len(value) > key[3]: return False elif key[1] is int: # 如果比最小值还小或者比最大值还大 if value < key[2] or value > key[3]: return False # 如果有没有最小值但有最大值 elif not key[2] and key[3]: if key[1] is str or key[1] is list: # 如果比最大值还大 if len(value) > key[3]: return False elif key[1] is int: # 如果比最大值还大 if value > key[3]: return False return json_action else: return False
def get_single_collection(taskid, plugin_id, skip_num): try: log_query = mongodb_tasklog_pool['task%s_run' % taskid].find( {'id': plugin_id}, {"_id": 0} ).skip(skip_num).limit(1) except Exception as e: api_logger.error("测试任务:%s运行日志数据读取失败,失败原因:%s" % (taskid, repr(e))) return False, None else: api_logger.debug("测试任务:%s运行日志数据读取成功" % taskid) return True, list(log_query)
def key_column_delete(): # 初始化返回内容 response_json = {"code": 200, "msg": "数据删除成功", "data": None} # 取出必传入参 request_user_id = flask.request.headers['UserId'] column_id = flask.request.args['id'] depository_id = flask.request.args['depositoryId'] # 判断目录是否存在 try: mysql_column_info = model_mysql_case.query.filter( model_mysql_case.id == column_id, model_mysql_case.depositoryId == depository_id, model_mysql_case.type == 1).first() api_logger.debug("仓库目录信息读取成功") except Exception as e: api_logger.error("仓库目录信息读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: mysql_column_info.status = -1 mysql_column_info.updateUser = request_user_id mysql_column_info.updateTime = str( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) if mysql_column_info is None: return route.error_msgs[201]['msg_no_catalogue'] else: # 删除目录下所有case/column try: mysql_children_info = model_mysql_case.query.filter( model_mysql_case.columnId == column_id).all() api_logger.debug("仓库目录信息读取成功") except Exception as e: api_logger.error("仓库目录信息读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if len(mysql_children_info) != 0: for mci in mysql_children_info: mci.status = -1 mci.updateUser = request_user_id mci.updateTime = str(datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S")) try: mysqlpool.session.commit() api_logger.error("仓库目录信息更新成功") except Exception as e: api_logger.error("仓库目录信息更新失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] # 最后返回内容 return response_json
def plan_post(): # 初始化返回内容 response_json = {"code": 200, "msg": "操作成功", "data": {}} # 取出必传入参 user_id = flask.request.json['userId'] plan_type = flask.request.json['planType'] plan_title = flask.request.json['planTitle'] open_level = flask.request.json['openLevel'] plan_description = flask.request.json['planDescription'] # 判断user_id是否存在 try: mysql_userinfo = model_mysql_userinfo.query.filter( model_mysql_userinfo.userId == user_id).first() api_logger.debug("账户基础信息读取成功") except Exception as e: api_logger.error("账户基础信息读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_userinfo is None: return route.error_msgs[201]['msg_no_user'] # 查询测试计划类型是否存在 try: mysql_plantype = model_mysql_plantype.query.filter( model_mysql_plantype.typeId == plan_type).first() except Exception as e: api_logger.error("测试计划类型读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_plantype is None: return route.error_msgs[201]['msg_no_plan_type'] """ 插入测试计划数据 关于测试计划所有者类型: 0 个人 1 团队 """ new_plan_info = model_mysql_planinfo( ownerId=user_id, planType=plan_type, planTitle=plan_title, planDescription=plan_description if plan_description else None, planOpenLevel=open_level, planOwnerType=0) mysqlpool.session.add(new_plan_info) mysqlpool.session.commit() # 最后返回内容 return response_json
def check_token(userId, token): # 去缓存的token中查询Mail,不存在的话即为从来没登陆过 # redis查询无错误信息,不作try处理 api_logger.debug("准备查询缓存token数据") tdata = model_redis_usertoken.query(userId) if tdata is None: api_logger.debug("缓存token数据为空") return False else: api_logger.debug("缓存token数据存在") # 格式化缓存基础信息内容 try: t = json.loads(tdata.decode("utf8")) api_logger.debug("缓存token数据json格式化成功") except Exception as e: api_logger.error("缓存token数据json格式化失败,失败原因:" + repr(e)) return False # 判断是否一致且有效 # 判断是否过期 if token != t["userToken"]: return False elif datetime.datetime.strptime( t["validTime"], "%Y-%m-%d %H:%M:%S") < datetime.datetime.now(): return False # 检查通过,返回True return True
def wrapper(*args, **kwargs): # 首先检查必传参数Mail/Token if 'UserId' not in flask.request.headers or 'Token' not in flask.request.headers: return error_msgs[302]['msg_request_params_incomplete'] user_id = flask.request.headers['UserId'] user_token = flask.request.headers['Token'] # 然后检查token是否正确 # 去缓存的token中查询Mail,不存在的话即为从来没登陆过 # redis查询无错误信息,不作try处理 api_logger.debug("准备查询缓存token数据") tdata = model_redis_usertoken.query(user_id) if tdata is None: api_logger.debug("缓存token数据为空") return error_msgs[201]['msg_before_login'] else: api_logger.debug("缓存token数据存在") # 格式化缓存基础信息内容 try: t = json.loads(tdata.decode("utf8")) api_logger.debug("缓存token数据json格式化成功") except Exception as e: api_logger.error("缓存token数据json格式化失败,失败原因:" + repr(e)) return error_msgs[500]['msg_json_format_fail'] # 判断是否一致且有效 # 判断是否过期 if user_token != t["userToken"]: return error_msgs[401]['msg_token_wrong'] elif datetime.datetime.strptime( t["validTime"], "%Y-%m-%d %H:%M:%S") < datetime.datetime.now(): return error_msgs[401]['msg_token_expired'] # 检查通过,执行应用逻辑 return func(*args, **kwargs)
def plan_delete(): # 初始化返回内容 response_json = {"code": 200, "msg": "操作成功", "data": {}} user_id = None # 取出必传入参 user_id = flask.request.headers['UserId'] plan_id = int(flask.request.args['planId']) # 查询mysql中账户信息,并取出账户id try: mysql_userinfo = model_mysql_userinfo.query.filter( model_mysql_userinfo.userId == user_id).first() api_logger.debug(user_id + "的账户基础信息读取成功") except Exception as e: api_logger.error(user_id + "的账户基础信息读取失败,失败原因:" + repr(e)) print(11111) return route.error_msgs[500]['msg_db_error'] else: if mysql_userinfo is None: return route.error_msgs[201]['msg_no_user'] else: user_id = mysql_userinfo.userId # 逻辑删除测试计划 try: mysql_planinfo = model_mysql_planinfo.query.filter( model_mysql_planinfo.planId == plan_id).first() except Exception as e: api_logger.error(user_id + "的测试计划信息读取失败,失败原因:" + repr(e)) print(22222) return route.error_msgs[500]['msg_db_error'] else: # 只有计划本人才有权限删除该计划 if user_id == mysql_planinfo.ownerId and mysql_planinfo: mysql_planinfo.status = -1 try: mysqlpool.session.commit() except Exception as e: api_logger.error("个人接口测试计划删除失败,失败原因:" + repr(e)) print(3333) return route.error_msgs[500]['msg_db_error'] elif user_id != mysql_planinfo.ownerId: return route.error_msgs[201]['msg_plan_user_error'] else: return route.error_msgs[201]['msg_no_plan'] # 最后返回内容 return response_json
def key_catalogue_post(): # 初始化返回内容 response_json = {"code": 200, "msg": "目录新增成功", "data": None} # 取出必传入参 catalogue_name = flask.request.json['catalogueName'] subject_id = flask.request.json['subjectId'] # subject_id判断关联的项目是否存在 try: mysql_subjectinfo = model_mysql_subject.query.filter( model_mysql_subject.subjectId == subject_id).first() api_logger.debug("项目信息读取成功") except Exception as e: api_logger.error("项目信息读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_subjectinfo is None: return route.error_msgs[201]['msg_no_subject'] # 查询名称是否存在 try: mysql_catalogue = model_mysql_catalogue.query.filter( model_mysql_catalogue.catalogueName == catalogue_name).first() except Exception as e: api_logger.error("读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_catalogue is None: pass else: return route.error_msgs[201]['msg_exit_catalogue'] #获取当前id """ 插入数据 """ new_catalogue_info = model_mysql_catalogue( subjectId=subject_id, catalogueName=catalogue_name, catalogueStatus=1, ) mysqlpool.session.add(new_catalogue_info) mysqlpool.session.commit() # 最后返回内容 return response_json
def get_the_last_log_finish_time(taskid): """ 根据taskId获取运行日志中最后一条的结束时间 :param taskid: 测试任务id,每个测试任务都有对应的snapId :return: True/False-方法执行结果 int/None-结束时间戳 """ try: log_query = mongodb_tasklog_pool['task%s_run' % taskid].find_one({}, sort=[('_id', -1)]) except Exception as e: api_logger.error("测试任务:%s运行日志数据读取失败,失败原因:%s" % (taskid, repr(e))) return False, None else: api_logger.debug("测试任务:%s运行日志数据读取成功" % taskid) return True, log_query['et']
def key_depository_post(): # 初始化返回内容 response_json = {"code": 200, "msg": "数据新增成功", "data": {}} # 取出必传入参 request_user_id = flask.request.headers['UserId'] depository_name = flask.request.json['name'] depository_description = flask.request.json['description'] # 判断user_id获取角色信息 try: mysql_userinfo = model_mysql_userinfo.query.filter( model_mysql_userinfo.userId == request_user_id).first() api_logger.debug("账户基础信息读取成功") except Exception as e: api_logger.error("账户基础信息读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_userinfo is None: return route.error_msgs[201]['msg_no_user'] # 查询名称是否存在 try: mysql_depository = model_mysql_depository.query.filter( model_mysql_depository.name == depository_name).first() except Exception as e: api_logger.error("测试计划类型读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_depository is not None: return route.error_msgs[201]['msg_exist_depository'] # 新增仓库基础信息 new_depository_info = model_mysql_depository( userId=request_user_id, name=depository_name, description=depository_description, ) try: mysqlpool.session.add(new_depository_info) mysqlpool.session.commit() except Exception as e: api_logger.error("仓库基础信息新增失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] # 最后返回内容 return response_json
def create_snap_when_close(plan_id): redis_get_table_bytes = modle_redis_apitestplanworktable.query_table( plan_id) if redis_get_table_bytes is not None: # mysql中新增snap # 将status为1的snap全部置为失效 try: model_mysql_tablesnap.query.filter( and_(model_mysql_tablesnap.planId == plan_id, model_mysql_tablesnap.status == 1)).update({"status": 0}) mysqlpool.session.commit() except Exception as e: api_logger.error("model_mysql_tablesnap数据更新失败,失败原因:" + repr(e)) return False else: api_logger.debug("model_mysql_tablesnap数据更新成功") try: mysqlpool.session.add( model_mysql_tablesnap( status=1, planId=plan_id, snapAddTime=datetime.datetime.now(), table=redis_get_table_bytes.decode('utf-8'))) mysqlpool.session.commit() except Exception as e: api_logger.error("mysql_snaps数据写入失败,失败原因:" + repr(e)) else: api_logger.debug("mysql_snaps数据写入成功") finally: # 不管如何,清空redis中的数据 delete_flag = modle_redis_apitestplanworktable.delete(plan_id) api_logger.debug( "redis中缓存清除完毕") if delete_flag else api_logger.debug( "redis中缓存清除失败")
def task_result_post(): # 初始化返回内容 response_json = {"code": 200, "msg": "操作成功", "data": {}} # 取出taskId/uuid/finishTime task_id = flask.request.json['taskId'] worker_uuid = flask.request.json['uuid'] task_status = flask.request.json['status'] # 根据uuid在查找workerId try: worker_data = model_mysql_workerinfo.query.filter( model_mysql_workerinfo.uniqueId == worker_uuid).first() except Exception as e: api_logger.debug("worker_data query failed:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if worker_data is None: return route.error_msgs[201]['msg_worker_not_exist'] # 根据taskId以及workerId查询分配记录 try: assign_data = model_mysql_taskassign.query.filter( and_(model_mysql_taskassign.taskId == task_id, model_mysql_taskassign.workerId == worker_data.workerId)).first() except Exception as e: api_logger.debug("assign_data query failed:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if assign_data is None: return route.error_msgs[201]['msg_no_assign'] else: assign_data.status = task_status assign_data.updateTime = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') if task_status == 10: assign_data.finishTime = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') elif task_status == 3: assign_data.startTime = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') mysqlpool.session.commit() return response_json
def user_put(): # 初始化返回内容 response_json = {"code": 200, "msg": "", "data": {}} # 取出传入参数值 requestvalue_userid = flask.request.json["user_id"] requestvalue_roleid = flask.request.json["role_id"] # 如果传入的roleId为0,则将当前账户的所属角色去除 if requestvalue_roleid != 0: # 6.校验所操作的角色是否存在 # 7.校验所操作的角色是否是超级管理员角色 try: ri_data = model_mysql_roleinfo.query.filter( model_mysql_roleinfo.roleId == requestvalue_roleid).first() except Exception as e: logmsg = "数据库中角色数据读取失败,失败原因:" + repr(e) api_logger.error(logmsg) return route.error_msgs[500]['msg_db_error'] else: if ri_data and ri_data.roleIsAdmin == 0: pass elif ri_data and ri_data.roleIsAdmin == 1: return route.error_msgs[201]['msg_role_is_admin'] else: return route.error_msgs[201]['msg_no_role'] # 8.修改mysql账户所属角色 try: u_data = model_mysql_userinfo.query.filter( model_mysql_userinfo.userId == requestvalue_userid).first() logmsg = "数据库中账号数据读取成功" api_logger.debug(logmsg) except Exception as e: logmsg = "数据库中账号数据读取失败,失败原因:" + repr(e) api_logger.error(logmsg) return route.error_msgs[500]['msg_db_error'] else: u_data.userRoleId = None if requestvalue_roleid == 0 else requestvalue_roleid mysqlpool.session.commit() # 返回成功信息 response_json["msg"] = "操作成功" # 最后返回内容 return response_json
def get_running_logs(taskid, snap_data, search_kind, query_offset=0, query_limit=200): """ 根据taskId获取运行日志数据 并将测试插件数据和运行日志作结合,最终生成待返回的日志信息 :param taskid: 测试任务id,每个测试任务都有对应的snapId :param search_kind: 查询类型,1为仅失败,2为仅通过,3为全部 :param snap_data: 测试任务的快照内容 :param query_offset: 分页查询偏移量 :param query_limit: 分页查询行数 :return: True/False-方法执行结果 initLog/None-测试任务日志 count/None-数据总数 """ try: if search_kind == 3: log_query = mongodb_tasklog_pool['task%s_run' % taskid].find( {}, { "_id": 0 }).skip(query_offset).limit(query_limit) else: log_query = mongodb_tasklog_pool['task%s_run' % taskid].find( { 's': False if search_kind == 1 else True }, { "_id": 0 }).skip(query_offset).limit(query_limit) except Exception as e: api_logger.error("测试任务:%s运行日志数据读取失败,失败原因:%s" % (taskid, repr(e))) return False, None, -1 else: api_logger.debug("测试任务:%s运行日志数据读取成功" % taskid) log_list = [] i = query_offset for lq in list(log_query): lq['title'] = snap_data[lq['id']]['title'] lq['i'] = i i += 1 log_list.append(lq) return True, log_list, log_query.count()
def get_snap_data(taskid): """ 根据taskId查询执行的测试计划快照内容 进行json解析 将snap数据转换为以id为key值为value的dict,转换时过滤掉无log的插件 存在log的插件id为:9-MYSQL请求/10-Redis请求/11-HTTP/HTTPS请求 :param taskid: 测试任务id,每个测试任务都有对应的snapId :return: True/False-方法执行成功与否,Dict/None-最终数据 """ try: task_snap_data = model_mysql_taskinfo.query.filter( model_mysql_taskinfo.taskId == taskid ).first() except Exception as e: api_logger.error("测试任务:%s基础数据读取失败,失败原因:%s" % (taskid, repr(e))) return False, None else: api_logger.debug("测试任务:%s基础数据读取成功" % taskid) if not task_snap_data: return True, None else: result_data = {} try: task_snap_data_json = json.loads(task_snap_data.snap) except Exception as e: api_logger.error("测试任务:%s基础数据json解析失败,失败原因:%s" % (taskid, repr(e))) return False, None else: api_logger.debug("测试任务:%s基础数据json解析成功" % taskid) def recurse_to_simple_dict(data): if type(data) is dict and 'id' in data: if data['originalId'] in [9, 10, 11]: result_data[data['id']] = { 'id': data['id'], 'oid': data['originalId'], 'title': data['title'] } for cr in data['children']: recurse_to_simple_dict(cr) recurse_to_simple_dict(task_snap_data_json[0]) return True, result_data
def check_operate(cls, alias): data = { "exist": None, "operationId": None, } # 查询关键操作唯一标识符 try: odata = model_mysql_operationinfo.query.filter_by( operationAlias=alias ).first() except Exception as e: logmsg = "操作查询失败,失败原因:" + repr(e) api_logger.debug(logmsg) return data if odata is None: data["exist"] = False return data else: data["exist"] = True data["operationId"] = odata.operationId return data
def check_function(cls, functionid, rootid): data = { "exist": None } try: data_mysql = model_mysql_functioninfo.query.filter_by( functionId=functionid, rootId=rootid ).first() except Exception as e: logmsg = "数据库中角色权限数据校验失败,失败原因:" + repr(e) api_logger.error(logmsg) else: logmsg = "数据库中角色权限数据校验成功" api_logger.debug(logmsg) if data_mysql is None: data["exist"] = False else: data["exist"] = True return data
def check_user(user_id): api_logger.debug("准备查询缓存账户数据") # 尝试从mysql中查询 try: api_logger.debug("准备查询账户数据") uinfo_mysql = model_mysql_userinfo.query.filter_by( userId=user_id).first() api_logger.debug("账户数据查询成功") except Exception as e: api_logger.error("账户数据查询失败,失败原因:" + repr(e)) return False else: # 如果mysql中未查询到 if uinfo_mysql is None: return False # 如果mysql中查询到了 else: # 判断账户状态 if uinfo_mysql.userStatus == 0: return False elif uinfo_mysql.userStatus == -1: return False elif uinfo_mysql.userStatus != 1: return False return True
def check_plan_owner(mail, plan_id): user_id = None # 取出入参 request_head_mail = mail plan_id = plan_id # 查询测试计划基础信息,并取出所属者账户id try: mysql_plan_info = model_mysql_planinfo.query.filter( model_mysql_planinfo.planId == plan_id ).first() except Exception as e: api_logger.error("model_mysql_planinfo数据读取失败,失败原因:" + repr(e)) return None, route.error_msgs[500]['msg_db_error'] else: if mysql_plan_info is None: return False, route.error_msgs[201]['msg_no_plan'] else: plan_user_id = mysql_plan_info.ownerId # 查询账户信息,并取出账户id try: mysql_userinfo = model_mysql_userinfo.query.filter( model_mysql_userinfo.userEmail == request_head_mail ).first() api_logger.debug("model_mysql_userinfo数据读取成功") except Exception as e: api_logger.error("model_mysql_userinfo数据读取失败,失败原因:" + repr(e)) return None, route.error_msgs[500]['msg_db_error'] else: if mysql_userinfo is None: return False, route.error_msgs[201]['msg_no_user'] else: request_user_id = mysql_userinfo.userId # 如果操作者和计划拥有者不是同一人,则报错 if plan_user_id != request_user_id: return False, route.error_msgs[201]['msg_plan_notopen'] else: return True, None
def key_subject_delete(): # 初始化返回内容 response_json = {"code": 200, "msg": "数据删除成功", "data": None} # 取出入参 subject_user_id = flask.request.headers['UserId'] subject_id = flask.request.args['subjectId'] # 判断user_id是否存在 try: mysql_userinfo = model_mysql_subject.query.filter( model_mysql_subject.userId == subject_user_id).first() api_logger.debug("账户基础信息读取成功") except Exception as e: api_logger.error("账户基础信息读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_userinfo is None: return route.error_msgs[201]['msg_no_user'] # 查询项目名称是否存在,存在即逻辑删除 try: mysql_subject = model_mysql_subject.query.filter( model_mysql_subject.subjectId == subject_id).first() if mysql_subject.userId == int(subject_user_id): mysql_subject.subjectStatus = -1 mysqlpool.session.commit() else: return route.error_msgs[201]['msg_no_auth'] except Exception as e: api_logger.error("测试计划类型读取失败,失败原因:" + repr(e)) return route.error_msgs[500]['msg_db_error'] else: if mysql_subject is None: return route.error_msgs[201]['msg_no_subject'] # 最后返回内容 return response_json
def get_task_running_status(taskid): """ 获取测试任务执行状态 获取分配的所有assign记录(当前测试任务下发逻辑为一个任务仅下发给一台worker)的status 0推送中,1推送成功,-1推送失败,2任务初始化中,-2任务初始化失败,3任务执行中,-3执行异常,10任务结束 任何一条assign记录的status为0/1/2/3则可以认为测试任务状态为进行中 :param taskid: 测试任务id :return True/False-方法执行结果, True/False/None-测试任务运行状态 """ try: # 虽然获取的是全部条目,但当前测试任务下发逻辑为1个任务仅下发至1台执行应用 task_assign_info_list = model_mysql_taskassign.query.filter( model_mysql_taskassign.taskId == taskid).all() except Exception as e: api_logger.error("测试任务:%s运行状态数据读取失败,失败原因:%s" % (taskid, repr(e))) return False, None else: api_logger.debug("测试任务:%s运行状态数据读取成功" % taskid) for tail in task_assign_info_list: if tail.status in [0, 1, 2, 3]: return True, True return True, False