refactor(接口测试): 增加接口导入响应体的对比判断以及过滤多余代码

--user=郭雨琦
This commit is contained in:
guoyuqi 2022-07-22 23:51:34 +08:00 committed by xiaomeinvG
parent 3210c11ffb
commit efbf710ad7
1 changed files with 30 additions and 192 deletions

View File

@ -165,8 +165,8 @@ public class ApiDefinitionService {
@Resource
private ApiScenarioMapper apiScenarioMapper;
private ThreadLocal<Long> currentApiOrder = new ThreadLocal<>();
private ThreadLocal<Long> currentApiCaseOrder = new ThreadLocal<>();
private final ThreadLocal<Long> currentApiOrder = new ThreadLocal<>();
private final ThreadLocal<Long> currentApiCaseOrder = new ThreadLocal<>();
public List<ApiDefinitionResult> list(ApiDefinitionRequest request) {
request = this.initRequest(request, true, true);
@ -311,10 +311,10 @@ public class ApiDefinitionService {
/**
* 初始化部分参数
*
* @param request
* @param request api 请求体
* @param defaultSorting
* @param checkThisWeekData
* @return
* @return ApiDefinitionRequest
*/
private ApiDefinitionRequest initRequest(ApiDefinitionRequest request, boolean defaultSorting, boolean checkThisWeekData) {
if (defaultSorting) {
@ -404,7 +404,7 @@ public class ApiDefinitionService {
paramMap.put("name", returnModel.getName());
paramMap.put("createUser", returnModel.getCreateUser());
paramMap.put("userId", returnModel.getUserId());
Set<String> specialReceiversSet = new HashSet<>();
this.getReceivers(request, returnModel, specialReceiversSet);
List<String> specialReceivers = new ArrayList<>(specialReceiversSet);
@ -484,7 +484,7 @@ public class ApiDefinitionService {
deleteFollows(api.getId());
});
// 删除用例和接口的关联关系
testCaseService.deleteTestCaseTestByTestIds(Arrays.asList(apiId));
testCaseService.deleteTestCaseTestByTestIds(List.of(apiId));
}
private void deleteFollows(String apiId) {
@ -631,7 +631,7 @@ public class ApiDefinitionService {
Project project = projectMapper.selectByPrimaryKey(request.getProjectId());
ProjectConfig config = projectApplicationService.getSpecificTypeValue(project.getId(), ProjectApplicationType.URL_REPEATABLE.name());
boolean urlRepeat = config.getUrlRepeatable();
if (project != null && urlRepeat) {
if (urlRepeat) {
if (moduleIdNotExist) {
criteria.andModulePathEqualTo(request.getModulePath());
} else {
@ -1021,7 +1021,7 @@ public class ApiDefinitionService {
if (order == null) {
order = ServiceUtils.getNextOrder(projectId, extApiTestCaseMapper::getLastOrder);
}
order = (order == null ? 0 : order) + ServiceUtils.ORDER_STEP;
order = order + ServiceUtils.ORDER_STEP;
currentApiCaseOrder.set(order);
return order;
}
@ -1173,7 +1173,6 @@ public class ApiDefinitionService {
apiSyncCaseRequest = apiDefinitionSyncService.getApiSyncCaseRequest(existApi.getProjectId());
}
//Compare the basic information of the API. If it contains the comparison that needs to be done for the synchronization information,
// put the data into the to-be-synchronized
if (!StringUtils.equals(exApiString, apiString)) {
@ -1227,15 +1226,10 @@ public class ApiDefinitionService {
JsonNode exApiResponse = null;
JsonNode apiResponse = null;
if (StringUtils.isBlank(apiDefinition.getResponse()) && StringUtils.isBlank(existApi.getResponse())) {
return false;
}
if (StringUtils.isBlank(apiDefinition.getResponse()) && StringUtils.isNotBlank(existApi.getResponse())) {
return false;
}
if (StringUtils.isNotBlank(apiDefinition.getResponse()) && StringUtils.isBlank(existApi.getResponse())) {
return false;
if (StringUtils.isBlank(apiDefinition.getResponse()) || StringUtils.isBlank(existApi.getResponse())) {
return !StringUtils.isBlank(apiDefinition.getResponse()) || !StringUtils.isBlank(existApi.getResponse());
}
try {
exApiResponse = objectMapper.readTree(existApi.getResponse());
apiResponse = objectMapper.readTree(apiDefinition.getResponse());
@ -1244,7 +1238,7 @@ public class ApiDefinitionService {
}
if (exApiResponse == null || apiResponse == null) {
return false;
return exApiResponse != null || apiResponse != null;
}
if (exApiResponse.get("headers") != null && apiResponse.get("headers") != null) {
@ -1293,8 +1287,9 @@ public class ApiDefinitionService {
}
if (exApiRequest == null || apiRequest == null) {
return false;
return exApiRequest != null || apiRequest != null;
}
if (exApiRequest.get("headers") != null && apiRequest.get("headers") != null) {
if (!StringUtils.equals(exApiRequest.get("headers").toString(), apiRequest.get("headers").toString())) {
if (apiSyncCaseRequest.getHeaders()) {
@ -1338,23 +1333,6 @@ public class ApiDefinitionService {
return false;
}
/**
* 如果是MS格式带用例导出最后创建用例重新设置接口id
*
* @param cases
* @param originId
* @param newId
*/
private void reSetImportCasesApiId(List<ApiTestCaseWithBLOBs> cases, String originId, String newId) {
if (CollectionUtils.isNotEmpty(cases)) {
cases.forEach(item -> {
if (StringUtils.equals(item.getApiDefinitionId(), originId)) {
item.setApiDefinitionId(newId);
}
});
}
}
private void reSetImportMocksApiId(List<MockConfigImportDTO> mocks, String originId, String newId, int apiNum) {
if (CollectionUtils.isNotEmpty(mocks)) {
int index = 1;
@ -1386,90 +1364,6 @@ public class ApiDefinitionService {
return request;
}
private void importMsCase(ApiDefinitionImport apiImport, SqlSession sqlSession,
ApiTestImportRequest request, ApiTestCaseMapper apiTestCaseMapper) {
List<ApiTestCaseWithBLOBs> cases = apiImport.getCases();
if (CollectionUtils.isNotEmpty(cases)) {
int batchCount = 0;
for (int i = 0; i < cases.size(); i++) {
ApiTestCaseWithBLOBs item = cases.get(i);
List<ApiDefinitionWithBLOBs> data = apiImport.getData();
List<ApiDefinitionWithBLOBs> collect = data.stream().filter(t -> t.getId().equals(item.getApiDefinitionId())).collect(Collectors.toList());
if (collect.isEmpty()) {
continue;
}
insertOrUpdateImportCase(item, request, collect.get(0), apiTestCaseMapper);
}
if (batchCount % 300 == 0) {
sqlSession.flushStatements();
}
}
}
/**
* 导入是插件或者postman时创建用例
* postman考虑是否有前置脚本
*/
private void importApiCase(ApiDefinitionWithBLOBs apiDefinition, ApiTestImportRequest apiTestImportRequest, ApiTestCaseMapper apiTestCaseMapper) {
try {
if (StringUtils.equalsAnyIgnoreCase(apiTestImportRequest.getPlatform(), ApiImportPlatform.Plugin.name(), ApiImportPlatform.Postman.name())) {
ApiTestCaseWithBLOBs apiTestCase = new ApiTestCaseWithBLOBs();
BeanUtils.copyBean(apiTestCase, apiDefinition);
apiTestCase.setApiDefinitionId(apiDefinition.getId());
apiTestCase.setPriority("P0");
if (apiTestCase.getName().length() > 255) {
apiTestCase.setName(apiTestCase.getName().substring(0, 255));
}
insertOrUpdateImportCase(apiTestCase, apiTestImportRequest, apiDefinition, apiTestCaseMapper);
}
} catch (Exception e) {
LogUtil.error("导入创建用例异常", e);
}
}
private void insertOrUpdateImportCase(ApiTestCaseWithBLOBs apiTestCase, ApiTestImportRequest apiTestImportRequest, ApiDefinitionWithBLOBs apiDefinition, ApiTestCaseMapper apiTestCaseMapper) {
SaveApiTestCaseRequest checkRequest = new SaveApiTestCaseRequest();
if (apiTestCase.getName().length() > 255) {
apiTestCase.setName(apiTestCase.getName().substring(0, 255));
checkRequest.setName(apiTestCase.getName().substring(0, 255));
} else {
checkRequest.setName(apiTestCase.getName());
}
checkRequest.setApiDefinitionId(apiTestCase.getApiDefinitionId());
checkRequest.setId(apiTestCase.getId());
ApiTestCase sameCase = apiTestCaseService.getSameCase(checkRequest);
if (sameCase == null) {
sameCase = apiTestCaseService.getSameCaseById(checkRequest);
}
apiTestCase.setUpdateUserId(SessionUtils.getUserId());
if (sameCase == null) {
apiTestCase.setId(UUID.randomUUID().toString());
apiTestCase.setStatus("");
apiTestCase.setNum(apiTestCaseService.getNextNum(apiTestCase.getApiDefinitionId(), apiDefinition.getNum(), apiDefinition.getProjectId()));
apiTestCase.setCreateTime(System.currentTimeMillis());
apiTestCase.setUpdateTime(System.currentTimeMillis());
apiTestCase.setCreateUserId(SessionUtils.getUserId());
if (StringUtils.isEmpty(apiTestImportRequest.getProjectId())) {
apiTestCase.setProjectId(SessionUtils.getCurrentProjectId());
} else {
apiTestCase.setProjectId(apiTestImportRequest.getProjectId());
}
apiTestCase.setOrder(getImportNextCaseOrder(apiTestImportRequest.getProjectId()));
apiTestCaseMapper.insert(apiTestCase);
} else if (StringUtils.equals("fullCoverage", apiTestImportRequest.getModeId())) {
apiTestCase.setId(sameCase.getId());
apiTestCase.setUpdateTime(System.currentTimeMillis());
apiTestCase.setCreateTime(null);
apiTestCase.setPriority(sameCase.getPriority());
apiTestCase.setCreateUserId(sameCase.getCreateUserId());
apiTestCase.setNum(sameCase.getNum());
apiTestCase.setOrder(sameCase.getOrder());
apiTestCase.setProjectId(sameCase.getProjectId());
apiTestCase.setVersion((sameCase.getVersion() == null ? 0 : sameCase.getVersion()) + 1);
apiTestCaseMapper.updateByPrimaryKeySelective(apiTestCase);
}
}
private void deleteFileByTestId(String apiId) {
ApiTestFileExample apiTestFileExample = new ApiTestFileExample();
apiTestFileExample.createCriteria().andTestIdEqualTo(apiId);
@ -1615,14 +1509,6 @@ public class ApiDefinitionService {
return buildAPIReportResult(result);
}
public ApiDefinitionExecResult getResultByJenkins(String testId, String type) {
return extApiDefinitionExecResultMapper.selectMaxResultByResourceIdAndType(testId, type);
}
public ApiTestCaseWithBLOBs getApiCaseInfo(String apiCaseId) {
return apiTestCaseMapper.selectByPrimaryKey(apiCaseId);
}
private void setModule(ApiDefinitionWithBLOBs item) {
if (item != null && StringUtils.isEmpty(item.getModuleId()) || "default-module".equals(item.getModuleId())) {
ApiModuleExample example = new ApiModuleExample();
@ -1639,8 +1525,10 @@ public class ApiDefinitionService {
//通过platform获取对应的导入解析类型
if (file != null) {
String originalFilename = file.getOriginalFilename();
String suffixName = originalFilename.substring(originalFilename.indexOf(".") + 1);
checkFileSuffixName(request, suffixName);
if (StringUtils.isNotBlank(originalFilename)) {
String suffixName = originalFilename.substring(originalFilename.indexOf(".") + 1);
checkFileSuffixName(request, suffixName);
}
}
ApiImportParser runService = ApiDefinitionImportParserFactory.getApiImportParser(request.getPlatform());
ApiDefinitionImport apiImport = null;
@ -1848,37 +1736,6 @@ public class ApiDefinitionService {
}
}
/**
* 初始化apiModuleId如果apiModuleId不存在则赋默认的moduleId
*
* @param apiDefinitionList
* @return
*/
private List<ApiDefinitionWithBLOBs> initApiModuleId(List<ApiDefinitionWithBLOBs> apiDefinitionList) {
Map<String, List<String>> protocalModuleIdMap = new HashMap<>();
apiDefinitionList.forEach(apiDefinition -> {
if (protocalModuleIdMap.containsKey(apiDefinition.getProtocol()) && !protocalModuleIdMap.get(apiDefinition.getProtocol()).contains(apiDefinition.getModuleId())) {
protocalModuleIdMap.get(apiDefinition.getProtocol()).add(apiDefinition.getModuleId());
} else {
protocalModuleIdMap.put(apiDefinition.getProtocol(), new ArrayList<>() {{
this.add(apiDefinition.getModuleId());
}});
}
});
Map<String, List<String>> rightfulModuleIdMap = apiModuleService.checkModuleIds(protocalModuleIdMap);
for (ApiDefinitionWithBLOBs apiBlobs : apiDefinitionList) {
if (!rightfulModuleIdMap.containsKey(apiBlobs.getProtocol()) || !rightfulModuleIdMap.get(apiBlobs.getProtocol()).contains(apiBlobs.getModuleId())) {
ApiModule defaultModule = apiModuleService.getDefaultNode(apiBlobs.getProjectId(), apiBlobs.getProtocol());
if (defaultModule != null) {
apiBlobs.setModuleId(defaultModule.getId());
apiBlobs.setModulePath(defaultModule.getName());
}
}
}
return apiDefinitionList;
}
public ReferenceDTO getReference(ApiScenarioRequest request) {
ReferenceDTO dto = new ReferenceDTO();
dto.setScenarioList(extApiScenarioMapper.selectReference(request));
@ -1995,7 +1852,7 @@ public class ApiDefinitionService {
* 数据统计-接口类型
*
* @param projectId 项目ID
* @return
* @return List
*/
public List<ApiDataCountResult> countProtocolByProjectID(String projectId) {
return extApiDefinitionMapper.countProtocolByProjectID(projectId);
@ -2071,23 +1928,6 @@ public class ApiDefinitionService {
return example;
}
private List<String> getAllApiIdsByFontedSelect(Map<String, List<String>> filters, String name, List<String> moduleIds, String projectId, List<String> unSelectIds, String protocol) {
ApiDefinitionRequest request = new ApiDefinitionRequest();
request.setFilters(filters);
request.setName(name);
request.setModuleIds(moduleIds);
request.setProjectId(projectId);
request.setWorkspaceId(SessionUtils.getCurrentWorkspaceId());
request.setProtocol(protocol);
List<ApiDefinitionResult> resList = extApiDefinitionMapper.list(request);
List<String> ids = new ArrayList<>(0);
if (!resList.isEmpty()) {
List<String> allIds = resList.stream().map(ApiDefinitionResult::getId).collect(Collectors.toList());
ids = allIds.stream().filter(id -> !unSelectIds.contains(id)).collect(Collectors.toList());
}
return ids;
}
public void removeToGcByParams(ApiBatchRequest request) {
// 去除Name排序
if (request.getCondition() != null && CollectionUtils.isNotEmpty(request.getCondition().getOrders())) {
@ -2111,7 +1951,6 @@ public class ApiDefinitionService {
return PageUtils.setPageInfo(page, resList);
}
public List<ApiDefinitionResult> listRelevanceReview(ApiDefinitionRequest request) {
request.setOrders(ServiceUtils.getDefaultSortOrder(request.getOrders()));
List<ApiDefinitionResult> resList = extApiDefinitionMapper.listRelevanceReview(request);
@ -2166,7 +2005,9 @@ public class ApiDefinitionService {
}
}
/*swagger定时导入*/
/**
* swagger定时导入
*/
public void createSchedule(ScheduleRequest request) {
/*保存swaggerUrl*/
SwaggerUrlProject swaggerUrlProject = new SwaggerUrlProject();
@ -2223,8 +2064,9 @@ public class ApiDefinitionService {
this.addOrUpdateSwaggerImportCronJob(request);
}
// 设置 SwaggerUrl 同步鉴权参数
/**
* 设置 SwaggerUrl 同步鉴权参数
*/
public String setAuthParams(ScheduleRequest request) {
// list 数组转化成 json 字符串
JSONObject configObj = new JSONObject();
@ -2239,7 +2081,6 @@ public class ApiDefinitionService {
return JSONObject.toJSONString(configObj);
}
/**
* 列表开关切换
*
@ -2437,19 +2278,16 @@ public class ApiDefinitionService {
if (CollectionUtils.isNotEmpty(definitions)) {
List<DetailColumn> columns = new LinkedList<>();
if (StringUtils.isNotEmpty(request.getMethod())) {
columns.clear();
definitions.forEach(item -> {
DetailColumn column = new DetailColumn(DefinitionReference.definitionColumns.get("method"), "method", item.getMethod(), null);
columns.add(column);
});
} else if (StringUtils.isNotEmpty(request.getStatus())) {
columns.clear();
definitions.forEach(item -> {
DetailColumn column = new DetailColumn(DefinitionReference.definitionColumns.get("status"), "status", StatusReference.statusMap.get(item.getStatus()), null);
columns.add(column);
});
} else if (StringUtils.isNotEmpty(request.getUserId())) {
columns.clear();
definitions.forEach(item -> {
DetailColumn column = new DetailColumn(DefinitionReference.definitionColumns.get("userId"), "userId", item.getUserId(), null);
columns.add(column);
@ -2483,9 +2321,7 @@ public class ApiDefinitionService {
public void removeToGcByExample(ApiDefinitionExampleWithOperation apiDefinitionExample) {
List<ApiDefinition> apiList = apiDefinitionMapper.selectByExample(apiDefinitionExample);
List<String> apiIdList = new ArrayList<>();
apiList.forEach(item -> {
apiIdList.add(item.getId());
});
apiList.forEach(item -> apiIdList.add(item.getId()));
this.removeToGc(apiIdList);
}
@ -2688,7 +2524,9 @@ public class ApiDefinitionService {
public void batchCopy(ApiBatchRequest request) {
//检查测试项目是否开启了url可重复
ProjectService projectService = CommonBeanFactory.getBean(ProjectService.class);
projectService.checkProjectIsRepeatable(request.getProjectId());
if (projectService != null) {
projectService.checkProjectIsRepeatable(request.getProjectId());
}
ServiceUtils.getSelectAllIds(request, request.getCondition(),
(query) -> extApiDefinitionMapper.selectIds(query));
List<String> ids = request.getIds();
@ -2696,7 +2534,7 @@ public class ApiDefinitionService {
List<ApiDefinitionWithBLOBs> apis = getByIds(ids);
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
ApiDefinitionMapper mapper = sqlSession.getMapper(ApiDefinitionMapper.class);
Long nextOrder = ServiceUtils.getNextOrder(request.getProjectId(), extApiDefinitionMapper::getLastOrder);
long nextOrder = ServiceUtils.getNextOrder(request.getProjectId(), extApiDefinitionMapper::getLastOrder);
int nextNum = getNextNum(request.getProjectId());