refactor(项目管理): 优化环境相关逻辑

This commit is contained in:
wxg0103 2024-03-05 14:12:43 +08:00 committed by Craftsman
parent 41ac431003
commit 9310007567
11 changed files with 119 additions and 29 deletions

View File

@ -637,5 +637,8 @@ INSERT INTO project_application (`project_id`, `type`, `type_value`) VALUES ('10
-- 初始化默认项目mock环境
INSERT INTO environment (`id`, `project_id`, `name`, `create_user`, `create_time`, `update_user`, `update_time`, `mock`,`pos`) VALUES (UUID_SHORT(), '100001100001', 'Mock环境', 'admin', unix_timestamp() * 1000, 'admin', unix_timestamp() * 1000, true, 5000);
INSERT INTO environment_blob (id,config)
VALUES ((SELECT id FROM environment where name = 'Mock环境') ,CONVERT('{"commonParams":{"requestTimeout":600000,"responseTimeout":600000},"commonVariables":[],"httpConfig":[{"protocol":"HTTP","hostname":"http://127.0.0.1:8081/mock-server/100001","type":"NONE","pathMatchRule":{"condition":null,"path":null},"moduleMatchRule":{"modules":[]},"headers":[],"description":null,"order":0,"moduleMatchRuleOrder":2}],"dataSources":[],"hostConfig":{"enable":null,"hosts":[]},"authConfig":{"username":null,"password":null,"verification":null,"sslConfig":{"entry":null,"files":null,"defaultAlias":null}},"preProcessorConfig":{"apiProcessorConfig":{"planProcessorConfig":{"processors":[]},"scenarioProcessorConfig":{"processors":[]},"requestProcessorConfig":{"processors":[]}}},"postProcessorConfig":{"apiProcessorConfig":{"planProcessorConfig":{"processors":[]},"scenarioProcessorConfig":{"processors":[]},"requestProcessorConfig":{"processors":[]}}},"assertionConfig":{"assertions":[]},"pluginConfigMap":{}}' USING UTF8));
-- set innodb lock wait timeout to default
SET SESSION innodb_lock_wait_timeout = DEFAULT;

View File

@ -7,6 +7,7 @@ import io.metersphere.jmeter.mock.Mock;
import io.metersphere.plugin.api.dto.ApiPluginSelectOption;
import io.metersphere.project.dto.customfunction.request.CustomFunctionRunRequest;
import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.domain.Environment;
import io.metersphere.sdk.dto.api.task.TaskRequestDTO;
import io.metersphere.system.dto.ProtocolDTO;
import io.swagger.v3.oas.annotations.Operation;
@ -75,4 +76,16 @@ public class ApiTestController {
public List<ApiPluginSelectOption> getFormOptions(@Validated @RequestBody ApiTestPluginOptionRequest request) {
return apiTestService.getFormOptions(request);
}
@GetMapping("/env-list/{projectId}")
@Operation(summary = "接口测试-环境列表")
@RequiresPermissions(value = {
PermissionConstants.PROJECT_API_DEFINITION_READ,
PermissionConstants.PROJECT_API_DEFINITION_CASE_READ,
PermissionConstants.PROJECT_API_DEBUG_READ,
PermissionConstants.PROJECT_API_SCENARIO_READ
}, logical = Logical.OR)
public List<Environment> getEnvList(@PathVariable String projectId) {
return apiTestService.getEnvList(projectId);
}
}

View File

@ -7,6 +7,8 @@ import io.metersphere.plugin.api.dto.ApiPluginOptionsRequest;
import io.metersphere.plugin.api.dto.ApiPluginSelectOption;
import io.metersphere.plugin.api.spi.AbstractApiPlugin;
import io.metersphere.plugin.api.spi.AbstractProtocolPlugin;
import io.metersphere.project.mapper.ExtEnvironmentMapper;
import io.metersphere.sdk.domain.Environment;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.system.dto.ProtocolDTO;
import io.metersphere.system.service.ApiPluginService;
@ -32,6 +34,8 @@ public class ApiTestService {
private ApiPluginService apiPluginService;
@Resource
private PluginLoadService pluginLoadService;
@Resource
private ExtEnvironmentMapper extEnvironmentMapper;
public List<ProtocolDTO> getProtocols(String orgId) {
List<ProtocolDTO> protocols = apiPluginService.getProtocols(orgId);
@ -73,4 +77,8 @@ public class ApiTestService {
public Object checkResourceExist(PluginWrapper pluginWrapper) {
return ServiceUtils.checkResourceExist(pluginWrapper, "permission.system_plugin.name");
}
public List<Environment> getEnvList(String projectId) {
return extEnvironmentMapper.selectByKeyword(null, false, projectId);
}
}

View File

@ -180,4 +180,10 @@ public class ApiTestControllerTests extends BaseTest {
return pluginService.add(request, mockMultipartFile);
}
@Test
public void getEnvList() throws Exception {
// @@请求成功
this.requestGet("/env-list/" + DEFAULT_PROJECT_ID);
}
}

View File

@ -17,6 +17,8 @@ import java.util.List;
public class HttpConfig implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@Schema(description = "id")
private String id;
@Schema(description = "http协议类型(http/https)")
@EnumValue(enumClass = HttpProtocolType.class)
private String protocol = HttpProtocolType.HTTP.name();

View File

@ -1,22 +1,38 @@
package io.metersphere.project.service;
import io.metersphere.project.domain.Project;
import io.metersphere.project.dto.environment.EnvironmentConfig;
import io.metersphere.project.dto.environment.http.HttpConfig;
import io.metersphere.project.mapper.ProjectMapper;
import io.metersphere.sdk.domain.Environment;
import io.metersphere.sdk.domain.EnvironmentBlob;
import io.metersphere.sdk.domain.EnvironmentExample;
import io.metersphere.sdk.mapper.EnvironmentBlobMapper;
import io.metersphere.sdk.mapper.EnvironmentMapper;
import io.metersphere.sdk.util.CommonBeanFactory;
import io.metersphere.sdk.util.JSON;
import io.metersphere.system.dto.sdk.BaseSystemConfigDTO;
import io.metersphere.system.service.CreateProjectResourceService;
import io.metersphere.system.service.SystemParameterService;
import io.metersphere.system.uid.IDGenerator;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class CreateEnvironmentResourceService implements CreateProjectResourceService {
public static final String MOCK_EVN_NAME = "Mock环境";
private static final String MOCK_EVN_SOCKET = "/mock-server/";
@Resource
private EnvironmentMapper environmentMapper;
@Resource
private EnvironmentBlobMapper environmentBlobMapper;
@Resource
private ProjectMapper projectMapper;
@Override
@ -37,6 +53,27 @@ public class CreateEnvironmentResourceService implements CreateProjectResourceSe
environment.setUpdateUser(project.getCreateUser());
environment.setUpdateTime(System.currentTimeMillis());
environmentMapper.insert(environment);
SystemParameterService systemParameterService = CommonBeanFactory.getBean(SystemParameterService.class);
if (systemParameterService != null) {
EnvironmentConfig environmentConfig = new EnvironmentConfig();
List<HttpConfig> httpConfigs = new ArrayList<>();
BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo();
String baseUrl = baseSystemConfigDTO.getUrl();
if (StringUtils.isNotEmpty(baseUrl)) {
if (CollectionUtils.isEmpty(httpConfigs)) {
HttpConfig httpConfig = new HttpConfig();
httpConfig.setHostname(StringUtils.join(baseUrl, MOCK_EVN_SOCKET, "100001"));
httpConfigs.add(httpConfig);
}
}
environmentConfig.setHttpConfig(httpConfigs);
EnvironmentBlob environmentBlob = new EnvironmentBlob();
environmentBlob.setId(environment.getId());
environmentBlob.setConfig(JSON.toJSONBytes(environmentConfig));
environmentBlobMapper.insert(environmentBlob);
}
}
}
}

