From 447e9a5bb5f54e361e1dd5d2f4196d1e97d5d220 Mon Sep 17 00:00:00 2001 From: song-tianyang Date: Mon, 31 Jul 2023 16:23:52 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E7=B3=BB=E7=BB=9F=E8=AE=BE=E7=BD=AE):=20?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=AE=A1=E7=90=86=E5=A2=9E=E5=8A=A0=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E7=94=A8=E6=88=B7=E5=88=B0=E7=94=A8=E6=88=B7=E7=BB=84?= =?UTF-8?q?=E7=9A=84=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../GlobalUserRoleRelationBatchRequest.java | 36 ++ .../sdk/service/BaseUserRoleService.java | 12 + .../GlobalUserRoleRelationController.java | 10 + .../system/controller/UserController.java | 6 +- .../system/mapper/ExtUserRoleMapper.xml | 7 +- .../GlobalUserRoleRelationLogService.java | 28 + .../GlobalUserRoleRelationService.java | 74 ++- .../system/service/GlobalUserRoleService.java | 5 +- .../system/service/UserService.java | 22 +- .../UserControllerNonePermissionTests.java | 86 ++- .../{ => user}/UserControllerTests.java | 492 +++++++++--------- .../UserParamUtils.java} | 38 +- .../system/utils/user/UserRequestUtils.java | 134 +++++ 13 files changed, 618 insertions(+), 332 deletions(-) create mode 100644 backend/framework/sdk/src/main/java/io/metersphere/sdk/dto/request/GlobalUserRoleRelationBatchRequest.java rename backend/services/system-setting/src/test/java/io/metersphere/system/controller/{ => user}/UserControllerNonePermissionTests.java (56%) rename backend/services/system-setting/src/test/java/io/metersphere/system/controller/{ => user}/UserControllerTests.java (58%) rename backend/services/system-setting/src/test/java/io/metersphere/system/utils/{UserTestUtils.java => user/UserParamUtils.java} (75%) create mode 100644 backend/services/system-setting/src/test/java/io/metersphere/system/utils/user/UserRequestUtils.java diff --git a/backend/framework/sdk/src/main/java/io/metersphere/sdk/dto/request/GlobalUserRoleRelationBatchRequest.java b/backend/framework/sdk/src/main/java/io/metersphere/sdk/dto/request/GlobalUserRoleRelationBatchRequest.java new file mode 100644 index 0000000000..bbafb237e2 --- /dev/null +++ b/backend/framework/sdk/src/main/java/io/metersphere/sdk/dto/request/GlobalUserRoleRelationBatchRequest.java @@ -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; + +} diff --git a/backend/framework/sdk/src/main/java/io/metersphere/sdk/service/BaseUserRoleService.java b/backend/framework/sdk/src/main/java/io/metersphere/sdk/service/BaseUserRoleService.java index f82e88b416..63c84fa2d5 100644 --- a/backend/framework/sdk/src/main/java/io/metersphere/sdk/service/BaseUserRoleService.java +++ b/backend/framework/sdk/src/main/java/io/metersphere/sdk/service/BaseUserRoleService.java @@ -6,6 +6,7 @@ import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest; import io.metersphere.sdk.exception.MSException; import io.metersphere.sdk.util.PermissionCache; import io.metersphere.system.domain.UserRole; +import io.metersphere.system.domain.UserRoleExample; import io.metersphere.system.mapper.UserRoleMapper; import jakarta.annotation.Resource; import org.apache.commons.collections.CollectionUtils; @@ -14,6 +15,7 @@ import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; @@ -132,6 +134,16 @@ public class BaseUserRoleService { return userRoleMapper.selectByPrimaryKey(id); } + public List getList(List 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) { UserRole userRole = userRoleMapper.selectByPrimaryKey(id); return userRole == null ? null : userRole.getName(); diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/GlobalUserRoleRelationController.java b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/GlobalUserRoleRelationController.java index 6f299d1dcf..ead7f14f65 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/GlobalUserRoleRelationController.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/GlobalUserRoleRelationController.java @@ -4,6 +4,7 @@ import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import io.metersphere.sdk.constants.PermissionConstants; import io.metersphere.sdk.dto.UserRoleRelationUserDTO; +import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest; import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest; import io.metersphere.sdk.log.annotation.Log; import io.metersphere.sdk.log.constants.OperationLogType; @@ -52,6 +53,15 @@ public class GlobalUserRoleRelationController { 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}") @Operation(summary = "删除全局用户组和用户的关联关系") @RequiresPermissions(PermissionConstants.SYSTEM_USER_ROLE_UPDATE) diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/UserController.java b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/UserController.java index c683b36170..bb5f95a78c 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/UserController.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/UserController.java @@ -111,11 +111,11 @@ public class UserController { } @PostMapping("/reset/password") + @Operation(summary = "重置用户密码") @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ_UPDATE) @Log(type = OperationLogType.UPDATE, expression = "#msClass.resetPasswordLog(#userId)", msClass = UserService.class) public boolean resetPassword(@RequestBody String userId) { - return userService.resetPassword(userId,SessionUtils.getUserId()); + userService.resetPassword(userId, SessionUtils.getUserId()); + return true; } - - } diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/mapper/ExtUserRoleMapper.xml b/backend/services/system-setting/src/main/java/io/metersphere/system/mapper/ExtUserRoleMapper.xml index e647c9c142..313deca153 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/mapper/ExtUserRoleMapper.xml +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/mapper/ExtUserRoleMapper.xml @@ -10,12 +10,15 @@ AND type = 'SYSTEM' + AND scope_id = 'GLOBAL' \ No newline at end of file diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleRelationLogService.java b/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleRelationLogService.java index 64171a341d..e044a77766 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleRelationLogService.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleRelationLogService.java @@ -4,18 +4,21 @@ import io.metersphere.sdk.constants.OperationLogConstants; import io.metersphere.sdk.dto.LogDTO; import io.metersphere.sdk.dto.OptionDTO; import io.metersphere.sdk.dto.UserDTO; +import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest; import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest; import io.metersphere.sdk.log.constants.OperationLogModule; import io.metersphere.sdk.log.constants.OperationLogType; import io.metersphere.sdk.mapper.BaseUserMapper; import io.metersphere.sdk.util.JSON; import io.metersphere.system.domain.UserRole; +import io.metersphere.system.domain.UserRoleExample; import io.metersphere.system.domain.UserRoleRelation; import io.metersphere.system.mapper.UserRoleMapper; import io.metersphere.system.mapper.UserRoleRelationMapper; import jakarta.annotation.Resource; import org.springframework.stereotype.Service; +import java.util.ArrayList; import java.util.List; /** @@ -55,6 +58,31 @@ public class GlobalUserRoleRelationLogService { return dto; } + public List batchAddLog(GlobalUserRoleRelationBatchRequest request) { + UserRoleExample example = new UserRoleExample(); + example.createCriteria().andIdIn(request.getRoleIds()); + List userRoles = userRoleMapper.selectByExample(example); + List userIds = request.getUserIds(); + List users = baseUserMapper.selectUserOptionByIds(userIds); + + List 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; + } + /** * 删除接口日志 * diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleRelationService.java b/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleRelationService.java index 1512f8909a..e0ea270de1 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleRelationService.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleRelationService.java @@ -1,17 +1,27 @@ package io.metersphere.system.service; import io.metersphere.sdk.dto.UserRoleRelationUserDTO; +import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest; import io.metersphere.sdk.dto.request.GlobalUserRoleRelationUpdateRequest; +import io.metersphere.sdk.exception.MSException; import io.metersphere.sdk.service.BaseUserRoleRelationService; import io.metersphere.sdk.util.BeanUtils; +import io.metersphere.sdk.util.Translator; import io.metersphere.system.domain.UserRole; import io.metersphere.system.domain.UserRoleRelation; +import io.metersphere.system.domain.UserRoleRelationExample; import io.metersphere.system.dto.request.GlobalUserRoleRelationQueryRequest; import io.metersphere.system.mapper.ExtUserRoleRelationMapper; +import io.metersphere.validation.groups.Created; +import io.metersphere.validation.groups.Updated; import jakarta.annotation.Resource; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.ibatis.session.SqlSessionFactory; 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 @@ -23,6 +33,10 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService { private ExtUserRoleRelationMapper extUserRoleRelationMapper; @Resource private GlobalUserRoleService globalUserRoleService; + @Resource + private UserService userService; + @Resource + private SqlSessionFactory sqlSessionFactory; public List list(GlobalUserRoleRelationQueryRequest request) { UserRole userRole = globalUserRoleService.get(request.getRoleId()); @@ -31,10 +45,23 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService { return extUserRoleRelationMapper.listGlobal(request); } + //校验用户组 + private void checkGlobalSystemUserRoleLegality(List checkIdList) { + List 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) { - UserRole userRole = globalUserRoleService.get(request.getRoleId()); - globalUserRoleService.checkSystemUserGroup(userRole); - globalUserRoleService.checkGlobalUserRole(userRole); + this.checkGlobalSystemUserRoleLegality( + Collections.singletonList(request.getRoleId())); + //检查用户的合法性 + userService.checkUserLegality(request.getUserIds()); request.getUserIds().forEach(userId -> { UserRoleRelation userRoleRelation = new UserRoleRelation(); BeanUtils.copyBean(userRoleRelation, request); @@ -44,6 +71,45 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService { }); } + public List selectByUserIdAndRuleId(List userIds, List 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 savedUserRoleRelation = this.selectByUserIdAndRuleId(request.getUserIds(), request.getRoleIds()); + //过滤已经存储过的用户关系 + Map> userRoleIdMap = savedUserRoleRelation.stream() + .collect(Collectors.groupingBy(UserRoleRelation::getUserId, Collectors.mapping(UserRoleRelation::getRoleId, Collectors.toList()))); + long createTime = System.currentTimeMillis(); + List 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 public void delete(String id) { UserRole userRole = getUserRole(id); diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleService.java b/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleService.java index fd600627ac..c67971b83f 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleService.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/service/GlobalUserRoleService.java @@ -4,7 +4,6 @@ import io.metersphere.sdk.dto.PermissionDefinitionItem; import io.metersphere.sdk.dto.request.PermissionSettingUpdateRequest; import io.metersphere.sdk.exception.MSException; import io.metersphere.sdk.service.BaseUserRoleService; -import io.metersphere.sdk.util.Translator; import io.metersphere.system.domain.UserRole; import io.metersphere.system.domain.UserRoleExample; import io.metersphere.system.dto.UserRoleOption; @@ -85,6 +84,7 @@ public class GlobalUserRoleService extends BaseUserRoleService { throw new MSException(GLOBAL_USER_ROLE_EXIST); } } + @Override public UserRole update(UserRole userRole) { UserRole originUserRole = get(userRole.getId()); @@ -106,9 +106,6 @@ public class GlobalUserRoleService extends BaseUserRoleService { if (globalRoleList.size() != roleIdList.size()) { throw new MSException("role.not.global"); } - if (!globalRoleList.contains(MEMBER.getValue())) { - throw new MSException(Translator.get("role.not.contains.member")); - } } public List getGlobalSystemRoleList() { diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserService.java b/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserService.java index 551a2a9c5c..6f57670ab8 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserService.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserService.java @@ -292,7 +292,7 @@ public class UserService { return response; } - private int deleteUserByList(List updateUserList){ + private int deleteUserByList(List updateUserList) { SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); BaseUserMapper batchDeleteMapper = sqlSession.getMapper(BaseUserMapper.class); int insertIndex = 0; @@ -328,7 +328,7 @@ public class UserService { return null; } - public LogDTO resetPasswordLog(String userId){ + public LogDTO resetPasswordLog(String userId) { User user = userMapper.selectByPrimaryKey(userId); if (user != null) { LogDTO dto = new LogDTO( @@ -377,20 +377,28 @@ public class UserService { return userMapper.selectByExample(example); } - public boolean resetPassword(String userId,String operator) { + public void resetPassword(String userId, String operator) { User user = userMapper.selectByPrimaryKey(userId); - if(user == null){ + if (user == null) { throw new MSException(Translator.get("user.not.exist")); } User updateModel = new User(); updateModel.setId(userId); - if(StringUtils.equalsIgnoreCase("admin",user.getId())){ + if (StringUtils.equalsIgnoreCase("admin", user.getId())) { updateModel.setPassword(CodingUtil.md5("metersphere")); - }else { + } else { updateModel.setPassword(CodingUtil.md5(user.getEmail())); } updateModel.setUpdateTime(System.currentTimeMillis()); updateModel.setUpdateUser(operator); - return userMapper.updateByPrimaryKeySelective(updateModel) > 0; + userMapper.updateByPrimaryKeySelective(updateModel); + } + + public void checkUserLegality(List userIds) { + UserExample example = new UserExample(); + example.createCriteria().andIdIn(userIds); + if (userMapper.countByExample(example) != userIds.size()) { + throw new MSException(Translator.get("user.id.not.exist")); + } } } diff --git a/backend/services/system-setting/src/test/java/io/metersphere/system/controller/UserControllerNonePermissionTests.java b/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/UserControllerNonePermissionTests.java similarity index 56% rename from backend/services/system-setting/src/test/java/io/metersphere/system/controller/UserControllerNonePermissionTests.java rename to backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/UserControllerNonePermissionTests.java index ec738f1ee7..d1e06ba24c 100644 --- a/backend/services/system-setting/src/test/java/io/metersphere/system/controller/UserControllerNonePermissionTests.java +++ b/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/UserControllerNonePermissionTests.java @@ -1,15 +1,14 @@ -package io.metersphere.system.controller; +package io.metersphere.system.controller.user; import com.jayway.jsonpath.JsonPath; -import io.metersphere.sdk.constants.SessionConstants; -import io.metersphere.sdk.util.JSON; +import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest; import io.metersphere.system.dto.UserCreateInfo; import io.metersphere.system.dto.UserRoleOption; import io.metersphere.system.dto.request.UserBatchProcessRequest; 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 org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.*; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 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.List; +import java.util.Objects; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 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 { @Resource private MockMvc mockMvc; - protected static String sessionId; - protected static String csrfToken; + UserRequestUtils userRequestUtils = null; + private static final String NONE_ROLE_USERNAME = "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.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, - UserTestUtils.getUserCreateDTO( + userRequestUtils.requestPost(userRequestUtils.URL_USER_CREATE, + UserParamUtils.getUserCreateDTO( paramRoleList, new ArrayList<>() {{ add(paramUserInfo); @@ -77,71 +77,57 @@ public class UserControllerNonePermissionTests { ), 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, - UserTestUtils.getUserUpdateDTO(paramUserInfo, paramRoleList), CHECK_RESULT_MATHER); + userRequestUtils.requestPost(userRequestUtils.URL_USER_UPDATE, + UserParamUtils.getUserUpdateDTO(paramUserInfo, paramRoleList), CHECK_RESULT_MATHER); //校验权限:启用/禁用用户 UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest(); userChangeEnableRequest.setEnable(false); userChangeEnableRequest.setUserIdList(new ArrayList<>() {{ this.add("testId"); }}); - this.requestPost(UserTestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, CHECK_RESULT_MATHER); + userRequestUtils.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, CHECK_RESULT_MATHER); //用户导入 //导入正常文件 - String filePath = this.getClass().getClassLoader().getResource("file/user_import_success.xlsx").getPath(); - MockMultipartFile file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserTestUtils.getFileBytes(filePath)); - this.requestFile(UserTestUtils.URL_USER_IMPORT, file, CHECK_RESULT_MATHER); + 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, UserParamUtils.getFileBytes(filePath)); + userRequestUtils.requestFile(userRequestUtils.URL_USER_IMPORT, file, CHECK_RESULT_MATHER); //用户删除 UserBatchProcessRequest request = new UserBatchProcessRequest(); request.setUserIdList(new ArrayList<>() {{ this.add("testId"); }}); - this.requestPost(UserTestUtils.URL_USER_DELETE, request, CHECK_RESULT_MATHER); + 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 public void login() throws Exception { - if (StringUtils.isAnyBlank(sessionId, csrfToken)) { + if (userRequestUtils == null) { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/login") .content("{\"username\":\"" + NONE_ROLE_USERNAME + "\",\"password\":\"" + NONE_ROLE_PASSWORD + "\"}") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - sessionId = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.sessionId"); - csrfToken = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.csrfToken"); + String sessionId = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.sessionId"); + 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)); - } } diff --git a/backend/services/system-setting/src/test/java/io/metersphere/system/controller/UserControllerTests.java b/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/UserControllerTests.java similarity index 58% rename from backend/services/system-setting/src/test/java/io/metersphere/system/controller/UserControllerTests.java rename to backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/UserControllerTests.java index 0dd6928078..3f8fbc7cb5 100644 --- a/backend/services/system-setting/src/test/java/io/metersphere/system/controller/UserControllerTests.java +++ b/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/UserControllerTests.java @@ -1,11 +1,11 @@ -package io.metersphere.system.controller; +package io.metersphere.system.controller.user; import base.BaseTest; -import io.metersphere.sdk.constants.SessionConstants; import io.metersphere.sdk.controller.handler.ResultHolder; import io.metersphere.sdk.dto.BasePageRequest; import io.metersphere.sdk.dto.ExcelParseDTO; import io.metersphere.sdk.dto.UserDTO; +import io.metersphere.sdk.dto.request.GlobalUserRoleRelationBatchRequest; import io.metersphere.sdk.log.constants.OperationLogType; import io.metersphere.sdk.util.BeanUtils; 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.UserTableResponse; import io.metersphere.system.mapper.UserMapper; +import io.metersphere.system.service.GlobalUserRoleRelationService; 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 org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; @@ -36,17 +38,13 @@ import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.SqlConfig; -import org.springframework.test.web.servlet.MockMvc; 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 java.util.*; 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; @@ -54,20 +52,21 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class UserControllerTests extends BaseTest { - @Resource - private MockMvc mockMvc; + @Resource private UserService userService; @Resource private UserMapper userMapper; + @Resource + private GlobalUserRoleRelationService globalUserRoleRelationService; //失败请求返回编码 private static final ResultMatcher BAD_REQUEST_MATCHER = status().isBadRequest(); private static final ResultMatcher ERROR_REQUEST_MATCHER = status().is5xxServerError(); //测试过程中需要用到的数据 private static final List USER_LIST = new ArrayList<>(); - private static final List defaultUserRoleList = new ArrayList<>(); + private static final List USER_ROLE_LIST = new ArrayList<>(); //默认数据 public static final String USER_DEFAULT_NAME = "tianyang.no.1"; public static final String USER_DEFAULT_EMAIL = "tianyang.no.1@126.com"; @@ -75,105 +74,33 @@ public class UserControllerTests extends BaseTest { //已删除的用户ID private static final List DELETED_USER_ID_LIST = new ArrayList<>(); - //记录查询到的组织信息 - 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 userRoleList = JSON.parseArray(JSON.toJSONString(resultHolder.getData()), UserRoleOption.class); - //返回值不为空 - Assertions.assertTrue(CollectionUtils.isNotEmpty(userRoleList)); - defaultUserRoleList.addAll(userRoleList); - } + UserRequestUtils userRequestUtils = null; - //成功入库的用户保存内存中,其他用例会使用到 - private void addUser2List(MvcResult mvcResult) throws Exception { - UserBatchCreateDTO userMaintainRequest = UserTestUtils.parseObjectFromMvcResult(mvcResult, UserBatchCreateDTO.class); - for(UserCreateInfo item : userMaintainRequest.getUserInfoList()){ - checkLog(item.getId(), OperationLogType.ADD); + @Override + @BeforeEach + public void login() throws Exception { + if (userRequestUtils == null) { + 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 @Order(0) 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); } @Test @Order(1) public void testAddSuccess() throws Exception { - if (CollectionUtils.isEmpty(defaultUserRoleList)) { + if (CollectionUtils.isEmpty(USER_ROLE_LIST)) { this.testGetGlobalSystemUserRoleSuccess(); } //模拟前台批量添加用户 - UserBatchCreateDTO userMaintainRequest = UserTestUtils.getUserCreateDTO( - defaultUserRoleList, + UserBatchCreateDTO userMaintainRequest = UserParamUtils.getUserCreateDTO( + USER_ROLE_LIST, new ArrayList<>() {{ add(new UserCreateInfo() {{ 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); - //批量添加一百多个用户 + //批量添加一百多个用户,只赋予其中1个权限。 这批用户用于后续的批量添加到用户组/组织/项目 List userCreateInfoList = new ArrayList<>(); for (int i = 0; i < 123; i++) { int finalI = i; @@ -198,17 +125,17 @@ public class UserControllerTests extends BaseTest { setEmail("tianyang.no.batch" + finalI + "@126.com"); }}); } - userMaintainRequest = UserTestUtils.getUserCreateDTO( - defaultUserRoleList, + userMaintainRequest = UserParamUtils.getUserCreateDTO( + Collections.singletonList(USER_ROLE_LIST.get(0)), userCreateInfoList ); - mvcResult = this.responsePost(UserTestUtils.URL_USER_CREATE, userMaintainRequest); + mvcResult = userRequestUtils.responsePost(userRequestUtils.URL_USER_CREATE, userMaintainRequest); this.addUser2List(mvcResult); //含有重复的用户名称 - userMaintainRequest = UserTestUtils.getUserCreateDTO( + userMaintainRequest = UserParamUtils.getUserCreateDTO( - defaultUserRoleList, + USER_ROLE_LIST, new ArrayList<>() {{ add(new UserCreateInfo() {{ 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); } @Test @Order(1) public void testAddError() throws Exception { - if (CollectionUtils.isEmpty(defaultUserRoleList)) { + if (CollectionUtils.isEmpty(USER_ROLE_LIST)) { this.testGetGlobalSystemUserRoleSuccess(); } UserBatchCreateDTO userMaintainRequest; @@ -247,67 +174,70 @@ public class UserControllerTests extends BaseTest { * 每一次校验,使用getErrorUserCreateDTO方法重新获取参数,避免上一步的参数干扰 */ //所有参数都为空 - userMaintainRequest = UserTestUtils.getUserCreateDTO(null, null); - this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); + userMaintainRequest = UserParamUtils.getUserCreateDTO(null, null); + this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); //用户组ID为空 - userMaintainRequest = UserTestUtils.getUserCreateDTO( + userMaintainRequest = UserParamUtils.getUserCreateDTO( null, errorUserList); - this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); + this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); //没有用户 - userMaintainRequest = UserTestUtils.getUserCreateDTO( - - defaultUserRoleList, + userMaintainRequest = UserParamUtils.getUserCreateDTO( + USER_ROLE_LIST, null); - this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); - //含有不存在的用户组 - userMaintainRequest = UserTestUtils.getUserCreateDTO( - defaultUserRoleList, + this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); + //用户组含有null + userMaintainRequest = UserParamUtils.getUserCreateDTO( + USER_ROLE_LIST, errorUserList); userMaintainRequest.getUserRoleIdList().add(null); 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( - defaultUserRoleList, + userMaintainRequest = UserParamUtils.getUserCreateDTO( + USER_ROLE_LIST, new ArrayList<>() ); userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{ 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( - defaultUserRoleList, + userMaintainRequest = UserParamUtils.getUserCreateDTO( + USER_ROLE_LIST, new ArrayList<>() ); userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{ 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( - defaultUserRoleList, + userMaintainRequest = UserParamUtils.getUserCreateDTO( + USER_ROLE_LIST, new ArrayList<>() ); userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{ setName("用户邮箱放飞自我"); setEmail("用户邮箱放飞自我"); }}); - this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); + this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, BAD_REQUEST_MATCHER); /* * 校验业务判断出错的反例 (500 error) * 需要保证数据库有正常数据 */ this.checkUserList(); - //不含有系统成员用户组 - userMaintainRequest = UserTestUtils.getUserCreateDTO( - defaultUserRoleList.stream().filter(item -> !StringUtils.equals(item.getId(), "member")).toList(), + //含有非法用户组 + userMaintainRequest = UserParamUtils.getUserCreateDTO( + new ArrayList<>() {{ + this.add(new UserRoleOption() {{ + this.setId("not system global user role id"); + }}); + }}, errorUserList); - this.requestPost(UserTestUtils.URL_USER_CREATE, userMaintainRequest, ERROR_REQUEST_MATCHER); + this.requestPost(userRequestUtils.URL_USER_CREATE, userMaintainRequest, ERROR_REQUEST_MATCHER); //含有重复的用户邮箱 - userMaintainRequest = UserTestUtils.getUserCreateDTO( - defaultUserRoleList, + userMaintainRequest = UserParamUtils.getUserCreateDTO( + USER_ROLE_LIST, errorUserList ); String firstUserEmail = userMaintainRequest.getUserInfoList().get(0).getEmail(); @@ -315,10 +245,10 @@ public class UserControllerTests extends BaseTest { setName("tianyang.no.error4"); 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( - defaultUserRoleList, + userMaintainRequest = UserParamUtils.getUserCreateDTO( + USER_ROLE_LIST, errorUserList ); 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 @@ -356,8 +286,8 @@ public class UserControllerTests extends BaseTest { } private UserDTO getUserByEmail(String email) throws Exception { - String url = String.format(UserTestUtils.URL_USER_GET, email); - return UserTestUtils.parseObjectFromMvcResult(this.responseGet(url), UserDTO.class); + String url = String.format(userRequestUtils.URL_USER_GET, email); + return userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseGet(url), UserDTO.class); } @Test @@ -365,8 +295,8 @@ public class UserControllerTests extends BaseTest { public void testGetByEmailError() throws Exception { //测试使用任意参数,不能获取到任何用户信息 this.checkUserList(); - String url = UserTestUtils.URL_USER_GET + UUID.randomUUID(); - MvcResult mvcResult = this.responseGet(url); + String url = userRequestUtils.URL_USER_GET + UUID.randomUUID(); + MvcResult mvcResult = userRequestUtils.responseGet(url); String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class); @@ -380,8 +310,8 @@ public class UserControllerTests extends BaseTest { @Order(3) public void testPageSuccess() throws Exception { this.checkUserList(); - BasePageRequest basePageRequest = UserTestUtils.getDefaultPageRequest(); - MvcResult mvcResult = this.responsePost(UserTestUtils.URL_USER_PAGE, basePageRequest); + BasePageRequest basePageRequest = UserParamUtils.getDefaultPageRequest(); + MvcResult mvcResult = userRequestUtils.responsePost(userRequestUtils.URL_USER_PAGE, basePageRequest); String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); 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()); //测试根据创建时间倒叙排列 - basePageRequest = UserTestUtils.getDefaultPageRequest(); + basePageRequest = UserParamUtils.getDefaultPageRequest(); basePageRequest.setSort(new HashMap<>() {{ 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); resultHolder = JSON.parseObject(returnData, ResultHolder.class); returnPager = JSON.parseObject(JSON.toJSONString(resultHolder.getData()), Pager.class); @@ -417,15 +347,15 @@ public class UserControllerTests extends BaseTest { //当前页码不大于0 BasePageRequest basePageRequest = new BasePageRequest(); 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 - basePageRequest = UserTestUtils.getDefaultPageRequest(); + basePageRequest = UserParamUtils.getDefaultPageRequest(); basePageRequest.setPageSize(250); - this.requestPost(UserTestUtils.URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER); + this.requestPost(userRequestUtils.URL_USER_PAGE, basePageRequest, BAD_REQUEST_MATCHER); //当前页数不大于5 basePageRequest = new BasePageRequest(); 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.setCurrent(1); @@ -433,7 +363,7 @@ public class UserControllerTests extends BaseTest { basePageRequest.setSort(new HashMap<>() {{ 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 @@ -447,47 +377,47 @@ public class UserControllerTests extends BaseTest { UserDTO checkDTO; //更改名字 user.setName("TEST-UPDATE"); - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); - response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); + response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); checkLog(response.getId(), OperationLogType.UPDATE); checkDTO = this.getUserByEmail(user.getEmail()); - UserTestUtils.compareUserDTO(response, checkDTO); + UserParamUtils.compareUserDTO(response, checkDTO); //更改邮箱 user.setEmail("songtianyang-test-email@12138.com"); - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); - response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); + response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); checkLog(response.getId(), OperationLogType.UPDATE); checkDTO = this.getUserByEmail(user.getEmail()); - UserTestUtils.compareUserDTO(response, checkDTO); + UserParamUtils.compareUserDTO(response, checkDTO); //更改手机号 user.setPhone("18511112222"); - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); - response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); + response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); checkLog(response.getId(), OperationLogType.UPDATE); checkDTO = this.getUserByEmail(user.getEmail()); - UserTestUtils.compareUserDTO(response, checkDTO); + UserParamUtils.compareUserDTO(response, checkDTO); //更改用户组(这里只改成用户成员权限) - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, - defaultUserRoleList.stream().filter(item -> StringUtils.equals(item.getId(), "member")).toList() + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, + 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()); checkLog(response.getId(), OperationLogType.UPDATE); - UserTestUtils.compareUserDTO(response, checkDTO); + UserParamUtils.compareUserDTO(response, checkDTO); //更改用户组(把上面的情况添加别的权限) - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); - response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); + response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); checkLog(response.getId(), OperationLogType.UPDATE); checkDTO = this.getUserByEmail(user.getEmail()); - UserTestUtils.compareUserDTO(response, checkDTO); + UserParamUtils.compareUserDTO(response, checkDTO); //用户信息复原 user = new UserCreateInfo(); BeanUtils.copyBean(user, USER_LIST.get(0)); - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); - response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); + response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); checkLog(response.getId(), OperationLogType.UPDATE); checkDTO = this.getUserByEmail(user.getEmail()); - UserTestUtils.compareUserDTO(response, checkDTO); + UserParamUtils.compareUserDTO(response, checkDTO); } @Test @@ -499,37 +429,37 @@ public class UserControllerTests extends BaseTest { //更改名字 BeanUtils.copyBean(user, USER_LIST.get(0)); user.setName(""); - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); - this.requestPost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER); + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); + this.requestPost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER); //email为空 BeanUtils.copyBean(user, USER_LIST.get(0)); user.setEmail(""); - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); - this.requestPost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER); + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); + this.requestPost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER); //手机号为空 BeanUtils.copyBean(user, USER_LIST.get(0)); user.setEmail(""); - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); - this.requestPost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER); + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); + this.requestPost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest, BAD_REQUEST_MATCHER); //用户组为空 BeanUtils.copyBean(user, USER_LIST.get(0)); - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, new ArrayList<>()); + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, 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验证 //邮箱重复 this.checkUserList(); BeanUtils.copyBean(user, USER_LIST.get(0)); user.setEmail(USER_LIST.get(USER_LIST.size() - 1).getEmail()); - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, defaultUserRoleList); - this.requestPost(UserTestUtils.URL_USER_UPDATE, userMaintainRequest, ERROR_REQUEST_MATCHER); + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); + this.requestPost(userRequestUtils.URL_USER_UPDATE, userMaintainRequest, ERROR_REQUEST_MATCHER); //用户组不包含系统成员 BeanUtils.copyBean(user, USER_LIST.get(0)); - userMaintainRequest = UserTestUtils.getUserUpdateDTO(user, - defaultUserRoleList.stream().filter(item -> !StringUtils.equals(item.getId(), "member")).toList() + userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, + 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 @@ -543,8 +473,8 @@ public class UserControllerTests extends BaseTest { this.add(userInfo.getId()); }}); userChangeEnableRequest.setEnable(false); - this.requestPost(UserTestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk()); - for(String item : userChangeEnableRequest.getUserIdList()){ + this.requestPost(userRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk()); + for (String item : userChangeEnableRequest.getUserIdList()) { checkLog(item, OperationLogType.UPDATE); } @@ -559,12 +489,12 @@ public class UserControllerTests extends BaseTest { //用户不存在 UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest(); 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<>() {{ 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;//导入返回值 //导入正常文件 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 userImportReportDTOByFile = userService.getUserExcelParseDTO(file); - response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); - UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值 + response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class); + UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值 List userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 - for (UserDTO item : userDTOList){ + for (UserDTO item : userDTOList) { checkLog(item.getId(), OperationLogType.ADD); } //导入空文件. 应当导入成功的数据为0 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)); - response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); + file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath)); + response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class); importSuccessData = 0; errorDataIndex = new int[]{}; - UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex); + UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex); //文件内没有一条合格数据 应当导入成功的数据为0 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)); - response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); + file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath)); + 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}; - UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex); + UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex); //邮箱和数据库里的重复 应当导入成功的数据为8 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); - response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); + response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class); importSuccessData = 8; errorDataIndex = new int[]{1, 7}; - UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex); + UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex); userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 - for (UserDTO item : userDTOList){ + for (UserDTO item : userDTOList) { checkLog(item.getId(), OperationLogType.ADD); } //文件内邮箱重复 应当导入成功的数据为8 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); - 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}; - UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex); + UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex); userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 - for (UserDTO item : userDTOList){ + for (UserDTO item : userDTOList) { checkLog(item.getId(), OperationLogType.ADD); } //文件不符合规范 应当导入成功的数据为0 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)); - response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); + file = new MockMultipartFile("file", "userImport.xlsx", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath)); + response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class); importSuccessData = 0; errorDataIndex = new int[]{}; - UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex); + UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex); //测试03版excel正常导入 应当导入成功的数据为10 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); - response = UserTestUtils.parseObjectFromMvcResult(this.responseFile(file), UserImportResponse.class); + response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(userRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class); importSuccessData = 10;//应该导入成功的数据数量 errorDataIndex = new int[]{};//出错数据的行数 - UserTestUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值 + UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值 userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 - for (UserDTO item : userDTOList){ + for (UserDTO item : userDTOList) { checkLog(item.getId(), OperationLogType.ADD); } } @@ -657,43 +587,97 @@ public class UserControllerTests extends BaseTest { String userId = USER_LIST.get(0).getId(); String userEmail = USER_LIST.get(0).getEmail(); //重置普通用户密码 - this.resetPasswordAndCheck(userId,userEmail); + this.resetPasswordAndCheck(userId, userEmail); this.checkLog(userId, OperationLogType.UPDATE); //重置admin的密码 - this.resetPasswordAndCheck("admin","metersphere"); + this.resetPasswordAndCheck("admin", "metersphere"); 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 @Order(8) 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 @Order(9) + public void testUserRoleRelationSuccess() throws Exception { + //UserList中的部分角色是没有添加到某权限中的 + if (USER_LIST.size() < 50) { + this.testAddSuccess(); + } + List 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 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 { this.checkUserList(); //删除已存的所有用户 UserBatchProcessRequest request = new UserBatchProcessRequest(); request.setUserIdList(USER_LIST.stream().map(UserCreateInfo::getId).collect(Collectors.toList())); - UserBatchProcessResponse response = UserTestUtils.parseObjectFromMvcResult(this.responsePost(UserTestUtils.URL_USER_DELETE, request), UserBatchProcessResponse.class); + 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.getSuccessCount()); //检查数据库 @@ -713,24 +697,54 @@ public class UserControllerTests extends BaseTest { //删除失败的方法要放在删除成功方法后面执行 @Test - @Order(10) + @Order(100) public void testUserDeleteError() throws Exception { //参数为空 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"); - 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(); } 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 checkImportUserInDb(ExcelParseDTO 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 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 checkImportUserInDb(ExcelParseDTO userImportReportDTOByFile) throws Exception { List returnList = new ArrayList<>(); for (UserExcelRowDTO item : userImportReportDTOByFile.getDataList()) { UserDTO userDTO = this.getUserByEmail(item.getEmail()); @@ -740,4 +754,18 @@ public class UserControllerTests extends BaseTest { 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); + } } diff --git a/backend/services/system-setting/src/test/java/io/metersphere/system/utils/UserTestUtils.java b/backend/services/system-setting/src/test/java/io/metersphere/system/utils/user/UserParamUtils.java similarity index 75% rename from backend/services/system-setting/src/test/java/io/metersphere/system/utils/UserTestUtils.java rename to backend/services/system-setting/src/test/java/io/metersphere/system/utils/user/UserParamUtils.java index 5827196611..96e27407c0 100644 --- a/backend/services/system-setting/src/test/java/io/metersphere/system/utils/UserTestUtils.java +++ b/backend/services/system-setting/src/test/java/io/metersphere/system/utils/user/UserParamUtils.java @@ -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.dto.BasePageRequest; @@ -24,32 +24,7 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.stream.Collectors; -public class UserTestUtils { - - //用户管理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 parseObjectFromMvcResult(MvcResult mvcResult, Class 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 class UserParamUtils { public static UserBatchCreateDTO getUserCreateDTO( List userRoleList, @@ -107,6 +82,8 @@ public class UserTestUtils { return buffer; } + + //用户信息对比 public static void compareUserDTO(UserEditRequest editRequest, UserDTO selectUserDTO) { Assertions.assertNotNull(editRequest); Assertions.assertNotNull(selectUserDTO); @@ -129,13 +106,14 @@ public class UserTestUtils { && selectUserSystemRoleId.containsAll(editRequest.getUserRoleIdList())); } + //导入结果判断 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) { Assertions.assertTrue(responsePost.getErrorMessages().containsKey(index)); diff --git a/backend/services/system-setting/src/test/java/io/metersphere/system/utils/user/UserRequestUtils.java b/backend/services/system-setting/src/test/java/io/metersphere/system/utils/user/UserRequestUtils.java new file mode 100644 index 0000000000..dcfffba0fa --- /dev/null +++ b/backend/services/system-setting/src/test/java/io/metersphere/system/utils/user/UserRequestUtils.java @@ -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 parseObjectFromMvcResult(MvcResult mvcResult, Class 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(); + } +}