refactor(接口测试): 接口管理测试增删改复制代码完善

This commit is contained in:
lan-yonghui 2023-11-20 22:04:46 +08:00 committed by Craftsman
parent c2c52dd971
commit 36a5753858
6 changed files with 100 additions and 109 deletions

View File

@ -5,12 +5,14 @@ import io.metersphere.plugin.api.spi.AbstractMsTestElement;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* @author lan
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class ApiDefinitionDTO extends ApiDefinition{
@Schema(description = "请求内容")

View File

@ -105,7 +105,7 @@
set deleted = 1,
delete_user = #{userId},
delete_time = UNIX_TIMESTAMP()*1000
where id in
where ref_id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>

View File

@ -145,25 +145,27 @@ public class ApiDefinitionLogService {
*/
public List<LogDTO> batchUpdateLog(ApiDefinitionBatchUpdateRequest request) {
List<String> ids = apiDefinitionService.getBatchApiIds(request, request.getProjectId(), request.getProtocol());
ApiDefinitionExample example = new ApiDefinitionExample();
example.createCriteria().andIdIn(ids);
List<ApiDefinition> apiDefinitions = apiDefinitionMapper.selectByExample(example);
List<LogDTO> dtoList = new ArrayList<>();
apiDefinitions.forEach(item -> {
LogDTO dto = new LogDTO(
item.getProjectId(),
"",
item.getId(),
item.getCreateUser(),
OperationLogType.UPDATE.name(),
OperationLogModule.API_DEFINITION,
item.getName());
if (CollectionUtils.isNotEmpty(ids)) {
ApiDefinitionExample example = new ApiDefinitionExample();
example.createCriteria().andIdIn(ids);
List<ApiDefinition> apiDefinitions = apiDefinitionMapper.selectByExample(example);
apiDefinitions.forEach(item -> {
LogDTO dto = new LogDTO(
item.getProjectId(),
"",
item.getId(),
item.getCreateUser(),
OperationLogType.UPDATE.name(),
OperationLogModule.API_DEFINITION,
item.getName());
dto.setPath("/api/definition/batch-update");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(item));
dtoList.add(dto);
});
dto.setPath("/api/definition/batch-update");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(item));
dtoList.add(dto);
});
}
return dtoList;
}
@ -189,12 +191,13 @@ public class ApiDefinitionLogService {
public List<LogDTO> batchMoveLog(ApiDefinitionBatchMoveRequest request) {
List<String> ids = apiDefinitionService.getBatchApiIds(request, request.getProjectId(), request.getProtocol());
ApiDefinitionExample example = new ApiDefinitionExample();
example.createCriteria().andIdIn(ids);
List<ApiDefinition> apiDefinitions = apiDefinitionMapper.selectByExample(example);
List<LogDTO> dtoList = new ArrayList<>();
apiDefinitions.forEach(item -> {
LogDTO dto = new LogDTO(
if (CollectionUtils.isNotEmpty(ids)) {
ApiDefinitionExample example = new ApiDefinitionExample();
example.createCriteria().andIdIn(ids);
List<ApiDefinition> apiDefinitions = apiDefinitionMapper.selectByExample(example);
apiDefinitions.forEach(item -> {
LogDTO dto = new LogDTO(
item.getProjectId(),
"",
item.getId(),
@ -203,29 +206,33 @@ public class ApiDefinitionLogService {
OperationLogModule.API_DEFINITION,
item.getName());
dto.setPath("/api/definition/batch-move");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(item));
dtoList.add(dto);
});
dto.setPath("/api/definition/batch-move");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(item));
dtoList.add(dto);
});
}
return dtoList;
}
public LogDTO followLog(String id) {
ApiDefinition apiDefinition = apiDefinitionMapper.selectByPrimaryKey(id);
Project project = projectMapper.selectByPrimaryKey(apiDefinition.getProjectId());
LogDTO dto = new LogDTO(
apiDefinition.getProjectId(),
project.getOrganizationId(),
id,
null,
OperationLogType.UPDATE.name(),
OperationLogModule.API_DEFINITION,
Translator.get("follow") + apiDefinition.getName());
if(apiDefinition != null){
Project project = projectMapper.selectByPrimaryKey(apiDefinition.getProjectId());
LogDTO dto = new LogDTO(
apiDefinition.getProjectId(),
project.getOrganizationId(),
id,
null,
OperationLogType.UPDATE.name(),
OperationLogModule.API_DEFINITION,
Translator.get("follow") + apiDefinition.getName());
dto.setPath("/api/definition/follow/" + id);
dto.setMethod(HttpMethodConstants.GET.name());
dto.setOriginalValue(JSON.toJSONBytes(apiDefinition));
return dto;
dto.setPath("/api/definition/follow/" + id);
dto.setMethod(HttpMethodConstants.GET.name());
dto.setOriginalValue(JSON.toJSONBytes(apiDefinition));
return dto;
}
return null;
}
}