View File

@ -14,16 +14,20 @@ import io.metersphere.sdk.mapper.EnvironmentGroupMapper;
import io.metersphere.sdk.mapper.EnvironmentGroupRelationMapper;
import io.metersphere.sdk.mapper.EnvironmentMapper;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.CommonBeanFactory;
import io.metersphere.sdk.util.JSON;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.UserRoleRelationExample;
import io.metersphere.system.dto.sdk.BaseSystemConfigDTO;
import io.metersphere.system.dto.sdk.OptionDTO;
import io.metersphere.system.dto.sdk.request.PosRequest;
import io.metersphere.system.mapper.UserRoleRelationMapper;
import io.metersphere.system.service.SystemParameterService;
import io.metersphere.system.uid.IDGenerator;
import io.metersphere.system.utils.ServiceUtils;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
@ -60,6 +64,7 @@ public class EnvironmentGroupService {
private EnvironmentService environmentService;
public static final Long ORDER_STEP = 5000L;
private static final String MOCK_EVN_SOCKET = "/mock-server/";
public EnvironmentGroup add(EnvironmentGroupRequest request, String userId) {
EnvironmentGroup environmentGroup = new EnvironmentGroup();
@ -198,6 +203,17 @@ public class EnvironmentGroupService {
EnvironmentConfig environmentConfig = JSON.parseObject(new String(environmentBlob.getConfig()), EnvironmentConfig.class);
dto.setDomain(ObjectUtils.isNotEmpty(environmentConfig) ? environmentConfig.getHttpConfig() : new ArrayList<>());
}
if (environment !=null && BooleanUtils.isTrue(environment.getMock())) {
SystemParameterService systemParameterService = CommonBeanFactory.getBean(SystemParameterService.class);
if (systemParameterService != null) {
BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo();
String baseUrl = baseSystemConfigDTO.getUrl();
if (StringUtils.isNotEmpty(baseUrl)) {
Project project = projectMapper.selectByPrimaryKey(environment.getProjectId());
dto.getDomain().getFirst().setHostname(StringUtils.join(baseUrl, MOCK_EVN_SOCKET, project.getNum()));
}
}
}
result.add(dto);
});
BeanUtils.copyBean(environmentGroupDTO, environmentGroup);

