refactor(接口测试): 优化mock匹配逻辑

This commit is contained in:
wxg0103 2024-05-23 15:55:04 +08:00 committed by Craftsman
parent 852353e15c
commit 1aeccb44d5
3 changed files with 30 additions and 32 deletions

View File

@ -4,7 +4,10 @@ import io.metersphere.api.domain.*;
import io.metersphere.api.dto.ApiFile; import io.metersphere.api.dto.ApiFile;
import io.metersphere.api.dto.definition.HttpResponse; import io.metersphere.api.dto.definition.HttpResponse;
import io.metersphere.api.dto.definition.ResponseBody; import io.metersphere.api.dto.definition.ResponseBody;
import io.metersphere.api.dto.mockserver.*; import io.metersphere.api.dto.mockserver.BodyParamMatchRule;
import io.metersphere.api.dto.mockserver.HttpRequestParam;
import io.metersphere.api.dto.mockserver.MockMatchRule;
import io.metersphere.api.dto.mockserver.MockResponse;
import io.metersphere.api.dto.request.http.MsHeader; import io.metersphere.api.dto.request.http.MsHeader;
import io.metersphere.api.dto.request.http.body.BinaryBody; import io.metersphere.api.dto.request.http.body.BinaryBody;
import io.metersphere.api.dto.request.http.body.Body; import io.metersphere.api.dto.request.http.body.Body;
@ -18,7 +21,10 @@ import io.metersphere.sdk.constants.HttpMethodConstants;
import io.metersphere.sdk.file.FileCenter; import io.metersphere.sdk.file.FileCenter;
import io.metersphere.sdk.file.FileRepository; import io.metersphere.sdk.file.FileRepository;
import io.metersphere.sdk.file.FileRequest; import io.metersphere.sdk.file.FileRequest;
import io.metersphere.sdk.util.*; import io.metersphere.sdk.util.JSON;
import io.metersphere.sdk.util.LogUtils;
import io.metersphere.sdk.util.TempFileUtils;
import io.metersphere.sdk.util.Translator;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
@ -90,11 +96,7 @@ public class MockServerService {
HttpRequestParam requestMockParams = MockServerUtils.getHttpRequestParam(request, requestUrlSuffix, apiDefinition.getPath(), !isUrlParamMethod(method)); HttpRequestParam requestMockParams = MockServerUtils.getHttpRequestParam(request, requestUrlSuffix, apiDefinition.getPath(), !isUrlParamMethod(method));
LogUtils.info("Mock [" + url + "] Header:{}", requestHeaderMap); LogUtils.info("Mock [" + url + "] Header:{}", requestHeaderMap);
LogUtils.info("Mock [" + url + "] request:{}", JSON.toJSONString(requestMockParams)); LogUtils.info("Mock [" + url + "] request:{}", JSON.toJSONString(requestMockParams));
ApiMockConfigDTO compareMockConfig = findMatchingMockConfig(apiDefinition.getId(), requestHeaderMap, requestMockParams); ApiDefinitionMockConfig compareMockConfig = findMatchingMockConfig(apiDefinition.getId(), requestHeaderMap, requestMockParams);
if (compareMockConfig != null && !compareMockConfig.isEnable()) {
return requestNotFound();
}
// Get and return the response body // Get and return the response body
try { try {
@ -113,10 +115,10 @@ public class MockServerService {
.orElse(null); .orElse(null);
} }
private ApiMockConfigDTO findMatchingMockConfig(String apiId, Map<String, String> requestHeaderMap, HttpRequestParam param) { private ApiDefinitionMockConfig findMatchingMockConfig(String apiId, Map<String, String> requestHeaderMap, HttpRequestParam param) {
// 查询符合条件的 ApiDefinitionMockConfig 列表 // 查询符合条件的 ApiDefinitionMockConfig 列表
ApiDefinitionMockExample mockExample = new ApiDefinitionMockExample(); ApiDefinitionMockExample mockExample = new ApiDefinitionMockExample();
mockExample.createCriteria().andApiDefinitionIdEqualTo(apiId); mockExample.createCriteria().andApiDefinitionIdEqualTo(apiId).andEnableEqualTo(true);
List<ApiDefinitionMock> apiDefinitionMockList = apiDefinitionMockMapper.selectByExample(mockExample); List<ApiDefinitionMock> apiDefinitionMockList = apiDefinitionMockMapper.selectByExample(mockExample);
if (CollectionUtils.isEmpty(apiDefinitionMockList)) { if (CollectionUtils.isEmpty(apiDefinitionMockList)) {
@ -127,20 +129,10 @@ public class MockServerService {
mockConfigExample.createCriteria().andIdIn(apiDefinitionMockList.stream().map(ApiDefinitionMock::getId).collect(Collectors.toList())); mockConfigExample.createCriteria().andIdIn(apiDefinitionMockList.stream().map(ApiDefinitionMock::getId).collect(Collectors.toList()));
List<ApiDefinitionMockConfig> mockConfigs = apiDefinitionMockConfigMapper.selectByExampleWithBLOBs(mockConfigExample); List<ApiDefinitionMockConfig> mockConfigs = apiDefinitionMockConfigMapper.selectByExampleWithBLOBs(mockConfigExample);
// 寻找匹配的 ApiDefinitionMockConfig // 寻找匹配的 ApiDefinitionMockConfig
ApiDefinitionMockConfig apiDefinitionMockConfig = mockConfigs.stream() return mockConfigs.stream()
.filter(mockConfig -> MockServerUtils.matchMockConfig(mockConfig.getMatching(), requestHeaderMap, param) && matchBinaryBody(mockConfig, param.getBinaryParamsObj(), apiDefinitionMockList.getFirst().getProjectId())) .filter(mockConfig -> MockServerUtils.matchMockConfig(mockConfig.getMatching(), requestHeaderMap, param) && matchBinaryBody(mockConfig, param.getBinaryParamsObj(), apiDefinitionMockList.getFirst().getProjectId()))
.findFirst() .findFirst()
.orElse(null); .orElse(null);
if (apiDefinitionMockConfig != null) {
ApiMockConfigDTO apiMockConfigDTO = new ApiMockConfigDTO();
BeanUtils.copyBean(apiMockConfigDTO, apiDefinitionMockConfig);
apiDefinitionMockList.stream().filter(mock -> StringUtils.equals(mock.getId(), apiDefinitionMockConfig.getId()))
.findFirst()
.ifPresent(mock -> apiMockConfigDTO.setEnable(mock.getEnable()));
return apiMockConfigDTO;
}
return null;
} }
private boolean matchBinaryBody(ApiDefinitionMockConfig mockConfig, byte[] binaryFile, String projectId) { private boolean matchBinaryBody(ApiDefinitionMockConfig mockConfig, byte[] binaryFile, String projectId) {

View File

@ -46,8 +46,8 @@ public class MockServerUtils {
try { try {
if (request instanceof ShiroHttpServletRequest shiroHttpServletRequest) { if (request instanceof ShiroHttpServletRequest shiroHttpServletRequest) {
if (StringUtils.equals(request.getContentType(), MediaType.APPLICATION_OCTET_STREAM_VALUE)) {
InputStream inputStream = shiroHttpServletRequest.getRequest().getInputStream(); InputStream inputStream = shiroHttpServletRequest.getRequest().getInputStream();
if (inputStream != null && inputStream.available() > 0 && StringUtils.equals(request.getContentType(), MediaType.APPLICATION_OCTET_STREAM_VALUE)) {
byte[] binaryParams = inputStream.readAllBytes(); byte[] binaryParams = inputStream.readAllBytes();
requestParam.setBinaryParamsObj(binaryParams); requestParam.setBinaryParamsObj(binaryParams);
} else if (StringUtils.equals(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) { } else if (StringUtils.equals(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
@ -60,6 +60,22 @@ public class MockServerUtils {
} }
} }
requestPostString = receiveData.toString(); requestPostString = receiveData.toString();
} else if (StringUtils.equals(request.getContentType(), MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
Map<String, String[]> parameterMap = request.getParameterMap();
LinkedHashMap<String, String> bodyParams = new LinkedHashMap<>();
if (parameterMap != null && !parameterMap.isEmpty()) {
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
String key = entry.getKey();
String[] value = entry.getValue();
if (value != null && value.length > 0) {
String valueStr = value[0];
if (StringUtils.isNotEmpty(valueStr)) {
bodyParams.put(key, valueStr);
}
}
}
requestParam.setBodyParamsObj(bodyParams);
}
} }
} }
String queryString = request.getQueryString(); String queryString = request.getQueryString();

View File

@ -1250,16 +1250,6 @@ public class ApiDefinitionMockControllerTests extends BaseTest {
MockHttpServletRequestBuilder requestBuilder = mockServerTestService.getRequestBuilder("GET", url); MockHttpServletRequestBuilder requestBuilder = mockServerTestService.getRequestBuilder("GET", url);
ResultActions action = mockMvc.perform(requestBuilder); ResultActions action = mockMvc.perform(requestBuilder);
MockHttpServletResponse mockServerResponse = action.andReturn().getResponse(); MockHttpServletResponse mockServerResponse = action.andReturn().getResponse();
//判断响应
mockServerResponse.getContentAsString(StandardCharsets.UTF_8);
mockData.setEnable(false);
apiDefinitionMockMapper.updateByPrimaryKeySelective(mockData);
requestBuilder = mockServerTestService.getRequestBuilder("GET", url);
action = mockMvc.perform(requestBuilder);
mockServerResponse = action.andReturn().getResponse();
//判断响应
mockServerResponse.getContentAsString(StandardCharsets.UTF_8);
} }