def update(self, request, **kwargs): """ pk: int { name: str, base_url: str, variables: [] parameters: [] request: [] } } """ pk = kwargs['pk'] try: config = models.Config.objects.get(id=pk) except ObjectDoesNotExist: return Response(response.CONFIG_NOT_EXISTS) format = Format(request.data, level="config") format.parse() if models.Config.objects.exclude(id=pk).filter( name=format.name).first(): return Response(response.CONFIG_EXISTS) case_step = models.CaseStep.objects.filter(method="config", name=config.name) for case in case_step: case.name = format.name case.body = format.testcase case.save()
def load_test(test, project=None): """ format testcase """ try: format_http = Format(test['newBody']) format_http.parse() testcase = format_http.testcase except KeyError: if 'case' in test.keys(): if test["body"]["method"] == "config": case_step = models.Config.objects.get( name=test["body"]["name"], project=project) else: case_step = models.CaseStep.objects.get(id=test['id']) else: if test["body"]["method"] == "config": case_step = models.Config.objects.get( name=test["body"]["name"], project=project) 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
def add(self, request): """ add new config { name: str project: int body: dict } """ config = Format(request.data, level='config') config.parse() try: config.project = models.Project.objects.get(id=config.project) except ObjectDoesNotExist: return Response(response.PROJECT_NOT_EXISTS) if models.Config.objects.filter(name=config.name, project=config.project).first(): return Response(response.CONFIG_EXISTS) config_body = { "name": config.name, "base_url": config.base_url, "body": config.testcase, "project": config.project } models.Config.objects.create(**config_body) return Response(response.CONFIG_ADD_SUCCESS)
def add(self, request): """ api-新增一个api 前端按照格式组装好,注意body """ 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, 'creator': request.user.username } try: models.API.objects.create(**api_body) except DataError: return Response(response.DATA_TO_LONG) return Response(response.API_ADD_SUCCESS)
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, name=api.name, config=parse_host(host, config), user=request.user) return Response(summary)
def run_api(request): """ run api by body """ api = Format(request.data) api.parse() summary = loader.debug_api(api.testcase, api.project) return Response(summary)
def run_api(request): """ run api by body """ name = request.data.pop('config') host = request.data.pop("host") api = Format(request.data) api.parse() test_data = None if request.data["testDataExcel"] != '请选择' and request.data["testDataSheet"]: test_data = (request.data["testDataExcel"], request.data["testDataSheet"]) 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) temp_config = [] temp_baseurl = '' if host != "请选择": host = models.HostIP.objects.get(name=host, project=api.project) host_info = json.loads(host.hostInfo) temp_config.extend(host_info["variables"]) temp_baseurl = host.base_url if host.base_url else '' if config and host != "请选择": config["variables"].extend(temp_config) if temp_baseurl: config["request"]["base_url"] = temp_baseurl if not config and host != "请选择": config = { "variables": temp_config, "request": { "base_url": temp_baseurl } } # if host != "请选择": # try: # host = models.HostIP.objects.get(name=host, project__id=api.project).value.splitlines() # api.testcase = parse_host(host, api.testcase) # except ObjectDoesNotExist: # logger.error("指定域名不存在:{name}".format(name=host)) try: summary = loader.debug_api(api.testcase, api.project, config=parse_host(host, config), test_data=test_data) except Exception as e: return Response({'traceback': str(e)}, status=400) return Response(summary)
def run_api(request): """ run api by body and config """ config = request.data.pop("config") api = Format(request.data) api.parse() summary = loader.debug_api(api.testcase, config, api.project) return Response(summary)
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: 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) else: 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)
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']) 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']) new_body = eval(case_step.body) name = test['body']['name'] if case_step.name != name: new_body['name'] = name if test["body"]["method"] == "config": url = "" method = "config" else: 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 run_api(request): """ run api by body """ name = request.data.pop('config') api = Format(request.data) api.parse() config = None if name == '请选择' else eval( models.Config.objects.get(name=name).body) summary = loader.debug_api(api.testcase, api.project, config=config) return Response(summary)
def add(self, request): """添加或更新一个或多个接口 """ add_apis = [] if request.data.get("bulk_add"): project_id = int(request.data.get("project")) node_id = int(request.data.get("nodeId")) temps = request.data.get("interfaces", {}) for temp in temps.values(): id = temp.get('id', 0) temp.update({"project": project_id, "nodeId": node_id}) api = Format(temp) 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 } obj = models.API.objects.filter(id=id, relation=node_id, project=project_id) if obj: obj.update(**api_body) else: add_apis.append(models.API(**api_body)) else: 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 } add_apis.append(models.API(**api_body)) try: if len(add_apis): models.API.objects.bulk_create(add_apis) except DataError: return Response(response.DATA_TO_LONG) except Exception as e: return Response({"error": str(e)}) return Response(response.API_ADD_SUCCESS)
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())
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)
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)
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)
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
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']) new_body = eval(case_step.body)
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()
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)