fix(Mock测试): 修复type为raw但是内容为空时出现的校验错误和接口测试存在全局前后置脚本时获取运行结果失败的错误

修复type为raw但是内容为空时出现的校验错误和接口测试存在全局前后置脚本时获取运行结果失败的错误
This commit is contained in:
song-tianyang 2021-10-22 10:54:48 +08:00 committed by song-tianyang
parent 153bff333b
commit d0704f3e15
5 changed files with 100 additions and 85 deletions

View File

@ -86,9 +86,6 @@ public class MockApiUtils {
if (bodyObj.containsKey("jsonSchema") && bodyObj.getJSONObject("jsonSchema").containsKey("properties")) {
String bodyRetunStr = bodyObj.getJSONObject("jsonSchema").getJSONObject("properties").toJSONString();
jsonString = JSONSchemaGenerator.getJson(bodyRetunStr);
// JSONObject bodyReturnObj = JSONObject.parseObject(bodyRetunStr);
// JSONObject returnObj = parseJsonSchema(bodyReturnObj);
// returnStr = returnObj.toJSONString();
}
} else {
if (bodyObj.containsKey("raw")) {
@ -112,9 +109,11 @@ public class MockApiUtils {
} else if (StringUtils.equalsIgnoreCase(type, "Raw")) {
if (bodyObj.containsKey("raw")) {
String raw = bodyObj.getString("raw");
JSONObject rawObject = new JSONObject();
rawObject.put("raw",raw);
returnJsonArray.add(rawObject);
if(StringUtils.isNotEmpty(raw)){
JSONObject rawObject = new JSONObject();
rawObject.put("raw",raw);
returnJsonArray.add(rawObject);
}
}
} else if (StringUtils.equalsAnyIgnoreCase(type, "Form Data", "WWW_FORM")) {
if (bodyObj.containsKey("kvs")) {
@ -209,7 +208,7 @@ public class MockApiUtils {
return values;
}
public static JSONObject getParams(JSONArray array) {
public static JSONObject getParamsByJSONArray(JSONArray array) {
JSONObject returnObject = new JSONObject();
for(int i = 0; i < array.size();i ++){
JSONObject obj = array.getJSONObject(i);
@ -440,25 +439,22 @@ public class MockApiUtils {
System.out.println(result.getResponseData());
}
public static RequestMockParams getParams(String urlParams, ApiDefinitionWithBLOBs api, HttpServletRequest request){
RequestMockParams returnParams = getGetParamMap(urlParams,api,request);
JSON paramJson = getPostParamMap(request);
if (paramJson instanceof JSONObject) {
JSONArray paramsArray = new JSONArray();
paramsArray.add(paramJson);
returnParams.setBodyParams(paramsArray);
} else if (paramJson instanceof JSONArray) {
JSONArray paramArray = (JSONArray) paramJson;
returnParams.setBodyParams(paramArray);
public static RequestMockParams getParams(String urlParams, String apiPath, JSONObject queryParamsObject,JSON paramJson){
RequestMockParams returnParams = getGetParamMap(urlParams,apiPath,queryParamsObject);
if(paramJson != null){
if (paramJson instanceof JSONObject) {
JSONArray paramsArray = new JSONArray();
paramsArray.add(paramJson);
returnParams.setBodyParams(paramsArray);
} else if (paramJson instanceof JSONArray) {
JSONArray paramArray = (JSONArray) paramJson;
returnParams.setBodyParams(paramArray);
}
}
return returnParams;
}
private static RequestMockParams getGetParamMap(String urlParams, ApiDefinitionWithBLOBs api, HttpServletRequest request) {
RequestMockParams requestMockParams = new RequestMockParams();
JSONObject urlParamsObject = getSendRestParamMapByIdAndUrl(api, urlParams);
public static JSONObject getParameterJsonObject(HttpServletRequest request){
JSONObject queryParamsObject = new JSONObject();
Enumeration<String> paramNameItor = request.getParameterNames();
while (paramNameItor.hasMoreElements()) {
@ -466,13 +462,20 @@ public class MockApiUtils {
String value = request.getParameter(key);
queryParamsObject.put(key, value);
}
return queryParamsObject;
}
private static RequestMockParams getGetParamMap(String urlParams, String apiPath, JSONObject queryParamsObject) {
RequestMockParams requestMockParams = new RequestMockParams();
JSONObject urlParamsObject = getSendRestParamMapByIdAndUrl(apiPath, urlParams);
requestMockParams.setRestParamsObj(urlParamsObject);
requestMockParams.setQueryParamsObj(queryParamsObject);
return requestMockParams;
}
private static JSON getPostParamMap(HttpServletRequest request) {
public static JSON getPostParamMap(HttpServletRequest request) {
if (StringUtils.equalsIgnoreCase("application/JSON", request.getContentType())) {
JSON returnJson = null;
try {
@ -511,7 +514,9 @@ public class MockApiUtils {
} else {
JSONObject object = new JSONObject();
String bodyParam = readBody(request);
object.put("raw",bodyParam);
if(StringUtils.isNotEmpty(bodyParam)){
object.put("raw",bodyParam);
}
Enumeration<String> paramNameItor = request.getParameterNames();
while (paramNameItor.hasMoreElements()) {
@ -523,10 +528,9 @@ public class MockApiUtils {
}
}
private static JSONObject getSendRestParamMapByIdAndUrl(ApiDefinitionWithBLOBs api, String urlParams) {
private static JSONObject getSendRestParamMapByIdAndUrl(String path, String urlParams) {
JSONObject returnJson = new JSONObject();
if (api != null) {
String path = api.getPath();
if (StringUtils.isNotEmpty(path)) {
if (path.startsWith("/")) {
path = path.substring(1);
}

View File

@ -73,58 +73,60 @@ public class ApiDefinitionExecResultService {
result.getScenarios().forEach(scenarioResult -> {
if (scenarioResult != null && CollectionUtils.isNotEmpty(scenarioResult.getRequestResults())) {
scenarioResult.getRequestResults().forEach(item -> {
ApiDefinitionExecResult saveResult = MessageCache.batchTestCases.get(result.getTestId());
if (saveResult == null) {
saveResult = apiDefinitionExecResultMapper.selectByPrimaryKey(result.getTestId());
}
item.getResponseResult().setConsole(result.getConsole());
boolean saved = true;
if (saveResult == null || scenarioResult.getRequestResults().size() > 1) {
saveResult = new ApiDefinitionExecResult();
if (isFirst[0]) {
isFirst[0] = false;
saveResult.setId(result.getTestId());
} else {
saveResult.setId(UUID.randomUUID().toString());
if(!StringUtils.equalsIgnoreCase(item.getMethod(),"Request") && !StringUtils.startsWithAny(item.getName(),"PRE_PROCESSOR_ENV_","POST_PROCESSOR_ENV_")){
ApiDefinitionExecResult saveResult = MessageCache.batchTestCases.get(result.getTestId());
if (saveResult == null) {
saveResult = apiDefinitionExecResultMapper.selectByPrimaryKey(result.getTestId());
}
saveResult.setActuator("LOCAL");
saveResult.setName(item.getName());
saveResult.setTriggerMode(triggerMode);
saveResult.setType(type);
saveResult.setCreateTime(item.getStartTime());
if (StringUtils.isNotEmpty(result.getUserId())) {
saveResult.setUserId(result.getUserId());
} else {
saveResult.setUserId(Objects.requireNonNull(SessionUtils.getUser()).getId());
item.getResponseResult().setConsole(result.getConsole());
boolean saved = true;
if (saveResult == null || scenarioResult.getRequestResults().size() > 1) {
saveResult = new ApiDefinitionExecResult();
if (isFirst[0]) {
isFirst[0] = false;
saveResult.setId(result.getTestId());
} else {
saveResult.setId(UUID.randomUUID().toString());
}
saveResult.setActuator("LOCAL");
saveResult.setName(item.getName());
saveResult.setTriggerMode(triggerMode);
saveResult.setType(type);
saveResult.setCreateTime(item.getStartTime());
if (StringUtils.isNotEmpty(result.getUserId())) {
saveResult.setUserId(result.getUserId());
} else {
saveResult.setUserId(Objects.requireNonNull(SessionUtils.getUser()).getId());
}
saved = false;
}
saved = false;
}
String status = item.isSuccess() ? "success" : "error";
saveResult.setName(getName(type, item.getName(), status, saveResult.getCreateTime(), saveResult.getId()));
saveResult.setStatus(status);
saveResult.setResourceId(item.getName());
saveResult.setContent(JSON.toJSONString(item));
saveResult.setStartTime(item.getStartTime());
saveResult.setEndTime(item.getResponseResult().getResponseTime());
String status = item.isSuccess() ? "success" : "error";
saveResult.setName(getName(type, item.getName(), status, saveResult.getCreateTime(), saveResult.getId()));
saveResult.setStatus(status);
saveResult.setResourceId(item.getName());
saveResult.setContent(JSON.toJSONString(item));
saveResult.setStartTime(item.getStartTime());
saveResult.setEndTime(item.getResponseResult().getResponseTime());
// 清空上次执行结果的内容只保留近五条结果
ApiDefinitionExecResult prevResult = extApiDefinitionExecResultMapper.selectMaxResultByResourceIdAndType(item.getName(), type);
if (prevResult != null) {
prevResult.setContent(null);
apiDefinitionExecResultMapper.updateByPrimaryKeyWithBLOBs(prevResult);
}
// 清空上次执行结果的内容只保留近五条结果
ApiDefinitionExecResult prevResult = extApiDefinitionExecResultMapper.selectMaxResultByResourceIdAndType(item.getName(), type);
if (prevResult != null) {
prevResult.setContent(null);
apiDefinitionExecResultMapper.updateByPrimaryKeyWithBLOBs(prevResult);
}
if (StringUtils.isNotEmpty(saveResult.getTriggerMode()) && saveResult.getTriggerMode().equals("CASE")) {
saveResult.setTriggerMode(TriggerMode.MANUAL.name());
if (StringUtils.isNotEmpty(saveResult.getTriggerMode()) && saveResult.getTriggerMode().equals("CASE")) {
saveResult.setTriggerMode(TriggerMode.MANUAL.name());
}
if (!saved) {
apiDefinitionExecResultMapper.insert(saveResult);
} else {
apiDefinitionExecResultMapper.updateByPrimaryKeyWithBLOBs(saveResult);
}
apiDefinitionService.removeCache(result.getTestId());
// 发送通知
sendNotice(saveResult);
}
if (!saved) {
apiDefinitionExecResultMapper.insert(saveResult);
} else {
apiDefinitionExecResultMapper.updateByPrimaryKeyWithBLOBs(saveResult);
}
apiDefinitionService.removeCache(result.getTestId());
// 发送通知
sendNotice(saveResult);
});
}
});

View File

@ -865,7 +865,13 @@ public class ApiDefinitionService {
public void addResult(TestResult res) {
if (res != null && CollectionUtils.isNotEmpty(res.getScenarios()) && res.getScenarios().get(0) != null && CollectionUtils.isNotEmpty(res.getScenarios().get(0).getRequestResults())) {
RequestResult result = res.getScenarios().get(0).getRequestResults().get(0);
RequestResult result = null;
for(RequestResult itemResult : res.getScenarios().get(0).getRequestResults()){
if(!StringUtils.equalsIgnoreCase(itemResult.getMethod(),"Request") && !StringUtils.startsWithAny(itemResult.getName(),"PRE_PROCESSOR_ENV_","POST_PROCESSOR_ENV_")){
result = itemResult;
break;
}
}
if (result.getName().indexOf(DelimiterConstants.SEPARATOR.toString()) != -1) {
result.setName(result.getName().substring(0, result.getName().indexOf(DelimiterConstants.SEPARATOR.toString())));
}

View File

@ -29,7 +29,6 @@ import io.metersphere.i18n.Translator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.XML;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@ -44,7 +43,6 @@ import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Service
@Transactional(rollbackFor = Exception.class)
@ -309,7 +307,7 @@ public class MockConfigService {
if(expectParamsObj.containsKey("arguments")){
JSONArray argumentsArray = expectParamsObj.getJSONArray("arguments");
JSONObject urlRequestParamObj = MockApiUtils.getParams(argumentsArray);
JSONObject urlRequestParamObj = MockApiUtils.getParamsByJSONArray(argumentsArray);
if(!JsonStructUtils.checkJsonObjCompliance(requestMockParams.getQueryParamsObj(), urlRequestParamObj)){
return false;
}
@ -317,7 +315,7 @@ public class MockConfigService {
if(expectParamsObj.containsKey("rest")){
JSONArray restArray = expectParamsObj.getJSONArray("rest");
JSONObject restRequestParamObj = MockApiUtils.getParams(restArray);
JSONObject restRequestParamObj = MockApiUtils.getParamsByJSONArray(restArray);
if(!JsonStructUtils.checkJsonObjCompliance(requestMockParams.getRestParamsObj(), restRequestParamObj)){
return false;
}
@ -1036,8 +1034,11 @@ public class MockConfigService {
String urlSuffix = this.getUrlSuffix(project.getSystemId(), request);
aualifiedApiList = apiDefinitionService.preparedUrl(project.getId(), method, urlSuffix, urlSuffix);
JSON paramJson = MockApiUtils.getPostParamMap(request);
JSONObject parameterObject = MockApiUtils.getParameterJsonObject(request);
for (ApiDefinitionWithBLOBs api : aualifiedApiList) {
RequestMockParams mockParams = MockApiUtils.getParams(urlSuffix, api, request);
RequestMockParams mockParams = MockApiUtils.getParams(urlSuffix, api.getPath(), parameterObject,paramJson);
MockConfigResponse mockConfigData = this.findByApiId(api.getId());
MockExpectConfigResponse finalExpectConfig = this.findExpectConfig(requestHeaderMap, mockConfigData.getMockExpectConfigList(), mockParams);
@ -1102,9 +1103,11 @@ public class MockConfigService {
*
* 匹配预期Mock的逻辑为 循环apiId进行筛选直到筛选到预期Mock如果筛选不到则取Api的响应模版来进行返回
*/
JSON paramJson = MockApiUtils.getPostParamMap(request);
JSONObject parameterObject = MockApiUtils.getParameterJsonObject(request);
for (ApiDefinitionWithBLOBs api : aualifiedApiList) {
RequestMockParams paramMap = MockApiUtils.getParams(urlSuffix, api, request);
RequestMockParams paramMap = MockApiUtils.getParams(urlSuffix, api.getPath(), parameterObject,paramJson);
MockConfigResponse mockConfigData = this.findByApiId(api.getId());
if (mockConfigData != null && mockConfigData.getMockExpectConfigList() != null) {

View File

@ -213,20 +213,20 @@ export default {
modeChange(mode) {
switch (this.body.type) {
case "JSON":
this.setContentType("application/json");
// this.setContentType("application/json");
break;
case "XML":
this.setContentType("text/xml");
// this.setContentType("text/xml");
break;
case "WWW_FORM":
this.setContentType("application/x-www-form-urlencoded");
// this.setContentType("application/x-www-form-urlencoded");
break;
// todo from data
// case "BINARY":
// this.setContentType("application/octet-stream");
// break;
default:
this.removeContentType();
// this.removeContentType();
break;
}
},