refactor(项目管理): 初始化mock环境

This commit is contained in:
wxg0103 2023-11-01 19:26:39 +08:00 committed by Craftsman
parent 0bb548561e
commit f9168d17fe
21 changed files with 323 additions and 89 deletions

View File

@ -1,15 +1,12 @@
package io.metersphere.sdk.domain;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import io.metersphere.validation.groups.*;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import jakarta.validation.constraints.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import lombok.Data;
@Data
public class Environment implements Serializable {
@ -40,6 +37,10 @@ public class Environment implements Serializable {
@Schema(description = "更新时间")
private Long updateTime;
@Schema(description = "是否是mock环境", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "{environment.mock.not_blank}", groups = {Created.class})
private Boolean mock;
private static final long serialVersionUID = 1L;
public enum Column {
@ -49,7 +50,8 @@ public class Environment implements Serializable {
createUser("create_user", "createUser", "VARCHAR", false),
updateUser("update_user", "updateUser", "VARCHAR", false),
createTime("create_time", "createTime", "BIGINT", false),
updateTime("update_time", "updateTime", "BIGINT", false);
updateTime("update_time", "updateTime", "BIGINT", false),
mock("mock", "mock", "BIT", false);
private static final String BEGINNING_DELIMITER = "`";

View File

@ -573,6 +573,66 @@ public class EnvironmentExample {
addCriterion("update_time not between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andMockIsNull() {
addCriterion("mock is null");
return (Criteria) this;
}
public Criteria andMockIsNotNull() {
addCriterion("mock is not null");
return (Criteria) this;
}
public Criteria andMockEqualTo(Boolean value) {
addCriterion("mock =", value, "mock");
return (Criteria) this;
}
public Criteria andMockNotEqualTo(Boolean value) {
addCriterion("mock <>", value, "mock");
return (Criteria) this;
}
public Criteria andMockGreaterThan(Boolean value) {
addCriterion("mock >", value, "mock");
return (Criteria) this;
}
public Criteria andMockGreaterThanOrEqualTo(Boolean value) {
addCriterion("mock >=", value, "mock");
return (Criteria) this;
}
public Criteria andMockLessThan(Boolean value) {
addCriterion("mock <", value, "mock");
return (Criteria) this;
}
public Criteria andMockLessThanOrEqualTo(Boolean value) {
addCriterion("mock <=", value, "mock");
return (Criteria) this;
}
public Criteria andMockIn(List<Boolean> values) {
addCriterion("mock in", values, "mock");
return (Criteria) this;
}
public Criteria andMockNotIn(List<Boolean> values) {
addCriterion("mock not in", values, "mock");
return (Criteria) this;
}
public Criteria andMockBetween(Boolean value1, Boolean value2) {
addCriterion("mock between", value1, value2, "mock");
return (Criteria) this;
}
public Criteria andMockNotBetween(Boolean value1, Boolean value2) {
addCriterion("mock not between", value1, value2, "mock");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {

View File

@ -9,6 +9,7 @@
<result column="update_user" jdbcType="VARCHAR" property="updateUser" />
<result column="create_time" jdbcType="BIGINT" property="createTime" />
<result column="update_time" jdbcType="BIGINT" property="updateTime" />
<result column="mock" jdbcType="BIT" property="mock" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
@ -69,7 +70,7 @@
</where>
</sql>
<sql id="Base_Column_List">
id, `name`, project_id, create_user, update_user, create_time, update_time
id, `name`, project_id, create_user, update_user, create_time, update_time, mock
</sql>
<select id="selectByExample" parameterType="io.metersphere.sdk.domain.EnvironmentExample" resultMap="BaseResultMap">
select
@ -104,10 +105,10 @@
<insert id="insert" parameterType="io.metersphere.sdk.domain.Environment">
insert into environment (id, `name`, project_id,
create_user, update_user, create_time,
update_time)
update_time, mock)
values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{projectId,jdbcType=VARCHAR},
#{createUser,jdbcType=VARCHAR}, #{updateUser,jdbcType=VARCHAR}, #{createTime,jdbcType=BIGINT},
#{updateTime,jdbcType=BIGINT})
#{updateTime,jdbcType=BIGINT}, #{mock,jdbcType=BIT})
</insert>
<insert id="insertSelective" parameterType="io.metersphere.sdk.domain.Environment">
insert into environment
@ -133,6 +134,9 @@
<if test="updateTime != null">
update_time,
</if>
<if test="mock != null">
mock,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
@ -156,6 +160,9 @@
<if test="updateTime != null">
#{updateTime,jdbcType=BIGINT},
</if>
<if test="mock != null">
#{mock,jdbcType=BIT},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="io.metersphere.sdk.domain.EnvironmentExample" resultType="java.lang.Long">
@ -188,6 +195,9 @@
<if test="record.updateTime != null">
update_time = #{record.updateTime,jdbcType=BIGINT},
</if>
<if test="record.mock != null">
mock = #{record.mock,jdbcType=BIT},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
@ -201,7 +211,8 @@
create_user = #{record.createUser,jdbcType=VARCHAR},
update_user = #{record.updateUser,jdbcType=VARCHAR},
create_time = #{record.createTime,jdbcType=BIGINT},
update_time = #{record.updateTime,jdbcType=BIGINT}
update_time = #{record.updateTime,jdbcType=BIGINT},
mock = #{record.mock,jdbcType=BIT}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
@ -227,6 +238,9 @@
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=BIGINT},
</if>
<if test="mock != null">
mock = #{mock,jdbcType=BIT},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
</update>
@ -237,17 +251,19 @@
create_user = #{createUser,jdbcType=VARCHAR},
update_user = #{updateUser,jdbcType=VARCHAR},
create_time = #{createTime,jdbcType=BIGINT},
update_time = #{updateTime,jdbcType=BIGINT}
update_time = #{updateTime,jdbcType=BIGINT},
mock = #{mock,jdbcType=BIT}
where id = #{id,jdbcType=VARCHAR}
</update>
<insert id="batchInsert" parameterType="map">
insert into environment
(id, `name`, project_id, create_user, update_user, create_time, update_time)
(id, `name`, project_id, create_user, update_user, create_time, update_time, mock
)
values
<foreach collection="list" item="item" separator=",">
(#{item.id,jdbcType=VARCHAR}, #{item.name,jdbcType=VARCHAR}, #{item.projectId,jdbcType=VARCHAR},
#{item.createUser,jdbcType=VARCHAR}, #{item.updateUser,jdbcType=VARCHAR}, #{item.createTime,jdbcType=BIGINT},
#{item.updateTime,jdbcType=BIGINT})
#{item.updateTime,jdbcType=BIGINT}, #{item.mock,jdbcType=BIT})
</foreach>
</insert>
<insert id="batchInsertSelective" parameterType="map">
@ -281,6 +297,9 @@
<if test="'update_time'.toString() == column.value">
#{item.updateTime,jdbcType=BIGINT}
</if>
<if test="'mock'.toString() == column.value">
#{item.mock,jdbcType=BIT}
</if>
</foreach>
)
</foreach>

View File

@ -40,7 +40,9 @@ CREATE TABLE operation_log_blob(
COLLATE = utf8mb4_general_ci COMMENT = '操作日志内容详情';
CREATE TABLE IF NOT EXISTS environment(
DROP TABLE IF EXISTS environment;
CREATE TABLE environment
(
`id` VARCHAR(50) NOT NULL COMMENT '环境ID',
`name` VARCHAR(255) NOT NULL COMMENT '环境名称',
`project_id` VARCHAR(50) NOT NULL COMMENT '项目ID',
@ -48,10 +50,9 @@ CREATE TABLE IF NOT EXISTS environment(
`update_user` VARCHAR(50) NOT NULL COMMENT '修改人',
`create_time` BIGINT NOT NULL COMMENT '创建时间',
`update_time` BIGINT NOT NULL COMMENT '更新时间',
`mock` BIT NOT NULL DEFAULT 0 COMMENT '是否是mock环境',
PRIMARY KEY (id)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_general_ci COMMENT = '环境';
) COMMENT = '环境';
CREATE INDEX idx_project_id ON environment(project_id);
CREATE INDEX idx_name ON environment(name);

View File

@ -683,5 +683,8 @@ VALUES (UUID_SHORT(), '100001100001', 'CRON', '0 0 2 * * ?', 'io.metersphere.pro
-- 初始化默认项目版本配置项
INSERT INTO project_application (`project_id`, `type`, `type_value`) VALUES ('100001100001', 'VERSION_ENABLE', 'FALSE');
-- 初始化默认项目mock环境
INSERT INTO environment (`id`, `project_id`, `name`, `create_user`, `create_time`, `update_user`, `update_time`, `mock`) VALUES (UUID_SHORT(), '100001100001', 'Mock环境', 'admin', unix_timestamp() * 1000, 'admin', unix_timestamp() * 1000, true);
-- set innodb lock wait timeout to default
SET SESSION innodb_lock_wait_timeout = DEFAULT;

View File

@ -457,6 +457,7 @@ project_template_enable=Enable the project template
global_parameters_already_exist=Global parameters already exist
global_parameters_is_not_exist=Global parameters is not exist
api_test_environment_not_exist=Environment is not exist
mock_environment_not_delete=Deletion is not allowed in the mock environment
parent.node.not_blank=Parent node can not blank

View File

@ -459,6 +459,7 @@ node.not_blank=节点不能为空
node.name.repeat=节点名称重复
project.cannot.match.parent=和父节点的项目无法匹配
api_test_environment_not_exist=环境不存在
mock_environment_not_delete=Mock环境不允许删除
# 状态流
status_flow.name=状态流

View File

@ -459,6 +459,7 @@ node.not_blank=節點不能為空
node.name.repeat=節點名稱重複
project.cannot.match.parent=和父節點的項目無法匹配
api_test_environment_not_exist=環境不存在
mock_environment_not_delete=Mock 環境不允許刪除
# 状态流
status_flow.name=狀態流

View File

@ -3,6 +3,7 @@ package io.metersphere.api.service.definition;
import io.metersphere.api.domain.ApiEnvironmentConfig;
import io.metersphere.api.domain.ApiEnvironmentConfigExample;
import io.metersphere.api.mapper.ApiEnvironmentConfigMapper;
import io.metersphere.sdk.domain.Environment;
import io.metersphere.sdk.domain.EnvironmentExample;
import io.metersphere.sdk.mapper.EnvironmentMapper;
import io.metersphere.system.uid.IDGenerator;
@ -41,8 +42,11 @@ public class ApiEnvironmentConfigService {
}
}
}
//为空的 默认显示mock环境 TODO
return null;
EnvironmentExample environmentExample = new EnvironmentExample();
environmentExample.createCriteria().andProjectIdEqualTo(projectId).andMockEqualTo(true);
List<Environment> environments = environmentMapper.selectByExample(environmentExample);
list.get(0).setEnvironmentId(environments.get(0).getId());
return list.get(0);
}
public String add(String envId, String userId, String projectId) {

View File

@ -104,16 +104,16 @@ public class ApiEnvironmentConfigControllerTests extends BaseTest {
Assertions.assertNotNull(environmentConfig);
Assertions.assertEquals(environmentConfig.getEnvironmentId(), envId);
mvcResult = responseGet(get + "1111111", "1111111");
environmentConfig = parseObjectFromMvcResult(mvcResult, ApiEnvironmentConfig.class);
Assertions.assertNull(environmentConfig);
responseGet(add + "env-1111", DEFAULT_PROJECT_ID);
ApiEnvironmentConfigExample example = new ApiEnvironmentConfigExample();
example.createCriteria().andCreateUserEqualTo("admin");
List<ApiEnvironmentConfig> apiEnvironmentConfigs = apiEnvironmentConfigMapper.selectByExample(example);
Assertions.assertEquals(apiEnvironmentConfigs.get(0).getEnvironmentId(), "env-1111");
mvcResult = responseGet(get + DEFAULT_PROJECT_ID, DEFAULT_PROJECT_ID);
environmentConfig = parseObjectFromMvcResult(mvcResult, ApiEnvironmentConfig.class);
Assertions.assertNotNull(environmentConfig);
}

View File

@ -15,7 +15,6 @@ import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Data
@ -46,9 +45,9 @@ public class EnvironmentConfig implements Serializable {
public EnvironmentConfig() {
this.commonParams = new CommonParams();
this.commonVariables = new ArrayList<>();
this.httpConfig = new ArrayList<>();
this.dataSources = new ArrayList<>();
this.commonVariables = List.of(new CommonVariables());
this.httpConfig = List.of(new HttpConfig());
this.dataSources = List.of(new DataSource());
this.hostConfig = new HostConfig();
this.tcpConfig = new TCPConfig();
this.authConfig = new AuthConfig();

View File

@ -26,9 +26,10 @@ public class EnvironmentRequest implements Serializable {
@Schema(description = "环境名称")
@NotBlank(message = "{environment_name_is_null}", groups = {Created.class, Updated.class})
private String name;
@Schema(description = "环境配置")
@NotNull(message = "{environment_config_is_null}", groups = {Created.class, Updated.class})
private EnvironmentConfig config;
@Schema(description = "是否是mock环境")
private Boolean mock;
}

View File

@ -1,7 +1,6 @@
package io.metersphere.project.dto.environment.assertions;
import io.metersphere.project.dto.environment.assertions.document.MsAssertionDocument;
import io.metersphere.project.dto.environment.http.ApplicationModule;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@ -9,8 +8,10 @@ import java.util.List;
@Data
public class EnvironmentAssertions {
@Schema(description = "应用模块")
private ApplicationModule module;
@Schema(description = "接口测试")
private Boolean apiTest = true;
@Schema(description = "UI测试")
private Boolean uiTest = false;
@Schema(description = "xpath类型 xml/html")
private String xpathType;
@Schema(description = "正则断言")

View File

@ -1,12 +0,0 @@
package io.metersphere.project.dto.environment.http;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
public class ApplicationModule {
@Schema(description = "接口测试")
private Boolean apiTest = true;
@Schema(description = "UI测试")
private Boolean uiTest = false;
}

View File

@ -12,17 +12,17 @@ import java.util.List;
@Data
public class HttpConfig implements Serializable {
@Schema(description = "环境域名")
private String socket;
@Schema(description = "domain")
private String domain;
@Schema(description = "协议")
private String protocol = "https";
@Schema(description = "应用模块接口测试、ui测试")
private List<ApplicationModule> applicationModule;
private String url;
@Schema(description = "接口测试")
private Boolean apiTest = true;
@Schema(description = "UI测试")
private Boolean uiTest = false;
@Schema(description = "启用条件 NONE/MODULE/PATH")
private String type;
@Schema(description = "启用条件为PATH时需要填写的路径/ 如果是模块时需要时模块的id")
private String type = "NONE";
@Schema(description = "启用条件为PATH时需要填写的路径/ key为equal时value为路径key为contain时value为包含的路径")
private List<KeyValue> details;
@Schema(description = "启用条件为MODULE时需要模块的id")
private List<String> moduleIds;
@Schema(description = "请求头")
private List<KeyValue> headers;
@Schema(description = "浏览器 选项为chrome/firefox")
@ -32,4 +32,8 @@ public class HttpConfig implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
public HttpConfig() {
this.headers = List.of(new KeyValue());
}
}

View File

@ -9,7 +9,7 @@ import java.io.Serializable;
@Data
public class TCPConfig implements Serializable {
@Schema(description = "TCPClient 选项为TCPClientImpl、BinaryTCPClientImpl、LengthPrefixedBinaryTCPClientImpl")
private String className;
private String className = "TCPClientImpl";
@Schema(description = "服务器名或IP")
private String server;
@Schema(description = "端口")
@ -25,11 +25,11 @@ public class TCPConfig implements Serializable {
@Schema(description = "So Linger")
private String soLinger;
@Schema(description = "Re-use connection")
private Boolean reUseConnection;
private Boolean reUseConnection = false;
@Schema(description = "设置无延迟")
private Boolean nodelay;
private Boolean nodelay = false;
@Schema(description = "Close Connection")
private Boolean closeConnection;
private Boolean closeConnection = false;
@Schema(description = "行尾(EOL)字节值")
private String eolByte;

View File

@ -0,0 +1,41 @@
package io.metersphere.project.service;
import io.metersphere.project.domain.Project;
import io.metersphere.project.mapper.ProjectMapper;
import io.metersphere.sdk.domain.Environment;
import io.metersphere.sdk.domain.EnvironmentExample;
import io.metersphere.sdk.mapper.EnvironmentMapper;
import io.metersphere.system.service.CreateProjectResourceService;
import io.metersphere.system.uid.IDGenerator;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
@Component
public class CreateEnvironmentResourceService implements CreateProjectResourceService {
public static final String MOCK_EVN_NAME = "Mock环境";
@Resource
private EnvironmentMapper environmentMapper;
@Resource
private ProjectMapper projectMapper;
@Override
public void createResources(String projectId) {
// 创建默认mock环境
EnvironmentExample example = new EnvironmentExample();
example.createCriteria().andProjectIdEqualTo(projectId).andMockEqualTo(true);
if (environmentMapper.countByExample(example) == 0) {
Project project = projectMapper.selectByPrimaryKey(projectId);
Environment environment = new Environment();
environment.setId(IDGenerator.nextStr());
environment.setCreateUser(project.getCreateUser());
environment.setName(MOCK_EVN_NAME);
environment.setMock(true);
environment.setProjectId(projectId);
environment.setCreateTime(System.currentTimeMillis());
environment.setUpdateUser(project.getCreateUser());
environment.setUpdateTime(System.currentTimeMillis());
environmentMapper.insert(environment);
}
}
}

View File

@ -14,23 +14,27 @@ import io.metersphere.sdk.domain.Environment;
import io.metersphere.sdk.domain.EnvironmentBlob;
import io.metersphere.sdk.domain.EnvironmentBlobExample;
import io.metersphere.sdk.domain.EnvironmentExample;
import io.metersphere.system.log.dto.LogDTO;
import io.metersphere.system.dto.sdk.OptionDTO;
import io.metersphere.sdk.exception.MSException;
import io.metersphere.system.file.FileRequest;
import io.metersphere.system.file.MinioRepository;
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.sdk.util.LogUtils;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.dto.sdk.BaseSystemConfigDTO;
import io.metersphere.system.dto.sdk.OptionDTO;
import io.metersphere.system.file.FileRequest;
import io.metersphere.system.file.MinioRepository;
import io.metersphere.system.log.constants.OperationLogModule;
import io.metersphere.system.log.constants.OperationLogType;
import io.metersphere.system.log.dto.LogDTO;
import io.metersphere.system.log.service.OperationLogService;
import io.metersphere.system.service.JdbcDriverPluginService;
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.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -63,6 +67,7 @@ public class EnvironmentService {
private static final String USERNAME = "user";
private static final String PASSWORD = "password";
private static final String PATH = "/project/environment/import";
private static final String MOCK_EVN_SOCKET = "/api/mock/";
public List<OptionDTO> getDriverOptions(String organizationId) {
return jdbcDriverPluginService.getJdbcDriverOption(organizationId);
@ -85,6 +90,9 @@ public class EnvironmentService {
if (environment == null) {
throw new MSException(Translator.get("api_test_environment_not_exist"));
}
if (BooleanUtils.isTrue(environment.getMock())) {
throw new MSException(Translator.get("mock_environment_not_delete"));
}
//删除环境的ssl文件
FileRequest fileRequest = new FileRequest();
fileRequest.setProjectId(StringUtils.join(DIR_PATH, environment.getProjectId()));
@ -99,6 +107,10 @@ public class EnvironmentService {
}
public List<Environment> list(EnvironmentDTO request) {
return extEnvironmentMapper.selectByKeyword(request.getKeyword(), false, request.getProjectId());
}
public EnvironmentRequest add(EnvironmentRequest request, String userId, List<MultipartFile> sslFiles) {
Environment environment = new Environment();
environment.setId(IDGenerator.nextStr());
@ -109,6 +121,7 @@ public class EnvironmentService {
environment.setCreateTime(System.currentTimeMillis());
environment.setUpdateUser(userId);
environment.setUpdateTime(System.currentTimeMillis());
environment.setMock(false);
environmentMapper.insert(environment);
request.setId(environment.getId());
EnvironmentBlob environmentBlob = new EnvironmentBlob();
@ -132,21 +145,32 @@ public class EnvironmentService {
return request;
}
public List<Environment> list(EnvironmentDTO request) {
return extEnvironmentMapper.selectByKeyword(request.getKeyword(), false, request.getProjectId());
}
public EnvironmentRequest get(String environmentId) {
EnvironmentRequest environmentRequest = new EnvironmentRequest();
Environment environment = environmentMapper.selectByPrimaryKey(environmentId);
if (environment == null) {
return null;
}
EnvironmentBlob environmentBlob = environmentBlobMapper.selectByPrimaryKey(environmentId);
environmentRequest.setProjectId(environment.getProjectId());
environmentRequest.setName(environment.getName());
environmentRequest.setId(environment.getId());
EnvironmentBlob environmentBlob = environmentBlobMapper.selectByPrimaryKey(environmentId);
if (environmentBlob == null) {
environmentRequest.setConfig(new EnvironmentConfig());
} else {
environmentRequest.setConfig(JSON.parseObject(new String(environmentBlob.getConfig()), EnvironmentConfig.class));
}
if (BooleanUtils.isTrue(environment.getMock())) {
SystemParameterService systemParameterService = CommonBeanFactory.getBean(SystemParameterService.class);
assert systemParameterService != null;
BaseSystemConfigDTO baseSystemConfigDTO = systemParameterService.getBaseInfo();
String baseUrl = baseSystemConfigDTO.getUrl();
if (StringUtils.isNotEmpty(baseUrl)) {
Project project = projectMapper.selectByPrimaryKey(environment.getProjectId());
environmentRequest.getConfig().getHttpConfig().get(0).setUrl(StringUtils.join(baseUrl, MOCK_EVN_SOCKET, project.getNum()));
}
}
return environmentRequest;
}
@ -198,7 +222,7 @@ public class EnvironmentService {
if (environment.getName() != null) {
EnvironmentExample environmentExample = new EnvironmentExample();
environmentExample.createCriteria().andNameEqualTo(environment.getName()).andProjectIdEqualTo(environment.getProjectId()).andIdNotEqualTo(environment.getId());
if (environmentMapper.selectByExample(environmentExample).size() > 0) {
if (!environmentMapper.selectByExample(environmentExample).isEmpty()) {
throw new MSException(Translator.get("api_test_environment_already_exists"));
}
}
@ -216,7 +240,7 @@ public class EnvironmentService {
if (CollectionUtils.isNotEmpty(environmentRequests)) {
List<Environment> environments = new ArrayList<>();
List<EnvironmentBlob> environmentBlobs = new ArrayList<>();
List<LogDTO> logDTOS = new ArrayList<>();
List<LogDTO> logDos = new ArrayList<>();
Project project = projectMapper.selectByPrimaryKey(currentProjectId);
environmentRequests.forEach(environmentRequest -> {
Environment environment = new Environment();
@ -226,6 +250,7 @@ public class EnvironmentService {
environment.setProjectId(currentProjectId);
environment.setUpdateUser(userId);
environment.setUpdateTime(System.currentTimeMillis());
environment.setMock(false);
checkEnvironmentExist(environment);
environment.setCreateTime(System.currentTimeMillis());
environment.setProjectId(currentProjectId);
@ -245,11 +270,11 @@ public class EnvironmentService {
logDTO.setMethod(HttpMethodConstants.POST.name());
logDTO.setOriginalValue(JSON.toJSONBytes(environmentRequest.getConfig()));
logDTO.setPath(PATH);
logDTOS.add(logDTO);
logDos.add(logDTO);
});
environmentMapper.batchInsert(environments);
environmentBlobMapper.batchInsert(environmentBlobs);
operationLogService.batchAdd(logDTOS);
operationLogService.batchAdd(logDos);
}
} catch (Exception e) {
LogUtils.error("获取文件输入流异常", e);

View File

@ -0,0 +1,62 @@
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.EnvironmentExample;
import io.metersphere.sdk.mapper.EnvironmentBlobMapper;
import io.metersphere.sdk.mapper.EnvironmentMapper;
import io.metersphere.system.base.BaseTest;
import io.metersphere.system.uid.IDGenerator;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@AutoConfigureMockMvc
public class CreateEnvironmentTests extends BaseTest {
@Resource
private CreateEnvironmentResourceService createEnvironmentResourceService;
@Resource
private EnvironmentMapper environmentMapper;
@Resource
private ProjectMapper projectMapper;
@Resource
private EnvironmentService environmentService;
@Resource
private EnvironmentBlobMapper environmentBlobMapper;
@Test
@Order(1)
public void testCreateResource() throws Exception {
Project initProject = new Project();
initProject.setId(IDGenerator.nextStr());
initProject.setNum(null);
initProject.setOrganizationId("100001");
initProject.setName("测试生成mock环境");
initProject.setDescription("测试生成mock环境");
initProject.setCreateUser("admin");
initProject.setUpdateUser("admin");
initProject.setCreateTime(System.currentTimeMillis());
initProject.setUpdateTime(System.currentTimeMillis());
initProject.setEnable(true);
initProject.setModuleSetting("[\"apiTest\",\"uiTest\"]");
projectMapper.insertSelective(initProject);
createEnvironmentResourceService.createResources(initProject.getId());
EnvironmentExample environmentExample = new EnvironmentExample();
environmentExample.createCriteria().andProjectIdEqualTo(initProject.getId()).andNameEqualTo("Mock环境");
List<Environment> environments = environmentMapper.selectByExample(environmentExample);
assert environments.size() == 1;
}
}

View File

@ -8,7 +8,6 @@ import io.metersphere.project.dto.environment.common.CommonParams;
import io.metersphere.project.dto.environment.datasource.DataSource;
import io.metersphere.project.dto.environment.host.Host;
import io.metersphere.project.dto.environment.host.HostConfig;
import io.metersphere.project.dto.environment.http.ApplicationModule;
import io.metersphere.project.dto.environment.http.HttpConfig;
import io.metersphere.project.dto.environment.script.ScriptContent;
import io.metersphere.project.dto.environment.script.post.EnvironmentPostScript;
@ -25,15 +24,15 @@ import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.domain.Environment;
import io.metersphere.sdk.domain.EnvironmentBlob;
import io.metersphere.sdk.domain.EnvironmentExample;
import io.metersphere.system.dto.sdk.OptionDTO;
import io.metersphere.system.file.FileRequest;
import io.metersphere.system.file.MinioRepository;
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.base.BaseTest;
import io.metersphere.system.controller.handler.ResultHolder;
import io.metersphere.system.dto.sdk.OptionDTO;
import io.metersphere.system.file.FileRequest;
import io.metersphere.system.file.MinioRepository;
import io.metersphere.system.log.constants.OperationLogType;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
@ -87,6 +86,7 @@ public class EnvironmentControllerTests extends BaseTest {
private static final ResultMatcher BAD_REQUEST_MATCHER = status().isBadRequest();
private static final ResultMatcher ERROR_REQUEST_MATCHER = status().is5xxServerError();
private static final String DIR_PATH = "/project-management/environment/";
private static String MOCKID;
@Resource
private MockMvc mockMvc;
@Resource
@ -148,7 +148,7 @@ public class EnvironmentControllerTests extends BaseTest {
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.header(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN")
.header("PROJECT", projectId);
.header(SessionConstants.CURRENT_PROJECT, projectId);
return mockMvc.perform(header)
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn();
@ -213,9 +213,7 @@ public class EnvironmentControllerTests extends BaseTest {
keyValue.setValue("value");
headers.add(keyValue);
httpConfig.setHeaders(headers);
httpConfig.setDomain("domain");
httpConfig.setProtocol("https");
httpConfig.setSocket("socket");
httpConfig.setUrl("http://www.baidu.com");
httpConfigs.add(httpConfig);
return httpConfigs;
@ -358,9 +356,7 @@ public class EnvironmentControllerTests extends BaseTest {
private EnvironmentAssertions createAssertions() {
EnvironmentAssertions assertions = new EnvironmentAssertions();
ApplicationModule applicationModule = new ApplicationModule();
applicationModule.setApiTest(true);
assertions.setModule(applicationModule);
assertions.setApiTest(true);
List<EnvAssertionRegex> regex = new ArrayList<>();
assertions.setRegex(regex);
List<EnvAssertionJsonPath> jsonPath = new ArrayList<>();
@ -765,6 +761,7 @@ public class EnvironmentControllerTests extends BaseTest {
environment.setUpdateUser("updateUser");
environment.setUpdateTime(System.currentTimeMillis());
environment.setCreateUser("createUser");
environment.setMock(false);
environment.setCreateTime(System.currentTimeMillis());
environmentMapper.insert(environment);
EnvironmentBlob environmentBlob = new EnvironmentBlob();
@ -777,6 +774,11 @@ public class EnvironmentControllerTests extends BaseTest {
Assertions.assertEquals("environmentId1", response.getId());
//校验权限
requestGetPermissionTest(PermissionConstants.PROJECT_ENVIRONMENT_READ, get + "projectId");
EnvironmentExample environmentExample = new EnvironmentExample();
environmentExample.createCriteria().andProjectIdEqualTo(DEFAULT_PROJECT_ID).andMockEqualTo(true);
List<Environment> environmentList = environmentMapper.selectByExample(environmentExample);
MOCKID = environmentList.get(0).getId();
this.responseGet(get + MOCKID);
}
@Test
@ -960,6 +962,8 @@ public class EnvironmentControllerTests extends BaseTest {
//删除环境不存在的
this.requestGet(delete + "environmentId2", ERROR_REQUEST_MATCHER);
this.requestGet(delete + MOCKID, ERROR_REQUEST_MATCHER);
//删除包含文件的环境
example = new EnvironmentExample();
example.createCriteria().andProjectIdEqualTo("projectId").andNameEqualTo("uploadFile");

View File

@ -1,7 +1,9 @@
package io.metersphere.project.controller;
import io.metersphere.project.domain.Project;
import io.metersphere.project.domain.ProjectVersion;
import io.metersphere.project.domain.ProjectVersionExample;
import io.metersphere.project.mapper.ProjectMapper;
import io.metersphere.project.mapper.ProjectVersionMapper;
import io.metersphere.project.request.ProjectApplicationRequest;
import io.metersphere.project.service.ProjectApplicationService;
@ -30,6 +32,8 @@ public class ProjectVersionResourceTests extends BaseTest {
private ProjectVersionMapper projectVersionMapper;
@Resource
private ProjectApplicationService projectApplicationService;
@Resource
private ProjectMapper projectMapper;
@Autowired
public ProjectVersionResourceTests(ProjectServiceInvoker serviceInvoker) {
@ -39,6 +43,19 @@ public class ProjectVersionResourceTests extends BaseTest {
@Test
@Order(1)
public void test() {
Project initProject = new Project();
initProject.setId(TEST_PROJECT_ID);
initProject.setNum(null);
initProject.setOrganizationId(DEFAULT_ORGANIZATION_ID);
initProject.setName("测试项目版本");
initProject.setDescription("测试项目版本");
initProject.setCreateUser("admin");
initProject.setUpdateUser("admin");
initProject.setCreateTime(System.currentTimeMillis());
initProject.setUpdateTime(System.currentTimeMillis());
initProject.setEnable(true);
initProject.setModuleSetting("[\"apiTest\",\"uiTest\"]");
projectMapper.insertSelective(initProject);
ProjectVersionExample example = new ProjectVersionExample();
example.createCriteria().andProjectIdEqualTo(TEST_PROJECT_ID);
// 默认为空