Example #1
0
def update_casestep(body, case):

    step_list = list(models.CaseStep.objects.filter(case=case).values('id'))

    for index in range(len(body)):

        test = body[index]
        try:
            format_http = Format(test['newBody'])
            format_http.parse()
            name = format_http.name
            new_body = format_http.testcase
            url = format_http.url
            method = format_http.method

        except KeyError:
            if 'case' in test.keys():
                case_step = models.CaseStep.objects.get(id=test['id'])
            else:
                case_step = models.API.objects.get(id=test['id'])

            new_body = eval(case_step.body)
            name = test['body']['name']

            if case_step.name != name:
                new_body['name'] = name

            url = test['body']['url']
            method = test['body']['method']

        kwargs = {
            "name": name,
            "body": new_body,
            "url": url,
            "method": method,
            "step": index,
        }
        if 'case' in test.keys():
            models.CaseStep.objects.filter(id=test['id']).update(**kwargs)
            step_list.remove({"id": test['id']})
        else:
            kwargs['case'] = case
            models.CaseStep.objects.create(**kwargs)

    #  去掉多余的step
    for content in step_list:
        models.CaseStep.objects.filter(id=content['id']).delete()
def save_api(request_data, now_tree):
    if request_data:
        api = Format(request_data)
        api.parse()
        api_body = {
            'name': api.name,
            'body': api.testcase,
            'url': api.url,
            'method': api.method,
            'project_id': PROJECT_ID,
            'relation': now_tree["id"]
        }
        print(api_body)
        try:
            models.API.objects.create(**api_body)
        except:
            print(traceback.print_exc())
Example #3
0
def generate_casestep(body, case):
    """
    生成用例集步骤
    [{
        id: int,
        project: int,
        name: str,
        method: str,
        url: str
    }]

    """
    #  index也是case step的执行顺序

    for index in range(len(body)):

        test = body[index]
        try:
            format_http = Format(test['newBody'])
            format_http.parse()
            name = format_http.name
            new_body = format_http.testcase
            url = format_http.url
            method = format_http.method

        except KeyError:
            api = models.API.objects.get(id=test['id'])
            new_body = eval(api.body)
            name = test['body']['name']

            if api.name != name:
                new_body['name'] = name

            url = test['body']['url']
            method = test['body']['method']

        kwargs = {
            "name": name,
            "body": new_body,
            "url": url,
            "method": method,
            "step": index,
            "case": case
        }

        models.CaseStep.objects.create(**kwargs)
Example #4
0
def run_api(request):
    """ run api by body
    """
    name = request.data.pop('config')
    host = request.data.pop("host")
    timestamp = request.data.pop("timestamp")

    api = Format(request.data)
    api.parse()

    logger_file = log_file + '/' + str(timestamp) + '.log'

    config = None
    if name != '请选择':
        try:
            config = eval(
                models.Config.objects.get(name=name,
                                          project__id=api.project).body)

        except ObjectDoesNotExist:
            logger.error("指定配置文件不存在:{name}".format(name=name))
            return Response(config_err)

    if host != "请选择":
        host = models.HostIP.objects.get(
            name=host, project__id=api.project).value.splitlines()
        api.testcase = parse_host(host, api.testcase)
    try:
        summary = loader.debug_api(api.testcase,
                                   api.project,
                                   name=api.name,
                                   config=parse_host(host, config),
                                   user=request.user,
                                   log_file=logger_file)
        if summary is None:
            with open(logger_file, 'r') as r:
                msg = r.readlines()
            summary = msg
            return Response({"error": summary})
        return Response(summary)
    except Exception as e:
        return Response({"error": "404"})
    finally:
        '''删除调试脚本的日志文件'''
        delfile(logger_file)
    def update(self, request, **kwargs):
        """
        更新接口
        """
        pk = kwargs['rig_id']
        api = Format(request.data)
        api.parse()

        api_body = {
            'name': api.name,
            'body': api.testcase,
            'url': api.url,
            'method': api.method,
        }

        try:
            models.API.objects.filter(rig_id=pk).update(**api_body)
        except ObjectDoesNotExist:
            return Response(response.API_NOT_FOUND)
        return Response(response.API_UPDATE_SUCCESS)
