feat(用户管理): 用户表格查询功能

This commit is contained in:
song-tianyang 2023-06-12 18:47:07 +08:00 committed by 建国
parent 5d3cd5654b
commit f5de73cd73
16 changed files with 376 additions and 117 deletions

View File

@ -1,15 +1,17 @@
package io.metersphere.system.domain;
import io.metersphere.validation.groups.*;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.io.Serializable;
import lombok.Data;
@Data
public class UserRoleRelation implements Serializable {
@Schema(title = "用户组关系ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{user_role_relation.id.not_blank}", groups = {Updated.class})
@NotBlank(message = "{user_role_relation.id.not_blank}", groups = {Created.class, Updated.class})
@Size(min = 1, max = 50, message = "{user_role_relation.id.length_range}", groups = {Created.class, Updated.class})
private String id;
@ -31,8 +33,10 @@ public class UserRoleRelation implements Serializable {
@Schema(title = "创建时间")
private Long createTime;
@Schema(title = "更新时间")
private Long updateTime;
@Schema(title = "创建人", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "{user_role_relation.create_user.not_blank}", groups = {Created.class})
@Size(min = 1, max = 50, message = "{user_role_relation.create_user.length_range}", groups = {Created.class, Updated.class})
private String createUser;
private static final long serialVersionUID = 1L;
}

View File

@ -444,63 +444,73 @@ public class UserRoleRelationExample {
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("update_time is null");
public Criteria andCreateUserIsNull() {
addCriterion("create_user is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("update_time is not null");
public Criteria andCreateUserIsNotNull() {
addCriterion("create_user is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(Long value) {
addCriterion("update_time =", value, "updateTime");
public Criteria andCreateUserEqualTo(String value) {
addCriterion("create_user =", value, "createUser");
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(Long value) {
addCriterion("update_time <>", value, "updateTime");
public Criteria andCreateUserNotEqualTo(String value) {
addCriterion("create_user <>", value, "createUser");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(Long value) {
addCriterion("update_time >", value, "updateTime");
public Criteria andCreateUserGreaterThan(String value) {
addCriterion("create_user >", value, "createUser");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(Long value) {
addCriterion("update_time >=", value, "updateTime");
public Criteria andCreateUserGreaterThanOrEqualTo(String value) {
addCriterion("create_user >=", value, "createUser");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(Long value) {
addCriterion("update_time <", value, "updateTime");
public Criteria andCreateUserLessThan(String value) {
addCriterion("create_user <", value, "createUser");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(Long value) {
addCriterion("update_time <=", value, "updateTime");
public Criteria andCreateUserLessThanOrEqualTo(String value) {
addCriterion("create_user <=", value, "createUser");
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<Long> values) {
addCriterion("update_time in", values, "updateTime");
public Criteria andCreateUserLike(String value) {
addCriterion("create_user like", value, "createUser");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<Long> values) {
addCriterion("update_time not in", values, "updateTime");
public Criteria andCreateUserNotLike(String value) {
addCriterion("create_user not like", value, "createUser");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(Long value1, Long value2) {
addCriterion("update_time between", value1, value2, "updateTime");
public Criteria andCreateUserIn(List<String> values) {
addCriterion("create_user in", values, "createUser");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(Long value1, Long value2) {
addCriterion("update_time not between", value1, value2, "updateTime");
public Criteria andCreateUserNotIn(List<String> values) {
addCriterion("create_user not in", values, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserBetween(String value1, String value2) {
addCriterion("create_user between", value1, value2, "createUser");
return (Criteria) this;
}
public Criteria andCreateUserNotBetween(String value1, String value2) {
addCriterion("create_user not between", value1, value2, "createUser");
return (Criteria) this;
}
}

View File

@ -7,7 +7,7 @@
<result column="role_id" jdbcType="VARCHAR" property="roleId" />
<result column="source_id" jdbcType="VARCHAR" property="sourceId" />
<result column="create_time" jdbcType="BIGINT" property="createTime" />
<result column="update_time" jdbcType="BIGINT" property="updateTime" />
<result column="create_user" jdbcType="VARCHAR" property="createUser" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
@ -68,7 +68,7 @@
</where>
</sql>
<sql id="Base_Column_List">
id, user_id, role_id, source_id, create_time, update_time
id, user_id, role_id, source_id, create_time, create_user
</sql>
<select id="selectByExample" parameterType="io.metersphere.system.domain.UserRoleRelationExample" resultMap="BaseResultMap">
select
@ -102,10 +102,10 @@
</delete>
<insert id="insert" parameterType="io.metersphere.system.domain.UserRoleRelation">
insert into user_role_relation (id, user_id, role_id,
source_id, create_time, update_time
source_id, create_time, create_user
)
values (#{id,jdbcType=VARCHAR}, #{userId,jdbcType=VARCHAR}, #{roleId,jdbcType=VARCHAR},
#{sourceId,jdbcType=VARCHAR}, #{createTime,jdbcType=BIGINT}, #{updateTime,jdbcType=BIGINT}
#{sourceId,jdbcType=VARCHAR}, #{createTime,jdbcType=BIGINT}, #{createUser,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="io.metersphere.system.domain.UserRoleRelation">
@ -126,8 +126,8 @@
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
<if test="createUser != null">
create_user,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
@ -146,8 +146,8 @@
<if test="createTime != null">
#{createTime,jdbcType=BIGINT},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=BIGINT},
<if test="createUser != null">
#{createUser,jdbcType=VARCHAR},
</if>
</trim>
</insert>
@ -175,8 +175,8 @@
<if test="record.createTime != null">
create_time = #{record.createTime,jdbcType=BIGINT},
</if>
<if test="record.updateTime != null">
update_time = #{record.updateTime,jdbcType=BIGINT},
<if test="record.createUser != null">
create_user = #{record.createUser,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
@ -190,7 +190,7 @@
role_id = #{record.roleId,jdbcType=VARCHAR},
source_id = #{record.sourceId,jdbcType=VARCHAR},
create_time = #{record.createTime,jdbcType=BIGINT},
update_time = #{record.updateTime,jdbcType=BIGINT}
create_user = #{record.createUser,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
@ -210,8 +210,8 @@
<if test="createTime != null">
create_time = #{createTime,jdbcType=BIGINT},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=BIGINT},
<if test="createUser != null">
create_user = #{createUser,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=VARCHAR}
@ -222,7 +222,7 @@
role_id = #{roleId,jdbcType=VARCHAR},
source_id = #{sourceId,jdbcType=VARCHAR},
create_time = #{createTime,jdbcType=BIGINT},
update_time = #{updateTime,jdbcType=BIGINT}
create_user = #{createUser,jdbcType=VARCHAR}
where id = #{id,jdbcType=VARCHAR}
</update>
</mapper>

View File

@ -338,25 +338,24 @@ CREATE INDEX idx_create_user ON user (`create_user`);
CREATE INDEX idx_update_user ON user (`update_user`);
DROP TABLE IF EXISTS user_role_relation;
CREATE TABLE user_role_relation
(
`id` VARCHAR(50) NOT NULL COMMENT '用户组关系ID',
`user_id` VARCHAR(50) NOT NULL COMMENT '用户ID',
`role_id` VARCHAR(50) NOT NULL COMMENT '组ID',
`source_id` VARCHAR(50) NOT NULL COMMENT '组织或项目ID',
`create_time` BIGINT NOT NULL COMMENT '创建时间',
`update_time` BIGINT NOT NULL COMMENT '更新时间',
PRIMARY KEY (id)
CREATE TABLE user_role_relation(
`id` VARCHAR(50) NOT NULL COMMENT '用户组关系ID' ,
`user_id` VARCHAR(50) NOT NULL COMMENT '用户ID' ,
`role_id` VARCHAR(50) NOT NULL COMMENT '组ID' ,
`source_id` VARCHAR(50) NOT NULL COMMENT '组织或项目ID' ,
`create_time` BIGINT NOT NULL COMMENT '创建时间' ,
`create_user` VARCHAR(50) NOT NULL COMMENT '创建人' ,
PRIMARY KEY (id)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_general_ci COMMENT = '用户组关系';
CREATE INDEX idx_user_id ON user_role_relation (`user_id`);
CREATE INDEX idx_group_id ON user_role_relation (`role_id`);
CREATE INDEX idx_source_id ON user_role_relation (`source_id`);
CREATE INDEX idx_create_time ON user_role_relation (`create_time`);
CREATE INDEX idx_update_time ON user_role_relation (`update_time`);
CREATE INDEX idx_user_id ON user_role_relation(`user_id`);
CREATE INDEX idx_group_id ON user_role_relation(`role_id`);
CREATE INDEX idx_source_id ON user_role_relation(`source_id`);
CREATE INDEX idx_create_time ON user_role_relation(`create_time`);
DROP TABLE IF EXISTS user_role_permission;
CREATE TABLE user_role_permission

View File

@ -20,7 +20,7 @@ INSERT INTO user_role (id, name, description, internal, type, create_time, updat
INSERT INTO user_role (id, name, description, internal, type, create_time, update_time, create_user, scope_id) VALUES ('org_member', '组织成员(系统)', '组织成员', 1, 'ORGANIZATION', 1620674220008, 1620674220000, 'admin', 'global');
-- 初始化用户和组的关系
INSERT INTO user_role_relation (id, user_id, role_id, source_id, create_time, update_time) VALUES ('c3bb9b4f-46d8-4952-9681-8889974487d1', 'admin', 'super', 'system', 1684747668375, 1684747668375);
INSERT INTO user_role_relation (id, user_id, role_id, source_id, create_time, create_user) VALUES ('c3bb9b4f-46d8-4952-9681-8889974487d1', 'admin', 'super', 'system', 1684747668375, 'admin');
-- 初始化用户组权限

View File

@ -1,8 +1,13 @@
package io.metersphere.sdk.dto;
import com.google.common.base.CaseFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
@ -19,9 +24,24 @@ public class BasePageRequest {
@Schema(title = "每页显示条数")
private int pageSize;
@Schema(title = "排序字段(字段:asc/desc")
private Map<String, String> sort;
@Schema(title = "排序字段(model中的字段 : asc/desc")
private Map<@Valid @Pattern(regexp = "^[A-Za-z]+$") String, @Valid @NotBlank String> sort;
@Schema(title = "过滤字段")
private Map<String, Object> filter;
public String getSortString() {
if (sort == null || sort.isEmpty()) {
return null;
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : sort.entrySet()) {
String column = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.getKey());
sb.append(column)
.append(StringUtils.SPACE)
.append(StringUtils.equalsIgnoreCase(entry.getValue(), "DESC") ? "DESC" : "ASC")
.append(",");
}
return sb.substring(0, sb.length() - 1);
}
}

View File

@ -20,4 +20,6 @@ public interface BaseUserMapper {
String selectEmailInDB(@Param("email") String email, @Param("id") String id);
List<User> selectUserIdByEmailList(@Param("emailList") List<String> emailList);
List<User> selectByKeyword(String keyword);
}

View File

@ -52,4 +52,12 @@
#{email}
</foreach>
</select>
<select id="selectByKeyword" resultType="io.metersphere.system.domain.User">
SELECT *
FROM user
<if test="keyword != null and keyword != ''">
WHERE name LIKE CONCAT('%', #{keyword}, '%')
OR email LIKE CONCAT('%', #{keyword}, '%')
</if>
</select>
</mapper>

View File

@ -1,17 +1,27 @@
package io.metersphere.system.controller;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.dto.BasePageRequest;
import io.metersphere.sdk.dto.UserDTO;
import io.metersphere.sdk.util.PageUtils;
import io.metersphere.sdk.util.Pager;
import io.metersphere.sdk.util.SessionUtils;
import io.metersphere.system.dto.UserMaintainRequest;
import io.metersphere.system.dto.UserBatchCreateDTO;
import io.metersphere.system.dto.response.UserInfo;
import io.metersphere.system.service.UserService;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@ -26,8 +36,23 @@ public class UserController {
@PostMapping("/add")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_ADD)
public UserMaintainRequest addUser(@Validated({Created.class}) @RequestBody UserMaintainRequest userCreateDTO) {
public UserBatchCreateDTO addUser(@Validated({Created.class}) @RequestBody UserBatchCreateDTO userCreateDTO) {
userCreateDTO.setCreateUserToList(SessionUtils.getSessionId());
return userService.add(userCreateDTO);
}
@PostMapping("/update")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
public UserBatchCreateDTO updateUser(@Validated({Updated.class}) @RequestBody UserBatchCreateDTO userCreateDTO) {
userCreateDTO.setCreateUserToList(SessionUtils.getSessionId());
return userService.add(userCreateDTO);
}
@PostMapping("/page")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_ADD)
public Pager<List<UserInfo>> list(@Validated @RequestBody BasePageRequest request) {
Page<Object> page = PageHelper.startPage(request.getCurrent(), request.getPageSize(),
StringUtils.isNotBlank(request.getSortString()) ? request.getSortString() : "create_time desc");
return PageUtils.setPageInfo(page, userService.list(request));
}
}

View File

@ -12,16 +12,19 @@ import lombok.Data;
import java.util.List;
@Data
public class UserMaintainRequest {
public class UserBatchCreateDTO {
@Schema(title = "用户信息集合", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(groups = {Created.class, Updated.class}, message = "{user.info.not_empty}")
List<@Valid User> userInfoList;
@Schema(title = "组织Id", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(groups = {Created.class, Updated.class}, message = "{user.organizationId.not_blank}")
String organizationId;
@Schema(title = "项目ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(groups = {Created.class, Updated.class}, message = "{user.projectId.not_blank}")
String projectId;
@NotEmpty(groups = {Created.class, Updated.class}, message = "{user.organizationId.not_blank}")
List<@Valid @NotBlank(message = "{user.organizationId.not_blank}", groups = {Created.class, Updated.class}) String> organizationIdList;
@Schema(title = "用户组", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(groups = {Created.class, Updated.class}, message = "{user_role.id.not_blank}")
List<@Valid @NotBlank(message = "{user_role.id.not_blank}", groups = {Created.class, Updated.class}) String> userRoleIdList;
public void setCreateUserToList(String userSessionId) {
userInfoList.forEach(user -> {

View File

@ -0,0 +1,17 @@
package io.metersphere.system.dto.response;
import io.metersphere.system.domain.Organization;
import io.metersphere.system.domain.User;
import io.metersphere.system.domain.UserRole;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
@Data
public class UserInfo extends User {
@Schema(title = "用户所属组织")
List<Organization> organizationList;
@Schema(title = "用户所属用户组")
List<UserRole> userRoleList;
}

View File

@ -0,0 +1,71 @@
package io.metersphere.system.service;
import io.metersphere.system.domain.User;
import io.metersphere.system.domain.UserRoleRelation;
import io.metersphere.system.mapper.UserRoleRelationMapper;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Service
@Transactional(rollbackFor = Exception.class)
public class UserRoleRelationService {
@Resource
private SqlSessionFactory sqlSessionFactory;
private UserRoleRelationMapper userRoleRelationMapper;
public void batchSave(@Validated({Created.class, Updated.class})
@NotEmpty(groups = {Created.class, Updated.class}, message = "{user.organizationId.not_blank}")
List<@Valid @NotBlank(message = "{user.organizationId.not_blank}", groups = {Created.class, Updated.class}) String> organizationIdList,
@NotEmpty(groups = {Created.class, Updated.class}, message = "{user_role.id.not_blank}")
List<@Valid @NotBlank(message = "{user_role.id.not_blank}", groups = {Created.class, Updated.class}) String> userRoleIdList,
@NotEmpty(groups = {Created.class, Updated.class}, message = "{user.info.not_empty}")
List<@Valid User> userInfoList) {
long operationTime = System.currentTimeMillis();
List<UserRoleRelation> userRoleRelationSaveList = new ArrayList<>();
//添加用户组织关系
for (String orgId : organizationIdList) {
for (String userRoleId : userRoleIdList) {
for (User user : userInfoList) {
UserRoleRelation userRoleRelation = new UserRoleRelation();
userRoleRelation.setId(UUID.randomUUID().toString());
userRoleRelation.setUserId(user.getId());
userRoleRelation.setRoleId(userRoleId);
userRoleRelation.setSourceId(orgId);
userRoleRelation.setCreateTime(operationTime);
userRoleRelation.setCreateUser(user.getCreateUser());
userRoleRelationSaveList.add(userRoleRelation);
}
}
}
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserRoleRelationMapper batchSaveMapper = sqlSession.getMapper(UserRoleRelationMapper.class);
try {
int insertIndex = 0;
for (UserRoleRelation userRoleRelation : userRoleRelationSaveList) {
batchSaveMapper.insert(userRoleRelation);
insertIndex++;
if (insertIndex % 50 == 0) {
sqlSession.flushStatements();
}
}
sqlSession.flushStatements();
} finally {
SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);
}
}
}

View File

@ -1,16 +1,18 @@
package io.metersphere.system.service;
import io.metersphere.sdk.dto.BasePageRequest;
import io.metersphere.sdk.dto.UserDTO;
import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.mapper.BaseUserMapper;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.CodingUtil;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.User;
import io.metersphere.system.dto.UserMaintainRequest;
import io.metersphere.system.dto.UserBatchCreateDTO;
import io.metersphere.system.dto.response.UserInfo;
import io.metersphere.system.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -26,6 +28,8 @@ public class UserService {
private BaseUserMapper baseUserMapper;
@Resource
private UserMapper userMapper;
@Resource
private UserRoleRelationService userRoleRelationService;
private void validateUserInfo(List<User> userList) {
//判断参数内是否含有重复邮箱
@ -46,24 +50,31 @@ public class UserService {
}
}
}
if (CollectionUtils.isNotEmpty(repeatEmailList)) {
throw new MSException(Translator.get("user.email.repeat", repeatEmailList.toString()));
}
}
public UserMaintainRequest add(UserMaintainRequest userCreateDTO) {
private void validateOrgAndProject(List<String> orgIdList, List<String> userRoleIdList) {
// todo 判断组织和用户组是否合法
}
public UserBatchCreateDTO add(UserBatchCreateDTO userCreateDTO) {
this.validateUserInfo(userCreateDTO.getUserInfoList());
this.validateOrgAndProject(userCreateDTO.getOrganizationIdList(), userCreateDTO.getUserRoleIdList());
long createTime = System.currentTimeMillis();
//添加用户
for (User user : userCreateDTO.getUserInfoList()) {
user.setId(UUID.randomUUID().toString());
if (StringUtils.isEmpty(user.getPassword())) {
user.setPassword(CodingUtil.md5(user.getEmail()));
}
user.setPassword(CodingUtil.md5(user.getEmail()));
user.setCreateTime(createTime);
user.setUpdateTime(createTime);
userMapper.insertSelective(user);
}
userRoleRelationService.batchSave(
userCreateDTO.getOrganizationIdList(), userCreateDTO.getUserRoleIdList(), userCreateDTO.getUserInfoList());
return userCreateDTO;
}
@ -72,4 +83,14 @@ public class UserService {
return baseUserMapper.selectByEmail(email);
}
public List<UserInfo> list(BasePageRequest request) {
List<UserInfo> returnList = new ArrayList<>();
List<User> userList = baseUserMapper.selectByKeyword(request.getKeyword());
for (User user : userList) {
UserInfo userInfo = new UserInfo();
BeanUtils.copyBean(userInfo, user);
returnList.add(userInfo);
}
return returnList;
}
}

View File

@ -0,0 +1,6 @@
package io.metersphere.system.utils;
//批量处理类
public class BatchProcessUtils {
private static int BATCH_SIZE = 100;
}

View File

@ -1,12 +1,16 @@
package io.metersphere.system.controller;
import com.jayway.jsonpath.JsonPath;
import io.metersphere.api.domain.ApiDefinition;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.controller.handler.ResultHolder;
import io.metersphere.sdk.dto.BasePageRequest;
import io.metersphere.sdk.dto.UserDTO;
import io.metersphere.sdk.util.JSON;
import io.metersphere.sdk.util.Pager;
import io.metersphere.system.domain.User;
import io.metersphere.system.dto.UserMaintainRequest;
import io.metersphere.system.dto.UserBatchCreateDTO;
import io.metersphere.system.dto.response.UserInfo;
import io.metersphere.system.utils.UserTestUtils;
import io.metersphere.utils.JsonUtils;
import jakarta.annotation.Resource;
@ -22,6 +26,7 @@ import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
@ -39,6 +44,13 @@ public class UserControllerTests {
private static String sessionId;
private static String csrfToken;
private static final String URL_USER_CREATE = "/user/add";
private static final String URL_USER_GET = "/user/get/";
private static final String URL_USER_PAGE = "/user/page";
private static final ResultMatcher BAD_REQUEST_MATCHER = status().isBadRequest();
private static final ResultMatcher ERROR_REQUEST_MATCHER = status().is5xxServerError();
private static final List<User> USER_LIST = new ArrayList<>();
//成功入库的用户保存内存中其他用例会使用到
@ -49,7 +61,7 @@ public class UserControllerTests {
//返回请求正常
Assertions.assertNotNull(resultHolder);
UserMaintainRequest userMaintainRequest = JSON.parseObject(JSON.toJSONString(resultHolder.getData()), UserMaintainRequest.class);
UserBatchCreateDTO userMaintainRequest = JSON.parseObject(JSON.toJSONString(resultHolder.getData()), UserBatchCreateDTO.class);
//返回值不为空
Assertions.assertNotNull(userMaintainRequest);
@ -110,10 +122,9 @@ public class UserControllerTests {
@Test
@Order(1)
public void testAddSuccess() throws Exception {
String url = "/user/add";
//模拟前台批量添加用户
UserMaintainRequest userMaintainRequest = UserTestUtils.getSimpleUserCreateDTO();
MvcResult mvcResult = this.responsePost(url, userMaintainRequest);
UserBatchCreateDTO userMaintainRequest = UserTestUtils.getSimpleUserCreateDTO();
MvcResult mvcResult = this.responsePost(URL_USER_CREATE, userMaintainRequest);
this.addUser2List(mvcResult);
//含有重复的用户名称
@ -133,49 +144,57 @@ public class UserControllerTests {
}});
}}
);
mvcResult = this.responsePost(url, userMaintainRequest);
mvcResult = this.responsePost(URL_USER_CREATE, userMaintainRequest);
this.addUser2List(mvcResult);
}
@Test
@Order(2)
public void testAddError() throws Exception {
String url = "/user/add";
UserMaintainRequest userMaintainRequest;
boolean projectIsEmpty = true;
UserBatchCreateDTO userMaintainRequest;
boolean roleIsEmpty = true;
boolean organizationIsEmpty = true;
boolean userIsEmpty = true;
/*
* 校验参数不合法的反例
* 每一次校验使用getErrorUserCreateDTO方法重新获取参数避免上一步的参数干扰
*/
ResultMatcher resultMatcher = status().isBadRequest();
//所有参数都为空
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(organizationIsEmpty, projectIsEmpty, userIsEmpty);
this.requestPost(url, userMaintainRequest, resultMatcher);
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(organizationIsEmpty, roleIsEmpty, userIsEmpty);
this.requestPost(URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//组织ID为空
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(organizationIsEmpty, !projectIsEmpty, !userIsEmpty);
this.requestPost(url, userMaintainRequest, resultMatcher);
//项目ID为空
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(!organizationIsEmpty, projectIsEmpty, !userIsEmpty);
this.requestPost(url, userMaintainRequest, resultMatcher);
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(organizationIsEmpty, !roleIsEmpty, !userIsEmpty);
this.requestPost(URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//用户组ID为空
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(!organizationIsEmpty, roleIsEmpty, !userIsEmpty);
this.requestPost(URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//没有用户
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(!organizationIsEmpty, !projectIsEmpty, userIsEmpty);
this.requestPost(url, userMaintainRequest, resultMatcher);
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(!organizationIsEmpty, !roleIsEmpty, userIsEmpty);
this.requestPost(URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//含有不存在的组织
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(!organizationIsEmpty, !roleIsEmpty, !userIsEmpty);
userMaintainRequest.getOrganizationIdList().add(null);
userMaintainRequest.getOrganizationIdList().add("");
this.requestPost(URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//含有不存在的用户组
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(!organizationIsEmpty, !roleIsEmpty, !userIsEmpty);
userMaintainRequest.getUserRoleIdList().add(null);
userMaintainRequest.getUserRoleIdList().add("");
this.requestPost(URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//含有用户名称为空的数据
userMaintainRequest = UserTestUtils.getSimpleUserCreateDTO();
userMaintainRequest.getUserInfoList().add(new User() {{
setEmail("tianyang.name.empty@126.com");
setSource("LOCAL");
}});
this.requestPost(url, userMaintainRequest, resultMatcher);
this.requestPost(URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//含有用户邮箱为空的数据
userMaintainRequest = UserTestUtils.getSimpleUserCreateDTO();
userMaintainRequest.getUserInfoList().add(new User() {{
setName("tianyang.email.empty");
setSource("LOCAL");
}});
this.requestPost(url, userMaintainRequest, resultMatcher);
this.requestPost(URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//用户邮箱不符合标准
userMaintainRequest = UserTestUtils.getSimpleUserCreateDTO();
userMaintainRequest.getUserInfoList().add(new User() {{
@ -183,32 +202,31 @@ public class UserControllerTests {
setEmail("用户邮箱放飞自我");
setSource("LOCAL");
}});
this.requestPost(url, userMaintainRequest, resultMatcher);
this.requestPost(URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//用户来源为空
userMaintainRequest = UserTestUtils.getSimpleUserCreateDTO();
userMaintainRequest.getUserInfoList().add(new User() {{
setName("tianyang.source.empty");
setEmail("tianyang.source.empty@126.com");
}});
this.requestPost(url, userMaintainRequest, resultMatcher);
this.requestPost(URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
/*
* 校验业务判断出错的反例 500 error)
* 需要保证数据库有正常数据
*/
resultMatcher = status().is5xxServerError();
this.checkUserList();
//含有重复的用户邮箱
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(!organizationIsEmpty, !projectIsEmpty, !userIsEmpty);
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(!organizationIsEmpty, !roleIsEmpty, !userIsEmpty);
String firstUserEmail = userMaintainRequest.getUserInfoList().get(0).getEmail();
userMaintainRequest.getUserInfoList().add(new User() {{
setName("tianyang.no.error4");
setEmail(firstUserEmail);
setSource("LOCAL");
}});
this.requestPost(url, userMaintainRequest, resultMatcher);
this.requestPost(URL_USER_CREATE, userMaintainRequest, ERROR_REQUEST_MATCHER);
//测试请求参数中含有数据库中已存在的邮箱情况
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(!organizationIsEmpty, !projectIsEmpty, userIsEmpty);
userMaintainRequest = UserTestUtils.getErrorUserCreateDTO(!organizationIsEmpty, !roleIsEmpty, userIsEmpty);
userMaintainRequest.setUserInfoList(
new ArrayList<>() {{
add(new User() {{
@ -218,14 +236,14 @@ public class UserControllerTests {
}});
}}
);
this.requestPost(url, userMaintainRequest, resultMatcher);
this.requestPost(URL_USER_CREATE, userMaintainRequest, ERROR_REQUEST_MATCHER);
}
@Test
@Order(3)
public void testGetByEmailSuccess() throws Exception {
this.checkUserList();
String url = "/user/get/" + UserTestUtils.USER_DEFAULT_EMAIL;
String url = URL_USER_GET + UserTestUtils.USER_DEFAULT_EMAIL;
MvcResult mvcResult = this.responseGet(url);
String returnData = mvcResult.getResponse().getContentAsString();
@ -248,7 +266,7 @@ public class UserControllerTests {
public void testGetByEmailError() throws Exception {
//测试使用任意参数不能获取到任何用户信息
this.checkUserList();
String url = "/user/get/" + UUID.randomUUID();
String url = URL_USER_GET + UUID.randomUUID();
MvcResult mvcResult = this.responseGet(url);
String returnData = mvcResult.getResponse().getContentAsString();
@ -258,4 +276,43 @@ public class UserControllerTests {
//返回值为空
Assertions.assertNull(resultHolder.getData());
}
@Test
@Order(4)
public void testPageSuccess() throws Exception {
BasePageRequest basePageRequest = UserTestUtils.getDefaultPageRequest();
MvcResult mvcResult = this.responsePost(URL_USER_PAGE, basePageRequest);
String returnData = mvcResult.getResponse().getContentAsString();
ResultHolder resultHolder = JsonUtils.parseObject(returnData, ResultHolder.class);
//返回请求正常
Assertions.assertNotNull(resultHolder);
Pager<UserInfo> returnPager = JSON.parseObject(JSON.toJSONString(resultHolder.getData()), Pager.class);
//返回值不为空
Assertions.assertNotNull(returnPager);
//返回值的页码和当前页码相同
Assertions.assertEquals(returnPager.getCurrent(), basePageRequest.getCurrent());
//返回的数据量不超过规定要返回的数据量相同
Assertions.assertTrue(((List<ApiDefinition>) returnPager.getList()).size() <= basePageRequest.getPageSize());
}
@Test
@Order(4)
public void testPageError() throws Exception {
//当前页码不大于0
BasePageRequest basePageRequest = new BasePageRequest();
basePageRequest.setPageSize(5);
this.requestPost(URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER);
//当前页数不大于5
basePageRequest = new BasePageRequest();
basePageRequest.setCurrent(1);
this.requestPost(URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER);
//排序字段不合法
basePageRequest = new BasePageRequest();
basePageRequest.setCurrent(1);
basePageRequest.setPageSize(5);
basePageRequest.setSort(new HashMap<>() {{
put("SELECT * FROM user", "asc");
}});
this.requestPost(URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER);
}
}

View File

@ -1,7 +1,8 @@
package io.metersphere.system.utils;
import io.metersphere.sdk.dto.BasePageRequest;
import io.metersphere.system.domain.User;
import io.metersphere.system.dto.UserMaintainRequest;
import io.metersphere.system.dto.UserBatchCreateDTO;
import java.util.ArrayList;
@ -10,12 +11,16 @@ public class UserTestUtils {
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 ORGANIZATION_ID = "ms-organization";
public static final String PROJECT_ID = "ms-project";
public static final String USER_ROLE_ID = "ms-user-role";
public static UserMaintainRequest getSimpleUserCreateDTO() {
UserMaintainRequest userMaintainRequest = new UserMaintainRequest();
userMaintainRequest.setOrganizationId(ORGANIZATION_ID);
userMaintainRequest.setProjectId(PROJECT_ID);
public static UserBatchCreateDTO getSimpleUserCreateDTO() {
UserBatchCreateDTO userMaintainRequest = new UserBatchCreateDTO();
userMaintainRequest.setOrganizationIdList(new ArrayList<>() {{
add(ORGANIZATION_ID);
}});
userMaintainRequest.setUserRoleIdList(new ArrayList<>() {{
add(USER_ROLE_ID);
}});
userMaintainRequest.setUserInfoList(new ArrayList<>() {{
add(new User() {{
setName(USER_DEFAULT_NAME);
@ -31,13 +36,17 @@ public class UserTestUtils {
return userMaintainRequest;
}
public static UserMaintainRequest getErrorUserCreateDTO(boolean organizationIsEmpty, boolean projectIsEmpty, boolean userIsEmpty) {
UserMaintainRequest userMaintainRequest = new UserMaintainRequest();
public static UserBatchCreateDTO getErrorUserCreateDTO(boolean organizationIsEmpty, boolean roleIsEmpty, boolean userIsEmpty) {
UserBatchCreateDTO userMaintainRequest = new UserBatchCreateDTO();
if (!organizationIsEmpty) {
userMaintainRequest.setOrganizationId(ORGANIZATION_ID);
userMaintainRequest.setOrganizationIdList(new ArrayList<>() {{
add(ORGANIZATION_ID);
}});
}
if (!projectIsEmpty) {
userMaintainRequest.setProjectId(PROJECT_ID);
if (!roleIsEmpty) {
userMaintainRequest.setUserRoleIdList(new ArrayList<>() {{
add(USER_ROLE_ID);
}});
}
if (!userIsEmpty) {
userMaintainRequest.setUserInfoList(new ArrayList<>() {{
@ -55,4 +64,11 @@ public class UserTestUtils {
}
return userMaintainRequest;
}
public static BasePageRequest getDefaultPageRequest() {
return new BasePageRequest() {{
this.setCurrent(1);
this.setPageSize(10);
}};
}
}