Example #1
0
def getInterfaceDataForId(request):
    langDict = getLangTextDict(request)
    serviceConf = ServiceConfService.queryServiceConfSort(request)

    # 根据版本判断应该从哪个表里取数据 王吉亮添加于20180224
    if VersionService.isCurrentVersion(request):
        getDBData = MockHttpService.getInterfaceForIdToDict(request.GET.get("id"))
        interfaceIdList = getDBData['interfaceIds'].strip(",").split(',')
        interfaceList = []
        for tmpInterfaceId in interfaceIdList:
            if tmpInterfaceId.strip() != "":
                interfaceList.append(dbModelToDict(HTTP_interfaceService.getInterfaceByInterfaceId(tmpInterfaceId.strip())))
        getDBData['interfaceList'] = interfaceList
    else:
        getDBData = MockHttpService.getVersionInterfaceForIdToDict(request.GET.get("id"),request.session.get("version"))
    return HttpResponse(ApiReturn(ApiReturn.CODE_OK, langDict["web"]["httpInterfaceSuccess"], json.dumps(getDBData)).toJson())
Example #2
0
def follow(request):
    operate = request.GET.get("oprate", "follow")
    mockId = request.GET.get("mockId", "")
    follower = request.session.get("loginName")
    if mockId == "":
        return HttpResponse(ApiReturn(code=ApiReturn.CODE_ERROR,message="mockId必传").toJson())
    retcode, retmsg = MockHttpService.follow(mockId,operate,follower)
    return HttpResponse(ApiReturn(code=retcode,message=retmsg).toJson())
Example #3
0
def interfaceAdd(request):
    # 当前版本使用历史代码,不更新。
    if request.method != 'POST':
        return HttpResponse(ApiReturn(ApiReturn.CODE_METHOD_ERROR, "请求方式错误", "").toJson())
    data = json.loads(request.POST.get("interfaceData"))
    try:
        if 'advancedPythonCode' in data.keys():
            retB,retS = verifyPythonMode(data['advancedPythonCode'])
            if retB == False:
                retMsg = "高级模式python代码非法:%s" % retS
                return HttpResponse(ApiReturn(ApiReturn.CODE_ERROR, retMsg, retMsg).toJson())

        MockHttpService.addHttpMockInfo(data, request.session.get("loginName"))
    except Exception as e:
        logger.error(traceback.format_exc())
        return HttpResponse(ApiReturn(ApiReturn.CODE_INTERFACE_ERROR, "添加接口错误", "Failed: %s" % e).toJson())
    return HttpResponse(ApiReturn(ApiReturn.CODE_OK, "添加成功", "").toJson())
Example #4
0
def interfaceDel(request):
    id = request.GET.get("id")
    try:
        if VersionService.isCurrentVersion(request):
            interfaceData = MockHttpService.getInterfaceForId(request.GET.get("id"))
        else:
            interfaceData = MockHttpService.getVersionInterfaceForId(request.GET.get("id"))

    except Exception as e:
        print(traceback.format_exc())
        return HttpResponse(ApiReturn(ApiReturn.CODE_INTERFACE_ERROR, "参数id错误 %s" % e).toJson())

    if MockHttpService.delInterfaceForId(request,id) == 1:
        addUserLog(request, "MOCK服务->删除MOCK[%s]->成功。" % id, "PASS")
        return HttpResponse(ApiReturn(ApiReturn.CODE_OK).toJson())
    else:
        return HttpResponse(ApiReturn(ApiReturn.CODE_INTERFACE_ERROR).toJson())
