def updateCommonAssertList(self, List, Commonfield): if not getattr(self, Commonfield) and getattr(self, Commonfield) != "": return -1 com = getattr(self, Commonfield) oldlist = [] try: oldlist = json.loads(com) except Exception as e: globalVars.getLogger().error("json转换失败" + CommonValueHandle.text2str(e.message)) oldlist = [] try: for i in oldlist: a = CustomizeAssertModel.objects.get(pk=int(i)) a.delete() except Exception as e: globalVars.getLogger().error(e.message) re = [] for i in List: assertobj = CustomizeAssertModel() assertobj.updateFromDict(i) re.append(assertobj.id) try: setattr(self, Commonfield, json.dumps(re)) self.save() return 0 except Exception: return -1
def createHistory(self): try: history = TaskHistoryModel() history.taskId = self.id history.taskName = self.name history.suiteId = self.suite.id history.envId = self.env.id history.project = self.project history.taskType = self.taskType #0代表非定时任务,1代表是定时任务 history.repeatDateTime = self.repeatDateTime history.repeatType = self.repeatType #-1代表不重复,1代表每天,3代表每三天,7代表每周 history.status = self.status #0代表未运行,1代表运行中 history.successRate = self.successRate #成功率 history.nextResultVersion = self.nextResultVersion #代表下一次执行的结果的一个标识,就是一个版本号 history.lastResultVersion = self.lastResultVersion #代表上一次执行的结果的一个标识,就是一个版本号 history.lastRunningTime = self.lastRunningTime #上次执行时间 history.lastRunningUser = self.lastRunningUser #上次执行人 history.lastRunningSuccessCount = self.lastRunningSuccessCount #上次成功的的数目 history.lastRunningfailedCount = self.lastRunningfailedCount #上次失败的的数目 history.lastRunningResultIdList = self.lastRunningResultIdList #结果的id列表,用来跟case的id对应起来,本身的排序是跟测试套件里面的case 的排序一致 history.lastRunningPreResultIdList = self.lastRunningPreResultIdList #结果的id列表,用来跟precase的id对应起来,本身的排序是跟测试套件里面的case 的排序一致 history.lastRunningResult = self.lastRunningResult history.save() except Exception as e: globalVars.getLogger().error("历史数据保存失败:" + CommonValueHandle.text2str(e.message)) pass
def copyApi(request): req = simplejson.loads(request.body) aId = None if req.has_key("aId"): aId = req["aId"] if not aId: globalVars.getLogger().error("aId不能为空") return HttpResponse(globalVars.responseJson("false", "参数错误"), content_type="application/json") try: api = ApiDefine.objects.get(pk=int(aId)) newApi = api.cloneApi() newApi.save() except Exception as e: globalVars.getLogger().error(u"复制api失败:" + CommonValueHandle.text2unicode(e.message)) return HttpResponse(globalVars.responseJson("false", "复制失败"), content_type="application/json") else: tmp = {} tmp["name"] = newApi.name tmp["aId"] = newApi.id tmp["mId"] = newApi.module.id tmp["method"] = newApi.method tmp["pId"] = newApi.project.id tmp["parentId"] = newApi.module.id tmp["type"] = "api" tmp["cId"] = -1 return HttpResponse(globalVars.responseJson("true", "", tmp), content_type="application/json")
def doPostSql(self): self.postSql = str(self.suite.postSql).strip() globalVars.getLogger().info("执行后置sql条件:"+str(self.postSql)) if not self.postSql: return True else: return self.__excuteSql(self.postSql)
def runJobByloop(self): if self.__isTimeRight(): globalVars.getLogger().info("开始执行定时任务:") globalVars.getLogger().info(self.name) try: excute = TestTaskExcute(self.taskId,-1) ret = excute.excute() if True!=ret: globalVars.getLogger().error("执行任务失败:"+ret) except Exception as e: globalVars.getLogger().error("定时任务执行失败:"+CommonValueHandle.text2str(e.message)) else: historys = TaskHistoryModel.objects.filter(taskId=int(self.taskId)).order_by("-lastResultVersion") if len(historys) > 0: current = historys[0] name = current.taskName successRate = current.successRate lastRunningSuccessCount = current.lastRunningSuccessCount lastRunningfailedCount = current.lastRunningfailedCount lastRunningTime = current.lastRunningTime message = u"任务 " + name + u" 的执行结果:\n" + u"执行时间: " + str(lastRunningTime) + u", 成功率:" + str( successRate) + u", 成功:" + str(lastRunningSuccessCount) + u", 失败:" + str(lastRunningfailedCount) + \ u"\n 详细报告地址:http://t27.klook.io/history/" + str(current.id) send_mail(u'接口自动化测试报告', message, settings.EMAIL_HOST_USER,settings.EMAIL_RECEIVERS) globalVars.getLogger().info("定时任务执行成功") else: return ""
def apiPageIndex(request, pId): token = request.COOKIES[globalVars.IToken] try: tokenObj = Token.objects.get(Token=token) taskCount = TaskModel.objects.filter(project_id=int(pId)).count() apiCount = ApiDefine.objects.filter(project_id=int(pId)).count() caseCount = TestCaseModel.objects.filter(project_id=int(pId)).count() suiteCount = TestSuiteModel.objects.filter(project_id=int(pId)).count() tasks = TaskHistoryModel.objects.filter(project_id=int(pId)) charts = [] for i in tasks: charts.append(i.getChartData()) except Token.DoesNotExist: globalVars.getLogger().error("token不存在") return HttpResponseRedirect(reverse('login')) else: data = {} data["userName"] = tokenObj.user.user data["userId"] = tokenObj.user.id data["task"] = taskCount data["api"] = apiCount data["case"] = caseCount data["suite"] = suiteCount data["pId"] = pId data["charts"] = json.dumps(charts) return render(request, "apiIndex.html", globalVars.responeContent("true", "success", data))
def delCommonData(self, Commonfield, CommonId): if not getattr(self, Commonfield) and getattr(self, Commonfield) != "": return Commonfield + ":没有这样的字段" com = getattr(self, Commonfield) jsonData = [] if com == "" or com == None: jsonData = [] else: jsonData = json.loads(getattr(self, Commonfield)) if isinstance(jsonData, list): try: CommonId = int(CommonId) for i in jsonData: if i == CommonId: CommonParmasModel.objects.get(pk=CommonId).delete() jsonData.remove(i) setattr(self, Commonfield, json.dumps(jsonData)) self.save() except Exception as e: globalVars.getLogger().error( Commonfield + "删除失败" + CommonValueHandle.text2str(e.message)) return Commonfield + "删除header失败:" + CommonValueHandle.text2str( e.message) else: return CommonId else: globalVars.getLogger().error(Commonfield + "的数据格式不正确") return Commonfield + "的数据格式不正确"
def updateSuiteRequirement(request): req = simplejson.loads(request.body) suId = None rIds = None if req.has_key("suId"): suId=req["suId"] if req.has_key("rIds"): rIds = req["rIds"] if not suId: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: if not rIds: rIds = [] suite = TestSuiteModel.objects.get(pk=int(suId)) suite.updateRequirement(rIds) except Exception as e: globalVars.getLogger().error("修改测试套件的前置条件失败:"+CommonValueHandle.text2str(e.message)) return HttpResponse(globalVars.responseJson("false", "修改测试套件的前置条件失败"), content_type="application/json") else: content={} content["preRequirement"] = suite.getPreRequirement() content["suId"] = suite.id return HttpResponse(globalVars.responseJson("true","",content), content_type="application/json")
def getSummary(request): req = json.loads(request.body) pId = None print("~~~~~~~~") print(req) print("6666666") if req.has_key("pId"): pId = req["pId"] if not pId: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: taskCount = TaskModel.objects.filter(project_id=int(pId)).count() apiCount = ApiDefine.objects.filter(project_id=int(pId)).count() caseCount = TestCaseModel.objects.filter(project_id=int(pId)).count() suiteCount = TestSuiteModel.objects.filter(project_id=int(pId)).count() except Exception as e: globalVars.getLogger().error("获取结果失败:" + CommonValueHandle.text2str(e.message)) return HttpResponse(globalVars.responseJson("false", "获取结果失败"), content_type="application/json") else: data = {} data["task"] = taskCount data["api"] = apiCount data["case"] = caseCount data["suite"] = suiteCount return HttpResponse(globalVars.responseJson("true", "", data), content_type="application/json")
def getTestSuiteList(request): req = simplejson.loads(request.body) try: pId = req["pId"] except KeyError: pId = None if not pId: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: suiteList = TestSuiteModel.objects.filter(project_id=int(pId)) except Exception as e: globalVars.getLogger().error("删除测试套件失败:"+CommonValueHandle.text2str(e.message)) return HttpResponse(globalVars.responseJson("false", "删除测试套件失败"), content_type="application/json") else: dataList = [] for suite in suiteList: content={} content["name"]=suite.name content["suId"] = suite.id content["dec"] = suite.dec dataList.append(content) return HttpResponse(globalVars.responseJson("true","",dataList), content_type="application/json")
def updateTestSuiteBaseInfo(request): req = simplejson.loads(request.body) suId = None name = None dec = None if req.has_key("suId"): suId = req["suId"] if req.has_key("name"): name = req["name"] if req.has_key("dec"): dec = req["dec"] if not suId or not name or not dec: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: suite = TestSuiteModel.objects.get(pk=int(suId)) suite.name=name suite.dec=dec suite.save() except Exception as e: globalVars.getLogger().error("更新测试套件失败:"+CommonValueHandle.text2str(e.message)) return HttpResponse(globalVars.responseJson("false", "更新测试套件失败"), content_type="application/json") else: content={} content["name"]=suite.name content["suId"] = suite.id content["dec"] = suite.dec return HttpResponse(globalVars.responseJson("true","",content), content_type="application/json")
def getSqlSetting(request): req = json.loads(request.body) eId = None if req.has_key("eId"): eId = req["eId"] if not eId: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: sql = DatabaseSettingModel.objects.filter(env_id=int(eId)) currentSql = None except Exception as e: globalVars.getLogger().error("保存sql设置失败:" + CommonValueHandle.text2str(e.message)) return HttpResponse(globalVars.responseJson("false", "保存sql设置失败"), content_type="application/json") else: if 0 < len(sql): currentSql = sql[0] return HttpResponse(globalVars.responseJson( "true", "", currentSql.getDict()), content_type="application/json") else: return HttpResponse(globalVars.responseJson("true", ""), content_type="application/json")
def updateEnv(request): req = json.loads(request.body) eId = None name = None if req.has_key("eId"): eId = req["eId"] if req.has_key("name"): name = req["name"] if not eId or not name: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: env = EnvModel.objects.get(pk=int(eId)) env.name = name env.save() except Exception as e: globalVars.getLogger().error("修改执行环境失败:" + CommonValueHandle.text2str(e.message)) return HttpResponse(globalVars.responseJson("false", "修改执行环境失败"), content_type="application/json") else: return HttpResponse(globalVars.responseJson("true", "", env.getDict()), content_type="application/json")
def updateValuePicker(self, List): oldList = globalVars.str2List(self.valuePicker) for i in oldList: try: p = PickerValuesModel.objects.get(pk=int(i)) p.delete() except Exception: pass if List and isinstance(List, list): re = [] for o in List: try: p = PickerValuesModel() if o.has_key("name"): p.name = o["name"] if o.has_key("value"): p.value = o["value"] if o.has_key("expression"): p.expression = o["expression"] p.save() re.append(p.id) except Exception as e: globalVars.getLogger().error(e.message) return self.valuePicker = globalVars.list2Str(re) self.save() else: return
def getApiDetail(request): req = simplejson.loads(request.body) aId = None if req.has_key("aId"): aId = req["aId"] if not aId: globalVars.getLogger().error("aId不能为空") return HttpResponse(globalVars.responseJson("false", "参数错误"), content_type="application/json") try: api = ApiDefine.objects.get(pk=int(aId)) except ApiModules.DoesNotExist: globalVars.getLogger().error("模块mId不存在") return HttpResponse(globalVars.responseJson("false", "模块不存在"), content_type="application/json") else: context = {} context["aId"] = api.id context["mId"] = api.module.id context["pId"] = api.project.id context["uId"] = api.user.id context["name"] = api.name context["url"] = api.url context["method"] = api.method context["dec"] = api.dec context["header"] = api.getHeader() context["parmasType"] = api.parmasType context["parmas"] = api.getParmas() context["parmasExample"] = api.parmasExample context["responseStatus"] = api.responseStatus context["responseType"] = api.responseType context["response"] = api.getResponse() context["responseExample"] = api.responseExample return HttpResponse(globalVars.responseJson("true", "", context), content_type="application/json")
def getChart(request): req = json.loads(request.body) pId = None print("~~~~~~~~") print(req) print("6666666") if req.has_key("pId"): pId = req["pId"] if not pId: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: now = datetime.datetime.now() delta = datetime.timedelta(days=-30) n_days = now + delta tasks = TaskHistoryModel.objects.filter(project_id=int(pId), lastRunningTime__gt=n_days) data = [] for i in tasks: data.append(i.getChartData()) except Exception as e: globalVars.getLogger().error("获取结果失败:" + CommonValueHandle.text2str(e.message)) return HttpResponse(globalVars.responseJson("false", "获取结果失败"), content_type="application/json") else: return HttpResponse(globalVars.responseJson("true", "", data), content_type="application/json")
def updateApiMethod(request): req = simplejson.loads(request.body) aId = None method = None if req.has_key("aId"): aId = req["aId"] if req.has_key("method"): method = req["method"] if not aId or not method: globalVars.getLogger().error("aId或者url不能为空") return HttpResponse(globalVars.responseJson("false", "参数错误"), content_type="application/json") try: api = ApiDefine.objects.get(pk=int(aId)) api.method = method api.save() except Exception as e: globalVars.getLogger().error(u"修改api失败:" + CommonValueHandle.text2unicode(e.message)) return HttpResponse(globalVars.responseJson("false", "修改api失败"), content_type="application/json") else: return HttpResponse(globalVars.responseJson("true", ""), content_type="application/json")
def addSystemAssert(request): req = simplejson.loads(request.body) name = None key = None value = "" atype = 0 pId = None if req.has_key("name"): name=req["name"] if req.has_key("key"): key=req["key"] if req.has_key("value"): value=req["value"] if req.has_key("type"): atype=req["type"] if req.has_key("pId"): pId=req["pId"] if not name or not key or not pId: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: publicAssert = PublicAssertModel.objects.create(name=name,key=key,value=value,type=atype,project_id=int(pId)) except Exception as e: globalVars.getLogger().error("添加全局断言失败:"+CommonValueHandle.text2str(e.message)) return HttpResponse(globalVars.responseJson("false", "添加全局断言失败"), content_type="application/json") else: return HttpResponse(globalVars.responseJson("true","",publicAssert.getDict()), content_type="application/json")
def updateApiDelResponse(request): req = simplejson.loads(request.body) aId = None rId = None if req.has_key("aId"): aId = req["aId"] if req.has_key("rId"): rId = req["rId"] if not aId or not rId: globalVars.getLogger().error("aId或者rId不能为空") return HttpResponse(globalVars.responseJson("false", "参数错误"), content_type="application/json") try: api = ApiDefine.objects.get(pk=int(aId)) res = api.delResponse(rId) if isinstance(res, unicode) or isinstance(res, str): return HttpResponse(globalVars.responseJson( "false", u"删除api response失败:" + CommonValueHandle.text2unicode(res)), content_type="application/json") except Exception as e: globalVars.getLogger().error(u"修改api失败:" + CommonValueHandle.text2unicode(e.message)) return HttpResponse(globalVars.responseJson("false", "修改参数失败"), content_type="application/json") else: data = {} data["delId"] = res return HttpResponse(globalVars.responseJson("true", "", data), content_type="application/json")
def addGlobalValues(request): req = simplejson.loads(request.body) name = None value = "" atype = None pId = None eId = None if req.has_key("name"): name=req["name"] if req.has_key("value"): value=req["value"] if req.has_key("type"): atype=req["type"] if req.has_key("pId"): pId=req["pId"] if req.has_key("eId"): eId=req["eId"] if not name or not value or not pId or not atype: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: values = GlobalValuesModel.objects.create(name=name,value=value,type=atype,project_id=int(pId),env_id=int(eId)) except Exception as e: globalVars.getLogger().error("添加全局断言失败:"+CommonValueHandle.text2str(e.message)) return HttpResponse(globalVars.responseJson("false", "添加全局断言失败"), content_type="application/json") else: return HttpResponse(globalVars.responseJson("true","",values.getDict()), content_type="application/json")
def changeCommonDataTurn(self, Commonfield, direction, commonId): if not getattr(self, Commonfield) and getattr(self, Commonfield) != "": return Commonfield + ":没有这样的字段" com = getattr(self, Commonfield) jsonData = [] if com == "" or com == None: jsonData = [] else: jsonData = json.loads(getattr(self, Commonfield)) if isinstance(jsonData, list): commonId = int(commonId) for i, v in enumerate(jsonData): if v == commonId: if direction == "up": if i != 0: jsonData[i] = jsonData[i - 1] jsonData[i - 1] = commonId else: if i != (len(jsonData) - 1): jsonData[i] = jsonData[i + 1] jsonData[i + 1] = v try: setattr(self, Commonfield, json.dumps(jsonData)) self.save() except Exception as e: globalVars.getLogger().error( Commonfield + "删除失败" + CommonValueHandle.text2str(e.message)) return Commonfield + "删除header失败:" + CommonValueHandle.text2str( e.message) else: return commonId else: globalVars.getLogger().error(Commonfield + "的数据格式不正确") return Commonfield + "的数据格式不正确"
def requirementAddPicker(request): req = simplejson.loads(request.body) rId = None name = None value = None expression = None if req.has_key("rId"): rId=req["rId"] if req.has_key("name"): name=req["name"] if req.has_key("value"): value=req["value"] if req.has_key("expression"): expression=req["expression"] if not rId or not value or not expression: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: picker = PickerValuesModel.objects.create(name=name,value=value,expression=expression) require = RequirementModel.objects.get(pk=int(rId)) require.addPickerValue(picker.id); except Exception as e: globalVars.getLogger().error(u"新建变量提取失败:"+CommonValueHandle.text2unicode(e.message)) return HttpResponse(globalVars.responseJson("false", "新建变量提取失败"), content_type="application/json") else: return HttpResponse(globalVars.responseJson("true","",picker.getDict()), content_type="application/json")
def doSuiteCase(self): try: globalVars.getLogger().info("开始执行案例") self.cases = self.suite.getCases() for i in self.cases: globalVars.getLogger().info(" ") globalVars.getLogger().info("案例名称:"+ CommonValueHandle.text2str(i["name"])) te = TestCaseExcute(i["cId"],self.globalVars,self.runningVars,[],self.task.env,0,self.task.nextResultVersion) re = te.excute() reId = -1 if True != re: globalVars.getLogger().info("执行案例出现错误!"+CommonValueHandle.text2str(re)) reId = te.saveResult(self.task.id,"执行案例出现错误!"+CommonValueHandle.text2str(re)) self.failed= self.failed+1 else: reId = te.saveResult(self.task.id,"执行成功") # self.resultIds.append(reId) if te.result > -1: self.success= self.success+1 else: self.failed= self.failed+1 self.resultIds.append(reId) except Exception as e: globalVars.getLogger().err("案例执行失败:"+CommonValueHandle.text2str(e.message)) return CommonValueHandle.text2str(e.message) else: return True
def deleteApi(request): req = simplejson.loads(request.body) aId = None print("~~~~~~~~") print(req) print("6666666") if req.has_key("aId"): aId = req["aId"] if not aId: globalVars.getLogger().error("aId不能为空") return HttpResponse(globalVars.responseJson("false", "参数错误"), content_type="application/json") try: api = ApiDefine.objects.get(pk=int(aId)) TestCaseModel.objects.filter(api=api).delete() api.delete() except Exception as e: globalVars.getLogger().error(u"删除api失败:" + CommonValueHandle.text2unicode(e.message)) return HttpResponse(globalVars.responseJson("false", "删除接口失败"), content_type="application/json") else: return HttpResponse(globalVars.responseJson("true", ""), content_type="application/json")
def getTaskHistoryReport(request): req = simplejson.loads(request.body) hId = None if req.has_key("hId"): hId = req["hId"] if not hId: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: history = TaskHistoryModel.objects.get(pk=int(hId)) suite = TestSuiteModel.objects.get(pk=int(history.suiteId)) preSql = suite.preSql postSql = suite.postSql except Exception as e: globalVars.getLogger().error(u"查询历史数据失败:" + CommonValueHandle.text2unicode(e.message)) return HttpResponse(globalVars.responseJson( "false", u"查询历史数据失败:" + CommonValueHandle.text2unicode(e.message)), content_type="application/json") else: data = {} data["preSql"] = preSql data["postSql"] = postSql data["preCases"] = history.getPreCaseResult() data["Cases"] = history.getCaseResult() return HttpResponse(globalVars.responseJson("true", "", data), content_type="application/json")
def updateTestSuiteCases(request): req = json.loads(request.body) suId = None casesId = None if req.has_key("suId"): suId = req["suId"] if req.has_key("casesId"): casesId = req["casesId"] if not suId: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: suite = TestSuiteModel.objects.get(pk=int(suId)) suite.casesId = casesId suite.save() except Exception as e: globalVars.getLogger().error("编辑测试套件失败:" + CommonValueHandle.text2str(e.message)) return HttpResponse(globalVars.responseJson("false", "编辑测试套件失败"), content_type="application/json") else: return HttpResponse(globalVars.responseJson("true", "", suite.getDict()), content_type="application/json")
def getTaskHistory(request): req = simplejson.loads(request.body) tId = None if req.has_key("tId"): tId = req["tId"] if not tId: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: historys = TaskHistoryModel.objects.filter( taskId=int(tId)).order_by("-lastResultVersion") except Exception as e: globalVars.getLogger().error(u"查询历史数据失败:" + CommonValueHandle.text2unicode(e.message)) return HttpResponse(globalVars.responseJson( "false", u"查询历史数据失败:" + CommonValueHandle.text2unicode(e.message)), content_type="application/json") else: data = [] for t in historys: tmp = {} tmp["time"] = t.lastRunningTime tmp["hId"] = t.id tmp["version"] = t.lastResultVersion tmp["name"] = t.taskName data.append(tmp) return HttpResponse(globalVars.responseJson("true", "", data), content_type="application/json")
def excuteSqlAssert(self, env, sql, sqlAssert): sql = sql.strip() if not env: return "环境变量不能为空" settings = DatabaseSettingModel.objects.filter(env=env) if (len(settings) < 1): return None setting = settings[0] host = setting.host user = setting.user psw = setting.psw database = setting.database port = setting.port SSHHost = setting.sshHost SSHUser = setting.sshUser SSHPort = setting.sshPort SSHKey = setting.sshKey SSHPsw = setting.sshPsw ret = True if not SSHHost: # 基础连接方式 globalVars.getLogger().info("使用基础连接方式") ret = self.__baseExcuteSql(host, user, psw, port, database, sql, sqlAssert) else: #ssh连接方式 globalVars.getLogger().info("使用ssh连接方式") ret = self.__sshExcuteSql(host, user, psw, port, database, SSHHost, SSHPort, SSHUser, SSHPsw, SSHKey, sql, sqlAssert) self.closeConn() return ret
def getCasesList(request): req = simplejson.loads(request.body) tId = None if req.has_key("tId"): tId = req["tId"] if not tId: globalVars.getLogger().error("参数不正确,请检查请求参数") return HttpResponse(globalVars.responseJson("false", "参数不正确,请检查请求参数"), content_type="application/json") try: task = TaskModel.objects.get(pk=int(tId)) cases = task.getCases() except Exception as e: globalVars.getLogger().error(u"修改任务失败:" + CommonValueHandle.text2unicode(e.message)) return HttpResponse(globalVars.responseJson("false", "修改任务失败"), content_type="application/json") else: re = {} re["cases"] = cases re["lastRunningSuccessCount"] = task.lastRunningSuccessCount re["lastRunningfailedCount"] = task.lastRunningfailedCount re["lastRunningTime"] = task.lastRunningTime re["lastRunningUser"] = task.lastRunningUser re["lastRunningResult"] = task.lastRunningResult re["preSql"] = task.getPreSql() re["postSql"] = task.getPostSql() re["preRequirement"] = task.getPreRequirement() return HttpResponse(globalVars.responseJson("true", "", re), content_type="application/json")
def run1(q, db_host, db_user, db_psw, db_port, db, sshHost, sshPort, sshUser, sshPsw, sshKey): if not db_host or not db_user or not db_psw or not db_port or not db or not sshHost or not sshPort or not sshUser: globalVars.getLogger().error("参数错误") q.put(0) return if (not sshPsw and not sshKey): globalVars.getLogger().error("参数错误") q.put(0) return try: if not sshPsw: accessory_dir = os.path.join(settings.STATIC_ROOT, "sshKeys") keyUrl = "%s/%s" % (accessory_dir, sshKey) if not os.path.exists(keyUrl): globalVars.getLogger().error(keyUrl + "路径不存在") q.put(0) return with SSHTunnelForwarder( (sshHost, sshPort), ssh_pkey=keyUrl, ssh_username=sshUser, remote_bind_address=(db_host, db_port)) as server: # print server conn = MySQLdb.connect( host='127.0.0.1', port=server.local_bind_port, user=db_user, passwd=db_psw, db=db, charset="utf8", cursorclass=MySQLdb.cursors.DictCursor) else: with SSHTunnelForwarder( (sshHost, sshPort), ssh_password=sshPsw, ssh_username=sshUser, remote_bind_address=(db_host, db_port)) as server: conn = MySQLdb.connect( host='127.0.0.1', port=server.local_bind_port, user=db_user, passwd=db_psw, db=db, charset="utf8", cursorclass=MySQLdb.cursors.DictCursor) except Exception as e: globalVars.getLogger().error( "连接数据库失败:" + CommonValueHandle.text2str(e.message)) traceback() q.put(0) return else: globalVars.getLogger().error("连接数据库失败:") q.put(1) return