View File

@ -6,7 +6,6 @@ import io.metersphere.project.domain.Project;
import io.metersphere.project.domain.ProjectExample;
import io.metersphere.project.dto.environment.*;
import io.metersphere.project.dto.environment.datasource.DataSource;
import io.metersphere.project.dto.environment.http.HttpConfig;
import io.metersphere.project.mapper.ExtEnvironmentMapper;
import io.metersphere.project.mapper.ProjectMapper;
import io.metersphere.sdk.constants.DefaultRepositoryDir;
@ -189,16 +188,12 @@ public class EnvironmentService {
}
if (BooleanUtils.isTrue(environment.getMock())) {
SystemParameterService systemParameterService = CommonBeanFactory.getBean(SystemParameterService.class);
assert systemParameterService != null;
if (systemParameterService != null) {
BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo();
String baseUrl = baseSystemConfigDTO.getUrl();
if (StringUtils.isNotEmpty(baseUrl)) {
Project project = projectMapper.selectByPrimaryKey(environment.getProjectId());
List<HttpConfig> httpConfigs = environmentInfoDTO.getConfig().getHttpConfig();
if (CollectionUtils.isEmpty(httpConfigs)) {
HttpConfig httpConfig = new HttpConfig();
httpConfig.setHostname(StringUtils.join(baseUrl, MOCK_EVN_SOCKET, project.getNum()));
httpConfigs.add(new HttpConfig());
environmentInfoDTO.getConfig().getHttpConfig().getFirst().setHostname(StringUtils.join(baseUrl, MOCK_EVN_SOCKET, project.getNum()));
}
}
}
@ -395,7 +390,7 @@ public class EnvironmentService {
// 接口协议环境脚本
List<PluginScript> pluginScripts = new ArrayList<>(orgApiPluginWrappers.size());
orgApiPluginWrappers.stream().forEach(wrapper -> {
orgApiPluginWrappers.forEach(wrapper -> {
Plugin plugin = wrapper.getPlugin();
if (plugin instanceof AbstractProtocolPlugin protocolPlugin) {
Optional.ofNullable(pluginScriptService.get(wrapper.getPluginId(), protocolPlugin.getEnvProtocolScriptId()))
@ -435,13 +430,9 @@ public class EnvironmentService {
for (Environment environment : environments) {
EnvironmentInfoDTO environmentInfo = BeanUtils.copyBean(new EnvironmentInfoDTO(), environment);
EnvironmentBlob environmentBlob = envBlobMap.get(environment.getId());
if (environmentBlob == null) {
environmentInfo.setConfig(new EnvironmentConfig());
} else {
if (environmentBlob.getConfig() != null) {
environmentInfo.setConfig(JSON.parseObject(new String(environmentBlob.getConfig()), EnvironmentConfig.class));
}
}
if (BooleanUtils.isTrue(environment.getMock())) {
if (StringUtils.isNotEmpty(baseUrl)) {
@ -500,6 +491,17 @@ public class EnvironmentService {
if (environmentConfig != null && CollectionUtils.isNotEmpty(environmentConfig.getHttpConfig())) {
environmentOptionsDTO.setDomain(environmentConfig.getHttpConfig());
}
if (BooleanUtils.isTrue(environment.getMock())) {
SystemParameterService systemParameterService = CommonBeanFactory.getBean(SystemParameterService.class);
if (systemParameterService != null) {
BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo();
String baseUrl = baseSystemConfigDTO.getUrl();
if (StringUtils.isNotEmpty(baseUrl)) {
Project project = projectMapper.selectByPrimaryKey(environment.getProjectId());
environmentOptionsDTO.getDomain().getFirst().setHostname(StringUtils.join(baseUrl, MOCK_EVN_SOCKET, project.getNum()));
}
}
}
}
environmentOptions.add(environmentOptionsDTO);
});

View File

@ -3,8 +3,8 @@ package io.metersphere.project.controller;
import io.metersphere.project.domain.Project;
import io.metersphere.project.mapper.ProjectMapper;
import io.metersphere.project.service.CreateEnvironmentResourceService;
import io.metersphere.project.service.EnvironmentService;
import io.metersphere.sdk.domain.Environment;
import io.metersphere.sdk.domain.EnvironmentBlob;
import io.metersphere.sdk.domain.EnvironmentExample;
import io.metersphere.sdk.mapper.EnvironmentBlobMapper;
import io.metersphere.sdk.mapper.EnvironmentMapper;
@ -30,11 +30,9 @@ public class CreateEnvironmentTests extends BaseTest {
@Resource
private EnvironmentMapper environmentMapper;
@Resource
private ProjectMapper projectMapper;
@Resource
private EnvironmentService environmentService;
@Resource
private EnvironmentBlobMapper environmentBlobMapper;
@Resource
private ProjectMapper projectMapper;
@Test
@Order(1)
@ -57,6 +55,8 @@ public class CreateEnvironmentTests extends BaseTest {
environmentExample.createCriteria().andProjectIdEqualTo(initProject.getId()).andNameEqualTo("Mock环境");
List<Environment> environments = environmentMapper.selectByExample(environmentExample);
assert environments.size() == 1;
EnvironmentBlob environmentBlob = environmentBlobMapper.selectByPrimaryKey(environments.get(0).getId());
assert environmentBlob != null;
}
}

View File

@ -1226,7 +1226,7 @@ public class EnvironmentControllerTests extends BaseTest {
public void addCover() throws Exception {
List<Environment> environments = environmentMapper.selectByExample(new EnvironmentExample());
//获取id集合 过滤一下mock为false的
List<String> ids = environments.stream().filter(environment -> !environment.getMock()).map(Environment::getId).toList();
List<String> ids = environments.stream().map(Environment::getId).toList();
environmentService.getByIds(ids);
environmentService.getEnvironmentBlobsByIds(List.of());
}

View File

@ -139,16 +139,19 @@ public class EnvironmentGroupControllerTests extends BaseTest {
MvcResult mvcResult = this.requestMultipartWithOkAndReturn("/project/environment/add", paramMap);
EnvironmentRequest response = parseObjectFromMvcResult(mvcResult, EnvironmentRequest.class);
Assertions.assertNotNull(response);
Environment environment = environmentMapper.selectByPrimaryKey(response.getId());
//创建环境组
EnvironmentGroupRequest groupRequest = new EnvironmentGroupRequest();
groupRequest.setProjectId(DEFAULT_PROJECT_ID);
groupRequest.setName("group");
EnvironmentGroupProjectDTO environmentGroupProjectDTO = new EnvironmentGroupProjectDTO();
environmentGroupProjectDTO.setEnvironmentId(environment.getId());
environmentGroupProjectDTO.setProjectId(DEFAULT_PROJECT_ID);
groupRequest.setEnvGroupProject(List.of(environmentGroupProjectDTO));
//塞mock环境
EnvironmentGroupProjectDTO environmentGroupProjectDTO1 = new EnvironmentGroupProjectDTO();
EnvironmentExample environmentExample = new EnvironmentExample();
environmentExample.createCriteria().andProjectIdEqualTo(DEFAULT_PROJECT_ID).andMockEqualTo(true);
List<Environment> environments = environmentMapper.selectByExample(environmentExample);
environmentGroupProjectDTO1.setEnvironmentId(environments.getFirst().getId());
environmentGroupProjectDTO1.setProjectId(DEFAULT_PROJECT_ID);
groupRequest.setEnvGroupProject(List.of(environmentGroupProjectDTO1));
mvcResult = this.responsePost(add, groupRequest);
EnvironmentGroup groupResponse = parseObjectFromMvcResult(mvcResult, EnvironmentGroup.class);
Assertions.assertNotNull(groupResponse);