Example #5
0
def operationInterface(request, context):
    langDict = getLangTextDict(request)
    context["id"] = request.GET.get("id")
    context["option"] = request.GET.get("option")
    context["addHTTPInterface"] = "current-page"
    context["title"] = "HTTP MOCK-" + request.GET.get("id")

    if not isRelease:
        context["env"] = "test"
    try:
        if VersionService.isCurrentVersion(request):
            context["dataAddBy"] = MockHttpService.getInterfaceForId(
                request.GET.get("id")).addBy
        else:
            context["dataAddBy"] = MockHttpService.getVersionInterfaceForId(
                request.GET.get("id")).addBy

    except Exception as e:

        return render(request, "permission/page_404.html")

    # 文本
    text = {}
    try:
        text["pageTitle"] = "MOCK接口"
        if context["option"] == "select":
            text["subPageTitle"] = "查看MOCK接口"
        elif context["option"] == "edit":
            text["subPageTitle"] = "编辑MOCK接口"
        elif context["option"] == "copy":
            text["subPageTitle"] = "添加MOCK接口"
    except Exception as e:
        return HttpResponse("参数错误 %s" % e)
    context["text"] = text

    context.update(getConfigs(request))
    context.update(getServiceConf(request))
    context["debugBtnCount"] = commonWebConfig.debugBtnCount
    getDebugBtnList = getDebugBtn(request)
    context.update(getDebugBtnList)
    context["serviceJson"] = json.dumps(
        ServiceConfService.queryServiceConfSort(request))
    context["importStr"] = getPythonThirdLib()

    return render(request, "mock_server/http/HTTP_interface.html", context)
Example #6
0
def interfaceGetSyncTestCaseStep(request):
    id = request.GET.get("id")
    if VersionService.isCurrentVersion(request):
        interfaceData = dbModelToDict(MockHttpService.getInterfaceForId(id))
        syncList = syncDelTipList(interfaceData)
    else:
        interfaceData = dbModelToDict(HTTP_interfaceService.getVersionInterfaceForId(id))
        syncList = syncVersionDelTipList(interfaceData, VersionService.getVersionName(request))
    return HttpResponse(ApiReturn(body=syncList).toJson())
Example #7
0
def runContrackTask(request):
    mockId = request.GET.get("mockId")
    httpConfKey = request.GET.get("httpConfKey")
    if(mockId):
        mockInfo = MockHttpService.getInterfaceByMockId(mockId)
        if mockInfo:
            if mockInfo.interfaceIds.strip(",").strip() == "":
                return HttpResponse(ApiReturn(code=ApiReturn.CODE_ERROR, message="没有发现契约接口信息!", body=mockId + httpConfKey).toJson())
        else:
            return HttpResponse(ApiReturn(code=ApiReturn.CODE_ERROR, message="没有发现mock信息!", body=mockId + httpConfKey).toJson())
    else:
        return HttpResponse(ApiReturn(code=ApiReturn.CODE_ERROR, message="必须有mockId参数!", body=mockId + httpConfKey).toJson())

    if httpConfKey:
        pass
    else:
        return HttpResponse(ApiReturn(code=ApiReturn.CODE_ERROR, message="必须有httpConfKey参数!", body=mockId + httpConfKey).toJson())

    taskExc = TbTaskExecute()
    taskExc.taskId = "CONTRACT_TASK_%s" % mockId
    taskExc.title = "契约测试:%s" % mockInfo.title
    taskExc.taskdesc = taskExc.title
    taskExc.protocol = "HTTP"
    taskExc.businessLineGroup = "['%s']" % BusinessService.getBusinessLineNameById(mockInfo.businessLineId)
    taskExc.modulesGroup = "['%s']" % ModulesService.getModuleNameById(mockInfo.moduleId)
    taskExc.interfaceCount = len(mockInfo.interfaceIds.strip(",").split(","))
    taskExc.taskInterfaces = mockInfo.interfaceIds.strip(",")
    taskExc.caseCount = 0
    taskExc.interfaceNum = taskExc.interfaceCount

    taskExc.httpConfKey = TbConfigHttp.objects.filter(httpConfKey=httpConfKey.strip()).get()
    taskExc.execComments = "执行契约测试任务"
    taskExc.testResultMsg = ""
    taskExc.testReportUrl = ""

    taskExc.addBy = TbUser.objects.filter(loginName = request.session.get("loginName")).get()
    taskExc.execBy = TbUser.objects.filter(loginName = request.session.get("loginName")).get()
    taskExc.save(force_insert=True)

    addDataResult = dbModelToDict(taskExc)
    # 将任务执行的信息写入缓存,任务执行的前缀为 taskExecute_executeId
    RedisCache().set_data("%s_taskExecute_%s" % ("HTTP", addDataResult["id"]), "0:0:0:0:0", 60 * 60 * 12)
    RedisCache().set_data("%s_taskExecuteStatus_%s" % ("HTTP", addDataResult["id"]), "1", 60 * 60 * 12)
    # tcpin = '{"do":3,"TaskExecuteId":"%s"}' % addDataResult["id"]
    tcpin = '{"do":3,"TaskExecuteId":%s,"TaskExecuteEnv":"%s","TaskId":"%s","protocol":"HTTP"}' % (addDataResult["id"], addDataResult["httpConfKey_id"], addDataResult["taskId"])
    retApiResult = send_tcp_request(tcpin)
    if retApiResult.code != ApiReturn.CODE_OK:
        retmsg = 1
        RedisCache().del_data("%s_taskExecute_%s" % ("HTTP", addDataResult["id"]))
        RedisCache().del_data("%s_taskExecuteStatus_%s" % ("HTTP", addDataResult["id"]))
    bodyDict = {
        "taskExecuteId":taskExc.id,
        "taskId":taskExc.taskId
    }
    return HttpResponse(ApiReturn(code=ApiReturn.CODE_OK,message="ok",body=bodyDict).toJson())
