feat(系统设置): 用户管理增加添加用户到用户组的功能

This commit is contained in:
song-tianyang 2023-07-31 16:23:52 +08:00 committed by 建国
parent 8fadf99743
commit 447e9a5bb5
13 changed files with 618 additions and 332 deletions

View File

@ -0,0 +1,36 @@
package io.metersphere.sdk.dto.request;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.util.List;
@Data
public class GlobalUserRoleRelationBatchRequest {
@Schema(title = "用户ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "{user_role_relation.user_id.not_blank}", groups = {Created.class, Updated.class})
@Valid
private List<
@NotBlank(message = "{user_role_relation.user_id.not_blank}", groups = {Created.class, Updated.class})
@Size(min = 1, max = 50, message = "{user_role_relation.user_id.length_range}", groups = {Created.class, Updated.class})
String
> userIds;
@Schema(title = "组ID", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "{user_role_relation.role_id.not_blank}", groups = {Created.class})
@Size(min = 1, max = 50, message = "{user_role_relation.role_id.length_range}", groups = {Created.class, Updated.class})
@Valid
private List<
@NotBlank(message = "{user_role_relation.role_id.not_blank}", groups = {Created.class, Updated.class})
@Size(min = 1, max = 50, message = "{user_role_relation.user_id.length_range}", groups = {Created.class, Updated.class})
String
> roleIds;
}

View File

@ -6,6 +6,7 @@ import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest;
import io.metersphere.sdk.exception.MSException; import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.util.PermissionCache; import io.metersphere.sdk.util.PermissionCache;
import io.metersphere.system.domain.UserRole; import io.metersphere.system.domain.UserRole;
import io.metersphere.system.domain.UserRoleExample;
import io.metersphere.system.mapper.UserRoleMapper; import io.metersphere.system.mapper.UserRoleMapper;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
@ -14,6 +15,7 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@ -132,6 +134,16 @@ public class BaseUserRoleService {
return userRoleMapper.selectByPrimaryKey(id); return userRoleMapper.selectByPrimaryKey(id);
} }
public List<UserRole> getList(List<String> idList) {
if(CollectionUtils.isEmpty(idList)){
return new ArrayList<>();
}else {
UserRoleExample example = new UserRoleExample();
example.createCriteria().andIdIn(idList);
return userRoleMapper.selectByExample(example);
}
}
public String getLogDetails(String id) { public String getLogDetails(String id) {
UserRole userRole = userRoleMapper.selectByPrimaryKey(id); UserRole userRole = userRoleMapper.selectByPrimaryKey(id);
return userRole == null ? null : userRole.getName(); return userRole == null ? null : userRole.getName();

View File

@ -4,6 +4,7 @@ import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import io.metersphere.sdk.constants.PermissionConstants; import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.dto.UserRoleRelationUserDTO; import io.metersphere.sdk.dto.UserRoleRelationUserDTO;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest; import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest;
import io.metersphere.sdk.log.annotation.Log; import io.metersphere.sdk.log.annotation.Log;
import io.metersphere.sdk.log.constants.OperationLogType; import io.metersphere.sdk.log.constants.OperationLogType;
@ -52,6 +53,15 @@ public class GlobalUserRoleRelationController {
globalUserRoleRelationService.add(request); globalUserRoleRelationService.add(request);
} }
//用户管理页面批量添加用户到多个用户组 权限所属是用户管理的编辑页面权限
@PostMapping("/add/batch")
@Operation(summary = "批量添加用户到多个用户组中")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
@Log(type = OperationLogType.ADD, expression = "#msClass.batchAddLog(#request)", msClass = GlobalUserRoleRelationLogService.class)
public void batchAdd(@Validated({Created.class}) @RequestBody GlobalUserRoleRelationBatchRequest request) {
globalUserRoleRelationService.batchAdd(request, SessionUtils.getUserId());
}
@GetMapping("/delete/{id}") @GetMapping("/delete/{id}")
@Operation(summary = "删除全局用户组和用户的关联关系") @Operation(summary = "删除全局用户组和用户的关联关系")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_UPDATE) @RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_UPDATE)

View File

@ -111,11 +111,11 @@ public class UserController {
} }
@PostMapping("/reset/password") @PostMapping("/reset/password")
@Operation(summary = "重置用户密码")
@RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE) @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE)
@Log(type = OperationLogType.UPDATE, expression = "#msClass.resetPasswordLog(#userId)", msClass = UserService.class) @Log(type = OperationLogType.UPDATE, expression = "#msClass.resetPasswordLog(#userId)", msClass = UserService.class)
public boolean resetPassword(@RequestBody String userId) { public boolean resetPassword(@RequestBody String userId) {
return userService.resetPassword(userId,SessionUtils.getUserId()); userService.resetPassword(userId, SessionUtils.getUserId());
return true;
} }
} }

View File

