refactor(资源池): 资源池部分功能移动到xpack

This commit is contained in:
guoyuqi 2023-11-16 18:54:37 +08:00 committed by 刘瑞斌
parent fe0cf474fc
commit cc66c92b40
9 changed files with 184 additions and 346 deletions

View File

@ -70,11 +70,14 @@ schedule.create_user.length_range=定时任务创建人长度必须在{min}和{m
system_parameter.param_key.not_blank=系统参数Key不能为空
system_parameter.type.not_blank=系统参数类型不能为空
system_parameter.type.length_range=系统参数类型长度必须在{min}和{max}之间
# 资源池
test_resource.id.not_blank=资源池节点ID不能为空
test_resource.test_resource_pool_id.not_blank=资源池ID不能为空
test_resource.test_resource_pool_id.length_range=资源池ID长度必须在{min}和{max}之间
test_resource.status.not_blank=资源池节点状态不能为空
test_resource.status.length_range=资源池节点状态长度必须在{min}和{max}之间
test_resource_pool.node_must_be_two=资源池节点最多为2个
test_resource_pool.node_must_have_one=资源池节点至少保留一个
test_resource_pool.id.not_blank=资源池ID不能为空
test_resource_pool.name.not_blank=资源池名称不能为空
test_resource_pool.name.length_range=资源池名称长度必须在{min}和{max}之间
@ -82,6 +85,7 @@ test_resource_pool.type.not_blank=资源池类型不能为空
test_resource_pool.type.length_range=资源池类型长度必须在{min}和{max}之间
test_resource_pool.status.not_blank=资源池状态不能为空
test_resource_pool.status.length_range=资源池状态长度必须在{min}和{max}之间
user.not.delete=用户不能删除
user.not.disable=用户不能禁用
user.id.not_blank=用户ID不能为空

View File

@ -71,11 +71,14 @@ schedule.create_user.length_range=Schedule create user must be between {min} and
system_parameter.param_key.not_blank=System parameter param key must not be blank
system_parameter.type.not_blank=System parameter type must not be blank
system_parameter.type.length_range=System parameter type must be between {min} and {max} characters long
#资源池
test_resource.id.not_blank=Test resource id must not be blank
test_resource.test_resource_pool_id.not_blank=Test resource test resource pool id must not be blank
test_resource.test_resource_pool_id.length_range=Test resource test resource pool id must be between {min} and {max} characters long
test_resource.status.not_blank=Test resource status must not be blank
test_resource.status.length_range=Test resource status must be between {min} and {max} characters long
test_resource_pool.node_must_be_two=The maximum number of resource pool nodes is 2
test_resource_pool.node_must_have_one=Reserve at least one resource pool node
test_resource_pool.id.not_blank=Test resource pool id must not be blank
test_resource_pool.name.not_blank=Test resource pool name must not be blank
test_resource_pool.name.length_range=Test resource pool name must be between {min} and {max} characters long

View File

@ -71,11 +71,14 @@ schedule.create_user.length_range=定时任务创建人长度必须在{min}和{m
system_parameter.param_key.not_blank=系统参数Key不能为空
system_parameter.type.not_blank=系统参数类型不能为空
system_parameter.type.length_range=系统参数类型长度必须在{min}和{max}之间
# 资源池
test_resource.id.not_blank=资源池节点ID不能为空
test_resource.test_resource_pool_id.not_blank=资源池ID不能为空
test_resource.test_resource_pool_id.length_range=资源池ID长度必须在{min}和{max}之间
test_resource.status.not_blank=资源池节点状态不能为空
test_resource.status.length_range=资源池节点状态长度必须在{min}和{max}之间
test_resource_pool.node_must_be_two=资源池节点最多为2个
test_resource_pool.node_must_have_one=资源池节点至少保留一个
test_resource_pool.id.not_blank=资源池ID不能为空
test_resource_pool.name.not_blank=资源池名称不能为空
test_resource_pool.name.length_range=资源池名称长度必须在{min}和{max}之间
@ -83,6 +86,7 @@ test_resource_pool.type.not_blank=资源池类型不能为空
test_resource_pool.type.length_range=资源池类型长度必须在{min}和{max}之间
test_resource_pool.status.not_blank=资源池状态不能为空
test_resource_pool.status.length_range=资源池状态长度必须在{min}和{max}之间
user.not.delete=用户不能删除
user.not.disable=用户不能禁用
user.id.not_blank=用户ID不能为空

View File

@ -71,11 +71,14 @@ schedule.create_user.length_range=定時任務創建人長度必須在{min}和{m
system_parameter.param_key.not_blank=系統參數Key不能為空
system_parameter.type.not_blank=系統參數類型不能為空
system_parameter.type.length_range=系統參數類型長度必須在{min}和{max}之間
# 资源池
test_resource.id.not_blank=資源池節點ID不能為空
test_resource.test_resource_pool_id.not_blank=資源池ID不能為空
test_resource.test_resource_pool_id.length_range=資源池ID長度必須在{min}和{max}之間
test_resource.status.not_blank=資源池節點狀態不能為空
test_resource.status.length_range=資源池節點狀態長度必須在{min}和{max}之間
test_resource_pool.node_must_be_two=資源池節點最多為2個
test_resource_pool.node_must_have_one=資源池節點至少保留一個
test_resource_pool.id.not_blank=資源池ID不能為空
test_resource_pool.name.not_blank=資源池名稱不能為空
test_resource_pool.name.length_range=資源池名稱長度必須在{min}和{max}之間

View File

@ -3,15 +3,23 @@ package io.metersphere.api.controller;
import io.metersphere.api.engine.ApiEngine;
import io.metersphere.api.engine.EngineFactory;
import io.metersphere.sdk.constants.ResourcePoolTypeEnum;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.dto.api.task.TaskRequest;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.CommonBeanFactory;
import io.metersphere.sdk.util.JSON;
import io.metersphere.system.base.BaseTest;
import io.metersphere.system.controller.handler.ResultHolder;
import io.metersphere.system.domain.TestResourcePool;
import io.metersphere.system.domain.TestResourcePoolBlob;
import io.metersphere.system.dto.pool.TestResourceDTO;
import io.metersphere.system.dto.pool.TestResourcePoolDTO;
import io.metersphere.system.dto.pool.TestResourcePoolRequest;
import io.metersphere.system.mapper.TestResourcePoolBlobMapper;
import io.metersphere.system.mapper.TestResourcePoolMapper;
import io.metersphere.system.service.TestResourcePoolService;
import io.metersphere.system.uid.IDGenerator;
import io.metersphere.system.utils.SessionUtils;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
@ -19,24 +27,20 @@ import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.io.UnsupportedEncodingException;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@AutoConfigureMockMvc
public class KubernetesEngineTests extends BaseTest {
@Resource
private MockMvc mockMvc;
private static final String TEST_RESOURCE_POOL_ADD = "/test/resource/pool/add";
private TestResourcePoolMapper testResourcePoolMapper;
@Resource
private TestResourcePoolBlobMapper testResourcePoolBlobMapper;
private static final String configurationWidthOutOrgIds = "{\n" +
" \"loadTestImage\": \"123\",\n" +
" \"loadTestHeap\": \"123\",\n" +
@ -85,6 +89,8 @@ public class KubernetesEngineTests extends BaseTest {
@Value("${embedded.mockserver.port}")
private int port;
protected TestResourcePoolService testResourcePoolService;
private void setResources(TestResourcePoolRequest testResourcePoolDTO, boolean isPart) {
TestResourceDTO testResourceDTO;
if (isPart) {
@ -99,13 +105,7 @@ public class KubernetesEngineTests extends BaseTest {
testResourcePoolDTO.setTestResourceDTO(testResourceDTO);
}
private static TestResourcePool getResult(MvcResult mvcResult) throws UnsupportedEncodingException {
String contentAsString = mvcResult.getResponse().getContentAsString();
ResultHolder resultHolder = JSON.parseObject(contentAsString, ResultHolder.class);
return JSON.parseObject(JSON.toJSONString(resultHolder.getData()), TestResourcePool.class);
}
private String addPool(String type) throws Exception {
private String addPool(String type) {
TestResourcePoolRequest testResourcePoolRequest = new TestResourcePoolRequest();
testResourcePoolRequest.setId("");
testResourcePoolRequest.setName("api_test_pool");
@ -117,16 +117,47 @@ public class KubernetesEngineTests extends BaseTest {
//应用全部
testResourcePoolRequest.setAllOrg(true);
setResources(testResourcePoolRequest, false);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(TEST_RESOURCE_POOL_ADD)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(testResourcePoolRequest))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andReturn();
String userId = SessionUtils.getUserId();
TestResourcePoolDTO testResourcePool = new TestResourcePoolDTO();
BeanUtils.copyBean(testResourcePool, testResourcePoolRequest);
testResourcePool.setCreateUser(userId);
testResourcePool.setCreateTime(System.currentTimeMillis());
//应用全部 关系表里不会存值
TestResourcePool testResourcePool = getResult(mvcResult);
return testResourcePool.getId();
TestResourcePool testResourcePoolRequest1 = addTestResourcePool(testResourcePool);
return testResourcePoolRequest1.getId();
}
public TestResourcePool addTestResourcePool(TestResourcePoolDTO testResourcePool) {
testResourcePoolService = CommonBeanFactory.getBean(TestResourcePoolService.class);
String id = IDGenerator.nextStr();
testResourcePoolService.checkTestResourcePool(testResourcePool);
TestResourcePoolBlob testResourcePoolBlob = new TestResourcePoolBlob();
testResourcePoolBlob.setId(id);
TestResourceDTO testResourceDTO = testResourcePool.getTestResourceDTO();
testResourcePoolService.checkAndSaveOrgRelation(testResourcePool, id, testResourceDTO);
testResourcePoolService.checkApiConfig(testResourceDTO, testResourcePool, testResourcePool.getType());
testResourcePoolService.checkLoadConfig(testResourceDTO, testResourcePool, testResourcePool.getType());
testResourcePoolService.checkUiConfig(testResourceDTO, testResourcePool);
if (CollectionUtils.isEmpty(testResourceDTO.getNodesList())) {
testResourceDTO.setNodesList(new ArrayList<>());
}
String configuration = JSON.toJSONString(testResourceDTO);
testResourcePoolBlob.setConfiguration(configuration.getBytes());
buildTestPoolBaseInfo(testResourcePool, id);
testResourcePoolMapper.insert(testResourcePool);
testResourcePoolBlobMapper.insert(testResourcePoolBlob);
testResourcePool.setId(id);
return testResourcePool;
}
public static void buildTestPoolBaseInfo(TestResourcePool testResourcePool, String id) {
testResourcePool.setId(id);
testResourcePool.setUpdateTime(System.currentTimeMillis());
if (testResourcePool.getEnable() == null) {
testResourcePool.setEnable(true);
}
testResourcePool.setDeleted(false);
}
@Test

View File

@ -3,20 +3,17 @@ package io.metersphere.system.controller;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.system.dto.sdk.QueryResourcePoolRequest;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.system.consul.CacheNode;
import io.metersphere.system.dto.pool.TestResourcePoolDTO;
import io.metersphere.system.dto.pool.TestResourcePoolRequest;
import io.metersphere.system.dto.pool.TestResourcePoolReturnDTO;
import io.metersphere.system.dto.sdk.QueryResourcePoolRequest;
import io.metersphere.system.log.annotation.Log;
import io.metersphere.system.log.constants.OperationLogType;
import io.metersphere.system.service.TestResourcePoolService;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.system.utils.PageUtils;
import io.metersphere.system.utils.Pager;
import io.metersphere.system.utils.SessionUtils;
import io.metersphere.system.consul.CacheNode;
import io.metersphere.system.domain.TestResourcePool;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
@ -35,28 +32,6 @@ public class TestResourcePoolController {
@Resource
private TestResourcePoolService testResourcePoolService;
@PostMapping("/add")
@Operation(summary = "系统设置-系统-资源池-添加资源池")
@RequiresPermissions(PermissionConstants.SYSTEM_TEST_RESOURCE_POOL_READ_ADD)
@Log(type = OperationLogType.ADD, expression = "#msClass.addLog(#request)", msClass = TestResourcePoolService.class)
public TestResourcePool addTestResourcePool(@Validated({Created.class}) @RequestBody TestResourcePoolRequest request) {
String userId = SessionUtils.getUserId();
TestResourcePoolDTO testResourcePool = new TestResourcePoolDTO();
BeanUtils.copyBean(testResourcePool, request);
testResourcePool.setCreateUser(userId);
testResourcePool.setCreateTime(System.currentTimeMillis());
return testResourcePoolService.addTestResourcePool(testResourcePool);
}
@GetMapping("/delete/{poolId}")
@CacheNode // 把监控节点缓存起来
@Operation(summary = "系统设置-系统-资源池-删除资源池")
@RequiresPermissions(PermissionConstants.SYSTEM_TEST_RESOURCE_POOL_READ_DELETE)
@Log(type = OperationLogType.DELETE, expression = "#msClass.deleteLog(#testResourcePoolId)", msClass = TestResourcePoolService.class)
public void deleteTestResourcePool(@PathVariable(value = "poolId") String testResourcePoolId) {
testResourcePoolService.deleteTestResourcePool(testResourcePoolId);
}
@PostMapping("/update")
@CacheNode // 把监控节点缓存起来
@Operation(summary = "系统设置-系统-资源池-更新资源池")
@ -85,13 +60,7 @@ public class TestResourcePoolController {
return testResourcePoolService.getTestResourcePoolDetail(testResourcePoolId);
}
@PostMapping("/set/enable/{poolId}")
@Operation(summary = "系统设置-系统-资源池-资源池禁用")
@RequiresPermissions(PermissionConstants.SYSTEM_TEST_RESOURCE_POOL_READ_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.updateLog(#testResourcePoolId)", msClass = TestResourcePoolService.class)
public void unableTestResourcePool(@PathVariable(value = "poolId") String testResourcePoolId) {
testResourcePoolService.unableTestResourcePool(testResourcePoolId);
}
}

View File

@ -1,7 +1,5 @@
package io.metersphere.system.service;
import io.metersphere.project.domain.ProjectTestResourcePoolExample;
import io.metersphere.project.mapper.ProjectTestResourcePoolMapper;
import io.metersphere.sdk.constants.HttpMethodConstants;
import io.metersphere.sdk.constants.OperationLogConstants;
import io.metersphere.sdk.constants.ResourcePoolTypeEnum;
@ -49,35 +47,9 @@ public class TestResourcePoolService {
private SqlSessionFactory sqlSessionFactory;
@Resource
private OrganizationMapper organizationMapper;
@Resource
private ProjectTestResourcePoolMapper projectTestResourcePoolMapper;
public TestResourcePool addTestResourcePool(TestResourcePoolDTO testResourcePool) {
String id = IDGenerator.nextStr();
checkTestResourcePool(testResourcePool);
TestResourcePoolBlob testResourcePoolBlob = new TestResourcePoolBlob();
testResourcePoolBlob.setId(id);
TestResourceDTO testResourceDTO = testResourcePool.getTestResourceDTO();
checkAndSaveOrgRelation(testResourcePool, id, testResourceDTO);
checkApiConfig(testResourceDTO, testResourcePool, testResourcePool.getType());
checkLoadConfig(testResourceDTO, testResourcePool, testResourcePool.getType());
checkUiConfig(testResourceDTO, testResourcePool);
if (CollectionUtils.isEmpty(testResourceDTO.getNodesList())) {
testResourceDTO.setNodesList(new ArrayList<>());
}
String configuration = JSON.toJSONString(testResourceDTO);
testResourcePoolBlob.setConfiguration(configuration.getBytes());
buildTestPoolBaseInfo(testResourcePool, id);
testResourcePoolMapper.insert(testResourcePool);
testResourcePoolBlobMapper.insert(testResourcePoolBlob);
testResourcePool.setId(id);
return testResourcePool;
}
private void checkAndSaveOrgRelation(TestResourcePool testResourcePool, String id, TestResourceDTO testResourceDTO) {
public void checkAndSaveOrgRelation(TestResourcePool testResourcePool, String id, TestResourceDTO testResourceDTO) {
//防止前端传入的应用组织为空
if ((testResourcePool.getAllOrg() == null || !testResourcePool.getAllOrg()) && CollectionUtils.isEmpty(testResourceDTO.getOrgIds())) {
throw new MSException(Translator.get("resource_pool_application_organization_is_empty"));
@ -105,16 +77,7 @@ public class TestResourcePoolService {
SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);
}
private static void buildTestPoolBaseInfo(TestResourcePool testResourcePool, String id) {
testResourcePool.setId(id);
testResourcePool.setUpdateTime(System.currentTimeMillis());
if (testResourcePool.getEnable() == null) {
testResourcePool.setEnable(true);
}
testResourcePool.setDeleted(false);
}
private boolean checkLoadConfig(TestResourceDTO testResourceDTO, TestResourcePool testResourcePool, String type) {
public boolean checkLoadConfig(TestResourceDTO testResourceDTO, TestResourcePool testResourcePool, String type) {
if (testResourcePool.getLoadTest() == null || !testResourcePool.getLoadTest()) {
return true;
}
@ -142,18 +105,18 @@ public class TestResourcePoolService {
}
}
private boolean checkUiConfig(TestResourceDTO testResourceDTO, TestResourcePool testResourcePool) {
public void checkUiConfig(TestResourceDTO testResourceDTO, TestResourcePool testResourcePool) {
if (testResourcePool.getUiTest() == null || !testResourcePool.getUiTest()) {
return true;
return;
}
UiResourceService resourcePoolService = CommonBeanFactory.getBean(UiResourceService.class);
if (resourcePoolService == null) {
return false;
return;
}
return resourcePoolService.validate(testResourceDTO);
resourcePoolService.validate(testResourceDTO);
}
private boolean checkApiConfig(TestResourceDTO testResourceDTO, TestResourcePool testResourcePool, String type) {
public boolean checkApiConfig(TestResourceDTO testResourceDTO, TestResourcePool testResourcePool, String type) {
if (testResourcePool.getApiTest() == null || !testResourcePool.getApiTest()) {
return true;
}
@ -164,32 +127,6 @@ public class TestResourcePoolService {
return validate;
}
public void deleteTestResourcePool(String testResourcePoolId) {
TestResourcePool testResourcePool = testResourcePoolMapper.selectByPrimaryKey(testResourcePoolId);
if (testResourcePool == null) {
throw new MSException(Translator.get("test_resource_pool_not_exists"));
}
//删除与组织的关系
deleteOrgRelation(testResourcePoolId);
deleteProjectRelation(testResourcePoolId);
testResourcePool.setUpdateTime(System.currentTimeMillis());
testResourcePool.setEnable(false);
testResourcePool.setDeleted(true);
testResourcePoolMapper.updateByPrimaryKeySelective(testResourcePool);
}
private void deleteProjectRelation(String testResourcePoolId) {
ProjectTestResourcePoolExample projectTestResourcePoolExample = new ProjectTestResourcePoolExample();
projectTestResourcePoolExample.createCriteria().andTestResourcePoolIdEqualTo(testResourcePoolId);
projectTestResourcePoolMapper.deleteByExample(projectTestResourcePoolExample);
}
private void deleteOrgRelation(String testResourcePoolId) {
TestResourcePoolOrganizationExample testResourcePoolOrganizationExample = new TestResourcePoolOrganizationExample();
testResourcePoolOrganizationExample.createCriteria().andTestResourcePoolIdEqualTo(testResourcePoolId);
testResourcePoolOrganizationMapper.deleteByExample(testResourcePoolOrganizationExample);
}
public void updateTestResourcePool(TestResourcePoolDTO testResourcePool) {
checkTestResourcePool(testResourcePool);
testResourcePool.setUpdateTime(System.currentTimeMillis());
@ -201,6 +138,10 @@ public class TestResourcePoolService {
if (CollectionUtils.isEmpty(testResourceDTO.getNodesList())) {
testResourceDTO.setNodesList(new ArrayList<>());
}
TestResourcePoolValidateService testResourcePoolValidateService = CommonBeanFactory.getBean(TestResourcePoolValidateService.class);
if (testResourcePoolValidateService!=null) {
testResourcePoolValidateService.validateNodeList(testResourceDTO.getNodesList());
}
String configuration = JSON.toJSONString(testResourceDTO);
TestResourcePoolBlob testResourcePoolBlob = new TestResourcePoolBlob();
testResourcePoolBlob.setId(testResourcePool.getId());
@ -302,43 +243,6 @@ public class TestResourcePoolService {
return testResourcePoolReturnDTO;
}
public LogDTO addLog(TestResourcePoolRequest request) {
LogDTO dto = new LogDTO(
OperationLogConstants.SYSTEM,
OperationLogConstants.SYSTEM,
request.getId(),
null,
OperationLogType.ADD.name(),
OperationLogModule.SETTING_SYSTEM_RESOURCE_POOL,
request.getName());
dto.setPath("/test/resource/pool/add");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(request));
return dto;
}
public LogDTO deleteLog(String id) {
TestResourcePool pool = testResourcePoolMapper.selectByPrimaryKey(id);
if (pool != null) {
LogDTO dto = new LogDTO(
OperationLogConstants.SYSTEM,
OperationLogConstants.SYSTEM,
id,
pool.getCreateUser(),
OperationLogType.DELETE.name(),
OperationLogModule.SETTING_SYSTEM_RESOURCE_POOL,
pool.getName());
dto.setPath("/delete");
dto.setMethod(HttpMethodConstants.POST.name());
dto.setOriginalValue(JSON.toJSONBytes(pool));
return dto;
}
return null;
}
public LogDTO updateLog(String resourcePoolId) {
TestResourcePool pool = testResourcePoolMapper.selectByPrimaryKey(resourcePoolId);
if (pool != null) {
@ -360,32 +264,4 @@ public class TestResourcePoolService {
}
public void unableTestResourcePool(String testResourcePoolId) {
TestResourcePool testResourcePool = testResourcePoolMapper.selectByPrimaryKey(testResourcePoolId);
if (testResourcePool == null) {
throw new MSException(Translator.get("test_resource_pool_not_exists"));
}
testResourcePool.setUpdateTime(System.currentTimeMillis());
Boolean enable = testResourcePool.getEnable();
if (!enable) {
TestResourcePoolBlob testResourcePoolBlob = testResourcePoolBlobMapper.selectByPrimaryKey(testResourcePoolId);
byte[] configuration = testResourcePoolBlob.getConfiguration();
String testResourceDTOStr = new String(configuration);
TestResourceDTO testResourceDTO = JSON.parseObject(testResourceDTOStr, TestResourceDTO.class);
boolean apiValidate = checkApiConfig(testResourceDTO, testResourcePool, testResourcePool.getType());
if (! apiValidate) {
throw new MSException(Translator.get("test_resource_pool_is_valid_fail"));
}
boolean loadValidate = checkLoadConfig(testResourceDTO, testResourcePool, testResourcePool.getType());
if (! loadValidate) {
throw new MSException(Translator.get("test_resource_pool_is_valid_fail"));
}
}
if (enable) {
testResourcePool.setEnable(false);
} else {
testResourcePool.setEnable(true);
}
testResourcePoolMapper.updateByPrimaryKeySelective(testResourcePool);
}
}

View File

@ -0,0 +1,11 @@
package io.metersphere.system.service;
import io.metersphere.system.dto.pool.TestResourceNodeDTO;
import java.util.List;
public interface TestResourcePoolValidateService {
void validateNodeList(List<TestResourceNodeDTO> nodesList);
}

View File

@ -1,24 +1,30 @@
package io.metersphere.system.controller;
import io.metersphere.system.base.BaseTest;
import io.metersphere.sdk.constants.ResourcePoolTypeEnum;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.system.controller.handler.ResultHolder;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.CommonBeanFactory;
import io.metersphere.sdk.util.JSON;
import io.metersphere.system.utils.Pager;
import io.metersphere.system.base.BaseTest;
import io.metersphere.system.controller.handler.ResultHolder;
import io.metersphere.system.domain.TestResourcePool;
import io.metersphere.system.domain.TestResourcePoolBlob;
import io.metersphere.system.domain.TestResourcePoolOrganization;
import io.metersphere.system.domain.TestResourcePoolOrganizationExample;
import io.metersphere.system.dto.pool.*;
import io.metersphere.system.dto.sdk.QueryResourcePoolRequest;
import io.metersphere.system.mapper.TestResourcePoolBlobMapper;
import io.metersphere.system.mapper.TestResourcePoolMapper;
import io.metersphere.system.mapper.TestResourcePoolOrganizationMapper;
import io.metersphere.system.service.TestResourcePoolService;
import io.metersphere.system.uid.IDGenerator;
import io.metersphere.system.utils.Pager;
import io.metersphere.system.utils.SessionUtils;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.*;
import org.mockserver.client.MockServerClient;
import org.mockserver.model.Header;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
@ -30,19 +36,15 @@ import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class TestResourcePoolControllerTests extends BaseTest {
@ -52,7 +54,14 @@ class TestResourcePoolControllerTests extends BaseTest {
@Resource
private TestResourcePoolOrganizationMapper testResourcePoolOrganizationMapper;
@Resource
private MockServerClient mockServerClient;
private TestResourcePoolMapper testResourcePoolMapper;
@Resource
private TestResourcePoolBlobMapper testResourcePoolBlobMapper;
@Resource
private MockServerClient mockServerClient;
protected TestResourcePoolService testResourcePoolService;
@Value("${embedded.mockserver.host}")
private String host;
@ -108,7 +117,7 @@ class TestResourcePoolControllerTests extends BaseTest {
"}";
private MvcResult addTestResourcePoolSuccess(String name, Boolean allOrg, Boolean partOrg, Boolean useApi, Boolean useLoad, Boolean useUi, String type) throws Exception {
private TestResourcePool addTestResourcePoolSuccess(String name, Boolean allOrg, Boolean partOrg, Boolean useApi, Boolean useLoad, Boolean useUi, String type) throws Exception {
TestResourcePoolRequest testResourcePoolRequest = new TestResourcePoolRequest();
testResourcePoolRequest.setId("");
testResourcePoolRequest.setName(name);
@ -120,15 +129,13 @@ class TestResourcePoolControllerTests extends BaseTest {
//应用全部
testResourcePoolRequest.setAllOrg(allOrg);
setResources(testResourcePoolRequest, partOrg);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(TEST_RESOURCE_POOL_ADD)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(testResourcePoolRequest))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andReturn();
String userId = SessionUtils.getUserId();
TestResourcePoolDTO testResourcePool = new TestResourcePoolDTO();
BeanUtils.copyBean(testResourcePool, testResourcePoolRequest);
testResourcePool.setCreateUser(userId);
testResourcePool.setCreateTime(System.currentTimeMillis());
//应用全部 关系表里不会存值
TestResourcePool testResourcePoolRequest1 = getResult(mvcResult);
TestResourcePool testResourcePoolRequest1 = addTestResourcePool(testResourcePool);
List<TestResourcePoolOrganization> testResourcePoolOrganizations = getTestResourcePoolOrganizations(testResourcePoolRequest1);
if (allOrg) {
Assertions.assertTrue(CollectionUtils.isEmpty(testResourcePoolOrganizations));
@ -137,9 +144,39 @@ class TestResourcePoolControllerTests extends BaseTest {
Assertions.assertTrue((CollectionUtils.isNotEmpty(testResourcePoolOrganizations) && testResourcePoolOrganizations.size() == 2));
}
return testResourcePoolRequest1;
}
public TestResourcePool addTestResourcePool(TestResourcePoolDTO testResourcePool) {
testResourcePoolService = CommonBeanFactory.getBean(TestResourcePoolService.class);
String id = IDGenerator.nextStr();
testResourcePoolService.checkTestResourcePool(testResourcePool);
TestResourcePoolBlob testResourcePoolBlob = new TestResourcePoolBlob();
testResourcePoolBlob.setId(id);
TestResourceDTO testResourceDTO = testResourcePool.getTestResourceDTO();
testResourcePoolService.checkAndSaveOrgRelation(testResourcePool, id, testResourceDTO);
testResourcePoolService.checkApiConfig(testResourceDTO, testResourcePool, testResourcePool.getType());
testResourcePoolService.checkLoadConfig(testResourceDTO, testResourcePool, testResourcePool.getType());
testResourcePoolService.checkUiConfig(testResourceDTO, testResourcePool);
if (CollectionUtils.isEmpty(testResourceDTO.getNodesList())) {
testResourceDTO.setNodesList(new ArrayList<>());
}
String configuration = JSON.toJSONString(testResourceDTO);
testResourcePoolBlob.setConfiguration(configuration.getBytes());
buildTestPoolBaseInfo(testResourcePool, id);
testResourcePoolMapper.insert(testResourcePool);
testResourcePoolBlobMapper.insert(testResourcePoolBlob);
testResourcePool.setId(id);
return testResourcePool;
}
return mvcResult;
public static void buildTestPoolBaseInfo(TestResourcePool testResourcePool, String id) {
testResourcePool.setId(id);
testResourcePool.setUpdateTime(System.currentTimeMillis());
if (testResourcePool.getEnable() == null) {
testResourcePool.setEnable(true);
}
testResourcePool.setDeleted(false);
}
@Test
@ -199,34 +236,6 @@ class TestResourcePoolControllerTests extends BaseTest {
this.addTestResourcePoolSuccess("test_pool_7", false, true, true, false, false, ResourcePoolTypeEnum.K8S.name());
}
@Test
@Order(8)
void addTestResourcePoolFailedBySameName() throws Exception {
TestResourcePoolRequest testResourcePoolRequest = new TestResourcePoolRequest();
testResourcePoolRequest.setName("test_pool_7");
testResourcePoolRequest.setType(ResourcePoolTypeEnum.K8S.name());
testResourcePoolRequest.setApiTest(true);
testResourcePoolRequest.setLoadTest(false);
testResourcePoolRequest.setUiTest(false);
//添加成功 需要加应用组织的 全部 部分组织的测试 既有全部又有list
//应用全部
testResourcePoolRequest.setAllOrg(false);
setResources(testResourcePoolRequest, true);
mockMvc.perform(MockMvcRequestBuilders.post(TEST_RESOURCE_POOL_ADD)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(testResourcePoolRequest))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(ERROR_REQUEST_MATCHER)
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
private static TestResourcePool getResult(MvcResult mvcResult) throws UnsupportedEncodingException {
String contentAsString = mvcResult.getResponse().getContentAsString();
ResultHolder resultHolder = JSON.parseObject(contentAsString, ResultHolder.class);
return JSON.parseObject(JSON.toJSONString(resultHolder.getData()), TestResourcePool.class);
}
private List<TestResourcePoolOrganization> getTestResourcePoolOrganizations(TestResourcePool testResourcePoolRequest1) {
TestResourcePoolOrganizationExample testResourcePoolOrganizationExample = new TestResourcePoolOrganizationExample();
@ -234,12 +243,6 @@ class TestResourcePoolControllerTests extends BaseTest {
return testResourcePoolOrganizationMapper.selectByExample(testResourcePoolOrganizationExample);
}
@Test
@Order(9)
void addUiTestResourcePoolFiled() throws Exception {
this.dealTestResourcePoolFiled("ADD");
}
@Test
@Order(10)
/*@Sql(scripts = {"/dml/init_test_resource_pool.sql"},
@ -291,8 +294,7 @@ class TestResourcePoolControllerTests extends BaseTest {
@Test
@Order(13)
void getResourcePoolsDetailWidthBlobK8s() throws Exception {
MvcResult testPoolBlob = this.addTestResourcePoolSuccess("test_pool_blob_k8s", false, true, true, true, true, ResourcePoolTypeEnum.K8S.name());
TestResourcePool testResourcePoolRequest1 = getResult(testPoolBlob);
TestResourcePool testResourcePoolRequest1 = this.addTestResourcePoolSuccess("test_pool_blob_k8s", false, true, true, true, true, ResourcePoolTypeEnum.K8S.name());
String id = testResourcePoolRequest1.getId();
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/test/resource/pool/detail/" + id)
.header(SessionConstants.HEADER_TOKEN, sessionId)
@ -331,8 +333,7 @@ class TestResourcePoolControllerTests extends BaseTest {
@Test
@Order(14)
void getResourcePoolsDetailWidthBlobNode() throws Exception {
MvcResult testPoolBlob = this.addTestResourcePoolSuccess("test_pool_blob_node", false, true, true, true, true, ResourcePoolTypeEnum.NODE.name());
TestResourcePool testResourcePoolRequest1 = getResult(testPoolBlob);
TestResourcePool testResourcePoolRequest1 = this.addTestResourcePoolSuccess("test_pool_blob_node", false, true, true, true, true, ResourcePoolTypeEnum.NODE.name());
String id = testResourcePoolRequest1.getId();
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/test/resource/pool/detail/" + id)
.header(SessionConstants.HEADER_TOKEN, sessionId)
@ -350,7 +351,7 @@ class TestResourcePoolControllerTests extends BaseTest {
}
if (testResourcePoolRequest1.getApiTest()) {
Assertions.assertTrue(testResourcePoolReturnDTO.getTestResourceReturnDTO().getNodesList().size()>0);
Assertions.assertTrue(testResourcePoolReturnDTO.getTestResourceReturnDTO().getNodesList().size() > 0);
for (TestResourceNodeDTO testResourceNodeDTO : testResourcePoolReturnDTO.getTestResourceReturnDTO().getNodesList()) {
Assertions.assertNotNull(testResourceNodeDTO.getIp());
Assertions.assertNotNull(testResourceNodeDTO.getPort());
@ -359,7 +360,7 @@ class TestResourcePoolControllerTests extends BaseTest {
}
if (testResourcePoolRequest1.getLoadTest()) {
Assertions.assertTrue(testResourcePoolReturnDTO.getTestResourceReturnDTO().getNodesList().size()>0);
Assertions.assertTrue(testResourcePoolReturnDTO.getTestResourceReturnDTO().getNodesList().size() > 0);
for (TestResourceNodeDTO testResourceNodeDTO : testResourcePoolReturnDTO.getTestResourceReturnDTO().getNodesList()) {
Assertions.assertNotNull(testResourceNodeDTO.getIp());
Assertions.assertNotNull(testResourceNodeDTO.getPort());
@ -373,8 +374,7 @@ class TestResourcePoolControllerTests extends BaseTest {
@Test
@Order(15)
void getResourcePoolsDetailWidthBlobNoOtgIds() throws Exception {
MvcResult testPoolBlob = this.addTestResourcePoolSuccess("test_pool_blob_no_org_id", true, false, true, false, false, ResourcePoolTypeEnum.K8S.name());
TestResourcePool testResourcePoolRequest1 = getResult(testPoolBlob);
TestResourcePool testResourcePoolRequest1 = this.addTestResourcePoolSuccess("test_pool_blob_no_org_id", true, false, true, false, false, ResourcePoolTypeEnum.K8S.name());
String id = testResourcePoolRequest1.getId();
QueryResourcePoolRequest request = new QueryResourcePoolRequest();
request.setCurrent(1);
@ -412,8 +412,7 @@ class TestResourcePoolControllerTests extends BaseTest {
@Test
@Order(17)
void updateTestResourcePool() throws Exception {
MvcResult testPoolBlob = this.addTestResourcePoolSuccess("test_pool_blob2", false, true, true, false, false, ResourcePoolTypeEnum.K8S.name());
TestResourcePool testResourcePoolRequest1 = getResult(testPoolBlob);
TestResourcePool testResourcePoolRequest1 = this.addTestResourcePoolSuccess("test_pool_blob2", false, true, true, false, false, ResourcePoolTypeEnum.K8S.name());
String id = testResourcePoolRequest1.getId();
TestResourcePoolRequest testResourcePoolRequest = new TestResourcePoolRequest();
testResourcePoolRequest.setId(id);
@ -434,7 +433,7 @@ class TestResourcePoolControllerTests extends BaseTest {
listByKeyWord("test_pool_update");
}
private void setResources(TestResourcePoolRequest testResourcePoolDTO, boolean isPart) {
private void setResources(TestResourcePoolRequest testResourcePoolDTO, boolean isPart) {
TestResourceDTO testResourceDTO;
if (isPart) {
testResourceDTO = JSON.parseObject(configuration, TestResourceDTO.class);
@ -466,8 +465,7 @@ class TestResourcePoolControllerTests extends BaseTest {
testResourcePoolRequest.setId("");
this.requestPost(urlType, url, id, testResourcePoolRequest, status().isBadRequest());
MvcResult testPoolBlob = this.addTestResourcePoolSuccess("test_pool_blob2", false, true, true, false, false, ResourcePoolTypeEnum.K8S.name());
TestResourcePool testResourcePoolRequest1 = getResult(testPoolBlob);
TestResourcePool testResourcePoolRequest1 = this.addTestResourcePoolSuccess("test_pool_blob2", false, true, true, false, false, ResourcePoolTypeEnum.K8S.name());
id = testResourcePoolRequest1.getId();
}
@ -514,86 +512,6 @@ class TestResourcePoolControllerTests extends BaseTest {
this.requestPost(urlType, url, id, testResourcePoolRequest, ERROR_REQUEST_MATCHER);
}
@Test
//单独执行时请打开
/*@Sql(scripts = {"/dml/init_test_resource_pool.sql"},
config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED),
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)*/
@Order(19)
void deleteTestResourcePool() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/test/resource/pool/delete/103")
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
@Test
@Order(20)
void deleteTestResourcePoolFiled() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/test/resource/pool/delete/105")
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken))
.andExpect(ERROR_REQUEST_MATCHER)
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
@Test
@Order(21)
void unableTestResourcePoolSuccess() throws Exception {
MvcResult testPoolBlob = this.addTestResourcePoolSuccess("test_pool_blob4", false, true, true, false, false, ResourcePoolTypeEnum.K8S.name());
TestResourcePool testResourcePoolRequest1 = getResult(testPoolBlob);
String id = testResourcePoolRequest1.getId();
mockMvc.perform(MockMvcRequestBuilders.post("/test/resource/pool/set/enable/"+id)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken))
.andExpect(status().is5xxServerError())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
@Test
@Order(22)
void createExpectationForInvalidAuth() throws Exception {
mockServerClient
.when(
request()
.withMethod("GET")
.withPath("/status"))
.respond(
response()
.withStatusCode(200)
.withHeaders(
new Header("Content-Type", "application/json; charset=utf-8"),
new Header("Cache-Control", "public, max-age=86400"))
.withBody(JSON.toJSONString(ResultHolder.success("OK")))
);
MvcResult testPoolBlob = this.addTestResourcePoolSuccess("test_pool_blob3", false, true, true, false, false, ResourcePoolTypeEnum.NODE.name());
TestResourcePool testResourcePoolRequest1 = getResult(testPoolBlob);
String id = testResourcePoolRequest1.getId();
mockMvc.perform(MockMvcRequestBuilders.post("/test/resource/pool/set/enable/"+id)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
@Test
@Order(23)
void unableTestResourcePoolFiled() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/test/resource/pool/set/enable/105")
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken))
.andExpect(ERROR_REQUEST_MATCHER)
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
void listByKeyWord(String keyWord) throws Exception {
QueryResourcePoolRequest request = new QueryResourcePoolRequest();
request.setCurrent(1);
@ -686,5 +604,24 @@ class TestResourcePoolControllerTests extends BaseTest {
return testResourcePoolDTO;
}
/* @Test
@Order(22)
void createExpectationForInvalidAuth() throws Exception {
mockServerClient
.when(
request()
.withMethod("GET")
.withPath("/status"))
.respond(
response()
.withStatusCode(200)
.withHeaders(
new Header("Content-Type", "application/json; charset=utf-8"),
new Header("Cache-Control", "public, max-age=86400"))
.withBody(JSON.toJSONString(ResultHolder.success("OK")))
);
this.addTestResourcePoolSuccess("test_pool_blob3", false, true, true, false, false, ResourcePoolTypeEnum.NODE.name());
}*/
}