diff --git a/api-test/backend/src/main/java/io/metersphere/api/dto/mock/RequestMockParams.java b/api-test/backend/src/main/java/io/metersphere/api/dto/mock/RequestMockParams.java index 62df5fc401..972da0d5a0 100644 --- a/api-test/backend/src/main/java/io/metersphere/api/dto/mock/RequestMockParams.java +++ b/api-test/backend/src/main/java/io/metersphere/api/dto/mock/RequestMockParams.java @@ -2,7 +2,7 @@ package io.metersphere.api.dto.mock; import lombok.Getter; import lombok.Setter; -import org.json.JSONArray; +import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; /** @@ -12,30 +12,31 @@ import org.json.JSONObject; @Getter @Setter public class RequestMockParams { + private boolean isPost; + private String paramType; private JSONObject restParamsObj; - private JSONObject queryParamsObj; - private JSONArray bodyParams; - public JSONObject getParamsObj() { - JSONObject returnObj = new JSONObject(); - if (restParamsObj != null) { - for (String key : restParamsObj.keySet()) { - Object value = restParamsObj.get(key); - returnObj.put(key, value); - } - } - if (queryParamsObj != null) { - for (String key : queryParamsObj.keySet()) { - Object value = queryParamsObj.get(key); - returnObj.put(key, value); - } - } - return returnObj; - } + //form-data的kv类型参数也存储在queryParamObj中 + private JSONObject queryParamsObj; + + //JSONArray 或 JSONObject + private Object jsonParam; + + private JSONObject xmlToJsonParam; + + + private String raw; + public boolean isEmpty() { - return (restParamsObj == null || restParamsObj == null) && - (queryParamsObj == null || queryParamsObj == null) && - (bodyParams == null || bodyParams == null); + if (isPost) { + return (restParamsObj == null || restParamsObj.isEmpty()) && + (queryParamsObj == null || queryParamsObj.isEmpty()) + && StringUtils.isBlank(raw); + } else { + return (restParamsObj == null || restParamsObj.isEmpty()) && + (queryParamsObj == null || queryParamsObj.isEmpty()); + } + } } diff --git a/api-test/backend/src/main/java/io/metersphere/commons/enums/MockRequestType.java b/api-test/backend/src/main/java/io/metersphere/commons/enums/MockRequestType.java new file mode 100644 index 0000000000..0c6ec0f727 --- /dev/null +++ b/api-test/backend/src/main/java/io/metersphere/commons/enums/MockRequestType.java @@ -0,0 +1,5 @@ +package io.metersphere.commons.enums; + +public enum MockRequestType { + JSON, KV, XML, RAW +} diff --git a/api-test/backend/src/main/java/io/metersphere/commons/utils/mock/MockApiUtils.java b/api-test/backend/src/main/java/io/metersphere/commons/utils/mock/MockApiUtils.java index 079a3f56bd..820280eb21 100644 --- a/api-test/backend/src/main/java/io/metersphere/commons/utils/mock/MockApiUtils.java +++ b/api-test/backend/src/main/java/io/metersphere/commons/utils/mock/MockApiUtils.java @@ -8,6 +8,7 @@ import io.metersphere.api.exec.generator.JSONSchemaGenerator; import io.metersphere.commons.constants.ElementConstants; import io.metersphere.commons.constants.PropertyConstant; import io.metersphere.commons.enums.MockParamConditionEnums; +import io.metersphere.commons.enums.MockRequestType; import io.metersphere.commons.exception.MSException; import io.metersphere.commons.utils.*; import io.metersphere.jmeter.utils.ScriptEngineUtils; @@ -288,13 +289,7 @@ public class MockApiUtils { } } - if (headerMap == null) { - headerMap = new HashMap<>(); - } - if (requestMockParams == null) { - requestMockParams = new RequestMockParams(); - } - if (bodyObj == null && bodyObj == null) { + if (bodyObj == null || bodyObj.isEmpty()) { return StringUtils.EMPTY; } else { String returnStr = StringUtils.EMPTY; @@ -321,8 +316,7 @@ public class MockApiUtils { } } else if (StringUtils.equalsAnyIgnoreCase(type, "Raw")) { if (bodyObj.has("raw")) { - String raw = bodyObj.optString("raw"); - returnStr = raw; + returnStr = bodyObj.optString("raw"); } } else if (StringUtils.equalsAnyIgnoreCase(type, "XML")) { if (bodyObj.has("xmlHeader")) { @@ -339,8 +333,7 @@ public class MockApiUtils { } } else if (StringUtils.equalsAnyIgnoreCase(type, "fromApi")) { if (bodyObj.has("apiRspRaw")) { - String raw = bodyObj.optString("apiRspRaw"); - returnStr = raw; + returnStr = bodyObj.optString("apiRspRaw"); } } } @@ -351,67 +344,21 @@ public class MockApiUtils { } } - public static RequestMockParams getParams(String urlParams, String apiPath, JSONObject queryParamsObject, Object paramJson, boolean isPostRequest) { - RequestMockParams returnParams = getGetParamMap(urlParams, apiPath, queryParamsObject, isPostRequest); - if (paramJson != null) { - if (paramJson instanceof JSONObject) { - if (!((JSONObject) paramJson).keySet().isEmpty()) { - JSONArray bodyParams = returnParams.getBodyParams(); - if (bodyParams == null) { - bodyParams = new JSONArray(); - bodyParams.put(paramJson); - } else { - JSONArray oldArray = returnParams.getBodyParams(); - if (!JsonStructUtils.checkJsonArrayCompliance(oldArray, ((JSONObject) paramJson))) { - bodyParams.put(((JSONObject) paramJson)); - } - } - returnParams.setBodyParams(bodyParams); - } - } else if (paramJson instanceof JSONArray) { - JSONArray paramArray = (JSONArray) paramJson; - if (paramArray != null) { - returnParams.setBodyParams(paramArray); - } - } - } - return returnParams; - } - - public static JSONObject getParameterJsonObject(HttpServletRequest request) { - JSONObject queryParamsObject = new JSONObject(); - Enumeration paramNameItor = request.getParameterNames(); - while (paramNameItor.hasMoreElements()) { - String key = paramNameItor.nextElement(); - String value = request.getParameter(key); - queryParamsObject.put(key, value); - } - return queryParamsObject; - } - - private static RequestMockParams getGetParamMap(String urlParams, String apiPath, JSONObject queryParamsObject, boolean isPostRequest) { - RequestMockParams requestMockParams = new RequestMockParams(); - + public static void complementRestParam(String urlParams, String apiPath, RequestMockParams requestMockParams) { JSONObject urlParamsObject = getSendRestParamMapByIdAndUrl(apiPath, urlParams); - requestMockParams.setRestParamsObj(urlParamsObject); - requestMockParams.setQueryParamsObj(queryParamsObject); - - if (isPostRequest && !queryParamsObject.keySet().isEmpty()) { - JSONArray jsonArray = new JSONArray(); - if (queryParamsObject.length() != 0) { - jsonArray.put(queryParamsObject); - } - requestMockParams.setBodyParams(jsonArray); - } - return requestMockParams; } - public static Object getPostParamMap(HttpServletRequest request) { + public static RequestMockParams genRequestMockParamsFromHttpRequest(HttpServletRequest request, boolean isPost) { + RequestMockParams mockParams = new RequestMockParams(); + mockParams.setPost(isPost); + if (StringUtils.startsWithIgnoreCase(request.getContentType(), "application/JSON")) { + mockParams.setParamType(MockRequestType.JSON.name()); Object returnJson = null; try { String param = getRequestPostStr(request); + mockParams.setRaw(param); if (StringUtils.isNotEmpty(param)) { JSONValidator jsonValidator = JSONValidator.from(param); if (StringUtils.equalsIgnoreCase(PropertyConstant.ARRAY, jsonValidator.getType().name())) { @@ -420,39 +367,52 @@ public class MockApiUtils { returnJson = JSONUtil.parseObject(param); } } + mockParams.setJsonParam(returnJson); } catch (Exception e) { LogUtil.error(e); } - return returnJson; } else if (StringUtils.startsWithIgnoreCase(request.getContentType(), "text/xml")) { + mockParams.setParamType(MockRequestType.XML.name()); String xmlString = readXml(request); - JSONObject object = XMLUtil.xmlStringToJSONObject(xmlString); - return object; + JSONObject xmlJsonObject = XMLUtil.xmlStringToJSONObject(xmlString); + mockParams.setXmlToJsonParam(xmlJsonObject); + mockParams.setRaw(xmlString); } else if (StringUtils.startsWithIgnoreCase(request.getContentType(), "application/x-www-form-urlencoded")) { + mockParams.setParamType(MockRequestType.KV.name()); JSONObject object = new JSONObject(); - Enumeration paramNameItor = request.getParameterNames(); - while (paramNameItor.hasMoreElements()) { - String key = paramNameItor.nextElement(); + Enumeration paramNameItr = request.getParameterNames(); + while (paramNameItr.hasMoreElements()) { + String key = paramNameItr.nextElement(); String value = request.getParameter(key); object.put(key, value); } - return object; + mockParams.setQueryParamsObj(object); } else if (StringUtils.startsWithIgnoreCase(request.getContentType(), "text/plain")) { - JSONObject object = new JSONObject(); + mockParams.setParamType(MockRequestType.RAW.name()); String bodyParam = readBody(request); if (StringUtils.isNotEmpty(bodyParam)) { - object.put("raw", bodyParam); + mockParams.setRaw(bodyParam); } - return object; - - } else { - JSONObject object = new JSONObject(); + } else if (isPost) { String bodyParam = readBody(request); if (StringUtils.isNotEmpty(bodyParam)) { - object.put("raw", bodyParam); + mockParams.setParamType(MockRequestType.RAW.name()); + mockParams.setRaw(bodyParam); } - return object; } + + if (!StringUtils.equals(mockParams.getParamType(), MockRequestType.KV.name())) { + //非kv类型的请求要检查一下是否带有其它kv参数 + JSONObject object = new JSONObject(); + Enumeration paramNameItr = request.getParameterNames(); + while (paramNameItr.hasMoreElements()) { + String key = paramNameItr.nextElement(); + String value = request.getParameter(key); + object.put(key, value); + } + mockParams.setQueryParamsObj(object); + } + return mockParams; } private static JSONObject getSendRestParamMapByIdAndUrl(String path, String urlParams) { diff --git a/api-test/backend/src/main/java/io/metersphere/commons/utils/mock/MockScriptEngineUtils.java b/api-test/backend/src/main/java/io/metersphere/commons/utils/mock/MockScriptEngineUtils.java index a263fb7880..f848719e12 100644 --- a/api-test/backend/src/main/java/io/metersphere/commons/utils/mock/MockScriptEngineUtils.java +++ b/api-test/backend/src/main/java/io/metersphere/commons/utils/mock/MockScriptEngineUtils.java @@ -3,6 +3,7 @@ package io.metersphere.commons.utils.mock; import io.metersphere.api.dto.mock.RequestMockParams; import io.metersphere.commons.constants.ElementConstants; +import io.metersphere.commons.enums.MockRequestType; import io.metersphere.commons.utils.CommonBeanFactory; import io.metersphere.commons.utils.JSON; import io.metersphere.commons.utils.JSONUtil; @@ -15,9 +16,6 @@ import org.json.JSONObject; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -48,24 +46,6 @@ public class MockScriptEngineUtils { } } - public void loadJar(String jarPath) throws Exception { - try { - ClassLoader classLoader = ClassLoader.getSystemClassLoader(); - try { - Method method = classLoader.getClass().getDeclaredMethod("addURL", URL.class); - method.setAccessible(true); - method.invoke(classLoader, new File(jarPath).toURI().toURL()); - } catch (NoSuchMethodException e) { - Method method = classLoader.getClass() - .getDeclaredMethod("appendToClassPathForInstrumentation", String.class); - method.setAccessible(true); - method.invoke(classLoader, jarPath); - } - } catch (Exception e) { - LogUtil.error(e); - } - } - /** * 加载jar包 */ @@ -96,9 +76,12 @@ public class MockScriptEngineUtils { engine = scriptEngineFactory.getEngineByName(scriptLanguage); preScript = this.genPythonPreScript(url, headerMap, requestMockParams); } - MsDynamicClassLoader loader = MsClassLoader.loadJar(getJarPaths(projectId)); - Thread.currentThread().setContextClassLoader(loader); - engine.eval(preScript); + + if (engine != null) { + MsDynamicClassLoader loader = MsClassLoader.loadJar(getJarPaths(projectId)); + Thread.currentThread().setContextClassLoader(loader); + engine.eval(preScript); + } } catch (Exception e) { LogUtil.error(e); } @@ -106,9 +89,9 @@ public class MockScriptEngineUtils { } private String genBeanshellPreScript(String url, Map headerMap, RequestMockParams requestMockParams) { - StringBuffer preScriptBuffer = new StringBuffer(); + StringBuilder preScriptBuffer = new StringBuilder(); preScriptBuffer.append("Map vars = new HashMap();\n"); - preScriptBuffer.append("vars.put(\"address\",\"" + url + "\");\n"); + preScriptBuffer.append("vars.put(\"address\",\"").append(url).append("\");\n"); //写入请求头 if (headerMap != null) { for (Map.Entry headEntry : headerMap.entrySet()) { @@ -116,48 +99,53 @@ public class MockScriptEngineUtils { String headerValue = headEntry.getValue(); headerKey = StringUtils.replace(headerKey, "\\", "\\\\").replace("\"", "\\\""); headerValue = StringUtils.replace(headerValue, "\\", "\\\\").replace("\"", "\\\""); - preScriptBuffer.append("vars.put(\"header." + headerKey + "\",\"" + headerValue + "\");\n"); + preScriptBuffer.append("vars.put(\"header.").append(headerKey).append("\",\"").append(headerValue).append("\");\n"); } } - //写入body参数 if (requestMockParams != null) { - if (requestMockParams.getBodyParams() != null) { - if (requestMockParams.getBodyParams().length() == 1) { - //参数是jsonObject - JSONObject bodyParamObj = requestMockParams.getBodyParams().optJSONObject(0); - for (String key : bodyParamObj.keySet()) { - String value = String.valueOf(bodyParamObj.get(key)); - value = StringUtils.replace(value, "\\", "\\\\"); - value = StringUtils.replace(value, "\"", "\\\""); + //写入body参数 + if (requestMockParams.isPost()) { + if (requestMockParams.getQueryParamsObj() != null) { + JSONObject queryParamsObj = requestMockParams.getQueryParamsObj(); + for (String key : queryParamsObj.keySet()) { + String value = String.valueOf(queryParamsObj.get(key)); + value = StringUtils.replace(value, "\\", "\\\\").replace("\"", "\\\""); key = StringUtils.replace(key, "\\", "\\\\").replace("\"", "\\\""); - preScriptBuffer.append("vars.put(\"body." + key + "\",\"" + value + "\");\n"); - if (StringUtils.equalsIgnoreCase(key, "raw")) { - preScriptBuffer.append("vars.put(\"bodyRaw\",\"" + value + "\");\n"); - } + preScriptBuffer.append("vars.put(\"body.").append(key).append("\",\"").append(value).append("\");\n"); } - String jsonBody = bodyParamObj.toString(); + } + if (StringUtils.equals(requestMockParams.getParamType(), MockRequestType.JSON.name())) { + String jsonBody = requestMockParams.getRaw(); + jsonBody = StringUtils.replace(jsonBody, "\n", ""); jsonBody = StringUtils.replace(jsonBody, "\\", "\\\\"); jsonBody = StringUtils.replace(jsonBody, "\"", "\\\""); - preScriptBuffer.append("vars.put(\"body.json\",\"" + jsonBody + "\");\n"); - } else { - String bodyRowString = requestMockParams.getBodyParams().toString(); + preScriptBuffer.append("vars.put(\"body.json\",\"").append(jsonBody).append("\");\n"); + } else if (StringUtils.equals(requestMockParams.getParamType(), MockRequestType.XML.name())) { + String xmlRaw = requestMockParams.getRaw(); + xmlRaw = StringUtils.chomp(xmlRaw); + xmlRaw = StringUtils.replace(xmlRaw, "\n", ""); + xmlRaw = StringUtils.replace(xmlRaw, "\\", "\\\\"); + xmlRaw = StringUtils.replace(xmlRaw, "\"", "\\\""); + preScriptBuffer.append("vars.put(\"body.xml\",\"").append(xmlRaw).append("\");\n"); + } else if (StringUtils.equals(requestMockParams.getParamType(), MockRequestType.RAW.name())) { + String bodyRowString = requestMockParams.getRaw(); bodyRowString = StringUtils.replace(bodyRowString, "\\", "\\\\").replace("\"", "\\\""); - preScriptBuffer.append("vars.put(\"bodyRaw\",\"" + bodyRowString + "\");\n"); + preScriptBuffer.append("vars.put(\"bodyRaw\",\"").append(bodyRowString).append("\");\n"); } - } + //写入query参数 - if (requestMockParams.getQueryParamsObj() != null) { + if (!requestMockParams.isPost() && requestMockParams.getQueryParamsObj() != null) { JSONObject queryParamsObj = requestMockParams.getQueryParamsObj(); for (String key : queryParamsObj.keySet()) { String value = String.valueOf(queryParamsObj.get(key)); - value = StringUtils.replace(value, "\\", "\\\\"); - value = StringUtils.replace(value, "\"", "\\\""); + value = StringUtils.replace(value, "\\", "\\\\").replace("\"", "\\\""); key = StringUtils.replace(key, "\\", "\\\\").replace("\"", "\\\""); - preScriptBuffer.append("vars.put(\"query." + key + "\",\"" + value + "\");\n"); + preScriptBuffer.append("vars.put(\"query.").append(key).append("\",\"").append(value).append("\");\n"); } } + //写入rest参数 if (requestMockParams.getRestParamsObj() != null) { JSONObject restParamsObj = requestMockParams.getRestParamsObj(); @@ -166,7 +154,7 @@ public class MockScriptEngineUtils { key = StringUtils.replace(key, "\"", "\\\""); value = StringUtils.replace(value, "\"", "\\\""); key = StringUtils.replace(key, "\\", "\\\\").replace("\"", "\\\""); - preScriptBuffer.append("vars.put(\"rest." + key + "\",\"" + value + "\");\n"); + preScriptBuffer.append("vars.put(\"rest.").append(key).append("\",\"").append(value).append("\");\n"); } } } @@ -174,61 +162,70 @@ public class MockScriptEngineUtils { } private String genPythonPreScript(String url, Map headerMap, RequestMockParams requestMockParams) { - StringBuffer preScriptBuffer = new StringBuffer(); + StringBuilder preScriptBuffer = new StringBuilder(); preScriptBuffer.append("vars = {}; \n"); - preScriptBuffer.append("vars[\"address\"]=\"" + url + "\";\n"); + preScriptBuffer.append("vars[\"address\"]=\"").append(url).append("\";\n"); //写入请求头 for (Map.Entry headEntry : headerMap.entrySet()) { String headerKey = headEntry.getKey(); String headerValue = headEntry.getValue(); headerKey = StringUtils.replace(headerKey, "\\", "\\\\").replace("\"", "\\\""); headerValue = StringUtils.replace(headerValue, "\\", "\\\\").replace("\"", "\\\""); - preScriptBuffer.append("vars[\"header." + headerKey + "\"]=\"" + headerValue + "\";\n"); + preScriptBuffer.append("vars[\"header.").append(headerKey).append("\"]=\"").append(headerValue).append("\";\n"); } - //写入body参数 - if (requestMockParams.getBodyParams() != null) { - if (requestMockParams.getBodyParams().length() == 1) { - //参数是jsonObject - JSONObject bodyParamObj = requestMockParams.getBodyParams().optJSONObject(0); - for (String key : bodyParamObj.keySet()) { - String value = String.valueOf(bodyParamObj.get(key)); - value = StringUtils.replace(value, "\\", "\\\\"); - value = StringUtils.replace(value, "\"", "\\\""); - key = StringUtils.replace(key, "\\", "\\\\").replace("\"", "\\\""); - preScriptBuffer.append("vars[\"body." + key + "\"]=\"" + value + "\";\n"); - if (StringUtils.equalsIgnoreCase(key, "raw")) { - preScriptBuffer.append("vars[\"bodyRaw\"]=\"" + value + "\";\n"); + if (requestMockParams != null) { + //写入body参数 + if (requestMockParams.isPost()) { + if (requestMockParams.getQueryParamsObj() != null) { + JSONObject queryParamsObj = requestMockParams.getQueryParamsObj(); + for (String key : queryParamsObj.keySet()) { + String value = String.valueOf(queryParamsObj.get(key)); + value = StringUtils.replace(value, "\\", "\\\\").replace("\"", "\\\""); + key = StringUtils.replace(key, "\\", "\\\\").replace("\"", "\\\""); + preScriptBuffer.append("vars[\"body.").append(key).append("\"]=\"").append(value).append("\";\n"); } } - String jsonBody = bodyParamObj.toString(); - jsonBody = StringUtils.replace(jsonBody, "\\", "\\\\"); - jsonBody = StringUtils.replace(jsonBody, "\"", "\\\""); - preScriptBuffer.append("vars[\"body.json\"]=\"" + jsonBody + "\";\n"); - } else { - String bodyRaw = StringUtils.replace(requestMockParams.getBodyParams().toString(), "\\", "\\\\").replace("\"", "\\\""); - preScriptBuffer.append("vars[\"bodyRaw\"]=\"" + bodyRaw + "\";\n"); + if (StringUtils.equals(requestMockParams.getParamType(), MockRequestType.JSON.name())) { + String jsonRaw = requestMockParams.getRaw(); + jsonRaw = StringUtils.chomp(jsonRaw); + jsonRaw = StringUtils.replace(jsonRaw, "\n", ""); + jsonRaw = StringUtils.replace(jsonRaw, "\\", "\\\\"); + jsonRaw = StringUtils.replace(jsonRaw, "\"", "\\\""); + preScriptBuffer.append("vars[\"body.json\"]=\"").append(jsonRaw).append("\";\n"); + } else if (StringUtils.equals(requestMockParams.getParamType(), MockRequestType.XML.name())) { + String xmlRaw = requestMockParams.getRaw(); + xmlRaw = StringUtils.chomp(xmlRaw); + xmlRaw = StringUtils.replace(xmlRaw, "\n", ""); + xmlRaw = StringUtils.replace(xmlRaw, "\\", "\\\\"); + xmlRaw = StringUtils.replace(xmlRaw, "\"", "\\\""); + preScriptBuffer.append("vars[\"body.xml\"]=\"").append(xmlRaw).append("\";\n"); + } else if (StringUtils.equals(requestMockParams.getParamType(), MockRequestType.RAW.name())) { + String bodyRowString = requestMockParams.getRaw(); + bodyRowString = StringUtils.replace(bodyRowString, "\\", "\\\\").replace("\"", "\\\""); + preScriptBuffer.append("vars[\"bodyRaw\"]=\"").append(bodyRowString).append("\";\n"); + } } - } - //写入query参数 - if (requestMockParams.getQueryParamsObj() != null) { - JSONObject queryParamsObj = requestMockParams.getQueryParamsObj(); - for (String key : queryParamsObj.keySet()) { - String value = String.valueOf(queryParamsObj.get(key)); - value = StringUtils.replace(value, "\\", "\\\\"); - value = StringUtils.replace(value, "\"", "\\\""); - key = StringUtils.replace(key, "\\", "\\\\").replace("\"", "\\\""); - preScriptBuffer.append("vars[\"query." + key + "\"]=\"" + value + "\";\n"); + //写入query参数 + if (!requestMockParams.isPost() && requestMockParams.getQueryParamsObj() != null) { + JSONObject queryParamsObj = requestMockParams.getQueryParamsObj(); + for (String key : queryParamsObj.keySet()) { + String value = String.valueOf(queryParamsObj.get(key)); + value = StringUtils.replace(value, "\\", "\\\\").replace("\"", "\\\""); + key = StringUtils.replace(key, "\\", "\\\\").replace("\"", "\\\""); + preScriptBuffer.append("vars[\"query.").append(key).append("\"]=\"").append(value).append("\";\n"); + } } - } - //写入rest参数 - if (requestMockParams.getRestParamsObj() != null) { - JSONObject restParamsObj = requestMockParams.getRestParamsObj(); - for (String key : restParamsObj.keySet()) { - String value = String.valueOf(restParamsObj.get(key)); - key = StringUtils.replace(key, "\\", "\\\\").replace("\"", "\\\""); - value = StringUtils.replace(value, "\\", "\\\\").replace("\"", "\\\""); - preScriptBuffer.append("vars[\"rest." + key + "\"]=\"" + value + "\";\n"); + + //写入rest参数 + if (requestMockParams.getRestParamsObj() != null) { + JSONObject restParamsObj = requestMockParams.getRestParamsObj(); + for (String key : restParamsObj.keySet()) { + String value = String.valueOf(restParamsObj.get(key)); + key = StringUtils.replace(key, "\\", "\\\\").replace("\"", "\\\""); + value = StringUtils.replace(value, "\\", "\\\\").replace("\"", "\\\""); + preScriptBuffer.append("vars[\"rest.").append(key).append("\"]=\"").append(value).append("\";\n"); + } } } return preScriptBuffer.toString(); diff --git a/api-test/backend/src/main/java/io/metersphere/controller/mock/MockConfigController.java b/api-test/backend/src/main/java/io/metersphere/controller/mock/MockConfigController.java index 4a6048bcc9..c0fec6403b 100644 --- a/api-test/backend/src/main/java/io/metersphere/controller/mock/MockConfigController.java +++ b/api-test/backend/src/main/java/io/metersphere/controller/mock/MockConfigController.java @@ -8,15 +8,13 @@ import io.metersphere.api.dto.mock.config.MockConfigRequest; import io.metersphere.api.dto.mock.config.MockExpectConfigRequest; import io.metersphere.api.dto.mock.config.response.MockConfigResponse; import io.metersphere.api.dto.mock.config.response.MockExpectConfigResponse; -import io.metersphere.commons.constants.NoticeConstants; -import io.metersphere.commons.utils.mock.MockApiUtils; -import io.metersphere.commons.utils.mock.MockTestDataUtil; -import io.metersphere.notice.annotation.SendNotice; -import io.metersphere.service.definition.ApiDefinitionService; -import io.metersphere.service.MockConfigService; import io.metersphere.base.domain.ApiDefinitionWithBLOBs; import io.metersphere.base.domain.MockExpectConfig; import io.metersphere.base.domain.MockExpectConfigWithBLOBs; +import io.metersphere.commons.utils.mock.MockApiUtils; +import io.metersphere.commons.utils.mock.MockTestDataUtil; +import io.metersphere.service.MockConfigService; +import io.metersphere.service.definition.ApiDefinitionService; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -30,7 +28,7 @@ import java.util.Map; * @Description */ @RestController -@RequestMapping("/mock/config") +@RequestMapping("/mock-config") public class MockConfigController { @Resource diff --git a/api-test/backend/src/main/java/io/metersphere/service/MockConfigService.java b/api-test/backend/src/main/java/io/metersphere/service/MockConfigService.java index c7775dc467..94ebe95234 100644 --- a/api-test/backend/src/main/java/io/metersphere/service/MockConfigService.java +++ b/api-test/backend/src/main/java/io/metersphere/service/MockConfigService.java @@ -105,7 +105,7 @@ public class MockConfigService { } } - private MockConfigResponse assemblyMockConfingResponse(List configList) { + private MockConfigResponse assemblyMockConingResponse(List configList) { if (!configList.isEmpty()) { MockConfig config = configList.get(0); MockExpectConfigExample expectConfigExample = new MockExpectConfigExample(); @@ -131,9 +131,6 @@ public class MockConfigService { * 如果没数据就生成,有数据就返回一套数据结构! * 所有入参都没有必填项! * 如果为了查询,请写一个新的接口! - * - * @param request - * @return */ public MockConfigResponse genMockConfig(MockConfigRequest request) { MockConfigResponse returnRsp; @@ -153,46 +150,35 @@ public class MockConfigService { List configList = mockConfigMapper.selectByExample(example); if (configList.isEmpty()) { - long createTimeStmp = System.currentTimeMillis(); + long createTimeLong = System.currentTimeMillis(); MockConfig config = new MockConfig(); config.setProjectId(request.getProjectId()); config.setId(UUID.randomUUID().toString()); config.setCreateUserId(SessionUtils.getUserId()); - config.setCreateTime(createTimeStmp); - config.setUpdateTime(createTimeStmp); + config.setCreateTime(createTimeLong); + config.setUpdateTime(createTimeLong); if (request.getApiId() != null) { config.setApiId(request.getApiId()); mockConfigMapper.insert(config); } returnRsp = new MockConfigResponse(config, new ArrayList<>()); } else { - MockConfig config = configList.get(0); - MockExpectConfigExample expectConfigExample = new MockExpectConfigExample(); - expectConfigExample.createCriteria().andMockConfigIdEqualTo(config.getId()); - expectConfigExample.setOrderByClause("update_time DESC"); - - List expectConfigResponseList = new ArrayList<>(); - - List expectConfigList = mockExpectConfigMapper.selectByExampleWithBLOBs(expectConfigExample); - for (MockExpectConfigWithBLOBs expectConfig : expectConfigList) { - MockExpectConfigResponse response = new MockExpectConfigResponse(expectConfig); - expectConfigResponseList.add(response); - - } - returnRsp = new MockConfigResponse(config, expectConfigResponseList); + returnRsp = this.assemblyMockConingResponse(configList); } - return returnRsp; } + public void sendMockNotice(MockExpectConfigWithBLOBs mockExpectConfigWithBLOBs, String defaultContext, String event) { - String context = SessionUtils.getUserId().concat(defaultContext).concat(":").concat(mockExpectConfigWithBLOBs.getName()); - Map paramMap = new HashMap<>(); - MockConfig mockConfig = mockConfigMapper.selectByPrimaryKey(mockExpectConfigWithBLOBs.getMockConfigId()); - getParamMap(paramMap, SessionUtils.getUserId(), mockExpectConfigWithBLOBs, mockConfig); - NoticeModel noticeModel = NoticeModel.builder().operator(SessionUtils.getUserId()).context(context).testId(mockExpectConfigWithBLOBs.getId()).subject("接口定义通知").paramMap(paramMap).excludeSelf(true).event(event).build(); - noticeSendService.send(NoticeConstants.TaskType.API_DEFINITION_TASK, noticeModel); + if (SessionUtils.getUserId() != null) { + String context = SessionUtils.getUserId().concat(defaultContext).concat(":").concat(mockExpectConfigWithBLOBs.getName()); + Map paramMap = new HashMap<>(); + MockConfig mockConfig = mockConfigMapper.selectByPrimaryKey(mockExpectConfigWithBLOBs.getMockConfigId()); + getParamMap(paramMap, SessionUtils.getUserId(), mockExpectConfigWithBLOBs, mockConfig); + NoticeModel noticeModel = NoticeModel.builder().operator(SessionUtils.getUserId()).context(context).testId(mockExpectConfigWithBLOBs.getId()).subject("接口定义通知").paramMap(paramMap).excludeSelf(true).event(event).build(); + noticeSendService.send(NoticeConstants.TaskType.API_DEFINITION_TASK, noticeModel); + } } private void getParamMap(Map paramMap, String userId, MockExpectConfigWithBLOBs mockExpectConfigWithBLOBs, MockConfig mockConfig) { @@ -216,9 +202,9 @@ public class MockConfigService { public MockExpectConfig updateMockExpectConfigStatus(MockExpectConfigRequest request) { if (StringUtils.isNotEmpty(request.getId()) && StringUtils.isNotEmpty(request.getStatus())) { MockExpectConfigWithBLOBs model = new MockExpectConfigWithBLOBs(); - long timeStmp = System.currentTimeMillis(); + long timestamp = System.currentTimeMillis(); model.setId(request.getId()); - model.setUpdateTime(timeStmp); + model.setUpdateTime(timestamp); model.setStatus(request.getStatus()); mockExpectConfigMapper.updateByPrimaryKeySelective(model); sendMockNotice(model, "更新了mock", NoticeConstants.Event.MOCK_UPDATE); @@ -238,7 +224,7 @@ public class MockConfigService { if (request.getName() != null) { this.checkNameIsExists(request); } - long timeStmp = System.currentTimeMillis(); + long timestamp = System.currentTimeMillis(); MockExpectConfigWithBLOBs model = new MockExpectConfigWithBLOBs(); if (isSave) { String expectNum = this.getMockExpectId(request.getMockConfigId()); @@ -247,7 +233,7 @@ public class MockConfigService { model.setId(request.getId()); model.setMockConfigId(request.getMockConfigId()); - model.setUpdateTime(timeStmp); + model.setUpdateTime(timestamp); model.setStatus(request.getStatus()); if (request.getTags() != null) { model.setTags(JSON.toJSONString(request.getTags())); @@ -260,7 +246,7 @@ public class MockConfigService { model.setResponse(JSON.toJSONString(request.getResponse())); } if (isSave) { - model.setCreateTime(timeStmp); + model.setCreateTime(timestamp); model.setCreateUserId(SessionUtils.getUserId()); model.setStatus("true"); mockExpectConfigMapper.insert(model); @@ -321,7 +307,7 @@ public class MockConfigService { continue; } JSONObject requestObj = JSONUtil.parseObject(JSON.toJSONString(model.getRequest())); - MockExpectConfigResponse resultModel = null; + MockExpectConfigResponse resultModel; if (requestObj.has("params")) { resultModel = this.getEmptyRequestMockExpectByParams(requestHeaderMap, model); } else { @@ -340,13 +326,10 @@ public class MockConfigService { continue; } JSONObject mockExpectRequestObj = JSONUtil.parseObject(JSON.toJSONString(model.getRequest())); - boolean isMatch; + boolean isMatch = false; if (mockExpectRequestObj.has("params")) { isMatch = this.isRequestMockExpectMatchingByParams(requestHeaderMap, mockExpectRequestObj, requestMockParams); - } else { - isMatch = this.isRequestMockExpectMatching(mockExpectRequestObj, requestMockParams); } - if (isMatch) { returnModel = model; break; @@ -379,7 +362,6 @@ public class MockConfigService { if (expectParamsObj.has("body")) { JSONObject expectBodyObject = expectParamsObj.optJSONObject("body"); - JSONArray jsonArray = requestMockParams.getBodyParams(); String type = expectBodyObject.optString(PropertyConstant.TYPE); String paramsFilterType = "And"; if (expectBodyObject.has("paramsFilterType")) { @@ -389,11 +371,28 @@ public class MockConfigService { JSONArray kvsArr = expectBodyObject.optJSONArray("kvs"); List mockConfigRequestParams = MockApiUtils.getParamsByJSONArray(kvsArr); if (CollectionUtils.isNotEmpty(mockConfigRequestParams)) { - if (!MockApiUtils.checkParamsCompliance(jsonArray, mockConfigRequestParams, StringUtils.equals(paramsFilterType, "And"))) { + if (!MockApiUtils.checkParamsCompliance(requestMockParams.getQueryParamsObj(), mockConfigRequestParams, StringUtils.equals(paramsFilterType, "And"))) { return false; } } + } else if (StringUtils.equalsAnyIgnoreCase(type, "Raw") && expectBodyObject.has("raw")) { + String rawExpect = expectBodyObject.optString("raw"); + if (StringUtils.isEmpty(requestMockParams.getRaw()) || !StringUtils.contains(requestMockParams.getRaw(), rawExpect)) { + return false; + } } else { + JSONArray jsonArray = null; + if (StringUtils.equalsIgnoreCase(type, "xml") && requestMockParams.getXmlToJsonParam() != null) { + jsonArray = new JSONArray(); + jsonArray.put(requestMockParams.getXmlToJsonParam()); + } else if (StringUtils.equalsIgnoreCase(type, "json") && requestMockParams.getJsonParam() != null) { + if (requestMockParams.getJsonParam() instanceof JSONArray) { + jsonArray = (JSONArray) requestMockParams.getJsonParam(); + } else if (requestMockParams.getJsonParam() instanceof JSONObject) { + jsonArray = new JSONArray(); + jsonArray.put(requestMockParams.getJsonParam()); + } + } Object mockExpectJsonArray = MockApiUtils.getExpectBodyParams(expectBodyObject); if (mockExpectJsonArray instanceof JSONObject) { if (!JsonStructUtils.checkJsonArrayCompliance(jsonArray, (JSONObject) mockExpectJsonArray)) { @@ -427,69 +426,11 @@ public class MockConfigService { if (expectParamsObj.has("rest")) { JSONArray restArray = expectParamsObj.optJSONArray("rest"); List mockConfigRequestParams = MockApiUtils.getParamsByJSONArray(restArray); - if (!MockApiUtils.checkParamsCompliance(requestMockParams.getRestParamsObj(), mockConfigRequestParams, StringUtils.equals(restFilterType, "And"))) { - return false; - } + return MockApiUtils.checkParamsCompliance(requestMockParams.getRestParamsObj(), mockConfigRequestParams, StringUtils.equals(restFilterType, "And")); } return true; } - private boolean isRequestMockExpectMatching(JSONObject mockExpectRequestObj, RequestMockParams requestMockParams) { - boolean isJsonParam = mockExpectRequestObj.getBoolean("jsonParam"); - JSONObject mockExpectJson = new JSONObject(); - if (isJsonParam) { - String jsonParams = mockExpectRequestObj.optString("jsonData"); - JSONValidator jsonValidator = JSONValidator.from(jsonParams); - if (StringUtils.equalsIgnoreCase("Array", jsonValidator.getType().name())) { - JSONArray mockExpectArr = JSONUtil.parseArray(jsonParams); - for (int expectIndex = 0; expectIndex < mockExpectArr.length(); expectIndex++) { - JSONObject itemObj = mockExpectArr.optJSONObject(expectIndex); - mockExpectJson = itemObj; - } - } else if (StringUtils.equalsIgnoreCase("Object", jsonValidator.getType().name())) { - JSONObject mockExpectJsonItem = JSONUtil.parseObject(jsonParams); - mockExpectJson = mockExpectJsonItem; - } - } else { - JSONArray jsonArray = mockExpectRequestObj.optJSONArray("variables"); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject object = jsonArray.optJSONObject(i); - String name = StringUtils.EMPTY; - String value = StringUtils.EMPTY; - if (object.has("name")) { - name = String.valueOf(object.get("name")).trim(); - } - if (object.has("value")) { - value = String.valueOf(object.get("value")).trim(); - } - if (StringUtils.isNotEmpty(name)) { - mockExpectJson.put(name, value); - } - } - } - - boolean matchRest = false; - boolean matchQuery = false; - boolean matchBody = false; - - if (requestMockParams.getQueryParamsObj() != null) { - matchQuery = JsonStructUtils.checkJsonObjCompliance(requestMockParams.getQueryParamsObj(), mockExpectJson); - } - if (requestMockParams.getRestParamsObj() != null) { - matchRest = JsonStructUtils.checkJsonObjCompliance(requestMockParams.getRestParamsObj(), mockExpectJson); - } - if (requestMockParams.getBodyParams() != null) { - for (int i = 0; i < requestMockParams.getBodyParams().length(); i++) { - JSONObject reqJsonObj = requestMockParams.getBodyParams().optJSONObject(i); - matchBody = JsonStructUtils.checkJsonObjCompliance(reqJsonObj, mockExpectJson); - if (matchBody) { - break; - } - } - } - return matchRest || matchQuery || matchBody; - } - private MockExpectConfigResponse getEmptyRequestMockExpectByParams(Map requestHeaderMap, MockExpectConfigResponse model) { JSONObject requestObj = JSONUtil.parseObject(JSON.toJSONString(model.getRequest())); if (requestObj.has("params")) { @@ -632,14 +573,14 @@ public class MockConfigService { int httpCodeNum = 500; try { httpCodeNum = Integer.parseInt(responseJsonObj.optString("httpCode")); - } catch (Exception e) { + } catch (Exception ignored) { } response.setStatus(httpCodeNum); } if (responseJsonObj.has("delayed")) { try { sleepTime = Long.parseLong(String.valueOf(responseJsonObj.get("delayed"))); - } catch (Exception e) { + } catch (Exception ignored) { } } } else { @@ -662,14 +603,14 @@ public class MockConfigService { if (responseObj.has("delayed")) { try { sleepTime = Long.parseLong(String.valueOf(responseObj.get("delayed"))); - } catch (Exception e) { + } catch (Exception ignored) { } } } if (sleepTime > 0) { try { Thread.sleep(sleepTime); - } catch (Exception e) { + } catch (Exception ignored) { } } } catch (Exception e) { @@ -695,7 +636,7 @@ public class MockConfigService { if (mockExpectConfigWithBLOBs != null && StringUtils.isNotEmpty(mockExpectConfigWithBLOBs.getRequest())) { try { FileUtils.deleteBodyFiles(mockExpectConfigWithBLOBs.getId()); - } catch (Exception e) { + } catch (Exception ignored) { } } } @@ -708,8 +649,8 @@ public class MockConfigService { for (MockConfig mockConfig : mockConfigList) { example.clear(); example.createCriteria().andMockConfigIdEqualTo(mockConfig.getId()); - List deleteBolobs = mockExpectConfigMapper.selectByExampleWithBLOBs(example); - for (MockExpectConfigWithBLOBs model : deleteBolobs) { + List deleteBlobs = mockExpectConfigMapper.selectByExampleWithBLOBs(example); + for (MockExpectConfigWithBLOBs model : deleteBlobs) { this.deleteMockExpectFiles(model); } mockExpectConfigMapper.deleteByExample(example); @@ -771,11 +712,11 @@ public class MockConfigService { for (int index = 0; index < headArr.length(); index++) { JSONObject headObj = headArr.optJSONObject(index); - if (headObj.has("name") && !queryParamList.contains(headObj.has("name"))) { + if (headObj.has("name") && !queryParamList.contains(headObj.optString("name"))) { queryParamList.add(String.valueOf(headObj.get("name"))); } } - } catch (Exception e) { + } catch (Exception ignored) { } } if (requestObj.has("rest")) { @@ -783,11 +724,11 @@ public class MockConfigService { JSONArray headArr = requestObj.optJSONArray("rest"); for (int index = 0; index < headArr.length(); index++) { JSONObject headObj = headArr.optJSONObject(index); - if (headObj.has("name") && !restParamList.contains(headObj.has("name"))) { + if (headObj.has("name") && !restParamList.contains(headObj.optString("name"))) { restParamList.add(String.valueOf(headObj.get("name"))); } } - } catch (Exception e) { + } catch (Exception ignored) { } } //请求体参数类型 @@ -802,14 +743,14 @@ public class MockConfigService { JSONArray kvsArr = bodyObj.optJSONArray("kvs"); for (int i = 0; i < kvsArr.length(); i++) { JSONObject kv = kvsArr.optJSONObject(i); - if (kv.has("name") && !formDataList.contains(kv.has("name"))) { + if (kv.has("name") && !formDataList.contains(kv.optString("name"))) { formDataList.add(String.valueOf(kv.get("name"))); } } } } } - } catch (Exception e) { + } catch (Exception ignored) { } } @@ -851,7 +792,7 @@ public class MockConfigService { JSONObject returnObj = null; try { returnObj = JSONUtil.parseObject(request); - } catch (Exception e) { + } catch (Exception ignored) { } return returnObj; } @@ -868,7 +809,7 @@ public class MockConfigService { MockConfigExample.Criteria criteria = example.createCriteria(); criteria.andApiIdEqualTo(id); List configList = mockConfigMapper.selectByExample(example); - return this.assemblyMockConfingResponse(configList); + return this.assemblyMockConingResponse(configList); } public String checkReturnWithMockExpectByBodyParam(String method, Map requestHeaderMap, Project project, HttpServletRequest request, HttpServletResponse response) { @@ -876,23 +817,23 @@ public class MockConfigService { boolean matchApi = false; String url = request.getRequestURL().toString(); if (project != null) { + RequestMockParams requestMockParams = MockApiUtils.genRequestMockParamsFromHttpRequest(request, true); String urlSuffix = this.getUrlSuffix(project.getSystemId(), request); - List aualifiedApiList = apiDefinitionService.preparedUrl(project.getId(), method, urlSuffix, requestHeaderMap.get(MockApiHeaders.MOCK_API_RESOURCE_ID)); - Object paramJson = MockApiUtils.getPostParamMap(request); - JSONObject parameterObject = MockApiUtils.getParameterJsonObject(request); - for (ApiDefinitionWithBLOBs api : aualifiedApiList) { + List qualifiedApiList = apiDefinitionService.preparedUrl(project.getId(), method, urlSuffix, requestHeaderMap.get(MockApiHeaders.MOCK_API_RESOURCE_ID)); + for (ApiDefinitionWithBLOBs api : qualifiedApiList) { if (StringUtils.isEmpty(returnStr)) { - RequestMockParams mockParams = MockApiUtils.getParams(urlSuffix, api.getPath(), parameterObject, paramJson, true); + //补足rest参数 + MockApiUtils.complementRestParam(urlSuffix, api.getPath(), requestMockParams); MockConfigResponse mockConfigData = this.findByApiId(api.getId()); - MockExpectConfigResponse finalExpectConfig = this.findExpectConfig(requestHeaderMap, mockConfigData.getMockExpectConfigList(), mockParams); + MockExpectConfigResponse finalExpectConfig = this.findExpectConfig(requestHeaderMap, mockConfigData.getMockExpectConfigList(), requestMockParams); if (finalExpectConfig != null) { - returnStr = this.updateHttpServletResponse(project.getId(), finalExpectConfig, url, requestHeaderMap, mockParams, response); + returnStr = this.updateHttpServletResponse(project.getId(), finalExpectConfig, url, requestHeaderMap, requestMockParams, response); } else { returnStr = this.getApiDefinitionResponse(api, response); } } } - if (CollectionUtils.isNotEmpty(aualifiedApiList)) { + if (CollectionUtils.isNotEmpty(qualifiedApiList)) { matchApi = true; } } @@ -908,29 +849,27 @@ public class MockConfigService { String returnStr = StringUtils.EMPTY; boolean matchApi = false; String url = request.getRequestURL().toString(); - List aualifiedApiList = new ArrayList<>(); if (project != null) { + RequestMockParams requestMockParams = MockApiUtils.genRequestMockParamsFromHttpRequest(request, false); + String urlSuffix = this.getUrlSuffix(project.getSystemId(), request); - aualifiedApiList = apiDefinitionService.preparedUrl(project.getId(), method, urlSuffix, requestHeaderMap.get(MockApiHeaders.MOCK_API_RESOURCE_ID)); + List qualifiedApiList = apiDefinitionService.preparedUrl(project.getId(), method, urlSuffix, requestHeaderMap.get(MockApiHeaders.MOCK_API_RESOURCE_ID)); + /* + GET/DELETE 这种通过url穿参数的接口,在接口路径相同的情况下可能会出现这样的情况: + api1: /api/{name} 参数 name = "ABC" + api2: /api/{testParam} 参数 testParam = "ABC" - /** - * GET/DELETE 这种通过url穿参数的接口,在接口路径相同的情况下可能会出现这样的情况: - * api1: /api/{name} 参数 name = "ABC" - * api2: /api/{testParam} 参数 testParam = "ABC" - * - * 匹配预期Mock的逻辑为: 循环apiId进行筛选,直到筛选到预期Mock。如果筛选不到,则取Api的响应模版来进行返回 + 匹配预期Mock的逻辑为: 循环apiId进行筛选,直到筛选到预期Mock。如果筛选不到,则取Api的响应模版来进行返回 */ - Object paramJson = MockApiUtils.getPostParamMap(request); - JSONObject parameterObject = MockApiUtils.getParameterJsonObject(request); - - for (ApiDefinitionWithBLOBs api : aualifiedApiList) { + for (ApiDefinitionWithBLOBs api : qualifiedApiList) { if (StringUtils.isEmpty(returnStr)) { - RequestMockParams paramMap = MockApiUtils.getParams(urlSuffix, api.getPath(), parameterObject, paramJson, false); + //补足rest参数 + MockApiUtils.complementRestParam(urlSuffix, api.getPath(), requestMockParams); MockConfigResponse mockConfigData = this.findByApiId(api.getId()); if (mockConfigData != null && mockConfigData.getMockExpectConfigList() != null) { - MockExpectConfigResponse finalExpectConfig = this.findExpectConfig(requestHeaderMap, mockConfigData.getMockExpectConfigList(), paramMap); + MockExpectConfigResponse finalExpectConfig = this.findExpectConfig(requestHeaderMap, mockConfigData.getMockExpectConfigList(), requestMockParams); if (finalExpectConfig != null) { - returnStr = this.updateHttpServletResponse(project.getId(), finalExpectConfig, url, requestHeaderMap, paramMap, response); + returnStr = this.updateHttpServletResponse(project.getId(), finalExpectConfig, url, requestHeaderMap, requestMockParams, response); } else { returnStr = this.getApiDefinitionResponse(api, response); } @@ -938,7 +877,7 @@ public class MockConfigService { } } - if (CollectionUtils.isNotEmpty(aualifiedApiList)) { + if (CollectionUtils.isNotEmpty(qualifiedApiList)) { matchApi = true; } } @@ -991,7 +930,7 @@ public class MockConfigService { for (TcpTreeTableDataStruct dataStruct : list) { List nameList = dataStruct.getNameDeep(); for (String name : nameList) { - if (!returnList.contains(nameList)) { + if (!returnList.contains(name)) { returnList.add(name); } } @@ -1075,22 +1014,19 @@ public class MockConfigService { if (isMatch) { JSONObject responseObj = JSONUtil.parseObject(responseStr); if (responseObj.has("body")) { + MockExpectConfigDTO dto = new MockExpectConfigDTO(); + dto.setMockExpectConfig(expectConfig); + dto.setProjectId(projectId); if (isRaw) { - MockExpectConfigDTO dto = new MockExpectConfigDTO(); - dto.setMockExpectConfig(expectConfig); - dto.setProjectId(projectId); rawResult.add(dto); } else { - MockExpectConfigDTO dto = new MockExpectConfigDTO(); - dto.setMockExpectConfig(expectConfig); - dto.setProjectId(projectId); structResult.add(dto); } } } } - } catch (Exception e) { + } catch (Exception ignored) { } } } @@ -1112,7 +1048,7 @@ public class MockConfigService { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); XMLUtil.setExpandEntityReferencesFalse(documentBuilderFactory); DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); - builder.parse(new InputSource(new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8.name())))); + builder.parse(new InputSource(new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)))); isXml = true; } catch (Exception e) { e.printStackTrace(); @@ -1128,7 +1064,7 @@ public class MockConfigService { if (!StringUtils.equalsIgnoreCase("value", type)) { isJson = true; } - } catch (Exception e) { + } catch (Exception ignored) { } return isJson; } @@ -1163,7 +1099,6 @@ public class MockConfigService { } private void updateMockExpectConfigs(MockConfig mockConfig, List list, SqlSession sqlSession) { - int batchCount = 0; for (MockExpectConfigWithBLOBs mockExpect : list) { MockExpectConfig expectInDb = this.findMockExpectConfigByMockConfigIdAndExpectNum(mockConfig.getId(), mockExpect.getExpectNum()); if (expectInDb == null) { @@ -1181,9 +1116,7 @@ public class MockConfigService { } } - if (batchCount % 300 == 0) { - sqlSession.flushStatements(); - } + sqlSession.flushStatements(); } private MockExpectConfig findMockExpectConfigByMockConfigIdAndExpectNum(String mockConfigId, String expectNum) { @@ -1208,7 +1141,6 @@ public class MockConfigService { config.setApiId(apiId); mockConfigMapper.insert(config); - int batchCount = 0; for (MockExpectConfigWithBLOBs mockExpect : list) { mockExpect.setId(UUID.randomUUID().toString()); mockExpect.setMockConfigId(mockId); @@ -1217,9 +1149,7 @@ public class MockConfigService { mockExpect.setCreateUserId(SessionUtils.getUserId()); mockExpectConfigMapper.insert(mockExpect); } - if (batchCount % 300 == 0) { - sqlSession.flushStatements(); - } + sqlSession.flushStatements(); } @@ -1330,12 +1260,10 @@ public class MockConfigService { int num1 = Integer.parseInt(tcpMockPortArr[0]); int num2 = Integer.parseInt(tcpMockPortArr[1]); - int startNum = num1 > num2 ? num2 : num1; - int endNum = num1 < num2 ? num2 : num1; + int startNum = Math.min(num1, num2); + int endNum = Math.max(num1, num2); - if (port < startNum || port > endNum) { - inRange = false; - } else { + if (!(port < startNum || port > endNum)) { inRange = true; } } else { @@ -1344,7 +1272,7 @@ public class MockConfigService { inRange = true; } } - } catch (Exception e) { + } catch (Exception ignored) { } } return inRange; @@ -1358,7 +1286,7 @@ public class MockConfigService { JSONObject configObj = JSONUtil.parseObject(mockEnv.getConfig()); if (configObj.has("tcpConfig")) { JSONObject tcpConfigObj = configObj.optJSONObject("tcpConfig"); - int tcpPort = 0; + int tcpPort; if (tcpConfigObj.has("port")) { tcpPort = tcpConfigObj.optInt("port"); if (tcpPort == 0 || !TCPPool.isTcpOpen(tcpPort)) { diff --git a/api-test/frontend/src/api/api-mock.js b/api-test/frontend/src/api/api-mock.js index 8eba25bd6c..7506b650f8 100644 --- a/api-test/frontend/src/api/api-mock.js +++ b/api-test/frontend/src/api/api-mock.js @@ -2,41 +2,41 @@ import { get, post } from 'metersphere-frontend/src/plugins/request'; import { fileUpload } from '@/api/base-network'; export function getMockApiParams(id) { - return get('/mock/config/get-api-params/' + id); + return get('/mock-config/get-api-params/' + id); } export function updateMockExpectConfigStatus(mockParam) { - return post('/mock/config/update/expect', mockParam); + return post('/mock-config/update/expect', mockParam); } export function mockExpectConfig(id) { - return get('/mock/config/get-expect/' + id); + return get('/mock-config/get-expect/' + id); } export function delMock(id) { - return get('/mock/config/delete/' + id); + return get('/mock-config/delete/' + id); } export function createMockConfig(mockParam) { - return post('/mock/config/gen', mockParam); + return post('/mock-config/gen', mockParam); } export function getMockApiResponse(id) { - return get('/mock/config/get-api-response/' + id); + return get('/mock-config/get-api-response/' + id); } export function getTcpMockTestData(mockParam) { - return post('/mock/config/get-tcp-test-data', mockParam); + return post('/mock-config/get-tcp-test-data', mockParam); } export function getMockTestData(mockParam) { - return post('/mock/config/test-data', mockParam); + return post('/mock-config/test-data', mockParam); } export function updateMockExpectConfig(mockParam, file, files) { - return fileUpload('/mock/config/update/form', file, files, mockParam); + return fileUpload('/mock-config/update/form', file, files, mockParam); } export function getTcpMockInfo(projectId) { - return get('/mock/config/get-details/' + projectId); + return get('/mock-config/get-details/' + projectId); } diff --git a/api-test/frontend/src/business/automation/scenario/component/ApiResponseComponent.vue b/api-test/frontend/src/business/automation/scenario/component/ApiResponseComponent.vue index 1d292e5307..0019afb3e2 100644 --- a/api-test/frontend/src/business/automation/scenario/component/ApiResponseComponent.vue +++ b/api-test/frontend/src/business/automation/scenario/component/ApiResponseComponent.vue @@ -46,6 +46,7 @@ export default { this.getExecResult(); } else { this.response = this.result; + this.isActive = true; } if (this.apiActive) { this.isActive = false; @@ -58,7 +59,7 @@ export default { } else { this.getExecResult(); } - this.isActive = false; + this.isActive = true; }, apiItem() { this.getExecResult(); @@ -98,7 +99,7 @@ export default { } :deep(.el-card__body) { - padding: 15px; + padding: 10px; } .icon.is-active { diff --git a/api-test/frontend/src/business/definition/ApiDefinition.vue b/api-test/frontend/src/business/definition/ApiDefinition.vue index f127d6f502..0f4b43f8bb 100644 --- a/api-test/frontend/src/business/definition/ApiDefinition.vue +++ b/api-test/frontend/src/business/definition/ApiDefinition.vue @@ -285,7 +285,6 @@ import ApiCaseSimpleList from './components/list/ApiCaseSimpleList'; import ApiDocumentsPage from '@/business/definition/components/list/ApiDocumentsPage'; import MsTableButton from 'metersphere-frontend/src/components/MsTableButton'; import MsTabButton from '@/business/commons/MsTabs'; -import MockConfig from '@/business/definition/components/mock/MockConfig'; import ApiSchedule from '@/business/definition/components/import/ApiSchedule'; import MsEditCompleteContainer from './components/EditCompleteContainer'; import MsEnvironmentSelect from './components/case/MsEnvironmentSelect'; @@ -353,7 +352,6 @@ export default { MsRunTestSqlPage, MsRunTestDubboPage, ApiDocumentsPage, - MockConfig, MsEditCompleteContainer, MsEnvironmentSelect, MockEditDrawer, diff --git a/api-test/frontend/src/business/definition/components/EditCompleteContainer.vue b/api-test/frontend/src/business/definition/components/EditCompleteContainer.vue index 0472bd42a7..089fddfc17 100644 --- a/api-test/frontend/src/business/definition/components/EditCompleteContainer.vue +++ b/api-test/frontend/src/business/definition/components/EditCompleteContainer.vue @@ -96,15 +96,15 @@ v-if="currentProtocol === 'DUBBO'" /> -
+ -
-
+ + -
+ @@ -132,7 +132,6 @@ import MsRunTestTcpPage from './runtest/RunTestTCPPage'; import MsRunTestSqlPage from './runtest/RunTestSQLPage'; import MsRunTestDubboPage from './runtest/RunTestDubboPage'; import MockTab from '@/business/definition/components/mock/MockTab'; -import TcpMockConfig from '@/business/definition/components/mock/TcpMockConfig'; import ApiCaseSimpleList from './list/ApiCaseSimpleList'; import MsApiCaseList from './case/EditApiCase'; import { getUUID } from 'metersphere-frontend/src/utils'; @@ -153,7 +152,6 @@ export default { MsRunTestSqlPage, MsRunTestDubboPage, MockTab, - TcpMockConfig, ApiCaseSimpleList, MsApiCaseList, ApiBaseInfo, diff --git a/api-test/frontend/src/business/definition/components/case/ApiCaseItem.vue b/api-test/frontend/src/business/definition/components/case/ApiCaseItem.vue index ed1ee82d64..7edc8c568e 100644 --- a/api-test/frontend/src/business/definition/components/case/ApiCaseItem.vue +++ b/api-test/frontend/src/business/definition/components/case/ApiCaseItem.vue @@ -713,7 +713,7 @@ export default { if (!hideAlert) { this.$emit('refresh'); } - this.$emit('refreshCaseList'); + this.$emit('refreshCaseList',row.id); }, (error) => { this.isSave = false; diff --git a/api-test/frontend/src/business/definition/components/case/EditApiCase.vue b/api-test/frontend/src/business/definition/components/case/EditApiCase.vue index 6b402b6abf..26f00c2385 100644 --- a/api-test/frontend/src/business/definition/components/case/EditApiCase.vue +++ b/api-test/frontend/src/business/definition/components/case/EditApiCase.vue @@ -437,8 +437,20 @@ export default { refresh() { this.$emit('refresh'); }, - refreshCaseList() { - this.getApiTest(true, true); + refreshCaseList(id) { + return new Promise((resolve) => { + let commonUseEnvironment = store.useEnvironment; + this.environment = commonUseEnvironment ? commonUseEnvironment : ''; + getCaseById(id).then((response) => { + let apiCase = response.data; + if (apiCase) { + this.formatCase(apiCase); + apiCase.active = true; + this.apiCaseList = [apiCase]; + } + resolve(); + }); + }); }, reLoadCase() { this.$emit('reLoadCase'); diff --git a/api-test/frontend/src/business/definition/components/collapse/ApiCollapse.vue b/api-test/frontend/src/business/definition/components/collapse/ApiCollapse.vue deleted file mode 100644 index d0c0fb1728..0000000000 --- a/api-test/frontend/src/business/definition/components/collapse/ApiCollapse.vue +++ /dev/null @@ -1,72 +0,0 @@ - - diff --git a/api-test/frontend/src/business/definition/components/collapse/ApiCollapseItem.vue b/api-test/frontend/src/business/definition/components/collapse/ApiCollapseItem.vue deleted file mode 100644 index f49fb905ec..0000000000 --- a/api-test/frontend/src/business/definition/components/collapse/ApiCollapseItem.vue +++ /dev/null @@ -1,127 +0,0 @@ - - - - diff --git a/api-test/frontend/src/business/definition/components/mock/Components/MockApiBody.vue b/api-test/frontend/src/business/definition/components/mock/Components/MockApiBody.vue index 5df0ea7c81..c469c66cb8 100644 --- a/api-test/frontend/src/business/definition/components/mock/Components/MockApiBody.vue +++ b/api-test/frontend/src/business/definition/components/mock/Components/MockApiBody.vue @@ -23,7 +23,9 @@
- {{ $t('commons.batch_add') }} + + {{ $t('commons.batch_add') }} + -
- - -
- -
-
-
- -
- - - - - diff --git a/api-test/frontend/src/business/definition/components/mock/MockConfig.vue b/api-test/frontend/src/business/definition/components/mock/MockConfig.vue deleted file mode 100644 index 4d1cd1d3e4..0000000000 --- a/api-test/frontend/src/business/definition/components/mock/MockConfig.vue +++ /dev/null @@ -1,370 +0,0 @@ - - - - - diff --git a/api-test/frontend/src/business/definition/components/mock/MockTab.vue b/api-test/frontend/src/business/definition/components/mock/MockTab.vue index 966eb33f92..d938dc3d75 100644 --- a/api-test/frontend/src/business/definition/components/mock/MockTab.vue +++ b/api-test/frontend/src/business/definition/components/mock/MockTab.vue @@ -135,7 +135,7 @@ export default { tableSearch: '', apiParams: {}, pageSize: 10, - screenHeight: document.documentElement.clientHeight - 250, + screenHeight: 'calc(100vh - 205px)', operators: [ { tip: this.$t('api_test.automation.execute'), diff --git a/api-test/frontend/src/business/definition/components/mock/TcpMockConfig.vue b/api-test/frontend/src/business/definition/components/mock/TcpMockConfig.vue deleted file mode 100644 index 2b84306f9c..0000000000 --- a/api-test/frontend/src/business/definition/components/mock/TcpMockConfig.vue +++ /dev/null @@ -1,392 +0,0 @@ - - - - - diff --git a/test-track/backend/src/main/java/io/metersphere/plan/service/TestPlanReportService.java b/test-track/backend/src/main/java/io/metersphere/plan/service/TestPlanReportService.java index 5221ca9b9b..78a8a31706 100644 --- a/test-track/backend/src/main/java/io/metersphere/plan/service/TestPlanReportService.java +++ b/test-track/backend/src/main/java/io/metersphere/plan/service/TestPlanReportService.java @@ -198,7 +198,7 @@ public class TestPlanReportService { if (MapUtils.isNotEmpty(testPlanExecuteReportDTO.getTestPlanUiScenarioIdAndReportIdMap())) { // 场景用例 reportIds = new ArrayList<>(testPlanExecuteReportDTO.getTestPlanUiScenarioIdAndReportIdMap().values()); - planReportCaseDTOS = planApiScenarioReportService.selectForPlanReport(reportIds); + planReportCaseDTOS = planUiScenarioReportService.selectForPlanReport(reportIds); TestPlanStatusCalculator.buildStatusResultMap(planReportCaseDTOS, statusResultMap, report, ApiReportStatus.SUCCESS.name()); } }