Example #6
0
def run_api(request):
    """ run api by body
    """
    api = Format(request.data)
    api.parse()

    run_test_path = settings.RUN_TEST_PATH
    timedir = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime())
    projectPath = os.path.join(run_test_path, timedir)
    if ('debugtalk' in sys.modules.keys()):
        del sys.modules['debugtalk']
    create_scaffold(projectPath)
    debugApi = RunSingleApi(project=api.project,projectPath=projectPath,config=request.data['config'],
                apiBody=api.testcase,type="debugapi")

    debugApi.serializeTestCase()
    debugApi.serializeTestSuite()
    debugApi.serializeDebugtalk()
    debugApi.generateMapping()
    debugApi.run()
    return Response(debugApi.summary)
Example #7
0
    def update(self, request, **kwargs):
        """
        更新接口
        更新接口时同时更新testcase中的case_step的request和header
        """
        pk = kwargs['pk']
        api = Format(request.data)
        api.parse()

        api_body = {
            'name': api.name,
            'body': api.testcase,
            'url': api.url,
            'method': api.method,
        }

        try:
            models.API.objects.filter(id=pk).update(**api_body)
            case_step = models.CaseStep.objects.filter(apiId=pk)
            for case in case_step:
                csae_body = eval(case.body)
                csae_body["request"] = api_body["body"]["request"]
                csae_body["desc"]["header"] = api_body["body"]["desc"][
                    "header"]
                csae_body["desc"]["data"] = api_body["body"]["desc"]["data"]
                csae_body["desc"]["files"] = api_body["body"]["desc"]["files"]
                csae_body["desc"]["params"] = api_body["body"]["desc"][
                    "params"]

                case.url = api_body["url"]
                case.method = api_body["method"]
                case.body = csae_body
                case.save()

        except ObjectDoesNotExist:
            return Response(response.API_NOT_FOUND)

        return Response(response.API_UPDATE_SUCCESS)
Example #8
0
def load_test(test):
    """
    format testcase
    """

    try:
        format_http = Format(test['newBody'])
        format_http.parse()
        testcase = format_http.testcase

    except KeyError:
        if 'case' in test.keys():
            case_step = models.CaseStep.objects.get(id=test['id'])
        else:
            case_step = models.API.objects.get(id=test['id'])

        testcase = eval(case_step.body)
        name = test['body']['name']

        if case_step.name != name:
            testcase['name'] = name

    return testcase
Example #9
0
    def add(self, request):
        """
        新增一个接口
        """

        api = Format(request.data)
        api.parse()

        api_body = {
            'name': api.name,
            'body': api.testcase,
            'url': api.url,
            'method': api.method,
            'project': models.Project.objects.get(id=api.project),
            'relation': api.relation
        }

        try:
            models.API.objects.create(**api_body)
        except DataError:
            return Response(response.DATA_TO_LONG)

        return Response(response.API_ADD_SUCCESS)
Example #10
0
def run_api(request):
    """ run api by body
    """
    name = request.data.pop('config')
    host = request.data.pop("host")
    api = Format(request.data)
    api.parse()

    config = None
    if name != '请选择':
        try:
            config = eval(models.Config.objects.get(name=name, project__id=api.project).body)

        except ObjectDoesNotExist:
            logger.error("指定配置文件不存在:{name}".format(name=name))
            return Response(config_err)

    if host != "请选择":
        host = models.HostIP.objects.get(name=host, project__id=api.project).value.splitlines()
        api.testcase = parse_host(host, api.testcase)

    summary = loader.debug_api(api.testcase, api.project, config=parse_host(host, config), report_name=api.name)

    return Response(summary)
