feat(系统设置): 用户删除功能开发

This commit is contained in:
song-tianyang 2023-07-03 19:30:35 +08:00 committed by 建国
parent 7108d9c4ff
commit 921a076572
20 changed files with 261 additions and 46 deletions

View File

@ -4,6 +4,7 @@ import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
@ -61,5 +62,9 @@ public class User implements Serializable {
@Schema(title = "修改人")
private String updateUser;
@Schema(title = "是否删除", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "{user.deleted.not_blank}", groups = {Created.class})
private Boolean deleted;
private static final long serialVersionUID = 1L;
}

View File

@ -1053,6 +1053,66 @@ public class UserExample {
addCriterion("update_user not between", value1, value2, "updateUser");
return (Criteria) this;
}
public Criteria andDeletedIsNull() {
addCriterion("deleted is null");
return (Criteria) this;
}
public Criteria andDeletedIsNotNull() {
addCriterion("deleted is not null");
return (Criteria) this;
}
public Criteria andDeletedEqualTo(Boolean value) {
addCriterion("deleted =", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotEqualTo(Boolean value) {
addCriterion("deleted <>", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedGreaterThan(Boolean value) {
addCriterion("deleted >", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedGreaterThanOrEqualTo(Boolean value) {
addCriterion("deleted >=", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedLessThan(Boolean value) {
addCriterion("deleted <", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedLessThanOrEqualTo(Boolean value) {
addCriterion("deleted <=", value, "deleted");
return (Criteria) this;
}
public Criteria andDeletedIn(List<Boolean> values) {
addCriterion("deleted in", values, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotIn(List<Boolean> values) {
addCriterion("deleted not in", values, "deleted");
return (Criteria) this;
}
public Criteria andDeletedBetween(Boolean value1, Boolean value2) {
addCriterion("deleted between", value1, value2, "deleted");
return (Criteria) this;
}
public Criteria andDeletedNotBetween(Boolean value1, Boolean value2) {
addCriterion("deleted not between", value1, value2, "deleted");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {

View File

@ -16,6 +16,7 @@
<result column="last_project_id" jdbcType="VARCHAR" property="lastProjectId" />
<result column="create_user" jdbcType="VARCHAR" property="createUser" />
<result column="update_user" jdbcType="VARCHAR" property="updateUser" />
<result column="deleted" jdbcType="BIT" property="deleted" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
@ -77,7 +78,7 @@
</sql>
<sql id="Base_Column_List">
id, `name`, email, `password`, `enable`, create_time, update_time, `language`, last_organization_id,
phone, `source`, last_project_id, create_user, update_user
phone, `source`, last_project_id, create_user, update_user, deleted
</sql>
<select id="selectByExample" parameterType="io.metersphere.system.domain.UserExample" resultMap="BaseResultMap">
select
@ -114,12 +115,14 @@
`password`, `enable`, create_time,
update_time, `language`, last_organization_id,
phone, `source`, last_project_id,
create_user, update_user)
create_user, update_user, deleted
)
values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR}, #{enable,jdbcType=BIT}, #{createTime,jdbcType=BIGINT},
#{updateTime,jdbcType=BIGINT}, #{language,jdbcType=VARCHAR}, #{lastOrganizationId,jdbcType=VARCHAR},
#{phone,jdbcType=VARCHAR}, #{source,jdbcType=VARCHAR}, #{lastProjectId,jdbcType=VARCHAR},
#{createUser,jdbcType=VARCHAR}, #{updateUser,jdbcType=VARCHAR})
#{createUser,jdbcType=VARCHAR}, #{updateUser,jdbcType=VARCHAR}, #{deleted,jdbcType=BIT}
)
</insert>
<insert id="insertSelective" parameterType="io.metersphere.system.domain.User">
insert into user
@ -166,6 +169,9 @@
<if test="updateUser != null">
update_user,
</if>
<if test="deleted != null">
deleted,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
@ -210,6 +216,9 @@
<if test="updateUser != null">
#{updateUser,jdbcType=VARCHAR},
</if>
<if test="deleted != null">
#{deleted,jdbcType=BIT},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="io.metersphere.system.domain.UserExample" resultType="java.lang.Long">
@ -263,6 +272,9 @@
<if test="record.updateUser != null">
update_user = #{record.updateUser,jdbcType=VARCHAR},
</if>
<if test="record.deleted != null">
deleted = #{record.deleted,jdbcType=BIT},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
@ -283,7 +295,8 @@
`source` = #{record.source,jdbcType=VARCHAR},
last_project_id = #{record.lastProjectId,jdbcType=VARCHAR},
create_user = #{record.createUser,jdbcType=VARCHAR},
update_user = #{record.updateUser,jdbcType=VARCHAR}
update_user = #{record.updateUser,jdbcType=VARCHAR},
deleted = #{record.deleted,jdbcType=BIT}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
@ -330,6 +343,9 @@
<if test="updateUser != null">
update_user = #{updateUser,jdbcType=VARCHAR},
</if>
<if test="deleted != null">
deleted = #{deleted,jdbcType=BIT},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
</update>
@ -347,7 +363,8 @@
`source` = #{source,jdbcType=VARCHAR},
last_project_id = #{lastProjectId,jdbcType=VARCHAR},
create_user = #{createUser,jdbcType=VARCHAR},
update_user = #{updateUser,jdbcType=VARCHAR}
update_user = #{updateUser,jdbcType=VARCHAR},
deleted = #{deleted,jdbcType=BIT}
where id = #{id,jdbcType=VARCHAR}
</update>
</mapper>

View File

@ -295,12 +295,14 @@ CREATE TABLE IF NOT EXISTS user
`last_project_id` VARCHAR(50) COMMENT '当前项目ID',
`create_user` VARCHAR(50) NOT NULL COMMENT '创建人',
`update_user` VARCHAR(50) NOT NULL COMMENT '修改人',
`deleted` BIT NOT NULL DEFAULT 0 COMMENT '是否删除' ,
PRIMARY KEY (id)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_general_ci COMMENT = '用户';
CREATE INDEX idx_name ON user (`name`);
CREATE UNIQUE INDEX idx_email ON user (`email`);
CREATE INDEX idx_create_time ON user (`create_time`);

View File

@ -7,8 +7,8 @@ INSERT INTO organization (id, num, name, description, create_user, update_user,
INSERT INTO project (id, num, organization_id, name, description, create_user, update_user, create_time, update_time) VALUES (uuid(), 100001, (SELECT id FROM organization WHERE name LIKE '默认组织'), '默认项目', '系统默认创建的项目', 'admin', 'admin', unix_timestamp() * 1000, unix_timestamp() * 1000);
-- 初始化用户
insert into user(id, name, email, password, create_time, update_time, language, last_organization_id, phone, source, last_project_id, create_user, update_user)
VALUES ('admin', 'Administrator', 'admin@metersphere.io', MD5('metersphere'), UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, NULL, NUll, '', 'LOCAL', NULL, 'admin', 'admin');
insert into user(id, name, email, password, create_time, update_time, language, last_organization_id, phone, source, last_project_id, create_user, update_user,deleted)
VALUES ('admin', 'Administrator', 'admin@metersphere.io', MD5('metersphere'), UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, NULL, NUll, '', 'LOCAL', NULL, 'admin', 'admin',false);
-- 初始化用户组
INSERT INTO user_role (id, name, description, internal, type, create_time, update_time, create_user, scope_id) VALUES ('admin', '系统管理员', '拥有系统全部组织以及项目的操作权限', 1, 'SYSTEM', 1621224000000, 1621224000000, 'admin', 'GLOBAL');

View File

@ -23,5 +23,5 @@ public interface BaseUserMapper {
List<User> selectByKeyword(String keyword);
List<String> selectUserIdByIdList(@Param("idList") List<String> userIdList);
List<String> selectUnDeletedUserIdByIdList(@Param("idList") List<String> userIdList);
}

View File

@ -12,7 +12,7 @@
SELECT *
FROM user
LEFT JOIN user_extend ON user.id = user_extend.id
WHERE user.email = #{email}
WHERE user.email = #{email} AND deleted IS FALSE
</select>
<select id="findAll" resultType="io.metersphere.system.domain.User">
@ -23,12 +23,12 @@
<insert id="batchSave">
INSERT INTO user(id, name, email, password, status, create_time, update_time, language, last_organization_id,
phone,
source, last_project_id, create_user)
source, last_project_id, create_user,deleted)
VALUES
<foreach collection="users" item="user" separator=",">
(#{user.id}, #{user.name}, #{user.email}, #{user.password}, #{user.status}, #{user.createTime},
#{user.updateTime}, #{user.language},
#{user.lastOrganizationId}, #{user.phone}, #{user.source}, #{user.lastProjectId}, #{user.createUser})
#{user.lastOrganizationId}, #{user.phone}, #{user.source}, #{user.lastProjectId}, #{user.createUser}, #{user.deleted})
</foreach>
</insert>
@ -55,13 +55,14 @@
<select id="selectByKeyword" resultType="io.metersphere.system.domain.User">
SELECT *
FROM user
WHERE DELETED IS FALSE
<if test="keyword != null and keyword != ''">
WHERE name LIKE CONCAT('%', #{keyword}, '%')
AND name LIKE CONCAT('%', #{keyword}, '%')
OR email LIKE CONCAT('%', #{keyword}, '%')
</if>
</select>
<select id="selectUserIdByIdList" resultType="java.lang.String">
SELECT * from `user` WHERE id IN
<select id="selectUnDeletedUserIdByIdList" resultType="java.lang.String">
SELECT * from `user` WHERE deleted IS FALSE AND id IN
<foreach collection="idList" item="id" open="(" separator="," close=")">
#{id}
</foreach>

View File

@ -15,8 +15,9 @@ import io.metersphere.sdk.util.Pager;
import io.metersphere.sdk.util.SessionUtils;
import io.metersphere.system.dto.UserBatchCreateDTO;
import io.metersphere.system.dto.UserRoleOption;
import io.metersphere.system.dto.request.UserEditEnableRequest;
import io.metersphere.system.dto.request.UserChangeEnableRequest;
import io.metersphere.system.dto.request.UserEditRequest;
import io.metersphere.system.dto.response.UserBatchProcessResponse;
import io.metersphere.system.dto.response.UserImportResponse;
import io.metersphere.system.dto.response.UserTableResponse;
import io.metersphere.system.service.GlobalUserRoleService;
@ -76,7 +77,7 @@ public class UserController {
@PostMapping("/update/enable")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
public UserEditEnableRequest updateUserEnable(@Validated @RequestBody UserEditEnableRequest request) {
public UserBatchProcessResponse updateUserEnable(@Validated @RequestBody UserChangeEnableRequest request) {
return userService.updateUserEnable(request, SessionUtils.getSessionId());
}
@ -85,4 +86,11 @@ public class UserController {
public UserImportResponse importUser(@RequestPart(value = "file", required = false) MultipartFile excelFile) {
return userService.importByExcel(excelFile, UserSourceEnum.LOCAL.name(), SessionUtils.getSessionId());
}
@PostMapping("/delete")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_DELETE)
public UserBatchProcessResponse deleteUser(@Validated @RequestBody UserChangeEnableRequest userBatchProcessRequest) {
return userService.deleteUser(userBatchProcessRequest.getUserIdList());
}
}

View File

@ -4,13 +4,12 @@ import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class UserEditEnableRequest {
public class UserBatchProcessRequest {
@Schema(title = "用户ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "{user.not.empty}")
List<String> userIdList;
boolean enable;
List<String> userIdList = new ArrayList<>();
}

View File

@ -0,0 +1,8 @@
package io.metersphere.system.dto.request;
import lombok.Data;
@Data
public class UserChangeEnableRequest extends UserBatchProcessRequest {
boolean enable;
}

View File

@ -0,0 +1,9 @@
package io.metersphere.system.dto.response;
import lombok.Data;
@Data
public class UserBatchProcessResponse {
private long totalCount;
private long successCount;
}

View File

@ -205,4 +205,10 @@ public class UserRoleRelationService {
example.createCriteria().andUserIdEqualTo(id);
return userRoleRelationMapper.selectByExample(example);
}
public void deleteByUserIdList(@Valid @NotEmpty List<String> userIdList) {
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andUserIdIn(userIdList);
userRoleRelationMapper.deleteByExample(example);
}
}

View File

@ -20,8 +20,9 @@ import io.metersphere.system.dto.UserBatchCreateDTO;
import io.metersphere.system.dto.UserCreateInfo;
import io.metersphere.system.dto.excel.UserExcel;
import io.metersphere.system.dto.excel.UserExcelRowDTO;
import io.metersphere.system.dto.request.UserEditEnableRequest;
import io.metersphere.system.dto.request.UserChangeEnableRequest;
import io.metersphere.system.dto.request.UserEditRequest;
import io.metersphere.system.dto.response.UserBatchProcessResponse;
import io.metersphere.system.dto.response.UserImportResponse;
import io.metersphere.system.dto.response.UserTableResponse;
import io.metersphere.system.mapper.UserMapper;
@ -121,6 +122,7 @@ public class UserService {
user.setUpdateTime(createTime);
user.setPassword(CodingUtil.md5(user.getEmail()));
user.setSource(source);
user.setDeleted(false);
userMapper.insertSelective(user);
saveUserList.add(user);
}
@ -176,8 +178,12 @@ public class UserService {
return userEditRequest;
}
public UserEditEnableRequest updateUserEnable(UserEditEnableRequest request, String operator) {
public UserBatchProcessResponse updateUserEnable(UserChangeEnableRequest request, String operator) {
this.checkUserInDb(request.getUserIdList());
UserBatchProcessResponse response = new UserBatchProcessResponse();
response.setTotalCount(request.getUserIdList().size());
UserExample userExample = new UserExample();
userExample.createCriteria().andIdIn(
request.getUserIdList()
@ -186,12 +192,12 @@ public class UserService {
updateUser.setEnable(request.isEnable());
updateUser.setUpdateUser(operator);
updateUser.setUpdateTime(System.currentTimeMillis());
userMapper.updateByExampleSelective(updateUser, userExample);
return request;
response.setSuccessCount(userMapper.updateByExampleSelective(updateUser, userExample));
return response;
}
private void checkUserInDb(@Valid @NotEmpty List<String> userIdList) {
List<String> userInDb = baseUserMapper.selectUserIdByIdList(userIdList);
List<String> userInDb = baseUserMapper.selectUnDeletedUserIdByIdList(userIdList);
if (userIdList.size() != userInDb.size()) {
throw new MSException(Translator.get("user.not.exist"));
}
@ -258,4 +264,19 @@ public class UserService {
}
public UserBatchProcessResponse deleteUser(@Valid @NotEmpty List<String> userIdList) {
this.checkUserInDb(userIdList);
UserBatchProcessResponse response = new UserBatchProcessResponse();
response.setTotalCount(userIdList.size());
UserExample userExample = new UserExample();
userExample.createCriteria().andIdIn(userIdList);
//更新删除标志位
response.setSuccessCount(userMapper.updateByExampleSelective(new User() {{
setDeleted(true);
}}, userExample));
//删除用户角色关系
userRoleRelationService.deleteByUserIdList(userIdList);
return response;
}
}

View File

@ -239,7 +239,7 @@ public class SystemProjectControllerTests extends BaseTest {
@Test
@Order(10)
public void testGetProjectListByOrg() throws Exception{
public void testGetProjectListByOrg() throws Exception {
String organizationId = "organizationId";
MvcResult mvcResult = this.responseGet(prefix + "/list/" + organizationId);
String returnData = mvcResult.getResponse().getContentAsString();
@ -251,7 +251,7 @@ public class SystemProjectControllerTests extends BaseTest {
@Test
@Order(11)
public void testGetProjectListByOrgError() throws Exception{
public void testGetProjectListByOrgError() throws Exception {
String organizationId = "organizationId";
MvcResult mvcResult = this.responseGet(prefix + "/list/" + organizationId);
String returnData = mvcResult.getResponse().getContentAsString();
@ -263,7 +263,7 @@ public class SystemProjectControllerTests extends BaseTest {
@Test
@Order(12)
public void testRemoveProjectMember() throws Exception{
public void testRemoveProjectMember() throws Exception {
String projectId = "projectId";
String userId = "admin1";
mockMvc.perform(MockMvcRequestBuilders.get(prefix + "/remove-member/" + projectId + "/" + userId)
@ -275,7 +275,7 @@ public class SystemProjectControllerTests extends BaseTest {
@Test
@Order(13)
public void testAddProjectMember() throws Exception{
public void testAddProjectMember() throws Exception {
ProjectMemberRequest projectMemberRequest = new ProjectMemberRequest();
projectMemberRequest.setProjectId("projectId");
List<String> userIds = new ArrayList<>();
@ -286,5 +286,4 @@ public class SystemProjectControllerTests extends BaseTest {
}
}

View File

@ -5,7 +5,8 @@ import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.util.JSON;
import io.metersphere.system.dto.UserCreateInfo;
import io.metersphere.system.dto.UserRoleOption;
import io.metersphere.system.dto.request.UserEditEnableRequest;
import io.metersphere.system.dto.request.UserBatchProcessRequest;
import io.metersphere.system.dto.request.UserChangeEnableRequest;
import io.metersphere.system.utils.UserTestUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
@ -13,6 +14,7 @@ import org.junit.jupiter.api.*;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.web.servlet.MockMvc;
@ -23,7 +25,6 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.ArrayList;
import java.util.List;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -81,13 +82,24 @@ public class UserControllerNonePermissionTests {
this.requestPost(UserTestUtils.URL_USER_UPDATE,
UserTestUtils.getUserUpdateDTO(paramUserInfo, paramRoleList), CHECK_RESULT_MATHER);
//校验权限启用/禁用用户
UserEditEnableRequest userChangeEnableRequest = new UserEditEnableRequest();
UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest();
userChangeEnableRequest.setEnable(false);
userChangeEnableRequest.setUserIdList(new ArrayList<>() {{
this.add("testId");
}});
this.requestPost(UserTestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, CHECK_RESULT_MATHER);
//用户导入
//导入正常文件
String filePath = this.getClass().getClassLoader().getResource("file/user_import_success.xlsx").getPath();
MockMultipartFile file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserTestUtils.getFileBytes(filePath));
this.requestFile(UserTestUtils.URL_USER_IMPORT, file, CHECK_RESULT_MATHER);
//用户删除
UserBatchProcessRequest request = new UserBatchProcessRequest();
request.setUserIdList(new ArrayList<>() {{
this.add("testId");
}});
this.requestPost(UserTestUtils.URL_USER_DELETE, request, CHECK_RESULT_MATHER);
}
@BeforeEach
@ -110,7 +122,17 @@ public class UserControllerNonePermissionTests {
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher).andDo(print())
.andExpect(resultMatcher)
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
private void requestFile(String url, MockMultipartFile file, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.multipart(url)
.file(file)
.contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken))
.andExpect(resultMatcher)
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
@ -119,7 +141,7 @@ public class UserControllerNonePermissionTests {
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher).andDo(print())
.andExpect(resultMatcher)
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
}

View File

@ -9,14 +9,19 @@ import io.metersphere.sdk.dto.UserDTO;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.JSON;
import io.metersphere.sdk.util.Pager;
import io.metersphere.system.domain.User;
import io.metersphere.system.domain.UserExample;
import io.metersphere.system.dto.UserBatchCreateDTO;
import io.metersphere.system.dto.UserCreateInfo;
import io.metersphere.system.dto.UserRoleOption;
import io.metersphere.system.dto.excel.UserExcelRowDTO;
import io.metersphere.system.dto.request.UserEditEnableRequest;
import io.metersphere.system.dto.request.UserBatchProcessRequest;
import io.metersphere.system.dto.request.UserChangeEnableRequest;
import io.metersphere.system.dto.request.UserEditRequest;
import io.metersphere.system.dto.response.UserBatchProcessResponse;
import io.metersphere.system.dto.response.UserImportResponse;
import io.metersphere.system.dto.response.UserTableResponse;
import io.metersphere.system.mapper.UserMapper;
import io.metersphere.system.service.UserService;
import io.metersphere.system.utils.UserTestUtils;
import io.metersphere.utils.JsonUtils;
@ -40,6 +45,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@ -55,6 +61,8 @@ public class UserControllerTests extends BaseTest {
@Resource
private UserService userService;
@Resource
private UserMapper userMapper;
//失败请求返回编码
private static final ResultMatcher BAD_REQUEST_MATCHER = status().isBadRequest();
@ -66,6 +74,8 @@ public class UserControllerTests extends BaseTest {
public static final String USER_DEFAULT_NAME = "tianyang.no.1";
public static final String USER_DEFAULT_EMAIL = "tianyang.no.1@126.com";
public static final String USER_NONE_ROLE_EMAIL = "tianyang.none.role@163.com";
//已删除的用户ID
private static final List<String> DELETED_USER_ID_LIST = new ArrayList<>();
//记录查询到的组织信息
private void setDefaultUserRoleList(MvcResult mvcResult) throws Exception {
@ -94,6 +104,13 @@ public class UserControllerTests extends BaseTest {
}
}
private void checkUserDeleted() throws Exception {
if (CollectionUtils.isEmpty(DELETED_USER_ID_LIST)) {
//测试数据初始化入库
this.testUserDeleteSuccess();
}
}
private void requestPost(String url, Object param, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
@ -492,7 +509,7 @@ public class UserControllerTests extends BaseTest {
this.checkUserList();
//单独修改状态
UserCreateInfo userInfo = USER_LIST.get(0);
UserEditEnableRequest userChangeEnableRequest = new UserEditEnableRequest();
UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest();
userChangeEnableRequest.setUserIdList(new ArrayList<>() {{
this.add(userInfo.getId());
}});
@ -507,7 +524,7 @@ public class UserControllerTests extends BaseTest {
public void testUserChangeEnableError() throws Exception {
this.checkUserList();
//用户不存在
UserEditEnableRequest userChangeEnableRequest = new UserEditEnableRequest();
UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest();
userChangeEnableRequest.setEnable(false);
this.requestPost(UserTestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, BAD_REQUEST_MATCHER);
//含有非法用户
@ -519,7 +536,7 @@ public class UserControllerTests extends BaseTest {
@Test
@Order(6)
@Order(7)
public void testUserImportSuccess() throws Exception {
this.checkUserList();
//测试用户数据导入 每个导入文件都有10条数据不同文件出错的数据不同
@ -590,6 +607,43 @@ public class UserControllerTests extends BaseTest {
this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库
}
@Test
@Order(8)
public void testUserDeleteSuccess() throws Exception {
this.checkUserList();
//删除已存的所有用户
UserBatchProcessRequest request = new UserBatchProcessRequest();
request.setUserIdList(USER_LIST.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
UserBatchProcessResponse response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_DELETE, request), UserBatchProcessResponse.class);
Assertions.assertEquals(request.getUserIdList().size(), response.getTotalCount());
Assertions.assertEquals(request.getUserIdList().size(), response.getSuccessCount());
//检查数据库
UserExample example = new UserExample();
example.createCriteria().andIdIn(request.getUserIdList());
List<User> userList = userMapper.selectByExample(example);
for (User user : userList) {
Assertions.assertTrue(user.getDeleted());
}
//记录已经删除了的用户用于反例
DELETED_USER_ID_LIST.clear();
DELETED_USER_ID_LIST.addAll(request.getUserIdList());
}
@Test
@Order(9)
public void testUserDeleteError() throws Exception {
this.checkUserDeleted();
//参数为空
UserBatchProcessRequest request = new UserBatchProcessRequest();
this.requestPost(UserTestUtils.URL_USER_DELETE, request, BAD_REQUEST_MATCHER);
//用户不存在
request.getUserIdList().add("123456789012345678901234");
this.requestPost(UserTestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER);
//用户已经被删除
request.setUserIdList(DELETED_USER_ID_LIST);
this.requestPost(UserTestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER);
}
public void checkImportUserInDb(ExcelParseDTO<UserExcelRowDTO> userImportReportDTOByFile) throws Exception {
for (UserExcelRowDTO item : userImportReportDTOByFile.getDataList()) {
Assertions.assertNotNull(this.getUserByEmail(item.getEmail()));

View File

@ -35,6 +35,7 @@ public class UserTestUtils {
public static final String URL_GET_GLOBAL_SYSTEM = "/system/user/get/global/system/role";
public static final String URL_USER_UPDATE_ENABLE = "/system/user/update/enable";
public static final String URL_USER_IMPORT = "/system/user/import";
public static final String URL_USER_DELETE = "/system/user/delete";
public static <T> T parseObjectFromMvcResult(MvcResult mvcResult, Class<T> parseClass) {

View File

@ -1,4 +1,7 @@
-- 初始化一个没有任何权限的用户
insert into user(id, name, email, password, create_time, update_time, language, last_organization_id, phone, source, last_project_id, create_user, update_user)
VALUES ('tianyang.member.id', 'tianyang.member', 'tianyang.member@163.com', MD5('tianyang.member@163.com'), UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, NULL, NUll, '', 'LOCAL', NULL, 'admin', 'admin');
INSERT INTO user_role_relation (id, user_id, role_id, source_id, create_time, create_user) VALUES (uuid(), 'tianyang.member.id', 'member', 'system', 1684747668375, 'admin');
insert into user(id, name, email, password, create_time, update_time, language, last_organization_id, phone, source,
last_project_id, create_user, update_user)
VALUES ('tianyang.member.id', 'tianyang.member', 'tianyang.member@163.com', MD5('tianyang.member@163.com'),
UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, NULL, NUll, '', 'LOCAL', NULL, 'admin', 'admin');
INSERT INTO user_role_relation (id, user_id, role_id, source_id, create_time, create_user)
VALUES (uuid(), 'tianyang.member.id', 'member', 'system', 1684747668375, 'admin');

View File

@ -1,3 +1,3 @@
-- 初始化一个没有任何权限的用户
insert into user(id, name, email, password, create_time, update_time, language, last_organization_id, phone, source, last_project_id, create_user, update_user)
VALUES (uuid(), 'tianyang.none.role', 'tianyang.none.role@163.com', MD5('tianyang.none.role'), UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, NULL, NUll, '', 'LOCAL', NULL, 'admin', 'admin');
insert into user(id, name, email, password, create_time, update_time, language, last_organization_id, phone, source, last_project_id, create_user, update_user, deleted)
VALUES (uuid(), 'tianyang.none.role', 'tianyang.none.role@163.com', MD5('tianyang.none.role'), UNIX_TIMESTAMP() * 1000, UNIX_TIMESTAMP() * 1000, NULL, NUll, '', 'LOCAL', NULL, 'admin', 'admin', false);

View File

@ -1,6 +1,6 @@
#测试项目下的成员
INSERT INTO `project` VALUES( 'projectId1', NULL, '3a5b1bd3-05e5-11ee-ad96-0242ac1e0a02', '默认项目1', '系统默认创建的项目', 1686219258000, 1686219258000, 'admin','admin', NULL, b '0', NULL, NULL );
INSERT INTO `user` VALUES ('admin1', 'Administrator', 'admin1@metersphere.io', '3259a9d7f208ef9690025d1432558c5b', b'1', 1686219258000, 1686219258000, NULL, '3a5b1bd3-05e5-11ee-ad96-0242ac1e0a02', '', 'LOCAL', '3a6dbcc8-05e5-11ee-ad96-0242ac1e0a02', 'admin', 'admin');
INSERT INTO `user` VALUES ('admin2', 'Administrator', 'admin2@metersphere.io', '3259a9d7f208ef9690025d1432558c5b', b'1', 1686219258000, 1686219258000, NULL, '3a5b1bd3-05e5-11ee-ad96-0242ac1e0a02', '', 'LOCAL', '3a6dbcc8-05e5-11ee-ad96-0242ac1e0a02', 'admin', 'admin');
INSERT INTO `user` VALUES ('admin1', 'Administrator', 'admin1@metersphere.io', '3259a9d7f208ef9690025d1432558c5b', b'1', 1686219258000, 1686219258000, NULL, '3a5b1bd3-05e5-11ee-ad96-0242ac1e0a02', '', 'LOCAL', '3a6dbcc8-05e5-11ee-ad96-0242ac1e0a02', 'admin', 'admin',false);
INSERT INTO `user` VALUES ('admin2', 'Administrator', 'admin2@metersphere.io', '3259a9d7f208ef9690025d1432558c5b', b'1', 1686219258000, 1686219258000, NULL, '3a5b1bd3-05e5-11ee-ad96-0242ac1e0a02', '', 'LOCAL', '3a6dbcc8-05e5-11ee-ad96-0242ac1e0a02', 'admin', 'admin',false);
INSERT INTO user_role_relation VALUES ('c3bb9b4f-46d8-4952-9681-8889974487w','admin1','project_admin','projectId1','1684747668375','1684747668375');
INSERT INTO user_role_relation VALUES ('c3bb9b4f-46d8-4952-9681-8889974487q','admin2','project_admin','projectId1','1684747668321','1684747668336');