@ -10,12 +10,15 @@
<if test="isSystem "> <if test="isSystem ">
AND type = 'SYSTEM' AND type = 'SYSTEM'
</if> </if>
AND scope_id = 'GLOBAL'
</select> </select>
<select id="listOrganizationRoleMember" resultType="io.metersphere.system.domain.User"> <select id="listOrganizationRoleMember" resultType="io.metersphere.system.domain.User">
select u.* from user_role_relation urr left join user u on urr.user_id = u.id select u.*
from user_role_relation urr
left join user u on urr.user_id = u.id
where urr.source_id = #{request.organizationId} where urr.source_id = #{request.organizationId}
and urr.role_id = #{request.userRoleId} and urr.role_id = #{request.userRoleId}
and u.name like concat('%',#{request.userKeyWord},'%') and u.name like concat('%', #{request.userKeyWord}, '%')
</select> </select>
</mapper> </mapper>

View File

@ -4,18 +4,21 @@ import io.metersphere.sdk.constants.OperationLogConstants;
import io.metersphere.sdk.dto.LogDTO; import io.metersphere.sdk.dto.LogDTO;
import io.metersphere.sdk.dto.OptionDTO; import io.metersphere.sdk.dto.OptionDTO;
import io.metersphere.sdk.dto.UserDTO; import io.metersphere.sdk.dto.UserDTO;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest; import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest;
import io.metersphere.sdk.log.constants.OperationLogModule; import io.metersphere.sdk.log.constants.OperationLogModule;
import io.metersphere.sdk.log.constants.OperationLogType; import io.metersphere.sdk.log.constants.OperationLogType;
import io.metersphere.sdk.mapper.BaseUserMapper; import io.metersphere.sdk.mapper.BaseUserMapper;
import io.metersphere.sdk.util.JSON; import io.metersphere.sdk.util.JSON;
import io.metersphere.system.domain.UserRole; import io.metersphere.system.domain.UserRole;
import io.metersphere.system.domain.UserRoleExample;
import io.metersphere.system.domain.UserRoleRelation; import io.metersphere.system.domain.UserRoleRelation;
import io.metersphere.system.mapper.UserRoleMapper; import io.metersphere.system.mapper.UserRoleMapper;
import io.metersphere.system.mapper.UserRoleRelationMapper; import io.metersphere.system.mapper.UserRoleRelationMapper;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
@ -55,6 +58,31 @@ public class GlobalUserRoleRelationLogService {
return dto; return dto;
} }
public List<LogDTO> batchAddLog(GlobalUserRoleRelationBatchRequest request) {
UserRoleExample example = new UserRoleExample();
example.createCriteria().andIdIn(request.getRoleIds());
List<UserRole> userRoles = userRoleMapper.selectByExample(example);
List<String> userIds = request.getUserIds();
List<OptionDTO> users = baseUserMapper.selectUserOptionByIds(userIds);
List<LogDTO> returnList = new ArrayList<>();
for (UserRole userRole : userRoles) {
LogDTO dto = new LogDTO(
OperationLogConstants.SYSTEM,
OperationLogConstants.SYSTEM,
userRole.getId(),
null,
OperationLogType.ADD.name(),
OperationLogModule.SYSTEM_USER_ROLE_RELATION,
userRole.getName());
dto.setOriginalValue(JSON.toJSONBytes(users));
returnList.add(dto);
}
return returnList;
}
/** /**
* 删除接口日志 * 删除接口日志
* *

View File

@ -1,17 +1,27 @@
package io.metersphere.system.service; package io.metersphere.system.service;
import io.metersphere.sdk.dto.UserRoleRelationUserDTO; import io.metersphere.sdk.dto.UserRoleRelationUserDTO;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest; import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest;
import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.service.BaseUserRoleRelationService; import io.metersphere.sdk.service.BaseUserRoleRelationService;
import io.metersphere.sdk.util.BeanUtils; import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.UserRole; import io.metersphere.system.domain.UserRole;
import io.metersphere.system.domain.UserRoleRelation; import io.metersphere.system.domain.UserRoleRelation;
import io.metersphere.system.domain.UserRoleRelationExample;
import io.metersphere.system.dto.request.GlobalUserRoleRelationQueryRequest; import io.metersphere.system.dto.request.GlobalUserRoleRelationQueryRequest;
import io.metersphere.system.mapper.ExtUserRoleRelationMapper; import io.metersphere.system.mapper.ExtUserRoleRelationMapper;
import io.metersphere.validation.groups.Created;
import io.metersphere.validation.groups.Updated;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.util.List; import java.util.*;
import java.util.stream.Collectors;
/** /**
* @author jianxing * @author jianxing
@ -23,6 +33,10 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService {
private ExtUserRoleRelationMapper extUserRoleRelationMapper; private ExtUserRoleRelationMapper extUserRoleRelationMapper;
@Resource @Resource
private GlobalUserRoleService globalUserRoleService; private GlobalUserRoleService globalUserRoleService;
@Resource
private UserService userService;
@Resource
private SqlSessionFactory sqlSessionFactory;
public List<UserRoleRelationUserDTO> list(GlobalUserRoleRelationQueryRequest request) { public List<UserRoleRelationUserDTO> list(GlobalUserRoleRelationQueryRequest request) {
UserRole userRole = globalUserRoleService.get(request.getRoleId()); UserRole userRole = globalUserRoleService.get(request.getRoleId());
@ -31,10 +45,23 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService {
return extUserRoleRelationMapper.listGlobal(request); return extUserRoleRelationMapper.listGlobal(request);
} }
//校验用户组
private void checkGlobalSystemUserRoleLegality(List<String> checkIdList) {
List<UserRole> userRoleList = globalUserRoleService.getList(checkIdList);
if (userRoleList.size() != checkIdList.size()) {
throw new MSException(Translator.get("user_role_not_exist"));
}
userRoleList.forEach(userRole -> {
globalUserRoleService.checkSystemUserGroup(userRole);
globalUserRoleService.checkGlobalUserRole(userRole);
});
}
public void add(GlobalUserRoleRelationUpdateRequest request) { public void add(GlobalUserRoleRelationUpdateRequest request) {
UserRole userRole = globalUserRoleService.get(request.getRoleId()); this.checkGlobalSystemUserRoleLegality(
globalUserRoleService.checkSystemUserGroup(userRole); Collections.singletonList(request.getRoleId()));
globalUserRoleService.checkGlobalUserRole(userRole); //检查用户的合法性
userService.checkUserLegality(request.getUserIds());
request.getUserIds().forEach(userId -> { request.getUserIds().forEach(userId -> {
UserRoleRelation userRoleRelation = new UserRoleRelation(); UserRoleRelation userRoleRelation = new UserRoleRelation();
BeanUtils.copyBean(userRoleRelation, request); BeanUtils.copyBean(userRoleRelation, request);
@ -44,6 +71,45 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService {
}); });
} }
public List<UserRoleRelation> selectByUserIdAndRuleId(List<String> userIds, List<String> roleIds) {
UserRoleRelationExample example = new UserRoleRelationExample();
example.createCriteria().andUserIdIn(userIds).andRoleIdIn(roleIds);
return userRoleRelationMapper.selectByExample(example);
}
public void batchAdd(@Validated({Created.class, Updated.class}) GlobalUserRoleRelationBatchRequest request, String operator) {
//检查角色的合法性
this.checkGlobalSystemUserRoleLegality(request.getRoleIds());
//检查用户的合法性
userService.checkUserLegality(request.getUserIds());
List<UserRoleRelation> savedUserRoleRelation = this.selectByUserIdAndRuleId(request.getUserIds(), request.getRoleIds());
//过滤已经存储过的用户关系
Map<String, List<String>> userRoleIdMap = savedUserRoleRelation.stream()
.collect(Collectors.groupingBy(UserRoleRelation::getUserId, Collectors.mapping(UserRoleRelation::getRoleId, Collectors.toList())));
long createTime = System.currentTimeMillis();
List<UserRoleRelation> saveList = new ArrayList<>();
for (String userId : request.getUserIds()) {
for (String roleId : request.getRoleIds()) {
if (userRoleIdMap.containsKey(userId) && userRoleIdMap.get(userId).contains(roleId)) {
continue;
}
UserRoleRelation userRoleRelation = new UserRoleRelation();
userRoleRelation.setUserId(userId);
userRoleRelation.setRoleId(roleId);
userRoleRelation.setCreateUser(operator);
userRoleRelation.setCreateTime(createTime);
userRoleRelation.setSourceId(GlobalUserRoleService.SYSTEM_TYPE);
userRoleRelation.setId(UUID.randomUUID().toString());
saveList.add(userRoleRelation);
}
}
if (CollectionUtils.isNotEmpty(saveList)) {
userRoleRelationMapper.batchInsert(saveList);
}
}
@Override @Override
public void delete(String id) { public void delete(String id) {
UserRole userRole = getUserRole(id); UserRole userRole = getUserRole(id);

View File

@ -4,7 +4,6 @@ import io.metersphere.sdk.dto.PermissionDefinitionItem;
import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest; import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest;
import io.metersphere.sdk.exception.MSException; import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.service.BaseUserRoleService; import io.metersphere.sdk.service.BaseUserRoleService;
import io.metersphere.sdk.util.Translator;
import io.metersphere.system.domain.UserRole; import io.metersphere.system.domain.UserRole;
import io.metersphere.system.domain.UserRoleExample; import io.metersphere.system.domain.UserRoleExample;
import io.metersphere.system.dto.UserRoleOption; import io.metersphere.system.dto.UserRoleOption;
@ -85,6 +84,7 @@ public class GlobalUserRoleService extends BaseUserRoleService {
throw new MSException(GLOBAL_USER_ROLE_EXIST); throw new MSException(GLOBAL_USER_ROLE_EXIST);
} }
} }
@Override @Override
public UserRole update(UserRole userRole) { public UserRole update(UserRole userRole) {
UserRole originUserRole = get(userRole.getId()); UserRole originUserRole = get(userRole.getId());
@ -106,9 +106,6 @@ public class GlobalUserRoleService extends BaseUserRoleService {
if (globalRoleList.size() != roleIdList.size()) { if (globalRoleList.size() != roleIdList.size()) {
throw new MSException("role.not.global"); throw new MSException("role.not.global");
} }
if (!globalRoleList.contains(MEMBER.getValue())) {
throw new MSException(Translator.get("role.not.contains.member"));
}
} }
public List<UserRoleOption> getGlobalSystemRoleList() { public List<UserRoleOption> getGlobalSystemRoleList() {

View File

@ -292,7 +292,7 @@ public class UserService {
return response; return response;
} }
private int deleteUserByList(List<String> updateUserList){ private int deleteUserByList(List<String> updateUserList) {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
BaseUserMapper batchDeleteMapper = sqlSession.getMapper(BaseUserMapper.class); BaseUserMapper batchDeleteMapper = sqlSession.getMapper(BaseUserMapper.class);
int insertIndex = 0; int insertIndex = 0;
@ -328,7 +328,7 @@ public class UserService {
return null; return null;
} }
public LogDTO resetPasswordLog(String userId){ public LogDTO resetPasswordLog(String userId) {
User user = userMapper.selectByPrimaryKey(userId); User user = userMapper.selectByPrimaryKey(userId);
if (user != null) { if (user != null) {
LogDTO dto = new LogDTO( LogDTO dto = new LogDTO(
@ -377,20 +377,28 @@ public class UserService {
return userMapper.selectByExample(example); return userMapper.selectByExample(example);
} }
public boolean resetPassword(String userId,String operator) { public void resetPassword(String userId, String operator) {
User user = userMapper.selectByPrimaryKey(userId); User user = userMapper.selectByPrimaryKey(userId);
if(user == null){ if (user == null) {
throw new MSException(Translator.get("user.not.exist")); throw new MSException(Translator.get("user.not.exist"));
} }
User updateModel = new User(); User updateModel = new User();
updateModel.setId(userId); updateModel.setId(userId);
if(StringUtils.equalsIgnoreCase("admin",user.getId())){ if (StringUtils.equalsIgnoreCase("admin", user.getId())) {
updateModel.setPassword(CodingUtil.md5("metersphere")); updateModel.setPassword(CodingUtil.md5("metersphere"));
}else { } else {
updateModel.setPassword(CodingUtil.md5(user.getEmail())); updateModel.setPassword(CodingUtil.md5(user.getEmail()));
} }
updateModel.setUpdateTime(System.currentTimeMillis()); updateModel.setUpdateTime(System.currentTimeMillis());
updateModel.setUpdateUser(operator); updateModel.setUpdateUser(operator);
return userMapper.updateByPrimaryKeySelective(updateModel) > 0; userMapper.updateByPrimaryKeySelective(updateModel);
}
public void checkUserLegality(List<String> userIds) {
UserExample example = new UserExample();
example.createCriteria().andIdIn(userIds);
if (userMapper.countByExample(example) != userIds.size()) {
throw new MSException(Translator.get("user.id.not.exist"));
}
} }
} }

View File

@ -1,15 +1,14 @@
package io.metersphere.system.controller; package io.metersphere.system.controller.user;
import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.JsonPath;
import io.metersphere.sdk.constants.SessionConstants; import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest;
import io.metersphere.sdk.util.JSON;
import io.metersphere.system.dto.UserCreateInfo; import io.metersphere.system.dto.UserCreateInfo;
import io.metersphere.system.dto.UserRoleOption; import io.metersphere.system.dto.UserRoleOption;
import io.metersphere.system.dto.request.UserBatchProcessRequest; import io.metersphere.system.dto.request.UserBatchProcessRequest;
import io.metersphere.system.dto.request.UserChangeEnableRequest; import io.metersphere.system.dto.request.UserChangeEnableRequest;
import io.metersphere.system.utils.UserTestUtils; import io.metersphere.system.utils.user.UserParamUtils;
import io.metersphere.system.utils.user.UserRequestUtils;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.*; import org.junit.jupiter.api.*;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
@ -24,6 +23,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -38,8 +38,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class UserControllerNonePermissionTests { public class UserControllerNonePermissionTests {
@Resource @Resource
private MockMvc mockMvc; private MockMvc mockMvc;
protected static String sessionId; UserRequestUtils userRequestUtils = null;
protected static String csrfToken;
private static final String NONE_ROLE_USERNAME = "tianyang.member@163.com"; private static final String NONE_ROLE_USERNAME = "tianyang.member@163.com";
private static final String NONE_ROLE_PASSWORD = "tianyang.member@163.com"; private static final String NONE_ROLE_PASSWORD = "tianyang.member@163.com";
@ -64,12 +64,12 @@ public class UserControllerNonePermissionTests {
this.setName("member"); this.setName("member");
}}); }});
}}; }};
this.requestGet(String.format(UserTestUtils.URL_USER_GET, NONE_ROLE_USERNAME), CHECK_RESULT_MATHER); userRequestUtils.requestGet(String.format(userRequestUtils.URL_USER_GET, NONE_ROLE_USERNAME), CHECK_RESULT_MATHER);
//校验权限系统全局用户组获取 //校验权限系统全局用户组获取
this.requestGet(UserTestUtils.URL_GET_GLOBAL_SYSTEM, CHECK_RESULT_MATHER); userRequestUtils.requestGet(userRequestUtils.URL_GET_GLOBAL_SYSTEM, CHECK_RESULT_MATHER);
//校验权限用户创建 //校验权限用户创建
this.requestPost(UserTestUtils.URL_USER_CREATE, userRequestUtils.requestPost(userRequestUtils.URL_USER_CREATE,
UserTestUtils.getUserCreateDTO( UserParamUtils.getUserCreateDTO(
paramRoleList, paramRoleList,
new ArrayList<>() {{ new ArrayList<>() {{
add(paramUserInfo); add(paramUserInfo);
@ -77,71 +77,57 @@ public class UserControllerNonePermissionTests {
), ),
CHECK_RESULT_MATHER); CHECK_RESULT_MATHER);
//校验权限分页查询用户列表 //校验权限分页查询用户列表
this.requestPost(UserTestUtils.URL_USER_PAGE, UserTestUtils.getDefaultPageRequest(), CHECK_RESULT_MATHER); userRequestUtils.requestPost(userRequestUtils.URL_USER_PAGE, UserParamUtils.getDefaultPageRequest(), CHECK_RESULT_MATHER);
//校验权限修改用户 //校验权限修改用户
this.requestPost(UserTestUtils.URL_USER_UPDATE, userRequestUtils.requestPost(userRequestUtils.URL_USER_UPDATE,
UserTestUtils.getUserUpdateDTO(paramUserInfo, paramRoleList), CHECK_RESULT_MATHER); UserParamUtils.getUserUpdateDTO(paramUserInfo, paramRoleList), CHECK_RESULT_MATHER);
//校验权限启用/禁用用户 //校验权限启用/禁用用户
UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest(); UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest();
userChangeEnableRequest.setEnable(false); userChangeEnableRequest.setEnable(false);
userChangeEnableRequest.setUserIdList(new ArrayList<>() {{ userChangeEnableRequest.setUserIdList(new ArrayList<>() {{
this.add("testId"); this.add("testId");
}}); }});
this.requestPost(UserTestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, CHECK_RESULT_MATHER); userRequestUtils.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, CHECK_RESULT_MATHER);
//用户导入 //用户导入
//导入正常文件 //导入正常文件
String filePath = this.getClass().getClassLoader().getResource("file/user_import_success.xlsx").getPath(); String filePath = Objects.requireNonNull(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)); MockMultipartFile file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath));
this.requestFile(UserTestUtils.URL_USER_IMPORT, file, CHECK_RESULT_MATHER); userRequestUtils.requestFile(userRequestUtils.URL_USER_IMPORT, file, CHECK_RESULT_MATHER);
//用户删除 //用户删除
UserBatchProcessRequest request = new UserBatchProcessRequest(); UserBatchProcessRequest request = new UserBatchProcessRequest();
request.setUserIdList(new ArrayList<>() {{ request.setUserIdList(new ArrayList<>() {{
this.add("testId"); this.add("testId");
}}); }});
this.requestPost(UserTestUtils.URL_USER_DELETE, request, CHECK_RESULT_MATHER); userRequestUtils.requestPost(userRequestUtils.URL_USER_DELETE, request, CHECK_RESULT_MATHER);
//重置密码
userRequestUtils.requestPostString(userRequestUtils.URL_USER_RESET_PASSWORD, NONE_ROLE_USERNAME, CHECK_RESULT_MATHER);
//添加用户到用户组
GlobalUserRoleRelationBatchRequest userRoleRelationRequest = new GlobalUserRoleRelationBatchRequest();
userRoleRelationRequest.setUserIds(new ArrayList<>() {{
this.add(NONE_ROLE_USERNAME);
}});
userRoleRelationRequest.setRoleIds(new ArrayList<>() {{
this.add("member");
}});
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, userRoleRelationRequest, CHECK_RESULT_MATHER);
} }
@BeforeEach @BeforeEach
public void login() throws Exception { public void login() throws Exception {
if (StringUtils.isAnyBlank(sessionId, csrfToken)) { if (userRequestUtils == null) {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/login") MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/login")
.content("{\"username\":\"" + NONE_ROLE_USERNAME + "\",\"password\":\"" + NONE_ROLE_PASSWORD + "\"}") .content("{\"username\":\"" + NONE_ROLE_USERNAME + "\",\"password\":\"" + NONE_ROLE_PASSWORD + "\"}")
.contentType(MediaType.APPLICATION_JSON)) .contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn(); .andReturn();
sessionId = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.sessionId"); String sessionId = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.sessionId");
csrfToken = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.csrfToken"); String csrfToken = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.csrfToken");
userRequestUtils = new UserRequestUtils(mockMvc, sessionId, csrfToken);
} }
} }
private void requestPost(String url, Object param, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON))
.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));
}
private void requestGet(String url, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher)
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
} }

View File

@ -1,11 +1,11 @@
package io.metersphere.system.controller; package io.metersphere.system.controller.user;
import base.BaseTest; import base.BaseTest;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.controller.handler.ResultHolder; import io.metersphere.sdk.controller.handler.ResultHolder;
import io.metersphere.sdk.dto.BasePageRequest; import io.metersphere.sdk.dto.BasePageRequest;
import io.metersphere.sdk.dto.ExcelParseDTO; import io.metersphere.sdk.dto.ExcelParseDTO;
import io.metersphere.sdk.dto.UserDTO; import io.metersphere.sdk.dto.UserDTO;
import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest;
import io.metersphere.sdk.log.constants.OperationLogType; import io.metersphere.sdk.log.constants.OperationLogType;
import io.metersphere.sdk.util.BeanUtils; import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.CodingUtil; import io.metersphere.sdk.util.CodingUtil;
@ -24,8 +24,10 @@ import io.metersphere.system.dto.response.UserBatchProcessResponse;
import io.metersphere.system.dto.response.UserImportResponse; import io.metersphere.system.dto.response.UserImportResponse;
import io.metersphere.system.dto.response.UserTableResponse; import io.metersphere.system.dto.response.UserTableResponse;
import io.metersphere.system.mapper.UserMapper; import io.metersphere.system.mapper.UserMapper;
import io.metersphere.system.service.GlobalUserRoleRelationService;
import io.metersphere.system.service.UserService; import io.metersphere.system.service.UserService;
import io.metersphere.system.utils.UserTestUtils; import io.metersphere.system.utils.user.UserParamUtils;
import io.metersphere.system.utils.user.UserRequestUtils;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -36,17 +38,13 @@ import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig; import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; 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;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -54,20 +52,21 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@AutoConfigureMockMvc @AutoConfigureMockMvc
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class UserControllerTests extends BaseTest { public class UserControllerTests extends BaseTest {
@Resource
private MockMvc mockMvc;
@Resource @Resource
private UserService userService; private UserService userService;
@Resource @Resource
private UserMapper userMapper; private UserMapper userMapper;
@Resource
private GlobalUserRoleRelationService globalUserRoleRelationService;
//失败请求返回编码 //失败请求返回编码
private static final ResultMatcher BAD_REQUEST_MATCHER = status().isBadRequest(); private static final ResultMatcher BAD_REQUEST_MATCHER = status().isBadRequest();
private static final ResultMatcher ERROR_REQUEST_MATCHER = status().is5xxServerError(); private static final ResultMatcher ERROR_REQUEST_MATCHER = status().is5xxServerError();
//测试过程中需要用到的数据 //测试过程中需要用到的数据
private static final List<UserCreateInfo> USER_LIST = new ArrayList<>(); private static final List<UserCreateInfo> USER_LIST = new ArrayList<>();
private static final List<UserRoleOption> defaultUserRoleList = new ArrayList<>(); private static final List<UserRoleOption> USER_ROLE_LIST = new ArrayList<>();
//默认数据 //默认数据
public static final String USER_DEFAULT_NAME = "tianyang.no.1"; 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_DEFAULT_EMAIL = "tianyang.no.1@126.com";
@ -75,105 +74,33 @@ public class UserControllerTests extends BaseTest {
//已删除的用户ID //已删除的用户ID
private static final List<String> DELETED_USER_ID_LIST = new ArrayList<>(); private static final List<String> DELETED_USER_ID_LIST = new ArrayList<>();
//记录查询到的组织信息 UserRequestUtils userRequestUtils = null;
private void setDefaultUserRoleList(MvcResult mvcResult) throws Exception {
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
//返回请求正常
Assertions.assertNotNull(resultHolder);
List<UserRoleOption> userRoleList = JSON.parseArray(JSON.toJSONString(resultHolder.getData()), UserRoleOption.class);
//返回值不为空
Assertions.assertTrue(CollectionUtils.isNotEmpty(userRoleList));
defaultUserRoleList.addAll(userRoleList);
}
//成功入库的用户保存内存中其他用例会使用到 @Override
private void addUser2List(MvcResult mvcResult) throws Exception { @BeforeEach
UserBatchCreateDTO userMaintainRequest = UserTestUtils.parseObjectFromMvcResult(mvcResult, UserBatchCreateDTO.class); public void login() throws Exception {
for(UserCreateInfo item : userMaintainRequest.getUserInfoList()){ if (userRequestUtils == null) {
checkLog(item.getId(), OperationLogType.ADD); super.login();
userRequestUtils = new UserRequestUtils(mockMvc, sessionId, csrfToken);
} }
//返回值不为空
Assertions.assertNotNull(userMaintainRequest);
USER_LIST.addAll(userMaintainRequest.getUserInfoList());
}
private void checkUserList() throws Exception {
if (CollectionUtils.isEmpty(USER_LIST)) {
//测试数据初始化入库
this.testAddSuccess();
}
}
private void requestPost(String url, Object param, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
private MvcResult responsePost(String url, Object param) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
}
private void requestResetPassword(String param, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(UserTestUtils.URL_USER_RESET_PASSWORD)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(param)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
private MvcResult responseFile(MockMultipartFile file) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.multipart(UserTestUtils.URL_USER_IMPORT)
.file(file)
.contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
}
private MvcResult responseGet(String url) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andReturn();
} }
@Test @Test
@Order(0) @Order(0)
public void testGetGlobalSystemUserRoleSuccess() throws Exception { public void testGetGlobalSystemUserRoleSuccess() throws Exception {
MvcResult mvcResult = this.responseGet(UserTestUtils.URL_GET_GLOBAL_SYSTEM); MvcResult mvcResult = userRequestUtils.responseGet(userRequestUtils.URL_GET_GLOBAL_SYSTEM);
this.setDefaultUserRoleList(mvcResult); this.setDefaultUserRoleList(mvcResult);
} }
@Test @Test
@Order(1) @Order(1)
public void testAddSuccess() throws Exception { public void testAddSuccess() throws Exception {
if (CollectionUtils.isEmpty(defaultUserRoleList)) { if (CollectionUtils.isEmpty(USER_ROLE_LIST)) {
this.testGetGlobalSystemUserRoleSuccess(); this.testGetGlobalSystemUserRoleSuccess();
} }
//模拟前台批量添加用户 //模拟前台批量添加用户
UserBatchCreateDTO userMaintainRequest = UserTestUtils.getUserCreateDTO( UserBatchCreateDTO userMaintainRequest = UserParamUtils.getUserCreateDTO(
defaultUserRoleList, USER_ROLE_LIST,
new ArrayList<>() {{ new ArrayList<>() {{
add(new UserCreateInfo() {{ add(new UserCreateInfo() {{
setName(USER_DEFAULT_NAME); setName(USER_DEFAULT_NAME);
@ -185,11 +112,11 @@ public class UserControllerTests extends BaseTest {
}}); }});
}} }}
); );
MvcResult mvcResult = this.responsePost(UserTestUtils.URL_USER_CREATE, userMaintainRequest); MvcResult mvcResult = userRequestUtils.responsePost(userRequestUtils.URL_USER_CREATE, userMaintainRequest);
this.addUser2List(mvcResult); this.addUser2List(mvcResult);
//批量添加一百多个用户 //批量添加一百多个用户,只赋予其中1个权限 这批用户用于后续的批量添加到用户组/组织/项目
List<UserCreateInfo> userCreateInfoList = new ArrayList<>(); List<UserCreateInfo> userCreateInfoList = new ArrayList<>();
for (int i = 0; i < 123; i++) { for (int i = 0; i < 123; i++) {
int finalI = i; int finalI = i;
@ -198,17 +125,17 @@ public class UserControllerTests extends BaseTest {
setEmail("tianyang.no.batch" + finalI + "@126.com"); setEmail("tianyang.no.batch" + finalI + "@126.com");
}}); }});
} }
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
defaultUserRoleList, Collections.singletonList(USER_ROLE_LIST.get(0)),
userCreateInfoList userCreateInfoList
); );
mvcResult = this.responsePost(UserTestUtils.URL_USER_CREATE, userMaintainRequest); mvcResult = userRequestUtils.responsePost(userRequestUtils.URL_USER_CREATE, userMaintainRequest);
this.addUser2List(mvcResult); this.addUser2List(mvcResult);
//含有重复的用户名称 //含有重复的用户名称
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
defaultUserRoleList, USER_ROLE_LIST,
new ArrayList<>() {{ new ArrayList<>() {{
add(new UserCreateInfo() {{ add(new UserCreateInfo() {{
setName("tianyang.repeat"); setName("tianyang.repeat");
@ -220,14 +147,14 @@ public class UserControllerTests extends BaseTest {
}}); }});
}} }}
); );
mvcResult = this.responsePost(UserTestUtils.URL_USER_CREATE, userMaintainRequest); mvcResult = userRequestUtils.responsePost(userRequestUtils.URL_USER_CREATE, userMaintainRequest);
this.addUser2List(mvcResult); this.addUser2List(mvcResult);
} }
@Test @Test
@Order(1) @Order(1)
public void testAddError() throws Exception { public void testAddError() throws Exception {
if (CollectionUtils.isEmpty(defaultUserRoleList)) { if (CollectionUtils.isEmpty(USER_ROLE_LIST)) {
this.testGetGlobalSystemUserRoleSuccess(); this.testGetGlobalSystemUserRoleSuccess();
} }
UserBatchCreateDTO userMaintainRequest; UserBatchCreateDTO userMaintainRequest;
@ -247,67 +174,70 @@ public class UserControllerTests extends BaseTest {
* 每一次校验使用getErrorUserCreateDTO方法重新获取参数避免上一步的参数干扰 * 每一次校验使用getErrorUserCreateDTO方法重新获取参数避免上一步的参数干扰
*/ */
//所有参数都为空 //所有参数都为空
userMaintainRequest = UserTestUtils.getUserCreateDTO(null, null); userMaintainRequest = UserParamUtils.getUserCreateDTO(null, null);
this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//用户组ID为空 //用户组ID为空
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
null, null,
errorUserList); errorUserList);
this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//没有用户 //没有用户
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
USER_ROLE_LIST,
defaultUserRoleList,
null); null);
this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//含有不存在的用户组 //用户组含有null
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
defaultUserRoleList, USER_ROLE_LIST,
errorUserList); errorUserList);
userMaintainRequest.getUserRoleIdList().add(null); userMaintainRequest.getUserRoleIdList().add(null);
userMaintainRequest.getUserRoleIdList().add(""); userMaintainRequest.getUserRoleIdList().add("");
this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//含有用户名称为空的数据 //含有用户名称为空的数据
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
defaultUserRoleList, USER_ROLE_LIST,
new ArrayList<>() new ArrayList<>()
); );
userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{ userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{
setEmail("tianyang.name.empty@126.com"); setEmail("tianyang.name.empty@126.com");
}}); }});
this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//含有用户邮箱为空的数据 //含有用户邮箱为空的数据
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
defaultUserRoleList, USER_ROLE_LIST,
new ArrayList<>() new ArrayList<>()
); );
userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{ userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{
setName("tianyang.email.empty"); setName("tianyang.email.empty");
}}); }});
this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//用户邮箱不符合标准 //用户邮箱不符合标准
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
defaultUserRoleList, USER_ROLE_LIST,
new ArrayList<>() new ArrayList<>()
); );
userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{ userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{
setName("用户邮箱放飞自我"); setName("用户邮箱放飞自我");
setEmail("用户邮箱放飞自我"); setEmail("用户邮箱放飞自我");
}}); }});
this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER);
/* /*
* 校验业务判断出错的反例 500 error) * 校验业务判断出错的反例 500 error)
* 需要保证数据库有正常数据 * 需要保证数据库有正常数据
*/ */
this.checkUserList(); this.checkUserList();
//不含有系统成员用户组 //含有非法用户组
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
defaultUserRoleList.stream().filter(item -> !StringUtils.equals(item.getId(), "member")).toList(), new ArrayList<>() {{
this.add(new UserRoleOption() {{
this.setId("not system global user role id");
}});
}},
errorUserList); errorUserList);
this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, ERROR_REQUEST_MATCHER);
//含有重复的用户邮箱 //含有重复的用户邮箱
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
defaultUserRoleList, USER_ROLE_LIST,
errorUserList errorUserList
); );
String firstUserEmail = userMaintainRequest.getUserInfoList().get(0).getEmail(); String firstUserEmail = userMaintainRequest.getUserInfoList().get(0).getEmail();
@ -315,10 +245,10 @@ public class UserControllerTests extends BaseTest {
setName("tianyang.no.error4"); setName("tianyang.no.error4");
setEmail(firstUserEmail); setEmail(firstUserEmail);
}}); }});
this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, ERROR_REQUEST_MATCHER);
//测试请求参数中含有数据库中已存在的邮箱情况 //测试请求参数中含有数据库中已存在的邮箱情况
userMaintainRequest = UserTestUtils.getUserCreateDTO( userMaintainRequest = UserParamUtils.getUserCreateDTO(
defaultUserRoleList, USER_ROLE_LIST,
errorUserList errorUserList
); );
userMaintainRequest.setUserInfoList( userMaintainRequest.setUserInfoList(
@ -329,7 +259,7 @@ public class UserControllerTests extends BaseTest {
}}); }});
}} }}
); );
this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, ERROR_REQUEST_MATCHER);
} }
@Test @Test
@ -356,8 +286,8 @@ public class UserControllerTests extends BaseTest {
} }
private UserDTO getUserByEmail(String email) throws Exception { private UserDTO getUserByEmail(String email) throws Exception {
String url = String.format(UserTestUtils.URL_USER_GET, email); String url = String.format(userRequestUtils.URL_USER_GET, email);
return UserTestUtils.parseObjectFromMvcResult(this.responseGet(url), UserDTO.class); return userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseGet(url), UserDTO.class);
} }
@Test @Test
@ -365,8 +295,8 @@ public class UserControllerTests extends BaseTest {
public void testGetByEmailError() throws Exception { public void testGetByEmailError() throws Exception {
//测试使用任意参数不能获取到任何用户信息 //测试使用任意参数不能获取到任何用户信息
this.checkUserList(); this.checkUserList();
String url = UserTestUtils.URL_USER_GET + UUID.randomUUID(); String url = userRequestUtils.URL_USER_GET + UUID.randomUUID();
MvcResult mvcResult = this.responseGet(url); MvcResult mvcResult = userRequestUtils.responseGet(url);
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class); ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
@ -380,8 +310,8 @@ public class UserControllerTests extends BaseTest {
@Order(3) @Order(3)
public void testPageSuccess() throws Exception { public void testPageSuccess() throws Exception {
this.checkUserList(); this.checkUserList();
BasePageRequest basePageRequest = UserTestUtils.getDefaultPageRequest(); BasePageRequest basePageRequest = UserParamUtils.getDefaultPageRequest();
MvcResult mvcResult = this.responsePost(UserTestUtils.URL_USER_PAGE, basePageRequest); MvcResult mvcResult = userRequestUtils.responsePost(userRequestUtils.URL_USER_PAGE, basePageRequest);
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class); ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
//返回请求正常 //返回请求正常
@ -395,11 +325,11 @@ public class UserControllerTests extends BaseTest {
Assertions.assertTrue(JSON.parseArray(JSON.toJSONString(returnPager.getList())).size() <= basePageRequest.getPageSize()); Assertions.assertTrue(JSON.parseArray(JSON.toJSONString(returnPager.getList())).size() <= basePageRequest.getPageSize());
//测试根据创建时间倒叙排列 //测试根据创建时间倒叙排列
basePageRequest = UserTestUtils.getDefaultPageRequest(); basePageRequest = UserParamUtils.getDefaultPageRequest();
basePageRequest.setSort(new HashMap<>() {{ basePageRequest.setSort(new HashMap<>() {{
put("createTime", "desc"); put("createTime", "desc");
}}); }});
mvcResult = this.responsePost(UserTestUtils.URL_USER_PAGE, basePageRequest); mvcResult = userRequestUtils.responsePost(userRequestUtils.URL_USER_PAGE, basePageRequest);
returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
resultHolder = JSON.parseObject(returnData, ResultHolder.class); resultHolder = JSON.parseObject(returnData, ResultHolder.class);
returnPager = JSON.parseObject(JSON.toJSONString(resultHolder.getData()), Pager.class); returnPager = JSON.parseObject(JSON.toJSONString(resultHolder.getData()), Pager.class);
@ -417,15 +347,15 @@ public class UserControllerTests extends BaseTest {
//当前页码不大于0 //当前页码不大于0
BasePageRequest basePageRequest = new BasePageRequest(); BasePageRequest basePageRequest = new BasePageRequest();
basePageRequest.setPageSize(5); basePageRequest.setPageSize(5);
this.requestPost(UserTestUtils.URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER);
//pageSize超过100 //pageSize超过100
basePageRequest = UserTestUtils.getDefaultPageRequest(); basePageRequest = UserParamUtils.getDefaultPageRequest();
basePageRequest.setPageSize(250); basePageRequest.setPageSize(250);
this.requestPost(UserTestUtils.URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER);
//当前页数不大于5 //当前页数不大于5
basePageRequest = new BasePageRequest(); basePageRequest = new BasePageRequest();
basePageRequest.setCurrent(1); basePageRequest.setCurrent(1);
this.requestPost(UserTestUtils.URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER);
//排序字段不合法 //排序字段不合法
basePageRequest = new BasePageRequest(); basePageRequest = new BasePageRequest();
basePageRequest.setCurrent(1); basePageRequest.setCurrent(1);
@ -433,7 +363,7 @@ public class UserControllerTests extends BaseTest {
basePageRequest.setSort(new HashMap<>() {{ basePageRequest.setSort(new HashMap<>() {{
put("SELECT * FROM user", "asc"); put("SELECT * FROM user", "asc");
}}); }});
this.requestPost(UserTestUtils.URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER);
} }
@Test @Test
@ -447,47 +377,47 @@ public class UserControllerTests extends BaseTest {
UserDTO checkDTO; UserDTO checkDTO;
//更改名字 //更改名字
user.setName("TEST-UPDATE"); user.setName("TEST-UPDATE");
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkLog(response.getId(), OperationLogType.UPDATE); checkLog(response.getId(), OperationLogType.UPDATE);
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
UserTestUtils.compareUserDTO(response, checkDTO); UserParamUtils.compareUserDTO(response, checkDTO);
//更改邮箱 //更改邮箱
user.setEmail("songtianyang-test-email@12138.com"); user.setEmail("songtianyang-test-email@12138.com");
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkLog(response.getId(), OperationLogType.UPDATE); checkLog(response.getId(), OperationLogType.UPDATE);
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
UserTestUtils.compareUserDTO(response, checkDTO); UserParamUtils.compareUserDTO(response, checkDTO);
//更改手机号 //更改手机号
user.setPhone("18511112222"); user.setPhone("18511112222");
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkLog(response.getId(), OperationLogType.UPDATE); checkLog(response.getId(), OperationLogType.UPDATE);
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
UserTestUtils.compareUserDTO(response, checkDTO); UserParamUtils.compareUserDTO(response, checkDTO);
//更改用户组(这里只改成用户成员权限) //更改用户组(这里只改成用户成员权限)
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, userMaintainRequest = UserParamUtils.getUserUpdateDTO(user,
defaultUserRoleList.stream().filter(item -> StringUtils.equals(item.getId(), "member")).toList() USER_ROLE_LIST.stream().filter(item -> StringUtils.equals(item.getId(), "member")).toList()
); );
response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
checkLog(response.getId(), OperationLogType.UPDATE); checkLog(response.getId(), OperationLogType.UPDATE);
UserTestUtils.compareUserDTO(response, checkDTO); UserParamUtils.compareUserDTO(response, checkDTO);
//更改用户组(把上面的情况添加别的权限) //更改用户组(把上面的情况添加别的权限)
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkLog(response.getId(), OperationLogType.UPDATE); checkLog(response.getId(), OperationLogType.UPDATE);
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
UserTestUtils.compareUserDTO(response, checkDTO); UserParamUtils.compareUserDTO(response, checkDTO);
//用户信息复原 //用户信息复原
user = new UserCreateInfo(); user = new UserCreateInfo();
BeanUtils.copyBean(user, USER_LIST.get(0)); BeanUtils.copyBean(user, USER_LIST.get(0));
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkLog(response.getId(), OperationLogType.UPDATE); checkLog(response.getId(), OperationLogType.UPDATE);
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
UserTestUtils.compareUserDTO(response, checkDTO); UserParamUtils.compareUserDTO(response, checkDTO);
} }
@Test @Test
@ -499,37 +429,37 @@ public class UserControllerTests extends BaseTest {
//更改名字 //更改名字
BeanUtils.copyBean(user, USER_LIST.get(0)); BeanUtils.copyBean(user, USER_LIST.get(0));
user.setName(""); user.setName("");
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
this.requestPost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//email为空 //email为空
BeanUtils.copyBean(user, USER_LIST.get(0)); BeanUtils.copyBean(user, USER_LIST.get(0));
user.setEmail(""); user.setEmail("");
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
this.requestPost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//手机号为空 //手机号为空
BeanUtils.copyBean(user, USER_LIST.get(0)); BeanUtils.copyBean(user, USER_LIST.get(0));
user.setEmail(""); user.setEmail("");
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
this.requestPost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER);
//用户组为空 //用户组为空
BeanUtils.copyBean(user, USER_LIST.get(0)); BeanUtils.copyBean(user, USER_LIST.get(0));
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, new ArrayList<>()); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, new ArrayList<>());
userMaintainRequest.setUserRoleIdList(new ArrayList<>()); userMaintainRequest.setUserRoleIdList(new ArrayList<>());
this.requestPost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER);
// 500验证 // 500验证
//邮箱重复 //邮箱重复
this.checkUserList(); this.checkUserList();
BeanUtils.copyBean(user, USER_LIST.get(0)); BeanUtils.copyBean(user, USER_LIST.get(0));
user.setEmail(USER_LIST.get(USER_LIST.size() - 1).getEmail()); user.setEmail(USER_LIST.get(USER_LIST.size() - 1).getEmail());
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
this.requestPost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest, ERROR_REQUEST_MATCHER);
//用户组不包含系统成员 //用户组不包含系统成员
BeanUtils.copyBean(user, USER_LIST.get(0)); BeanUtils.copyBean(user, USER_LIST.get(0));
userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, userMaintainRequest = UserParamUtils.getUserUpdateDTO(user,
defaultUserRoleList.stream().filter(item -> !StringUtils.equals(item.getId(), "member")).toList() USER_ROLE_LIST.stream().filter(item -> !StringUtils.equals(item.getId(), "member")).toList()
); );
this.requestPost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest, ERROR_REQUEST_MATCHER);
} }
@Test @Test
@ -543,8 +473,8 @@ public class UserControllerTests extends BaseTest {
this.add(userInfo.getId()); this.add(userInfo.getId());
}}); }});
userChangeEnableRequest.setEnable(false); userChangeEnableRequest.setEnable(false);
this.requestPost(UserTestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk()); this.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk());
for(String item : userChangeEnableRequest.getUserIdList()){ for (String item : userChangeEnableRequest.getUserIdList()) {
checkLog(item, OperationLogType.UPDATE); checkLog(item, OperationLogType.UPDATE);
} }
@ -559,12 +489,12 @@ public class UserControllerTests extends BaseTest {
//用户不存在 //用户不存在
UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest(); UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest();
userChangeEnableRequest.setEnable(false); userChangeEnableRequest.setEnable(false);
this.requestPost(UserTestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, BAD_REQUEST_MATCHER);
//含有非法用户 //含有非法用户
userChangeEnableRequest.setUserIdList(new ArrayList<>() {{ userChangeEnableRequest.setUserIdList(new ArrayList<>() {{
this.add("BCDEDIT"); this.add("BCDEDIT");
}}); }});
this.requestPost(UserTestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, ERROR_REQUEST_MATCHER);
} }
@ -578,73 +508,73 @@ public class UserControllerTests extends BaseTest {
UserImportResponse response;//导入返回值 UserImportResponse response;//导入返回值
//导入正常文件 //导入正常文件
String filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_success.xlsx")).getPath(); String filePath = Objects.requireNonNull(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)); MockMultipartFile file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath));
ExcelParseDTO<UserExcelRowDTO> userImportReportDTOByFile = userService.getUserExcelParseDTO(file); ExcelParseDTO<UserExcelRowDTO> userImportReportDTOByFile = userService.getUserExcelParseDTO(file);
response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class);
UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值 UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值
List<UserDTO> userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 List<UserDTO> userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库
for (UserDTO item : userDTOList){ for (UserDTO item : userDTOList) {
checkLog(item.getId(), OperationLogType.ADD); checkLog(item.getId(), OperationLogType.ADD);
} }
//导入空文件. 应当导入成功的数据为0 //导入空文件. 应当导入成功的数据为0
filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_success_empty.xlsx")).getPath(); filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_success_empty.xlsx")).getPath();
file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserTestUtils.getFileBytes(filePath)); file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath));
response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class);
importSuccessData = 0; importSuccessData = 0;
errorDataIndex = new int[]{}; errorDataIndex = new int[]{};
UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex); UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);
//文件内没有一条合格数据 应当导入成功的数据为0 //文件内没有一条合格数据 应当导入成功的数据为0
filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_error_all.xlsx")).getPath(); filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_error_all.xlsx")).getPath();
file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserTestUtils.getFileBytes(filePath)); file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath));
response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class);
errorDataIndex = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; errorDataIndex = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex); UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);
//邮箱和数据库里的重复 应当导入成功的数据为8 //邮箱和数据库里的重复 应当导入成功的数据为8
filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_error_email_repeat_db.xlsx")).getPath(); filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_error_email_repeat_db.xlsx")).getPath();
file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserTestUtils.getFileBytes(filePath)); file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath));
userImportReportDTOByFile = userService.getUserExcelParseDTO(file); userImportReportDTOByFile = userService.getUserExcelParseDTO(file);
response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class);
importSuccessData = 8; importSuccessData = 8;
errorDataIndex = new int[]{1, 7}; errorDataIndex = new int[]{1, 7};
UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex); UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);
userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库
for (UserDTO item : userDTOList){ for (UserDTO item : userDTOList) {
checkLog(item.getId(), OperationLogType.ADD); checkLog(item.getId(), OperationLogType.ADD);
} }
//文件内邮箱重复 应当导入成功的数据为8 //文件内邮箱重复 应当导入成功的数据为8
filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_error_email_repeat_in_file.xlsx")).getPath(); filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_error_email_repeat_in_file.xlsx")).getPath();
file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserTestUtils.getFileBytes(filePath)); file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath));
userImportReportDTOByFile = userService.getUserExcelParseDTO(file); userImportReportDTOByFile = userService.getUserExcelParseDTO(file);
response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class);
errorDataIndex = new int[]{9, 10}; errorDataIndex = new int[]{9, 10};
UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex); UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);
userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库
for (UserDTO item : userDTOList){ for (UserDTO item : userDTOList) {
checkLog(item.getId(), OperationLogType.ADD); checkLog(item.getId(), OperationLogType.ADD);
} }
//文件不符合规范 应当导入成功的数据为0 //文件不符合规范 应当导入成功的数据为0
filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/abcde.gif")).getPath(); filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/abcde.gif")).getPath();
file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserTestUtils.getFileBytes(filePath)); file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath));
response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class);
importSuccessData = 0; importSuccessData = 0;
errorDataIndex = new int[]{}; errorDataIndex = new int[]{};
UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex); UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);
//测试03版excel正常导入 应当导入成功的数据为10 //测试03版excel正常导入 应当导入成功的数据为10
filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_success_03.xls")).getPath(); filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_success_03.xls")).getPath();
file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserTestUtils.getFileBytes(filePath)); file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath));
userImportReportDTOByFile = userService.getUserExcelParseDTO(file); userImportReportDTOByFile = userService.getUserExcelParseDTO(file);
response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class);
importSuccessData = 10;//应该导入成功的数据数量 importSuccessData = 10;//应该导入成功的数据数量
errorDataIndex = new int[]{};//出错数据的行数 errorDataIndex = new int[]{};//出错数据的行数
UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值 UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值
userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库
for (UserDTO item : userDTOList){ for (UserDTO item : userDTOList) {
checkLog(item.getId(), OperationLogType.ADD); checkLog(item.getId(), OperationLogType.ADD);
} }
} }
@ -657,43 +587,97 @@ public class UserControllerTests extends BaseTest {
String userId = USER_LIST.get(0).getId(); String userId = USER_LIST.get(0).getId();
String userEmail = USER_LIST.get(0).getEmail(); String userEmail = USER_LIST.get(0).getEmail();
//重置普通用户密码 //重置普通用户密码
this.resetPasswordAndCheck(userId,userEmail); this.resetPasswordAndCheck(userId, userEmail);
this.checkLog(userId, OperationLogType.UPDATE); this.checkLog(userId, OperationLogType.UPDATE);
//重置admin的密码 //重置admin的密码
this.resetPasswordAndCheck("admin","metersphere"); this.resetPasswordAndCheck("admin", "metersphere");
this.checkLog(userId, OperationLogType.UPDATE); this.checkLog(userId, OperationLogType.UPDATE);
} }
private void resetPasswordAndCheck(String userId,String userEmail) throws Exception{
User user = new User();
user.setId(userId);
user.setPassword("I can't say any dirty words");
Assertions.assertEquals(1, userMapper.updateByPrimaryKeySelective(user));
//调用重置密码的接口
this.requestResetPassword(userId,status().isOk());
//检查数据库
UserExample example = new UserExample();
example.createCriteria().andIdEqualTo(userId).andPasswordEqualTo(CodingUtil.md5(userEmail));
Assertions.assertEquals(1, userMapper.countByExample(example));
checkLog(userId, OperationLogType.UPDATE);
}
@Test @Test
@Order(8) @Order(8)
public void testUserResetPasswordError() throws Exception { public void testUserResetPasswordError() throws Exception {
//用户不存在 //用户不存在
this.requestResetPassword("none user",ERROR_REQUEST_MATCHER); userRequestUtils.requestPostString(userRequestUtils.URL_USER_RESET_PASSWORD, "none user", ERROR_REQUEST_MATCHER);
} }
@Test @Test
@Order(9) @Order(9)
public void testUserRoleRelationSuccess() throws Exception {
//UserList中的部分角色是没有添加到某权限中的
if (USER_LIST.size() < 50) {
this.testAddSuccess();
}
List<UserCreateInfo> last50Users = USER_LIST.subList(USER_LIST.size() - 50, USER_LIST.size());
//测试添加角色权限 预期数据每个用户都会增加对应的权限
GlobalUserRoleRelationBatchRequest request = new GlobalUserRoleRelationBatchRequest();
request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList()));
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, null);
//检查有权限的数据量是否一致
Assertions.assertEquals(
globalUserRoleRelationService.selectByUserIdAndRuleId(request.getUserIds(), request.getRoleIds()).size(),
request.getUserIds().size() * request.getRoleIds().size()
);
//检查日志
for (UserRoleOption option : USER_ROLE_LIST) {
this.checkLog(option.getId(), OperationLogType.ADD);
}
//测试重复添加用户权限预期结果不会额外增加数据
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, null);
//检查有权限的数据量是否一致
Assertions.assertEquals(
globalUserRoleRelationService.selectByUserIdAndRuleId(request.getUserIds(), request.getRoleIds()).size(),
request.getUserIds().size() * request.getRoleIds().size()
);
//检查日志
for (UserRoleOption option : USER_ROLE_LIST) {
this.checkLog(option.getId(), OperationLogType.ADD);
}
}
@Test
@Order(9)
public void testUserRoleRelationError() throws Exception {
//UserList中的部分角色是没有添加到某权限中的
if (USER_LIST.size() < 50) {
this.testAddSuccess();
}
List<UserCreateInfo> last50Users = USER_LIST.subList(USER_LIST.size() - 50, USER_LIST.size());
// 用户ID为空
GlobalUserRoleRelationBatchRequest request = new GlobalUserRoleRelationBatchRequest();
request.setUserIds(new ArrayList<>());
request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList()));
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, BAD_REQUEST_MATCHER);
// 角色id为空
request = new GlobalUserRoleRelationBatchRequest();
request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
request.setRoleIds(new ArrayList<>());
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, BAD_REQUEST_MATCHER);
// 用户ID含有不存在的
request = new GlobalUserRoleRelationBatchRequest();
request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList()));
request.getUserIds().add("none user");
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, ERROR_REQUEST_MATCHER);
// 角色ID含有不存在的
request = new GlobalUserRoleRelationBatchRequest();
request.setUserIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
request.setRoleIds(USER_ROLE_LIST.stream().map(UserRoleOption::getId).collect(Collectors.toList()));
request.getRoleIds().add("none role");
userRequestUtils.requestPost(userRequestUtils.URL_USER_ROLE_RELATION, request, ERROR_REQUEST_MATCHER);
}
//本测试类中会用到很多次用户数据所以测试删除的方法放于最后
@Test
@Order(99)
public void testUserDeleteSuccess() throws Exception { public void testUserDeleteSuccess() throws Exception {
this.checkUserList(); this.checkUserList();
//删除已存的所有用户 //删除已存的所有用户
UserBatchProcessRequest request = new UserBatchProcessRequest(); UserBatchProcessRequest request = new UserBatchProcessRequest();
request.setUserIdList(USER_LIST.stream().map(UserCreateInfo::getId).collect(Collectors.toList())); request.setUserIdList(USER_LIST.stream().map(UserCreateInfo::getId).collect(Collectors.toList()));
UserBatchProcessResponse response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_DELETE, request), UserBatchProcessResponse.class); UserBatchProcessResponse response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_DELETE, request), UserBatchProcessResponse.class);
Assertions.assertEquals(request.getUserIdList().size(), response.getTotalCount()); Assertions.assertEquals(request.getUserIdList().size(), response.getTotalCount());
Assertions.assertEquals(request.getUserIdList().size(), response.getSuccessCount()); Assertions.assertEquals(request.getUserIdList().size(), response.getSuccessCount());
//检查数据库 //检查数据库
@ -713,24 +697,54 @@ public class UserControllerTests extends BaseTest {
//删除失败的方法要放在删除成功方法后面执行 //删除失败的方法要放在删除成功方法后面执行
@Test @Test
@Order(10) @Order(100)
public void testUserDeleteError() throws Exception { public void testUserDeleteError() throws Exception {
//参数为空 //参数为空
UserBatchProcessRequest request = new UserBatchProcessRequest(); UserBatchProcessRequest request = new UserBatchProcessRequest();
this.requestPost(UserTestUtils.URL_USER_DELETE, request, BAD_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_DELETE, request, BAD_REQUEST_MATCHER);
//用户不存在 //用户不存在
request.getUserIdList().add("123456789012345678901234"); request.getUserIdList().add("123456789012345678901234");
this.requestPost(UserTestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER);
//用户已经被删除 //用户已经被删除
if(CollectionUtils.isEmpty(DELETED_USER_ID_LIST)){ if (CollectionUtils.isEmpty(DELETED_USER_ID_LIST)) {
this.testUserDeleteSuccess(); this.testUserDeleteSuccess();
} }
request.setUserIdList(DELETED_USER_ID_LIST); request.setUserIdList(DELETED_USER_ID_LIST);
this.requestPost(UserTestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER); this.requestPost(userRequestUtils.URL_USER_DELETE, request, ERROR_REQUEST_MATCHER);
} }
public List<UserDTO> checkImportUserInDb(ExcelParseDTO<UserExcelRowDTO> userImportReportDTOByFile) throws Exception { //记录查询到的组织信息
private void setDefaultUserRoleList(MvcResult mvcResult) throws Exception {
String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
//返回请求正常
Assertions.assertNotNull(resultHolder);
List<UserRoleOption> userRoleList = JSON.parseArray(JSON.toJSONString(resultHolder.getData()), UserRoleOption.class);
//返回值不为空
Assertions.assertTrue(CollectionUtils.isNotEmpty(userRoleList));
USER_ROLE_LIST.addAll(userRoleList);
}
//成功入库的用户保存内存中其他用例会使用到
private void addUser2List(MvcResult mvcResult) throws Exception {
UserBatchCreateDTO userMaintainRequest = userRequestUtils.parseObjectFromMvcResult(mvcResult, UserBatchCreateDTO.class);
for (UserCreateInfo item : userMaintainRequest.getUserInfoList()) {
checkLog(item.getId(), OperationLogType.ADD);
}
//返回值不为空
Assertions.assertNotNull(userMaintainRequest);
USER_LIST.addAll(userMaintainRequest.getUserInfoList());
}
private void checkUserList() throws Exception {
if (CollectionUtils.isEmpty(USER_LIST)) {
//测试数据初始化入库
this.testAddSuccess();
}
}
private List<UserDTO> checkImportUserInDb(ExcelParseDTO<UserExcelRowDTO> userImportReportDTOByFile) throws Exception {
List<UserDTO> returnList = new ArrayList<>(); List<UserDTO> returnList = new ArrayList<>();
for (UserExcelRowDTO item : userImportReportDTOByFile.getDataList()) { for (UserExcelRowDTO item : userImportReportDTOByFile.getDataList()) {
UserDTO userDTO = this.getUserByEmail(item.getEmail()); UserDTO userDTO = this.getUserByEmail(item.getEmail());
@ -740,4 +754,18 @@ public class UserControllerTests extends BaseTest {
return returnList; return returnList;
} }
private void resetPasswordAndCheck(String userId, String userEmail) throws Exception {
User user = new User();
user.setId(userId);
user.setPassword("I can't say any dirty words");
Assertions.assertEquals(1, userMapper.updateByPrimaryKeySelective(user));
//调用重置密码的接口
userRequestUtils.requestPostString(userRequestUtils.URL_USER_RESET_PASSWORD, userId, status().isOk());
//检查数据库
UserExample example = new UserExample();
example.createCriteria().andIdEqualTo(userId).andPasswordEqualTo(CodingUtil.md5(userEmail));
Assertions.assertEquals(1, userMapper.countByExample(example));
checkLog(userId, OperationLogType.UPDATE);
}
} }

View File

@ -1,4 +1,4 @@
package io.metersphere.system.utils; package io.metersphere.system.utils.user;
import io.metersphere.sdk.controller.handler.ResultHolder; import io.metersphere.sdk.controller.handler.ResultHolder;
import io.metersphere.sdk.dto.BasePageRequest; import io.metersphere.sdk.dto.BasePageRequest;
@ -24,32 +24,7 @@ import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class UserTestUtils { public class UserParamUtils {
//用户管理URL
public static final String URL_USER_CREATE = "/system/user/add";
public static final String URL_USER_UPDATE = "/system/user/update";
public static final String URL_USER_GET = "/system/user/get/%s";
public static final String URL_USER_PAGE = "/system/user/page";
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 final String URL_USER_RESET_PASSWORD = "/system/user/reset/password";
public static <T> T parseObjectFromMvcResult(MvcResult mvcResult, Class<T> parseClass) {
String returnData = "";
try {
returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
} catch (Exception ignore) {
}
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
//返回请求正常
Assertions.assertNotNull(resultHolder);
return JSON.parseObject(JSON.toJSONString(resultHolder.getData()), parseClass);
}
public static UserBatchCreateDTO getUserCreateDTO( public static UserBatchCreateDTO getUserCreateDTO(
List<UserRoleOption> userRoleList, List<UserRoleOption> userRoleList,
@ -107,6 +82,8 @@ public class UserTestUtils {
return buffer; return buffer;
} }
//用户信息对比
public static void compareUserDTO(UserEditRequest editRequest, UserDTO selectUserDTO) { public static void compareUserDTO(UserEditRequest editRequest, UserDTO selectUserDTO) {
Assertions.assertNotNull(editRequest); Assertions.assertNotNull(editRequest);
Assertions.assertNotNull(selectUserDTO); Assertions.assertNotNull(selectUserDTO);
@ -129,13 +106,14 @@ public class UserTestUtils {
&& selectUserSystemRoleId.containsAll(editRequest.getUserRoleIdList())); && selectUserSystemRoleId.containsAll(editRequest.getUserRoleIdList()));
} }
//导入结果判断
public static void checkImportResponse(UserImportResponse responsePost, int successCount, int[] errorDataIndex) { public static void checkImportResponse(UserImportResponse responsePost, int successCount, int[] errorDataIndex) {
//导入总数据是否一致 //导入总数据是否一致
Assertions.assertTrue(responsePost.getImportCount() == successCount + errorDataIndex.length); Assertions.assertEquals(responsePost.getImportCount(), successCount + errorDataIndex.length);
//导入成功数据是否一致 //导入成功数据是否一致
Assertions.assertTrue(responsePost.getSuccessCount() == successCount); Assertions.assertEquals(responsePost.getSuccessCount(), successCount);
//报错数据数量是否一致 //报错数据数量是否一致
Assertions.assertTrue(responsePost.getErrorMessages().size() == errorDataIndex.length); Assertions.assertEquals(responsePost.getErrorMessages().size(), errorDataIndex.length);
//报错数据行编码是否一致 //报错数据行编码是否一致
for (int index : errorDataIndex) { for (int index : errorDataIndex) {
Assertions.assertTrue(responsePost.getErrorMessages().containsKey(index)); Assertions.assertTrue(responsePost.getErrorMessages().containsKey(index));

View File

@ -0,0 +1,134 @@
package io.metersphere.system.utils.user;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.controller.handler.ResultHolder;
import io.metersphere.sdk.util.JSON;
import org.junit.jupiter.api.Assertions;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.nio.charset.StandardCharsets;
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;
public class UserRequestUtils {
//用户管理URL
public final String URL_USER_CREATE = "/system/user/add";
public final String URL_USER_UPDATE = "/system/user/update";
public final String URL_USER_GET = "/system/user/get/%s";
public final String URL_USER_PAGE = "/system/user/page";
public final String URL_GET_GLOBAL_SYSTEM = "/system/user/get/global/system/role";
public final String URL_USER_UPDATE_ENABLE = "/system/user/update/enable";
public final String URL_USER_IMPORT = "/system/user/import";
public final String URL_USER_DELETE = "/system/user/delete";
public final String URL_USER_RESET_PASSWORD = "/system/user/reset/password";
public final String URL_USER_ROLE_RELATION = "/user/role/relation/global/add/batch";
private final MockMvc mockMvc;
private final String sessionId;
private final String csrfToken;
public UserRequestUtils(MockMvc mockMvc, String sessionId, String csrfToken) {
this.mockMvc = mockMvc;
this.sessionId = sessionId;
this.csrfToken = csrfToken;
}
//解析返回值
public <T> T parseObjectFromMvcResult(MvcResult mvcResult, Class<T> parseClass) {
String returnData = "";
try {
returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
} catch (Exception ignore) {
}
ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class);
//返回请求正常
Assertions.assertNotNull(resultHolder);
return JSON.parseObject(JSON.toJSONString(resultHolder.getData()), parseClass);
}
//参数是对象
public void requestPost(String url, Object param, ResultMatcher resultMatcher) throws Exception {
if (resultMatcher == null) {
//默认检查200
resultMatcher = status().isOk();
}
mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
//参数是string
public void requestPostString(String url, String param, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(param)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
public void requestGet(String url, ResultMatcher resultMatcher) throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(resultMatcher)
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
public 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));
}
//以下是带返回值的请求
public MvcResult responseGet(String url) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.get(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)).andReturn();
}
public MvcResult responsePost(String url, Object param) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.post(url)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken)
.content(JSON.toJSONString(param))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
}
public MvcResult responseFile(String url, MockMultipartFile file) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.multipart(url)
.file(file)
.contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
.header(SessionConstants.HEADER_TOKEN, sessionId)
.header(SessionConstants.CSRF_TOKEN, csrfToken))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
}
}