Example #11
0
def update_casestep(body, case):
    step_list = list(models.CaseStep.objects.filter(case=case).values('id'))

    for index in range(len(body)):
        test = body[index]
        if 'newBody' in test.keys():
            format_http = Format(test['newBody'])
            format_http.parse()
            name = format_http.name
            new_body = format_http.testcase
            if 'case' in test.keys():
                case_step = models.CaseStep.objects.get(id=test['id'])
                api_id = case_step.apiId
            else:
                api_id = test['id']
            api = models.API.objects.get(id=api_id)
            url = api.url
            method = api.method
            api_body = eval(api.body)
            new_body["request"] = api_body["request"]
            new_body["desc"]["header"] = api_body["desc"]["header"]
            new_body["desc"]["data"] = api_body["desc"]["data"]
            new_body["desc"]["files"] = api_body["desc"]["files"]
            new_body["desc"]["params"] = api_body["desc"]["params"]

        else:
            if 'case' in test.keys():
                case_step = models.CaseStep.objects.get(id=test['id'])
                new_body = eval(case_step.body)
                if case_step.method != "config":
                    api_id = case_step.apiId
                    api = models.API.objects.get(id=api_id)
                    api_body = eval(api.body)
                    url = api.url
                    method = api.method
                    new_body["request"] = api_body["request"]
                    new_body["desc"]["header"] = api_body["desc"]["header"]
                    new_body["desc"]["data"] = api_body["desc"]["data"]
                    new_body["desc"]["files"] = api_body["desc"]["files"]
                    new_body["desc"]["params"] = api_body["desc"]["params"]
                else:
                    url = ""
                    method = "config"
                    api_id = 0
            elif test["body"]["method"] == "config":
                case_step = models.Config.objects.get(
                    name=test['body']['name'])
                new_body = eval(case_step.body)
                url = ""
                method = "config"
                api_id = 0
            else:
                case_step = models.API.objects.get(id=test['id'])
                new_body = eval(case_step.body)
                url = case_step.url
                method = case_step.method
                api_id = case_step.id

            name = test['body']['name']
            new_body['name'] = name

        kwargs = {
            "name": name,
            "body": new_body,
            "url": url,
            "method": method,
            "step": index,
            "apiId": api_id
        }
        if 'case' in test.keys():
            models.CaseStep.objects.filter(id=test['id']).update(**kwargs)
            step_list.remove({"id": test['id']})
        else:
            kwargs['case'] = case
            models.CaseStep.objects.create(**kwargs)

    #  去掉多余的step
    for content in step_list:
        models.CaseStep.objects.filter(id=content['id']).delete()