View File

@ -72,8 +72,6 @@ public class ApiDefinitionService {
@Resource
private SqlSessionFactory sqlSessionFactory;
@Resource
private ApiTestCaseService apiTestCaseService;
public List<ApiDefinitionDTO> getApiDefinitionPage(ApiDefinitionPageRequest request, Boolean deleted){
List<ApiDefinitionDTO> list = extApiDefinitionMapper.list(request, deleted);
@ -212,16 +210,17 @@ public class ApiDefinitionService {
public void batchMove(ApiDefinitionBatchMoveRequest request, String userId) {
List<String> ids = getBatchApiIds(request, request.getProjectId(), request.getProtocol());
if (CollectionUtils.isNotEmpty(ids)) {
List<String> refId = extApiDefinitionMapper.getRefIds(ids);
extApiDefinitionMapper.batchMove(request, refId, userId);
if (!ids.isEmpty()) {
List<String> refIds = extApiDefinitionMapper.getRefIds(ids);
if (!refIds.isEmpty()) {
extApiDefinitionMapper.batchMove(request, refIds, userId);
}
}
}
private void processApiDefinitions(List<ApiDefinitionDTO> list, String projectId) {
Set<String> userIds = extractUserIds(list);
Map<String, String> userMap = userLoginService.getUserNameMap(new ArrayList<>(userIds));
List<String> apiDefinitionIds = list.stream().map(ApiDefinitionDTO::getId).toList();
List<ApiCaseComputeDTO> apiCaseComputeList = extApiDefinitionMapper.selectApiCaseByIdsAndStatusIsNotTrash(apiDefinitionIds, projectId);
Map<String, ApiCaseComputeDTO> resultMap = apiCaseComputeList.stream().collect(Collectors.toMap(ApiCaseComputeDTO::getApiDefinitionId, Function.identity()));
@ -278,8 +277,6 @@ public class ApiDefinitionService {
FileRequest fileRequest = new FileRequest();
fileRequest.setFileName(file.getName());
fileRequest.setFolder(minioPath(projectId));
fileRequest.setProjectId(projectId);
fileRequest.setResourceId(apiId);
fileRequest.setStorage(StorageType.MINIO.name());
try {
minioRepository.saveFile(file, fileRequest);
@ -418,19 +415,13 @@ public class ApiDefinitionService {
return copyName;
}
public Map<String, ApiDefinitionBlob> copyBlobInfo(List<String> ids) {
ApiDefinitionBlobExample blobExample = new ApiDefinitionBlobExample();
blobExample.createCriteria().andIdIn(ids);
List<ApiDefinitionBlob> apiDefinitionBlobs = apiDefinitionBlobMapper.selectByExampleWithBLOBs(blobExample);
return apiDefinitionBlobs.stream().collect(Collectors.toMap(ApiDefinitionBlob::getId, apiDefinitionBlob -> apiDefinitionBlob));
}
private void handleDeleteApiDefinition(List<String> ids, Boolean deleteAll, String userId) {
if (deleteAll) {
//全部删除 进入回收站
List<String> refId = extApiDefinitionMapper.getRefIds(ids);
extApiDefinitionMapper.batchDelete(refId, userId);
if(CollectionUtils.isNotEmpty(refId)){
extApiDefinitionMapper.batchDelete(refId, userId);
}
} else {
//列表删除 需要判断是否存在多个版本问题
ids.forEach(id -> {

View File

@ -71,31 +71,9 @@ public class ApiDefinitionControllerTests extends BaseTest {
@Resource
private ApiDefinitionFollowerMapper apiDefinitionFollowerMapper;
@Resource
private ApiDefinitionModuleMapper apiDefinitionModuleMapper;
@Resource
private ExtBaseProjectVersionMapper extBaseProjectVersionMapper;
@Test
@Order(0)
@Sql(scripts = {"/dml/init_api_definition.sql"}, config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED))
public void initData(){
LogUtils.info("init api test data");
ApiDefinitionModule request = new ApiDefinitionModule();
request.setProjectId(DEFAULT_PROJECT_ID);
request.setName("a1");
request.setId(DEFAULT_MODULE_ID);
request.setProtocol("HTTP");
request.setParentId("root");
request.setPos(10L);
request.setCreateTime(0L);
request.setUpdateTime(0L);
request.setUpdateUser("admin");
request.setCreateUser("admin");
apiDefinitionModuleMapper.insertSelective(request);
}
@Test
@Order(1)
@ -121,7 +99,7 @@ public class ApiDefinitionControllerTests extends BaseTest {
ApiDefinition resultData = getResultData(mvcResult, ApiDefinition.class);
ApiDefinition apiDefinition = assertAddApiDefinition(request, msHttpElement, resultData.getId());
// 再插入一条数据便于修改时重名校验
request.setName("接口定义test1");
request.setName("接口定义test-6");
paramMap.clear();
paramMap.add("request", JSON.toJSONString(request));
mvcResult = this.requestMultipartWithOkAndReturn(ADD, paramMap);
@ -210,7 +188,7 @@ public class ApiDefinitionControllerTests extends BaseTest {
@Order(3)
@Sql(scripts = {"/dml/init_api_definition.sql"}, config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED))
public void testUpdate() throws Exception {
LogUtils.info("delete api test");
LogUtils.info("update api test");
ApiDefinition apiDefinition = apiDefinitionMapper.selectByPrimaryKey("1001");
ApiDefinitionUpdateRequest request = new ApiDefinitionUpdateRequest();
BeanUtils.copyBean(request, apiDefinition);
@ -461,49 +439,58 @@ public class ApiDefinitionControllerTests extends BaseTest {
checkLog(apiDefinition.getId(), OperationLogType.DELETE);
ApiDefinition apiDefinitionInfo = apiDefinitionMapper.selectByPrimaryKey(apiDefinition.getId());
Assertions.assertTrue(apiDefinitionInfo.getDeleted());
Assertions.assertEquals(apiDefinitionInfo.getDeleteUser(), "admin");
Assertions.assertEquals("admin", apiDefinitionInfo.getDeleteUser());
Assertions.assertNotNull(apiDefinitionInfo.getDeleteTime());
// @存在多个版本
MvcResult mvcResult = this.requestGetWithOk(VERSION + apiDefinition.getId()).andReturn();
// 列表删除
apiDefinitionDeleteRequest.setDeleteAll(false);
apiDefinitionDeleteRequest.setId("1004");
ApiDefinition delApiDefinition = apiDefinitionMapper.selectByPrimaryKey(apiDefinitionDeleteRequest.getId());
MvcResult mvcResult = this.requestGetWithOk(VERSION + apiDefinitionDeleteRequest.getId()).andReturn();
ApiDataUtils.setResolver(MsHTTPElement.class);
List<ApiDefinitionVersionDTO> apiDefinitionVersionDTO = getResultDataArray(mvcResult, ApiDefinitionVersionDTO.class);
if(!apiDefinitionVersionDTO.isEmpty()){
ApiDefinition delApiDefinition = apiDefinitionMapper.selectByPrimaryKey(apiDefinitionDeleteRequest.getId());
// 列表删除
apiDefinitionDeleteRequest.setDeleteAll(false);
apiDefinitionDeleteRequest.setId("1004");
this.requestPostWithOkAndReturn(DELETE, apiDefinitionDeleteRequest);
checkLog(apiDefinitionDeleteRequest.getId(), OperationLogType.DELETE);
Assertions.assertTrue(delApiDefinition.getDeleted());
Assertions.assertEquals(delApiDefinition.getDeleteUser(), "admin");
Assertions.assertNotNull(delApiDefinition.getDeleteTime());
// 效验数据
// 删除的数据为最新版本需要更新最近一条数据为最新数据
if(delApiDefinition.getLatest()){
ApiDefinitionExample example = new ApiDefinitionExample();
example.createCriteria().andRefIdEqualTo(delApiDefinition.getRefId()).andDeletedEqualTo(false).andProjectIdEqualTo(delApiDefinition.getProjectId());
example.setOrderByClause("update_time DESC");
apiDefinitionMapper.selectByExample(example).stream().findFirst().ifPresent(updateApiDefinition -> Assertions.assertTrue(updateApiDefinition.getLatest()));
ApiDefinition updateApiDefinition = apiDefinitionMapper.selectByExample(example).stream().findFirst().orElse(null);
if(updateApiDefinition != null) {
Assertions.assertTrue(updateApiDefinition.getLatest());
Assertions.assertFalse(updateApiDefinition.getDeleted());
}
}
// 全部删除
apiDefinitionDeleteRequest.setDeleteAll(true);
apiDefinitionDeleteRequest.setId("1006");
// @@请求成功
this.requestPostWithOkAndReturn(DELETE, apiDefinitionDeleteRequest);
List<String> ids = extApiDefinitionMapper.getApiDefinitionByRefId(apiDefinitionDeleteRequest.getId()).stream().map(ApiDefinitionVersionDTO::getId).toList();
ApiDefinitionExample apiDefinitionExample = new ApiDefinitionExample();
apiDefinitionExample.createCriteria().andIdIn(ids).andDeletedEqualTo(false);
List<ApiDefinition> apiDefinitions = apiDefinitionMapper.selectByExample(apiDefinitionExample);
if(CollectionUtils.isNotEmpty(apiDefinitions)){
apiDefinitions.forEach(item -> {
Assertions.assertTrue(item.getDeleted());
Assertions.assertEquals(item.getDeleteUser(), "admin");
Assertions.assertNotNull(item.getDeleteTime());
});
ApiDefinition delApiDefinitionInfo = apiDefinitionMapper.selectByPrimaryKey(apiDefinitionDeleteRequest.getId());
if(delApiDefinitionInfo != null){
Assertions.assertTrue(delApiDefinitionInfo.getDeleted());
Assertions.assertEquals("admin", delApiDefinitionInfo.getDeleteUser());
Assertions.assertNotNull(delApiDefinitionInfo.getDeleteTime());
}
checkLog(apiDefinitionDeleteRequest.getId(), OperationLogType.DELETE);
}
// 全部删除
apiDefinitionDeleteRequest.setDeleteAll(true);
apiDefinitionDeleteRequest.setId("1002");
// @@请求成功
this.requestPostWithOkAndReturn(DELETE, apiDefinitionDeleteRequest);
List<String> ids = extApiDefinitionMapper.getApiDefinitionByRefId(apiDefinitionDeleteRequest.getId()).stream().map(ApiDefinitionVersionDTO::getId).toList();
ApiDefinitionExample apiDefinitionExample = new ApiDefinitionExample();
apiDefinitionExample.createCriteria().andIdIn(ids);
List<ApiDefinition> apiDefinitions = apiDefinitionMapper.selectByExample(apiDefinitionExample);
if(CollectionUtils.isNotEmpty(apiDefinitions)){
apiDefinitions.forEach(item -> {
Assertions.assertTrue(item.getDeleted());
Assertions.assertEquals("admin", item.getDeleteUser());
Assertions.assertNotNull(item.getDeleteTime());
});
}
checkLog(apiDefinitionDeleteRequest.getId(), OperationLogType.DELETE);
// @@校验权限
requestPostPermissionTest(PermissionConstants.PROJECT_API_DEFINITION_DELETE, DELETE, apiDefinitionDeleteRequest);
}
@ -527,6 +514,7 @@ public class ApiDefinitionControllerTests extends BaseTest {
checkLog("1002", OperationLogType.DELETE);
checkLog("1005", OperationLogType.DELETE);
// 删除全部 条件为关键字为st-6的数据
request.setDeleteAll(true);
request.setSelectAll(true);
BaseCondition baseCondition = new BaseCondition();
baseCondition.setKeyword("st-6");

View File

@ -26,3 +26,6 @@ INSERT INTO `api_report` (`id`, `name`, `resource_id`, `create_time`, `update_ti
INSERT INTO `api_report` (`id`, `name`, `resource_id`, `create_time`, `update_time`, `create_user`, `update_user`, `deleted`, `status`, `start_time`, `end_time`, `run_mode`, `pool_id`, `trigger_mode`, `version_id`, `project_id`, `integrated_report_id`, `integrated`) VALUES ('10004', '报告004', 'resource_id_10001', 1680624405386, 1680624405386, 'admin', 'admin', b'0', 'SUCCESS', 1680624405386, 1680624405386, 'API', 'pol_id_100001', 'hand', NULL, '100001100001', 'NONE', b'0');
INSERT INTO `api_report` (`id`, `name`, `resource_id`, `create_time`, `update_time`, `create_user`, `update_user`, `deleted`, `status`, `start_time`, `end_time`, `run_mode`, `pool_id`, `trigger_mode`, `version_id`, `project_id`, `integrated_report_id`, `integrated`) VALUES ('10005', '报告005', 'resource_id_10001', 1680624405386, 1680624405386, 'admin', 'admin', b'0', 'ERROR', 1680624405386, 1680624405386, 'API', 'pol_id_100001', 'hand', NULL, '100001100001', 'NONE', b'0');
INSERT INTO `api_report` (`id`, `name`, `resource_id`, `create_time`, `update_time`, `create_user`, `update_user`, `deleted`, `status`, `start_time`, `end_time`, `run_mode`, `pool_id`, `trigger_mode`, `version_id`, `project_id`, `integrated_report_id`, `integrated`) VALUES ('10006', '报告006', 'resource_id_10001', 1680624405386, 1680624405386, 'admin', 'admin', b'0', 'SUCCESS', 1680624405386, 1680624405386, 'API', 'pol_id_100001', 'hand', NULL, '100001100001', 'NONE', b'0');
DELETE FROM `api_definition_module` WHERE `id` = '10001';
INSERT INTO `api_definition_module` (`id`, `name`, `protocol`, `parent_id`, `project_id`, `pos`, `create_time`, `update_time`, `update_user`, `create_user`) VALUES ('10001', 'module1', 'HTTP', 'root', '100001100001', 10, 0, 0, 'admin', 'admin');