Example #8
0
def interfaceSaveEdit(request):
    postLoad = json.loads(request.POST.get("interfaceData"))
    postLoad["modTime"] = datetime.datetime.now()
    postLoad["modBy"] = request.session.get("loginName")
    try:
        if 'advancedPythonCode' in postLoad.keys():
            retB, retS = verifyPythonMode(postLoad['advancedPythonCode'])
            if retB == False:
                retMsg = "高级模式python代码非法:%s" % retS
                return HttpResponse(
                    ApiReturn(ApiReturn.CODE_ERROR, retMsg, retMsg).toJson())

        print(postLoad)
        MockHttpService.interfaceSaveEdit(request, postLoad)
        addUserLog(request, "MOCK服务->更新MOCK[%s]->成功。" % id, "PASS")
        return HttpResponse(ApiReturn(ApiReturn.CODE_OK).toJson())
    except Exception as e:
        logger.error(traceback.format_exc())
        return HttpResponse(
            ApiReturn(ApiReturn.CODE_INTERFACE_ERROR,
                      '保存编辑失败!%s' % e).toJson())
Example #9
0
def mock(request, service, tagKey, httpConfKey, url):
    if request.method == "OPTIONS":
        #处理嗅探
        reqOrigin = request.META.get("HTTP_ORIGIN")
        response = HttpResponse(status=204)
        response[
            'Access-Control-Allow-Methods'] = "POST,GET,PUT,DELETE,HEAD,OPTIONS,PATCH"  # 支持那些请求方法,可以根据实际情况配置如 "POST, GET ,OPTIONS"
        response[
            'Access-Control-Allow-Origin'] = reqOrigin  # 实际操作中本人无法获取请求头中的Origin参数,所以这里我实际上是配置成了 "*",但是不建议这样操作,后续会有问题,可以根据实际情况写成固定的也可以 "完整域名"
        response[
            "Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie,X-CSRFToken"  # 如果配置接收的请求头有遗漏,当发送OPTIONS方法成功后,发送正式请求时将会在浏览器报错,可以根据浏览器中consolo的报错内容添加进去即可, 我这里需要配置的就是这两个
        response[
            "Access-Control-Allow-Credentials"] = "true"  # reqOrigin  # 实际操作中本人无法获取请求头中的Origin参数,所以这里我实际上是配置成了 "*",但是不建议这样操作,后续会有问题,可以根据实际情况写成固定的也可以 "完整域名"
        return response

    #httpConfKey应该包含 test1---rec-all-header-param-body
    whetherRecHeader = False  # 录制到db的时候是否录制header
    whetherRecParam = False  # 录制到db的时候是否录制param
    whetherRecBody = False  # 录制到db的时候是否录制body
    whetherRec = True  # 未记录的接口是否录制到db
    recEnvList = httpConfKey.split("---rec")
    if len(recEnvList) == 1:
        httpConfKey = recEnvList[0].strip()
    elif len(recEnvList) == 2:
        httpConfKey = recEnvList[0].strip()
        #分析recEnvList[1]
        if "-no" in recEnvList[1]:
            whetherRec = False

        if "-all" in recEnvList[1]:
            whetherRecHeader = True
            whetherRecParam = True
            whetherRecBody = True
        else:
            if "-header" in recEnvList[1]:
                whetherRecHeader = True
            if "-param" in recEnvList[1]:
                whetherRecParam = True
            if "-body" in recEnvList[1]:
                whetherRecBody = True

    retBl, mostPipeiMockInfo, processedReqHeader, reqUrl, reqParam, reqBody = getCorrectMockModel(
        request, service, tagKey, url)
    # print("###################################################")
    # print(retBl)
    # if retBl:
    #     print(mostPipeiMockInfo.mockId)
    # print(processedReqHeader)
    # print(reqUrl)
    # print(reqParam)
    # print(reqBody)
    # print("###################################################")
    if retBl == False:
        #没有匹配到mock数据,开始从环境来拿数据。
        reqHost = MockHttpService.getUri(httpConfKey, service)
        if reqHost == "":
            return HttpResponse(
                "Cannot find mockinfo, and cannot recode request because reqHost[%s]  not found in env [%s]."
                % (service, httpConfKey))

        if reqBody:
            bodyType = "raw"
            bodyContent = reqBody
        else:
            bodyType = None
            bodyContent = None

        if "HOST" in processedReqHeader.keys():
            del processedReqHeader['HOST']
        tcResp = HttpProcesserV2(method=request.method.upper(),
                                 host=reqHost,
                                 url=url,
                                 headers=json.dumps(processedReqHeader),
                                 params=djangoReqGetDictToParamStr(
                                     request.GET),
                                 bodyType=bodyType,
                                 bodyContent=bodyContent).sendRequest()
        if "requests.models.Response" in str(type(tcResp)):
            respContentText = getRespTextByResponse(tcResp)
            resp = HttpResponse(content=respContentText,
                                status=tcResp.status_code,
                                reason=tcResp.reason)
            # 设置cookie
            for ck, cv in tcResp.cookies.get_dict().items():
                resp.set_cookie(ck, cv)

            # 设置header
            allowdHeaderKeyList = ["content-type"]
            respHeaderDict = {}
            for ck, cv in tcResp.headers.items():
                if ck.lower() in allowdHeaderKeyList:
                    resp[ck] = cv
                    respHeaderDict[ck] = cv
            if whetherRec:
                #如果选择不记录到db,那么就不执行。
                mockInfoAuto = {}
                mockInfoAuto['title'] = "[自动录制]%s" % tcResp.url
                mockInfoAuto['businessLineId'] = 1
                mockInfoAuto['moduleId'] = 1
                mockInfoAuto['uriKey'] = service
                mockInfoAuto['tagKey'] = tagKey

                mockInfoAuto['reqMethod'] = request.method.upper()
                mockInfoAuto['reqUrl'] = url

                if whetherRecHeader:
                    mockInfoAuto['reqHeader'] = json.dumps(processedReqHeader)
                else:
                    #如果不录制header,假设contenttype是formdata,依然记录form data的值。
                    if "Content-Type" in processedReqHeader.keys():
                        #如果是formdata,就只记录content type,否则不记录
                        recContentType = processedReqHeader['Content-Type']
                        if recContentType.startswith("multipart/form-data"):
                            tmpHeader = {"Content-Type": recContentType}
                            mockInfoAuto['reqHeader'] = json.dumps(tmpHeader)

                if whetherRecParam:
                    mockInfoAuto['reqParam'] = reqParam
                if whetherRecBody:
                    mockInfoAuto['reqBody'] = reqBody

                mockInfoAuto['respStatusCode'] = tcResp.status_code
                mockInfoAuto['respStatusReason'] = tcResp.reason
                mockInfoAuto['respBody'] = respContentText
                mockInfoAuto['respHeader'] = json.dumps(respHeaderDict)
                mockInfoAuto['respCookie'] = json.dumps(
                    tcResp.cookies.get_dict())
                MockHttpService.addHttpMockInfo(mockInfoAuto, "")
            return resp
        else:
            return HttpResponse(str(tcResp),
                                status=509,
                                reason="Invalid mock rec response")
    #通过人会的mockModel来获取数据并判断
    respStatusCode, respStatusReason, respContentType, respCharset, respContent, respCookie, respHeader = getRespVarsByMockModel(
        mostPipeiMockInfo)
    # print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
    # print(respStatusCode, respStatusReason, respContentType, respCharset, respCookie,respHeader)
    # print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
    # 添加invoke历史
    #处理高级模式
    respStatusCode, respStatusReason, respContentType, respCharset, respContent, respCookie, respHeader = processAdvancedMode(
        mostPipeiMockInfo, request, reqUrl, reqParam, reqBody,
        processedReqHeader, respStatusCode, respStatusReason, respContentType,
        respCharset, respContent, respCookie, respHeader)
    #生成response并返回
    resp = HttpResponse(content=respContent,
                        status=respStatusCode,
                        reason=respStatusReason,
                        charset=respCharset,
                        content_type=respContentType)

    ###解决跨域问题
    reqOrigin = request.META.get("HTTP_ORIGIN")
    if reqOrigin:
        resp[
            "Access-Control-Allow-Methods"] = "POST,GET,PUT,DELETE,HEAD,OPTIONS,PATCH"  # 支持那些请求方法,可以根据实际情况配置如 "POST, GET ,OPTIONS"
        resp[
            "Access-Control-Allow-Origin"] = reqOrigin  # 实际操作中本人无法获取请求头中的Origin参数,所以这里我实际上是配置成了 "*",但是不建议这样操作,后续会有问题,可以根据实际情况写成固定的也可以 "完整域名"
        resp[
            "Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie,X-CSRFToken"  # 如果配置接收的请求头有遗漏,当发送OPTIONS方法成功后,发送正式请求时将会在浏览器报错,可以根据浏览器中consolo的报错内容添加进去即可, 我这里需要配置的就是这两个
        resp[
            "Access-Control-Allow-Credentials"] = "true"  # reqOrigin  # 实际操作中本人无法获取请求头中的Origin参数,所以这里我实际上是配置成了 "*",但是不建议这样操作,后续会有问题,可以根据实际情况写成固定的也可以 "完整域名"

    resp['mockinfo'] = "mockId[%s]addBy[%s]addTime[%s]url[%s]" % (
        mostPipeiMockInfo.mockId, mostPipeiMockInfo.addBy,
        mostPipeiMockInfo.addTime, mostPipeiMockInfo.reqUrl)
    #设置cookie
    if respCookie != "" and isJson(respCookie):
        cookieDict = json.loads(respCookie)
        for ck, cv in cookieDict.items():
            resp.set_cookie(ck, cv)

    #设置header
    if respHeader != "" and isJson(respHeader):
        headerDict = json.loads(respHeader)
        for ck, cv in headerDict.items():
            resp[ck] = cv

    addMockInvokeHistory(request, mostPipeiMockInfo, reqUrl, reqParam, reqBody,
                         processedReqHeader, respStatusCode, respStatusReason,
                         respContentType, respCharset, respContent, respCookie)
    return resp