Example #12
0
def generate_casestep(body, case):
    """
    生成用例集步骤
    [{
        id: int,
        project: int,
        name: str
    }]

    """
    #  index也是case step的执行顺序

    for index in range(len(body)):

        test = body[index]
        try:
            format_http = Format(test['newBody'])
            format_http.parse()
            name = format_http.name
            new_body = format_http.testcase

            apiId = test['id']
            api = models.API.objects.get(id=apiId)
            url = api.url
            method = api.method
            new_body['name'] = name
            api_body = eval(api.body)
            new_body["request"] = api_body["request"]
            new_body["desc"]["header"] = api_body["desc"]["header"]
            new_body["desc"]["data"] = api_body["desc"]["data"]
            new_body["desc"]["files"] = api_body["desc"]["files"]
            new_body["desc"]["params"] = api_body["desc"]["params"]

        except KeyError:
            if test["body"]["method"] == "config":
                name = test["body"]["name"]
                method = test["body"]["method"]
                config = models.Config.objects.get(name=name)
                url = config.base_url
                new_body = eval(config.body)
                apiId = 0
            else:
                apiId = test['id']
                api = models.API.objects.get(id=apiId)
                url = api.url
                method = api.method
                new_body = eval(api.body)
                name = test['body']['name']
                new_body['name'] = name

        kwargs = {
            "name": name,
            "body": new_body,
            "url": url,
            "method": method,
            "step": index,
            "case": case,
            "apiId": apiId
        }

        models.CaseStep.objects.create(**kwargs)
    def add(self, request):
        """
        新增一个接口
        {
  "header": {
    "header": {
      "wb-token": "$wb_token"
    },
    "desc": {
      "wb-token": "用户登陆token"
    }
  },
  "request": {
    "form": {
      "data": {},
      "desc": {}
    },
    "json": {},
    "params": {
      "params": {
        "goodsCode": "42470"
      },
      "desc": {
        "goodsCode": "商品编码"
      }
    },
    "files": {
      "files": {},
      "desc": {}
    }
  },
  "extract": {
    "extract": [],
    "desc": {}
  },
  "validate": {
    "validate": [{"equals": ["content.info.error",0]}]
  },
  "variables": {
    "variables": [
      {
        "auth_type": "APP_MEMBER_AUTH"
      },
      {
        "rpc_Group": "wbiao.seller.prod"
      },
      {
        "rpc_Interface": "cn.wbiao.seller.api.GoodsDetailService"
      },
      {
        "params_type": "Key_Value"
      },
      {
        "author": "xuqirong"
      }
    ],
    "desc": {
      "auth_type": "认证类型",
      "rpc_Group": "RPC服务组",
      "rpc_Interface": "后端服务接口",
      "params_type": "入参数形式",
      "author": "作者"
    }
  },
  "hooks": {
    "setup_hooks": [
      "${get_sign($request,$auth_type)}"
    ],
    "teardown_hooks": []
  },
  "url": "/wxmp/mall/goods/detail/getRecommendGoodsList",
  "method": "GET",
  "name": "查询关联的商品推荐列表-小程序需签名",
  "times": 1,
  "nodeId": "member",
  "project": 5,
  "rig_id":200014
}
        """

        api = Format(request.data)
        api.parse()
        # try:
        #     rig_env = api.rig_env
        # except KeyError:
        #     # 不传环境,使用默认测试环境0
        #     rig_env = 0
        try:
            relation = API_RELATION[api.relation]
        except KeyError:
            relation = API_RELATION['default']

        if api.rig_id:
            api.name = api.name + '-' + str(api.rig_id)

        if api.rig_env == 0:
            api.name += '-测试'

        elif api.rig_env == 1:
            api.name += '-生产'
            # 生产环境比测试环境的关系节点大20
            relation += 20
        else:
            api.name += '-预发布'

        api.testcase['name'] = api.name
        api_body = {
            'name': api.name,
            'body': api.testcase,
            'url': api.url,
            'method': api.method,
            'project': models.Project.objects.get(id=api.project),
            # 'relation': api.relation,
            'rig_id': api.rig_id,
            'rig_env': api.rig_env,
            'relation': relation
        }
        # try:
        #     relation = API_RELATION[api.relation]
        # except KeyError:
        #     relation = API_RELATION['default']

        # api_body['relation'] = relation
        try:
            # 增加api之前先删除已经存在的相同id的除了手动调试成功的api
            models.API.objects.filter(
                rig_id=api.rig_id).filter(~Q(tag=1)).update(
                    delete=1, update_time=datetime.datetime.now())
            # 创建成功,返回对象,方便获取id
            obj = models.API.objects.create(**api_body)
        except DataError:
            return Response(response.DATA_TO_LONG)

        # api作者
        # 2019年10月22日 修复rig增加api运行失败时,没有复制api到Java同学项目
        author = api_body['body']['variables'][4]['author']
        self.copy_to_java(api.rig_id, author)

        # api运行成功,就自动增加到用例集里面
        run_result = run.auto_run_api_pk(config=api.rig_env, id=obj.id)
        if run_result == 'success':
            run.update_auto_case_step(**api_body)

        return Response(response.API_ADD_SUCCESS)
Example #14
0
        case = models.Case.objects. \
            filter(relation=node, project=project).values('id')

        for case_id in case:
            models.CaseStep.objects.filter(case__id=case_id['id']).delete()
            models.Case.objects.filter(id=case_id['id']).delete()


def update_casestep(body, case, username):
    step_list = list(models.CaseStep.objects.filter(case=case).values('id'))

    for index in range(len(body)):

        test = body[index]
        try:
            format_http = Format(test['newBody'])
            format_http.parse()
            name = format_http.name
            new_body = format_http.testcase
            url = format_http.url
            method = format_http.method

        except KeyError:
            if 'case' in test.keys():
                case_step = models.CaseStep.objects.get(id=test['id'])
            elif test["body"]["method"] == "config":
                case_step = models.Config.objects.get(
                    name=test['body']['name'])
            else:
                case_step = models.API.objects.get(id=test['id'])