From 2bb7b7a8af276b791e04081c6347119323d285f3 Mon Sep 17 00:00:00 2001 From: Jianguo-Genius Date: Thu, 30 May 2024 18:12:27 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E7=B3=BB=E7=BB=9F=E8=AE=BE=E7=BD=AE):=20?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=94=A8=E6=88=B7=E5=88=9B=E5=BB=BA=E7=9A=84?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/resources/i18n/system.properties | 2 + .../resources/i18n/system_en_US.properties | 2 + .../resources/i18n/system_zh_CN.properties | 2 + .../resources/i18n/system_zh_TW.properties | 4 +- .../service/schedule/SwaggerUrlImportJob.java | 6 +- .../controller/ProjectLogController.java | 6 +- .../controller/OperationLogController.java | 16 +- .../controller/OrganizationLogController.java | 6 +- .../controller/PersonalCenterController.java | 10 +- .../SystemOrganizationController.java | 6 +- .../controller/SystemProjectController.java | 6 +- .../system/controller/UserController.java | 24 +- .../controller/result/SystemResultCode.java | 3 + .../GlobalUserRoleRelationService.java | 18 +- ...serService.java => NormalUserService.java} | 86 +- .../system/service/UserLogService.java | 5 +- .../service/UserRoleRelationService.java | 52 - .../system/service/UserXpackService.java | 15 + .../user/PersonalControllerTests.java | 8 +- .../controller/user/UserControllerTests.java | 1461 ----------------- .../plan/service/TestPlanReportService.java | 6 +- 21 files changed, 120 insertions(+), 1624 deletions(-) rename backend/services/system-setting/src/main/java/io/metersphere/system/service/{UserService.java => NormalUserService.java} (90%) create mode 100644 backend/services/system-setting/src/main/java/io/metersphere/system/service/UserXpackService.java delete mode 100644 backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/UserControllerTests.java diff --git a/backend/framework/sdk/src/main/resources/i18n/system.properties b/backend/framework/sdk/src/main/resources/i18n/system.properties index 35532fbbfb..5a665407e1 100644 --- a/backend/framework/sdk/src/main/resources/i18n/system.properties +++ b/backend/framework/sdk/src/main/resources/i18n/system.properties @@ -322,6 +322,8 @@ operation_history.type.length_range=变更记录操作类型长度必须在{min} operation_history.source_id.not_blank=变更记录资源 ID 不能为空 operation_history.version_id.not_blank=变更记录版本 ID 不能为空 operation_history.version_id.length_range=变更记录版本 ID 长度必须在{min}和{max}之间 +user_open_source_max=系统用户数超额({num}人),继续添加用户可申请企业版适用 +user_dept_max=系统用户数超额({num}人),继续添加用户可申请企业版扩容 diff --git a/backend/framework/sdk/src/main/resources/i18n/system_en_US.properties b/backend/framework/sdk/src/main/resources/i18n/system_en_US.properties index 2aad412326..07b238ec89 100644 --- a/backend/framework/sdk/src/main/resources/i18n/system_en_US.properties +++ b/backend/framework/sdk/src/main/resources/i18n/system_en_US.properties @@ -325,4 +325,6 @@ operation_history.version_id.not_blank=Operating history version id cannot be em operation_history.version_id.length_range=Operating history version id length must be between {min} and {max} permission.organization_task_center.name=Task center permission.organization_task_center.stop=Stop task +user_open_source_max=There are too many users({num}),please apply for the enterprise version to use +user_dept_max=There are too many users({num}),please apply for enterprise version expansion diff --git a/backend/framework/sdk/src/main/resources/i18n/system_zh_CN.properties b/backend/framework/sdk/src/main/resources/i18n/system_zh_CN.properties index 58a9d4e180..e3b6915e67 100644 --- a/backend/framework/sdk/src/main/resources/i18n/system_zh_CN.properties +++ b/backend/framework/sdk/src/main/resources/i18n/system_zh_CN.properties @@ -327,3 +327,5 @@ operation_history.version_id.length_range=变更记录版本 ID 长度必须在{ permission.organization_task_center.name=任务中心 permission.organization_task_center.stop=停止 +user_open_source_max=系统用户数超额({0}人),继续添加用户可申请企业版适用 +user_dept_max=系统用户数超额({0}人),继续添加用户可申请企业版扩容 diff --git a/backend/framework/sdk/src/main/resources/i18n/system_zh_TW.properties b/backend/framework/sdk/src/main/resources/i18n/system_zh_TW.properties index 18a9a3aa05..7b3ce440d2 100644 --- a/backend/framework/sdk/src/main/resources/i18n/system_zh_TW.properties +++ b/backend/framework/sdk/src/main/resources/i18n/system_zh_TW.properties @@ -325,4 +325,6 @@ operation_history.version_id.not_blank=變更記錄版本 ID 不能為空 operation_history.version_id.length_range=變更記錄版本 ID 長度必須在{min}和{max}之間 permission.organization_task_center.name=任務中心 -permission.organization_task_center.stop=停止 \ No newline at end of file +permission.organization_task_center.stop=停止 +user_open_source_max=系統用戶數超額({num}人),繼續添加用戶可申請企業版適用 +user_dept_max=系統用戶數超額({num}人),繼續添加用戶可申請企業版擴容 \ No newline at end of file diff --git a/backend/services/api-test/src/main/java/io/metersphere/api/service/schedule/SwaggerUrlImportJob.java b/backend/services/api-test/src/main/java/io/metersphere/api/service/schedule/SwaggerUrlImportJob.java index ba44c1e7d6..73794d58e3 100644 --- a/backend/services/api-test/src/main/java/io/metersphere/api/service/schedule/SwaggerUrlImportJob.java +++ b/backend/services/api-test/src/main/java/io/metersphere/api/service/schedule/SwaggerUrlImportJob.java @@ -9,7 +9,7 @@ import io.metersphere.api.service.definition.ApiDefinitionScheduleService; import io.metersphere.sdk.util.BeanUtils; import io.metersphere.sdk.util.CommonBeanFactory; import io.metersphere.system.schedule.BaseScheduleJob; -import io.metersphere.system.service.UserService; +import io.metersphere.system.service.NormalUserService; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobKey; @@ -18,12 +18,12 @@ import org.quartz.TriggerKey; public class SwaggerUrlImportJob extends BaseScheduleJob { private ApiDefinitionImportUtilService apiDefinitionImportUtilService; private ApiDefinitionScheduleService apiDefinitionScheduleService; - private UserService userService; + private NormalUserService normalUserService; public SwaggerUrlImportJob() { apiDefinitionImportUtilService = CommonBeanFactory.getBean(ApiDefinitionImportUtilService.class); apiDefinitionScheduleService = CommonBeanFactory.getBean(ApiDefinitionScheduleService.class); - userService = CommonBeanFactory.getBean(UserService.class); + normalUserService = CommonBeanFactory.getBean(NormalUserService.class); } @Override diff --git a/backend/services/project-management/src/main/java/io/metersphere/project/controller/ProjectLogController.java b/backend/services/project-management/src/main/java/io/metersphere/project/controller/ProjectLogController.java index 4716e6d800..12dcf2161b 100644 --- a/backend/services/project-management/src/main/java/io/metersphere/project/controller/ProjectLogController.java +++ b/backend/services/project-management/src/main/java/io/metersphere/project/controller/ProjectLogController.java @@ -10,7 +10,7 @@ import io.metersphere.system.log.service.OperationLogService; import io.metersphere.system.log.vo.OperationLogResponse; import io.metersphere.system.log.vo.ProOperationLogRequest; import io.metersphere.system.log.vo.SystemOperationLogRequest; -import io.metersphere.system.service.UserService; +import io.metersphere.system.service.NormalUserService; import io.metersphere.system.utils.PageUtils; import io.metersphere.system.utils.Pager; import io.metersphere.system.utils.SessionUtils; @@ -37,7 +37,7 @@ import java.util.List; public class ProjectLogController { @Autowired - private UserService userService; + private NormalUserService normalUserService; @Autowired private OperationLogService operationLogService; @@ -48,7 +48,7 @@ public class ProjectLogController { public List getUserList(@PathVariable(value = "projectId") String projectId, @Schema(description = "查询关键字,根据邮箱和用户名查询") @RequestParam(value = "keyword", required = false) String keyword) { - return userService.getUserListByOrgId(StringUtils.defaultIfBlank(projectId, SessionUtils.getCurrentProjectId()), keyword); + return normalUserService.getUserListByOrgId(StringUtils.defaultIfBlank(projectId, SessionUtils.getCurrentProjectId()), keyword); } diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/OperationLogController.java b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/OperationLogController.java index 0baaff35f6..a311e33623 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/OperationLogController.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/OperationLogController.java @@ -4,17 +4,17 @@ package io.metersphere.system.controller; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import io.metersphere.sdk.constants.PermissionConstants; -import io.metersphere.system.log.service.OperationLogService; -import io.metersphere.system.log.vo.SystemOperationLogRequest; -import io.metersphere.system.log.vo.OperationLogResponse; -import io.metersphere.system.utils.PageUtils; -import io.metersphere.system.utils.Pager; import io.metersphere.system.domain.User; import io.metersphere.system.dto.OrganizationProjectOptionsDTO; import io.metersphere.system.dto.response.OrganizationProjectOptionsResponse; +import io.metersphere.system.log.service.OperationLogService; +import io.metersphere.system.log.vo.OperationLogResponse; +import io.metersphere.system.log.vo.SystemOperationLogRequest; +import io.metersphere.system.service.NormalUserService; import io.metersphere.system.service.OrganizationService; import io.metersphere.system.service.SystemProjectService; -import io.metersphere.system.service.UserService; +import io.metersphere.system.utils.PageUtils; +import io.metersphere.system.utils.Pager; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.tags.Tag; @@ -41,7 +41,7 @@ public class OperationLogController { private OperationLogService operationLogService; @Resource - private UserService userService; + private NormalUserService normalUserService; @GetMapping("/get/options") @@ -77,7 +77,7 @@ public class OperationLogController { @RequiresPermissions(PermissionConstants.SYSTEM_LOG_READ) public List getUserList(@Schema(description = "查询关键字,根据邮箱和用户名查询") @RequestParam(value = "keyword", required = false) String keyword) { - List userList = userService.getUserList(keyword); + List userList = normalUserService.getUserList(keyword); return userList; } } diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/OrganizationLogController.java b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/OrganizationLogController.java index d14da9c969..09d5595344 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/OrganizationLogController.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/OrganizationLogController.java @@ -12,8 +12,8 @@ import io.metersphere.system.log.service.OperationLogService; import io.metersphere.system.log.vo.OperationLogResponse; import io.metersphere.system.log.vo.OrgOperationLogRequest; import io.metersphere.system.log.vo.SystemOperationLogRequest; +import io.metersphere.system.service.NormalUserService; import io.metersphere.system.service.SystemProjectService; -import io.metersphere.system.service.UserService; import io.metersphere.system.utils.PageUtils; import io.metersphere.system.utils.Pager; import io.metersphere.system.utils.SessionUtils; @@ -45,7 +45,7 @@ public class OrganizationLogController { private OperationLogService operationLogService; @Resource - private UserService userService; + private NormalUserService normalUserService; @GetMapping("/get/options/{organizationId}") @@ -67,7 +67,7 @@ public class OrganizationLogController { public List getLogUserList(@PathVariable(value = "organizationId") String organizationId, @Schema(description = "查询关键字,根据邮箱和用户名查询") @RequestParam(value = "keyword", required = false) String keyword) { - return userService.getUserListByOrgId(organizationId, keyword); + return normalUserService.getUserListByOrgId(organizationId, keyword); } diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/PersonalCenterController.java b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/PersonalCenterController.java index 3666ba3f37..c6f85c193a 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/PersonalCenterController.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/PersonalCenterController.java @@ -6,8 +6,8 @@ import io.metersphere.system.dto.request.user.PersonalUpdateRequest; import io.metersphere.system.dto.user.PersonalDTO; import io.metersphere.system.log.annotation.Log; import io.metersphere.system.log.constants.OperationLogType; +import io.metersphere.system.service.NormalUserService; import io.metersphere.system.service.UserLogService; -import io.metersphere.system.service.UserService; import io.metersphere.system.utils.SessionUtils; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; @@ -23,13 +23,13 @@ public class PersonalCenterController { @Resource - private UserService userService; + private NormalUserService normalUserService; @GetMapping("/get/{id}") @Operation(summary = "个人中心-获取信息") public PersonalDTO getInformation(@PathVariable String id) { this.checkPermission(id); - return userService.getPersonalById(id); + return normalUserService.getPersonalById(id); } @PostMapping("/update-info") @@ -37,7 +37,7 @@ PersonalCenterController { @Log(type = OperationLogType.UPDATE, expression = "#msClass.updateAccountLog(#request)", msClass = UserLogService.class) public boolean updateUser(@Validated @RequestBody PersonalUpdateRequest request) { this.checkPermission(request.getId()); - return userService.updateAccount(request, SessionUtils.getUserId()); + return normalUserService.updateAccount(request, SessionUtils.getUserId()); } @PostMapping("/update-password") @@ -45,7 +45,7 @@ PersonalCenterController { @Log(type = OperationLogType.UPDATE, expression = "#msClass.updatePasswordLog(#request)", msClass = UserLogService.class) public String updateUser(@Validated @RequestBody PersonalUpdatePasswordRequest request) { this.checkPermission(request.getId()); - if (userService.updatePassword(request)) { + if (normalUserService.updatePassword(request)) { SessionUtils.kickOutUser(SessionUtils.getUser().getId()); } return "OK"; diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/SystemOrganizationController.java b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/SystemOrganizationController.java index 23ed6ce14b..f14bd3345d 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/SystemOrganizationController.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/SystemOrganizationController.java @@ -11,10 +11,10 @@ import io.metersphere.system.dto.sdk.OptionDTO; import io.metersphere.system.dto.user.UserExtendDTO; import io.metersphere.system.log.annotation.Log; import io.metersphere.system.log.constants.OperationLogType; +import io.metersphere.system.service.NormalUserService; import io.metersphere.system.service.OrganizationService; import io.metersphere.system.service.SystemOrganizationLogService; import io.metersphere.system.service.SystemProjectService; -import io.metersphere.system.service.UserService; import io.metersphere.system.utils.PageUtils; import io.metersphere.system.utils.Pager; import io.metersphere.system.utils.SessionUtils; @@ -43,7 +43,7 @@ import java.util.Map; public class SystemOrganizationController { @Resource - private UserService userService; + private NormalUserService normalUserService; @Resource private SystemProjectService systemProjectService; @Resource @@ -182,6 +182,6 @@ public class SystemOrganizationController { public List getMemberOption(@PathVariable String sourceId, @Schema(description = "查询关键字,根据邮箱和用户名查询") @RequestParam(value = "keyword", required = false) String keyword) { - return userService.getMemberOption(sourceId, keyword); + return normalUserService.getMemberOption(sourceId, keyword); } } diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/SystemProjectController.java b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/SystemProjectController.java index 8f398e74a8..821c92cc0f 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/SystemProjectController.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/SystemProjectController.java @@ -15,9 +15,9 @@ import io.metersphere.system.dto.user.UserExtendDTO; import io.metersphere.system.log.annotation.Log; import io.metersphere.system.log.constants.OperationLogType; import io.metersphere.system.security.CheckOwner; +import io.metersphere.system.service.NormalUserService; import io.metersphere.system.service.SystemProjectLogService; import io.metersphere.system.service.SystemProjectService; -import io.metersphere.system.service.UserService; import io.metersphere.system.utils.PageUtils; import io.metersphere.system.utils.Pager; import io.metersphere.system.utils.SessionUtils; @@ -43,7 +43,7 @@ public class SystemProjectController { @Resource private SystemProjectService systemProjectService; @Resource - private UserService userService; + private NormalUserService normalUserService; @PostMapping("/add") @RequiresPermissions(PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ_ADD) @@ -156,7 +156,7 @@ public class SystemProjectController { @RequiresPermissions(PermissionConstants.SYSTEM_ORGANIZATION_PROJECT_READ) public List getUserList(@Schema(description = "查询关键字,根据邮箱和用户名查询") @RequestParam(value = "keyword", required = false) String keyword) { - return userService.getUserList(keyword); + return normalUserService.getUserList(keyword); } @PostMapping("/pool-options") 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 86a34264eb..fd4dcddb15 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 @@ -49,7 +49,7 @@ import java.util.Map; @RequestMapping("/system/user") public class UserController { @Resource - private UserService userService; + private NormalUserService normalUserService; @Resource private UserToolService userToolService; @Resource @@ -67,14 +67,14 @@ public class UserController { @Operation(summary = "通过email或id查找用户") @RequiresPermissions(PermissionConstants.SYSTEM_USER_READ) public UserDTO getUser(@PathVariable String keyword) { - return userService.getUserDTOByKeyword(keyword); + return normalUserService.getUserDTOByKeyword(keyword); } @PostMapping("/add") @Operation(summary = "系统设置-系统-用户-添加用户") @RequiresPermissions(PermissionConstants.SYSTEM_USER_ADD) public UserBatchCreateResponse addUser(@Validated({Created.class}) @RequestBody UserBatchCreateRequest userCreateDTO) { - return userService.addUser(userCreateDTO, UserSource.LOCAL.name(), SessionUtils.getUserId()); + return normalUserService.addUser(userCreateDTO, UserSource.LOCAL.name(), SessionUtils.getUserId()); } @PostMapping("/update") @@ -82,7 +82,7 @@ public class UserController { @RequiresPermissions(PermissionConstants.SYSTEM_USER_UPDATE) @Log(type = OperationLogType.UPDATE, expression = "#msClass.updateLog(#request)", msClass = UserLogService.class) public UserEditRequest updateUser(@Validated({Updated.class}) @RequestBody UserEditRequest request) { - return userService.updateUser(request, SessionUtils.getUserId()); + return normalUserService.updateUser(request, SessionUtils.getUserId()); } @PostMapping("/page") @@ -91,7 +91,7 @@ public class UserController { public Pager> list(@Validated @RequestBody BasePageRequest request) { Page page = PageHelper.startPage(request.getCurrent(), request.getPageSize(), StringUtils.isNotBlank(request.getSortString("id")) ? request.getSortString("id") : "create_time desc,id desc"); - return PageUtils.setPageInfo(page, userService.list(request)); + return PageUtils.setPageInfo(page, normalUserService.list(request)); } @PostMapping("/update/enable") @@ -99,14 +99,14 @@ public class UserController { @RequiresPermissions(PermissionConstants.SYSTEM_USER_UPDATE) @Log(type = OperationLogType.UPDATE, expression = "#msClass.batchUpdateEnableLog(#request)", msClass = UserLogService.class) public TableBatchProcessResponse updateUserEnable(@Validated @RequestBody UserChangeEnableRequest request) { - return userService.updateUserEnable(request, SessionUtils.getUserId(), SessionUtils.getUser().getName()); + return normalUserService.updateUserEnable(request, SessionUtils.getUserId(), SessionUtils.getUser().getName()); } @PostMapping(value = "/import", consumes = {"multipart/form-data"}) @Operation(summary = "系统设置-系统-用户-导入用户") @RequiresPermissions(PermissionConstants.SYSTEM_USER_IMPORT) public UserImportResponse importUser(@RequestPart(value = "file", required = false) MultipartFile excelFile) { - return userService.importByExcel(excelFile, UserSource.LOCAL.name(), SessionUtils.getUserId()); + return normalUserService.importByExcel(excelFile, UserSource.LOCAL.name(), SessionUtils.getUserId()); } @PostMapping("/delete") @@ -114,7 +114,7 @@ public class UserController { @Log(type = OperationLogType.DELETE, expression = "#msClass.deleteLog(#request)", msClass = UserLogService.class) @RequiresPermissions(PermissionConstants.SYSTEM_USER_DELETE) public TableBatchProcessResponse deleteUser(@Validated @RequestBody TableBatchProcessDTO request) { - return userService.deleteUser(request, SessionUtils.getUserId(), SessionUtils.getUser().getName()); + return normalUserService.deleteUser(request, SessionUtils.getUserId(), SessionUtils.getUser().getName()); } @PostMapping("/reset/password") @@ -122,7 +122,7 @@ public class UserController { @RequiresPermissions(PermissionConstants.SYSTEM_USER_UPDATE) @Log(type = OperationLogType.UPDATE, expression = "#msClass.resetPasswordLog(#request)", msClass = UserLogService.class) public TableBatchProcessResponse resetPassword(@Validated @RequestBody TableBatchProcessDTO request) { - return userService.resetPassword(request, SessionUtils.getUserId()); + return normalUserService.resetPassword(request, SessionUtils.getUserId()); } @GetMapping("/get/global/system/role") @@ -186,18 +186,18 @@ public class UserController { @Operation(summary = "系统设置-系统-用户-邀请用户注册") @RequiresPermissions(PermissionConstants.SYSTEM_USER_INVITE) public UserInviteResponse invite(@Validated @RequestBody UserInviteRequest request) { - return userService.saveInviteRecord(request, SessionUtils.getUser()); + return normalUserService.saveInviteRecord(request, SessionUtils.getUser()); } @GetMapping("/check-invite/{inviteId}") @Operation(summary = "系统设置-系统-用户-用户接受注册邀请并创建账户") public void checkInviteNum(@PathVariable String inviteId) { - userService.getUserInviteAndCheckEfficient(inviteId); + normalUserService.getUserInviteAndCheckEfficient(inviteId); } @PostMapping("/register-by-invite") @Operation(summary = "系统设置-系统-用户-用户接受注册邀请并创建账户") public String registerByInvite(@Validated @RequestBody UserRegisterRequest request) throws Exception { - return userService.registerByInvite(request); + return normalUserService.registerByInvite(request); } } diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/result/SystemResultCode.java b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/result/SystemResultCode.java index 5e62aa69c2..c7b31f9116 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/controller/result/SystemResultCode.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/controller/result/SystemResultCode.java @@ -7,6 +7,9 @@ import io.metersphere.sdk.exception.IResultCode; */ public enum SystemResultCode implements IResultCode { + USER_TOO_MANY(101511, "User too many"), + DEPT_USER_TOO_MANY(101512, "Department user too many"), + /** * 调用获取全局用户组接口,如果操作的是非全局的用户组,会返回该响应码 */ 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 f553c6be50..a8919789d7 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,20 +1,20 @@ package io.metersphere.system.service; import io.metersphere.sdk.constants.UserRoleScope; -import io.metersphere.system.dto.table.TableBatchProcessResponse; -import io.metersphere.system.dto.user.UserExcludeOptionDTO; -import io.metersphere.system.dto.user.UserRoleRelationUserDTO; -import io.metersphere.system.dto.sdk.request.GlobalUserRoleRelationUpdateRequest; import io.metersphere.sdk.exception.MSException; -import io.metersphere.system.uid.IDGenerator; 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.system.dto.request.user.UserRoleBatchRelationRequest; +import io.metersphere.system.dto.sdk.request.GlobalUserRoleRelationUpdateRequest; +import io.metersphere.system.dto.table.TableBatchProcessResponse; +import io.metersphere.system.dto.user.UserExcludeOptionDTO; +import io.metersphere.system.dto.user.UserRoleRelationUserDTO; +import io.metersphere.system.mapper.ExtUserRoleRelationMapper; +import io.metersphere.system.uid.IDGenerator; import io.metersphere.validation.groups.Created; import io.metersphere.validation.groups.Updated; import jakarta.annotation.Resource; @@ -41,7 +41,7 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService { @Resource private GlobalUserRoleService globalUserRoleService; @Resource - private UserService userService; + private NormalUserService normalUserService; @Resource private UserToolService userToolService; @Resource @@ -71,7 +71,7 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService { this.checkGlobalSystemUserRoleLegality( Collections.singletonList(request.getRoleId())); //检查用户的合法性 - userService.checkUserLegality(request.getUserIds()); + normalUserService.checkUserLegality(request.getUserIds()); List userRoleRelations = new ArrayList<>(); request.getUserIds().forEach(userId -> { UserRoleRelation userRoleRelation = new UserRoleRelation(); @@ -100,7 +100,7 @@ public class GlobalUserRoleRelationService extends BaseUserRoleRelationService { //获取本次处理的用户 request.setSelectIds(userToolService.getBatchUserIds(request)); //检查用户的合法性 - userService.checkUserLegality(request.getSelectIds()); + normalUserService.checkUserLegality(request.getSelectIds()); List savedUserRoleRelation = this.selectByUserIdAndRuleId(request.getSelectIds(), request.getRoleIds()); //过滤已经存储过的用户关系 Map> userRoleIdMap = savedUserRoleRelation.stream() 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/NormalUserService.java similarity index 90% rename from backend/services/system-setting/src/main/java/io/metersphere/system/service/UserService.java rename to backend/services/system-setting/src/main/java/io/metersphere/system/service/NormalUserService.java index 71b46d615f..7d4ea3a32e 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/NormalUserService.java @@ -2,9 +2,9 @@ package io.metersphere.system.service; import com.alibaba.excel.EasyExcelFactory; import io.metersphere.sdk.constants.ParamConstants; -import io.metersphere.sdk.constants.UserSource; import io.metersphere.sdk.exception.MSException; import io.metersphere.sdk.util.*; +import io.metersphere.system.controller.result.SystemResultCode; import io.metersphere.system.domain.*; import io.metersphere.system.dto.excel.UserExcel; import io.metersphere.system.dto.excel.UserExcelRowDTO; @@ -32,7 +32,6 @@ import io.metersphere.system.dto.user.response.UserTableResponse; import io.metersphere.system.log.service.OperationLogService; import io.metersphere.system.mapper.*; import io.metersphere.system.notice.sender.impl.MailNoticeSender; -import io.metersphere.system.uid.IDGenerator; import io.metersphere.system.utils.SessionUtils; import io.metersphere.system.utils.UserImportEventListener; import jakarta.annotation.Resource; @@ -63,7 +62,7 @@ import java.util.stream.Collectors; @Service @Transactional(rollbackFor = Exception.class) -public class UserService { +public class NormalUserService { @Resource private BaseUserMapper baseUserMapper; @Resource @@ -131,29 +130,17 @@ public class UserService { } private List saveUserAndRole(UserBatchCreateRequest userCreateDTO, String source, String operator, String requestPath) { - List insertList = new ArrayList<>(); - long createTime = System.currentTimeMillis(); - List saveUserList = new ArrayList<>(); - //添加用户 - for (UserCreateInfo userInfo : userCreateDTO.getUserInfoList()) { - userInfo.setId(IDGenerator.nextStr()); - User user = new User(); - BeanUtils.copyBean(user, userInfo); - user.setCreateUser(operator); - user.setCreateTime(createTime); - user.setUpdateUser(operator); - user.setUpdateTime(createTime); - user.setPassword(CodingUtils.md5(user.getEmail())); - user.setSource(source); - user.setDeleted(false); - userMapper.insertSelective(user); - saveUserList.add(user); - insertList.add(userInfo); + int responseCode = Objects.requireNonNull(CommonBeanFactory.getBean(UserXpackService.class)).guessWhatHowToAddUser(userCreateDTO, source, operator); + if (responseCode == 0) { + operationLogService.batchAdd(userLogService.getBatchAddLogs(userCreateDTO.getUserInfoList(), operator, requestPath)); + } else { + if (responseCode == -1) { + throw new MSException(SystemResultCode.USER_TOO_MANY, Translator.getWithArgs("user_open_source_max", 30)); + } else { + throw new MSException(SystemResultCode.DEPT_USER_TOO_MANY, Translator.getWithArgs("user_dept_max", responseCode)); + } } - userRoleRelationService.batchSave(userCreateDTO.getUserRoleIdList(), saveUserList); - //写入操作日志 - operationLogService.batchAdd(userLogService.getBatchAddLogs(saveUserList, requestPath)); - return insertList; + return userCreateDTO.getUserInfoList(); } public UserDTO getUserDTOByKeyword(String email) { @@ -277,15 +264,16 @@ public class UserService { } UserImportResponse importResponse = new UserImportResponse(); + ExcelParseDTO excelParseDTO = new ExcelParseDTO<>(); try { - ExcelParseDTO excelParseDTO = this.getUserExcelParseDTO(excelFile); - if (CollectionUtils.isNotEmpty(excelParseDTO.getDataList())) { - this.saveUserByExcelData(excelParseDTO.getDataList(), source, sessionId); - } - importResponse.generateResponse(excelParseDTO); + excelParseDTO = this.getUserExcelParseDTO(excelFile); } catch (Exception e) { LogUtils.info("import user error", e); } + if (CollectionUtils.isNotEmpty(excelParseDTO.getDataList())) { + this.saveUserByExcelData(excelParseDTO.getDataList(), source, sessionId); + } + importResponse.generateResponse(excelParseDTO); return importResponse; } @@ -297,7 +285,6 @@ public class UserService { /** * 校验excel导入的数据是否与数据库中的数据冲突 - * */ private ExcelParseDTO validateExcelUserInfo(@Valid @NotNull ExcelParseDTO excelParseDTO) { List prepareSaveList = excelParseDTO.getDataList(); @@ -540,28 +527,23 @@ public class UserService { this.add(userInvite.getEmail()); }}); - //创建用户 - long createTime = System.currentTimeMillis(); - User user = new User(); - user.setId(IDGenerator.nextStr()); - user.setEmail(userInvite.getEmail()); - user.setPassword(CodingUtils.md5(RsaUtils.privateDecrypt(request.getPassword(), RsaUtils.getRsaKey().getPrivateKey()))); - user.setName(request.getName()); - user.setPhone(request.getPhone()); - user.setCreateUser(userInvite.getInviteUser()); - user.setUpdateUser(userInvite.getInviteUser()); - user.setCreateTime(createTime); - user.setUpdateTime(createTime); - user.setSource(UserSource.LOCAL.name()); - user.setDeleted(false); - userMapper.insertSelective(user); + int responseCode = Objects.requireNonNull(CommonBeanFactory.getBean(UserXpackService.class)).guessWhatHowToAddUser(request, userInvite); + if (responseCode == 0) { + //删除本次邀请记录 + userInviteService.deleteInviteById(userInvite.getId()); + //写入操作日志 + UserExample userExample = new UserExample(); + userExample.createCriteria().andEmailEqualTo(userInvite.getEmail()); + userLogService.addRegisterLog(userMapper.selectByExample(userExample).getFirst(), userInvite); + return userInvite.getEmail(); + } else { + if (responseCode > 30) { + throw new MSException(SystemResultCode.DEPT_USER_TOO_MANY, Translator.getWithArgs("user_dept_max", responseCode)); + } else { + throw new MSException(SystemResultCode.USER_TOO_MANY, Translator.getWithArgs("user_open_source_max", responseCode)); - userRoleRelationService.batchSave(JSON.parseArray(userInvite.getRoles(), String.class), user); - //删除本次邀请记录 - userInviteService.deleteInviteById(userInvite.getId()); - //写入操作日志 - userLogService.addRegisterLog(user, userInvite); - return user.getId(); + } + } } public boolean updateAccount(PersonalUpdateRequest request, String operator) { diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserLogService.java b/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserLogService.java index 1dde9ba892..933b1682f4 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserLogService.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserLogService.java @@ -11,6 +11,7 @@ import io.metersphere.system.domain.*; import io.metersphere.system.dto.builder.LogDTOBuilder; import io.metersphere.system.dto.request.user.*; import io.metersphere.system.dto.table.TableBatchProcessDTO; +import io.metersphere.system.dto.user.UserCreateInfo; import io.metersphere.system.log.constants.OperationLogModule; import io.metersphere.system.log.constants.OperationLogType; import io.metersphere.system.log.dto.LogDTO; @@ -45,7 +46,7 @@ public class UserLogService { private UserRoleMapper userRoleMapper; //批量添加用户记录日志 - public List getBatchAddLogs(@Valid List userList, String requestPath) { + public List getBatchAddLogs(@Valid List userList, String operator, String requestPath) { List logs = new ArrayList<>(); userList.forEach(user -> { LogDTO log = LogDTOBuilder.builder() @@ -58,7 +59,7 @@ public class UserLogService { .sourceId(user.getId()) .content(user.getName() + "(" + user.getEmail() + ")") .originalValue(JSON.toJSONBytes(user)) - .createUser(user.getCreateUser()) + .createUser(operator) .build().getLogDTO(); logs.add(log); }); diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserRoleRelationService.java b/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserRoleRelationService.java index 309dce324c..20f2b29cf0 100644 --- a/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserRoleRelationService.java +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserRoleRelationService.java @@ -23,10 +23,7 @@ import jakarta.validation.Valid; import jakarta.validation.constraints.NotEmpty; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.ibatis.session.ExecutorType; -import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -82,55 +79,6 @@ public class UserRoleRelationService { return logs; } - public void batchSave(List userRoleIdList, List userList) { - long operationTime = System.currentTimeMillis(); - List userRoleRelationSaveList = new ArrayList<>(); - //添加用户组织关系 - for (String userRoleId : userRoleIdList) { - for (User user : userList) { - UserRoleRelation userRoleRelation = new UserRoleRelation(); - userRoleRelation.setId(IDGenerator.nextStr()); - userRoleRelation.setUserId(user.getId()); - userRoleRelation.setRoleId(userRoleId); - userRoleRelation.setSourceId(UserRoleScope.SYSTEM); - userRoleRelation.setCreateTime(operationTime); - userRoleRelation.setCreateUser(user.getCreateUser()); - userRoleRelation.setOrganizationId(UserRoleScope.SYSTEM); - userRoleRelationSaveList.add(userRoleRelation); - } - } - SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH); - UserRoleRelationMapper batchSaveMapper = sqlSession.getMapper(UserRoleRelationMapper.class); - int insertIndex = 0; - for (UserRoleRelation userRoleRelation : userRoleRelationSaveList) { - batchSaveMapper.insert(userRoleRelation); - insertIndex++; - if (insertIndex % 50 == 0) { - sqlSession.flushStatements(); - } - } - sqlSession.flushStatements(); - SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory); - } - - public void batchSave(List userRoleIdList, User user) { - long operationTime = System.currentTimeMillis(); - List userRoleRelationSaveList = new ArrayList<>(); - //添加用户组织关系 - for (String userRoleId : userRoleIdList) { - UserRoleRelation userRoleRelation = new UserRoleRelation(); - userRoleRelation.setId(IDGenerator.nextStr()); - userRoleRelation.setUserId(user.getId()); - userRoleRelation.setRoleId(userRoleId); - userRoleRelation.setSourceId(UserRoleScope.SYSTEM); - userRoleRelation.setOrganizationId(UserRoleScope.SYSTEM); - userRoleRelation.setCreateTime(operationTime); - userRoleRelation.setCreateUser(user.getCreateUser()); - userRoleRelationSaveList.add(userRoleRelation); - } - userRoleRelationMapper.batchInsert(userRoleRelationSaveList); - } - public Map> selectOrganizationProjectByUserId(String userId) { Map> returnMap = new LinkedHashMap<>(); UserRoleRelationExample example = new UserRoleRelationExample(); diff --git a/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserXpackService.java b/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserXpackService.java new file mode 100644 index 0000000000..35586c5d2a --- /dev/null +++ b/backend/services/system-setting/src/main/java/io/metersphere/system/service/UserXpackService.java @@ -0,0 +1,15 @@ +package io.metersphere.system.service; + +import io.metersphere.system.domain.UserInvite; +import io.metersphere.system.dto.request.UserRegisterRequest; +import io.metersphere.system.dto.user.request.UserBatchCreateRequest; + +/** + * 系统用户相关接口 + */ +public interface UserXpackService { + + int guessWhatHowToAddUser(UserBatchCreateRequest userCreateDTO, String source, String operator); + + int guessWhatHowToAddUser(UserRegisterRequest registerRequest, UserInvite userInvite) throws Exception; +} diff --git a/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/PersonalControllerTests.java b/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/PersonalControllerTests.java index 9947d8b1d9..6f931bec7a 100644 --- a/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/PersonalControllerTests.java +++ b/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/PersonalControllerTests.java @@ -15,7 +15,7 @@ import io.metersphere.system.dto.user.UserDTO; import io.metersphere.system.log.constants.OperationLogType; import io.metersphere.system.mapper.UserExtendMapper; import io.metersphere.system.mapper.UserMapper; -import io.metersphere.system.service.UserService; +import io.metersphere.system.service.NormalUserService; import io.metersphere.system.uid.IDGenerator; import io.metersphere.system.utils.user.PersonalRequestUtils; import jakarta.annotation.Resource; @@ -39,7 +39,7 @@ public class PersonalControllerTests extends BaseTest { @Resource private UserMapper userMapper; @Resource - private UserService userService; + private NormalUserService normalUserService; @Test @Order(0) @@ -63,7 +63,7 @@ public class PersonalControllerTests extends BaseTest { @Order(1) void testPersonalUpdateInfo() throws Exception { //方法测试 - userService.checkUserEmail(IDGenerator.nextStr(), "admin_update@metersphere.io"); + normalUserService.checkUserEmail(IDGenerator.nextStr(), "admin_update@metersphere.io"); PersonalUpdateRequest request = new PersonalUpdateRequest(); request.setId(loginUser); @@ -76,7 +76,7 @@ public class PersonalControllerTests extends BaseTest { boolean methodCheck = false; try { - userService.checkUserEmail(IDGenerator.nextStr(), "admin_update@metersphere.io"); + normalUserService.checkUserEmail(IDGenerator.nextStr(), "admin_update@metersphere.io"); } catch (Exception e) { methodCheck = true; } diff --git a/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/UserControllerTests.java b/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/UserControllerTests.java deleted file mode 100644 index c37a70fd6c..0000000000 --- a/backend/services/system-setting/src/test/java/io/metersphere/system/controller/user/UserControllerTests.java +++ /dev/null @@ -1,1461 +0,0 @@ -package io.metersphere.system.controller.user; - -import com.jayway.jsonpath.JsonPath; -import io.metersphere.project.domain.Project; -import io.metersphere.project.mapper.ProjectMapper; -import io.metersphere.sdk.constants.SessionConstants; -import io.metersphere.sdk.util.BeanUtils; -import io.metersphere.sdk.util.CodingUtils; -import io.metersphere.sdk.util.JSON; -import io.metersphere.sdk.util.RsaUtils; -import io.metersphere.system.base.BaseTest; -import io.metersphere.system.controller.handler.ResultHolder; -import io.metersphere.system.domain.User; -import io.metersphere.system.domain.UserExample; -import io.metersphere.system.domain.UserInvite; -import io.metersphere.system.domain.UserRoleRelationExample; -import io.metersphere.system.dto.excel.UserExcelRowDTO; -import io.metersphere.system.dto.request.UserInviteRequest; -import io.metersphere.system.dto.request.UserRegisterRequest; -import io.metersphere.system.dto.request.user.UserChangeEnableRequest; -import io.metersphere.system.dto.request.user.UserEditRequest; -import io.metersphere.system.dto.request.user.UserRoleBatchRelationRequest; -import io.metersphere.system.dto.sdk.BasePageRequest; -import io.metersphere.system.dto.sdk.BaseTreeNode; -import io.metersphere.system.dto.sdk.ExcelParseDTO; -import io.metersphere.system.dto.table.TableBatchProcessDTO; -import io.metersphere.system.dto.table.TableBatchProcessResponse; -import io.metersphere.system.dto.user.UserCreateInfo; -import io.metersphere.system.dto.user.UserDTO; -import io.metersphere.system.dto.user.request.UserBatchCreateRequest; -import io.metersphere.system.dto.user.response.*; -import io.metersphere.system.log.constants.OperationLogType; -import io.metersphere.system.mapper.UserInviteMapper; -import io.metersphere.system.mapper.UserMapper; -import io.metersphere.system.mapper.UserRoleRelationMapper; -import io.metersphere.system.service.GlobalUserRoleRelationService; -import io.metersphere.system.service.UserInviteService; -import io.metersphere.system.service.UserService; -import io.metersphere.system.service.UserToolService; -import io.metersphere.system.uid.IDGenerator; -import io.metersphere.system.utils.Pager; -import io.metersphere.system.utils.user.UserParamUtils; -import io.metersphere.system.utils.user.UserRequestUtils; -import jakarta.annotation.Resource; -import lombok.AllArgsConstructor; -import lombok.Data; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpHeaders; -import org.junit.jupiter.api.*; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.mock.web.MockMultipartFile; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.jdbc.SqlConfig; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.ResultMatcher; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -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.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - - -@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT) -@AutoConfigureMockMvc -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class UserControllerTests extends BaseTest { - - @Resource - private UserService userService; - @Resource - private UserToolService userToolService; - @Resource - private UserMapper userMapper; - @Resource - private GlobalUserRoleRelationService globalUserRoleRelationService; - @Resource - ProjectMapper projectMapper; - @Resource - private UserRoleRelationMapper userRoleRelationMapper; - //邀请记录 - private static final List INVITE_RECORD_ID_LIST = new ArrayList<>(); - - //失败请求返回编码 - 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 USER_ROLE_LIST = new ArrayList<>(); - private static final List ORG_LIST = new ArrayList<>(); - private static final List PROJECT_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"; - public static final String USER_NONE_ROLE_EMAIL = "tianyang.none.role@163.com"; - //已删除的用户ID - private static final List DELETED_USER_ID_LIST = new ArrayList<>(); - @Resource - private UserInviteMapper userInviteMapper; - - UserRequestUtils userRequestUtils = null; - - private static final List LOG_CHECK_LIST = new ArrayList<>(); - - @Override - @BeforeEach - public void login() throws Exception { - if (userRequestUtils == null) { - super.login(); - userRequestUtils = new UserRequestUtils(mockMvc, sessionId, csrfToken); - } - } - - @Test - @Order(0) - void testGetGlobalSystemUserRoleSuccess() throws Exception { - MvcResult mvcResult = userRequestUtils.responseGet(UserRequestUtils.URL_GET_GLOBAL_SYSTEM); - this.setDefaultUserRoleList(mvcResult); - } - - @Test - @Order(1) - void testAddSuccess() throws Exception { - if (CollectionUtils.isEmpty(USER_ROLE_LIST)) { - this.testGetGlobalSystemUserRoleSuccess(); - } - //模拟前台批量添加用户 - UserBatchCreateRequest userMaintainRequest = UserParamUtils.getUserCreateDTO( - USER_ROLE_LIST, - new ArrayList<>() {{ - add(new UserCreateInfo() {{ - setName(USER_DEFAULT_NAME); - setEmail(USER_DEFAULT_EMAIL); - }}); - add(new UserCreateInfo() {{ - setName("tianyang.no.2"); - setEmail("tianyang.no.2@126.com"); - }}); - }} - ); - 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; - userCreateInfoList.add(new UserCreateInfo() {{ - setName("tianyang.no.batch" + finalI); - setEmail("tianyang.no.batch" + finalI + "@126.com"); - }}); - } - userMaintainRequest = UserParamUtils.getUserCreateDTO( - Collections.singletonList(USER_ROLE_LIST.getFirst()), - userCreateInfoList - ); - mvcResult = userRequestUtils.responsePost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest); - this.addUser2List(mvcResult); - - //含有重复的用户名称 - userMaintainRequest = UserParamUtils.getUserCreateDTO( - - USER_ROLE_LIST, - new ArrayList<>() {{ - add(new UserCreateInfo() {{ - setName("tianyang.repeat"); - setEmail("tianyang.repeat.name.1@126.com"); - }}); - add(new UserCreateInfo() {{ - setName("tianyang.repeat"); - setEmail("tianyang.repeat.name.2@126.com"); - }}); - }} - ); - mvcResult = userRequestUtils.responsePost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest); - this.addUser2List(mvcResult); - } - - @Test - @Order(2) - @Sql(scripts = {"/dml/init_user_controller_test.sql"}, - config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED), - executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) - void testGetByEmailSuccess() throws Exception { - this.checkUserList(); - UserDTO userDTO = this.getUserByEmail(USER_DEFAULT_EMAIL); - //返回值不为空 - Assertions.assertNotNull(userDTO); - //返回邮箱等于参数邮箱,且用户名合法 - Assertions.assertEquals(userDTO.getEmail(), USER_DEFAULT_EMAIL); - Assertions.assertNotNull(userDTO.getName()); - - //查询脏数据:没有关联任何组织的用户,也应该正常查询出来 - userDTO = this.getUserByEmail(USER_NONE_ROLE_EMAIL); - //返回值不为空 - Assertions.assertNotNull(userDTO); - //返回邮箱等于参数邮箱,且用户名合法 - Assertions.assertEquals(userDTO.getEmail(), USER_NONE_ROLE_EMAIL); - Assertions.assertNotNull(userDTO.getName()); - } - - private UserDTO getUserByEmail(String email) throws Exception { - String url = String.format(UserRequestUtils.URL_USER_GET, email); - return userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseGet(url), UserDTO.class); - } - - @Test - @Order(2) - void testGetByEmailError() throws Exception { - //测试使用任意参数,不能获取到任何用户信息 - this.checkUserList(); - String url = UserRequestUtils.URL_USER_GET + IDGenerator.nextNum(); - MvcResult mvcResult = userRequestUtils.responseGet(url); - - String returnData = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); - ResultHolder resultHolder = JSON.parseObject(returnData, ResultHolder.class); - //返回请求正常 - Assertions.assertNotNull(resultHolder); - //返回值为空 - Assertions.assertNull(resultHolder.getData()); - } - - @Test - @Order(3) - void testPageSuccess() throws Exception { - if (CollectionUtils.isEmpty(USER_ROLE_LIST)) { - this.testGetGlobalSystemUserRoleSuccess(); - } - - List userRoleIdList = USER_ROLE_LIST.stream().map(UserSelectOption::getId).toList(); - this.checkUserList(); - BasePageRequest basePageRequest = UserParamUtils.getDefaultPageRequest(); - - Pager returnPager = userRequestUtils.selectUserPage(basePageRequest); - //返回值不为空 - Assertions.assertNotNull(returnPager); - //返回值的页码和当前页码相同 - Assertions.assertEquals(returnPager.getCurrent(), basePageRequest.getCurrent()); - Assertions.assertEquals(returnPager.getPageSize(), basePageRequest.getPageSize()); - //返回的数据量不超过规定要返回的数据量相同 - Assertions.assertTrue(JSON.parseArray(JSON.toJSONString(returnPager.getList())).size() <= basePageRequest.getPageSize()); - List userList = JSON.parseArray(JSON.toJSONString(returnPager.getList()), UserTableResponse.class); - //用户组不存在非全局用户组 - for (UserTableResponse response : userList) { - if (CollectionUtils.isNotEmpty(response.getUserRoleList())) { - response.getUserRoleList().forEach(role -> Assertions.assertTrue(userRoleIdList.contains(role.getId()))); - } - } - - //页码为50 - basePageRequest = UserParamUtils.getDefaultPageRequest(); - basePageRequest.setPageSize(50); - returnPager = userRequestUtils.selectUserPage(basePageRequest); - //返回值不为空 - Assertions.assertNotNull(returnPager); - //返回值的页码和当前页码相同 - Assertions.assertEquals(returnPager.getCurrent(), basePageRequest.getCurrent()); - Assertions.assertEquals(returnPager.getPageSize(), basePageRequest.getPageSize()); - //返回的数据量不超过规定要返回的数据量相同 - Assertions.assertTrue(JSON.parseArray(JSON.toJSONString(returnPager.getList())).size() <= basePageRequest.getPageSize()); - //用户组不存在非全局用户组 - userList = JSON.parseArray(JSON.toJSONString(returnPager.getList()), UserTableResponse.class); - for (UserTableResponse response : userList) { - if (CollectionUtils.isNotEmpty(response.getUserRoleList())) { - response.getUserRoleList().forEach(role -> Assertions.assertTrue(userRoleIdList.contains(role.getId()))); - } - } - - //测试根据创建时间倒叙排列 - basePageRequest = UserParamUtils.getDefaultPageRequest(); - basePageRequest.setSort(new HashMap<>() {{ - put("createTime", "desc"); - }}); - returnPager = userRequestUtils.selectUserPage(basePageRequest); - //第一个数据的createTime是最大的 - List userInfoList = JSON.parseArray(JSON.toJSONString(returnPager.getList()), UserTableResponse.class); - long firstCreateTime = userInfoList.getFirst().getCreateTime(); - for (UserTableResponse userInfo : userInfoList) { - Assertions.assertFalse(userInfo.getCreateTime() > firstCreateTime); - } - //用户组不存在非全局用户组 - userList = JSON.parseArray(JSON.toJSONString(returnPager.getList()), UserTableResponse.class); - for (UserTableResponse response : userList) { - if (CollectionUtils.isNotEmpty(response.getUserRoleList())) { - response.getUserRoleList().forEach(role -> Assertions.assertTrue(userRoleIdList.contains(role.getId()))); - } - } - - //查找不存在的用户 - basePageRequest = UserParamUtils.getDefaultPageRequest(); - basePageRequest.setKeyword(IDGenerator.nextStr()); - returnPager = userRequestUtils.selectUserPage(basePageRequest); - //返回值不为空 - Assertions.assertNotNull(returnPager); - //返回值的页码和当前页码相同 - Assertions.assertEquals(returnPager.getTotal(), 0); - Assertions.assertEquals(returnPager.getPageSize(), basePageRequest.getPageSize()); - //返回的数据量不超过规定要返回的数据量相同 - Assertions.assertEquals(0, JSON.parseArray(JSON.toJSONString(returnPager.getList())).size()); - } - - @Test - @Order(3) - void testPageError() throws Exception { - //当前页码不大于0 - BasePageRequest basePageRequest = new BasePageRequest(); - basePageRequest.setPageSize(5); - this.requestPost(UserRequestUtils.URL_USER_PAGE, basePageRequest).andExpect(BAD_REQUEST_MATCHER); - - //pageSize超过501 - basePageRequest = UserParamUtils.getDefaultPageRequest(); - basePageRequest.setPageSize(501); - this.requestPost(UserRequestUtils.URL_USER_PAGE, basePageRequest).andExpect(BAD_REQUEST_MATCHER); - - //当前页数不大于5 - basePageRequest = new BasePageRequest(); - basePageRequest.setCurrent(1); - this.requestPost(UserRequestUtils.URL_USER_PAGE, basePageRequest).andExpect(BAD_REQUEST_MATCHER); - - //排序字段不合法 - basePageRequest = new BasePageRequest(); - basePageRequest.setCurrent(1); - basePageRequest.setPageSize(5); - basePageRequest.setSort(new HashMap<>() {{ - put("SELECT * FROM user", "asc"); - }}); - this.requestPost(UserRequestUtils.URL_USER_PAGE, basePageRequest).andExpect(BAD_REQUEST_MATCHER); - - } - - @Test - @Order(4) - void testUserUpdateSuccess() throws Exception { - this.checkUserList(); - UserCreateInfo user = new UserCreateInfo(); - BeanUtils.copyBean(user, USER_LIST.getFirst()); - UserEditRequest userMaintainRequest; - UserEditRequest response; - UserDTO checkDTO; - //更改名字 - user.setName("TEST-UPDATE"); - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); - LOG_CHECK_LIST.add( - new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) - ); - checkDTO = this.getUserByEmail(user.getEmail()); - UserParamUtils.compareUserDTO(response, checkDTO); - //更改邮箱 - user.setEmail("songtianyang-test-email@12138.com"); - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); - LOG_CHECK_LIST.add( - new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) - ); - checkDTO = this.getUserByEmail(user.getEmail()); - UserParamUtils.compareUserDTO(response, checkDTO); - //更改手机号 - user.setPhone("18511112222"); - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); - LOG_CHECK_LIST.add( - new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) - ); - checkDTO = this.getUserByEmail(user.getEmail()); - UserParamUtils.compareUserDTO(response, checkDTO); - //更改用户组(这里只改成用户成员权限) - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, - USER_ROLE_LIST.stream().filter(item -> StringUtils.equals(item.getId(), "member")).toList() - ); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); - checkDTO = this.getUserByEmail(user.getEmail()); - LOG_CHECK_LIST.add( - new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) - ); - UserParamUtils.compareUserDTO(response, checkDTO); - //更改用户组(把上面的情况添加别的权限) - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); - LOG_CHECK_LIST.add( - new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) - ); - checkDTO = this.getUserByEmail(user.getEmail()); - UserParamUtils.compareUserDTO(response, checkDTO); - //用户信息复原 - user = new UserCreateInfo(); - BeanUtils.copyBean(user, USER_LIST.getFirst()); - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); - LOG_CHECK_LIST.add( - new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) - ); - checkDTO = this.getUserByEmail(user.getEmail()); - UserParamUtils.compareUserDTO(response, checkDTO); - } - - @Test - @Order(5) - void testUserUpdateError() throws Exception { - this.checkUserList(); - // 4xx 验证 - UserCreateInfo user = new UserCreateInfo(); - UserEditRequest userMaintainRequest; - //更改名字 - BeanUtils.copyBean(user, USER_LIST.getFirst()); - user.setName(""); - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); - this.requestPost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - - //email为空 - BeanUtils.copyBean(user, USER_LIST.getFirst()); - user.setEmail(""); - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); - this.requestPost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - - //手机号为空 - BeanUtils.copyBean(user, USER_LIST.getFirst()); - user.setEmail(""); - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); - this.requestPost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - - //用户组为空 - BeanUtils.copyBean(user, USER_LIST.getFirst()); - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, new ArrayList<>()); - userMaintainRequest.setUserRoleIdList(new ArrayList<>()); - this.requestPost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - - - // 500验证 - //邮箱重复 - this.checkUserList(); - BeanUtils.copyBean(user, USER_LIST.getFirst()); - user.setEmail(USER_LIST.getLast().getEmail()); - userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); - MvcResult mvcResult = this.requestPost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest).andExpect(ERROR_REQUEST_MATCHER).andReturn(); - ResultHolder resultHolder = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class); - Assertions.assertEquals(resultHolder.getMessage(), "用户邮箱已存在"); - } - - @Test - @Order(6) - void testUserChangeEnableSuccess() throws Exception { - this.checkUserList(); - - UserCreateInfo userInfo = USER_LIST.getFirst(); - - //先使用要操作的用户登录,用于检查会不会把账户踢出 - MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/login") - .content(String.format("{\"username\":\"%s\",\"password\":\"%s\"}", userInfo.getEmail(), userInfo.getEmail())) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); - String sessionId = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.sessionId"); - String csrfToken = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.csrfToken"); - //检查该用户状态登录中 - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/is-login"); - requestBuilder - .header(SessionConstants.HEADER_TOKEN, sessionId) - .header(SessionConstants.CSRF_TOKEN, csrfToken) - .header(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN"); - MvcResult loginResult = mockMvc.perform(requestBuilder).andReturn(); - ResultHolder checkLoginHolder = JSON.parseObject(loginResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class); - Assertions.assertNotNull(checkLoginHolder.getData()); - - //修改状态关闭 - UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest(); - userChangeEnableRequest.setSelectIds(new ArrayList<>() {{ - this.add(userInfo.getId()); - }}); - userChangeEnableRequest.setEnable(false); - this.requestPostWithOk(UserRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest); - for (String item : userChangeEnableRequest.getSelectIds()) { - LOG_CHECK_LIST.add( - new CheckLogModel(item, OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE_ENABLE) - ); - } - UserDTO userDTO = this.getUserByEmail(userInfo.getEmail()); - Assertions.assertEquals(userDTO.getEnable(), userChangeEnableRequest.isEnable()); - - //检查该用户被踢出 - requestBuilder = MockMvcRequestBuilders.get("/is-login"); - requestBuilder - .header(SessionConstants.HEADER_TOKEN, sessionId) - .header(SessionConstants.CSRF_TOKEN, csrfToken) - .header(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN"); - loginResult = mockMvc.perform(requestBuilder).andReturn(); - checkLoginHolder = JSON.parseObject(loginResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class); - Assertions.assertNull(checkLoginHolder.getData()); - - //修改状态开启 - userChangeEnableRequest.setEnable(true); - this.requestPostWithOk(UserRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest); - for (String item : userChangeEnableRequest.getSelectIds()) { - LOG_CHECK_LIST.add( - new CheckLogModel(item, OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE_ENABLE) - ); - } - - userDTO = this.getUserByEmail(userInfo.getEmail()); - Assertions.assertEquals(userDTO.getEnable(), userChangeEnableRequest.isEnable()); - } - - @Test - @Order(6) - void testUserChangeEnableError() throws Exception { - this.checkUserList(); - //用户不存在 - UserChangeEnableRequest userChangeEnableRequest = new UserChangeEnableRequest(); - userChangeEnableRequest.setEnable(false); - this.requestPost(UserRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest).andExpect(ERROR_REQUEST_MATCHER); - - //含有非法用户 - userChangeEnableRequest.setSelectIds(new ArrayList<>() {{ - this.add("BCDEDIT"); - }}); - this.requestPost(UserRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest).andExpect(ERROR_REQUEST_MATCHER); - //含有当前用户 - userChangeEnableRequest.setSelectIds(new ArrayList<>() {{ - this.add("admin"); - }}); - this.requestPost(UserRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest).andExpect(ERROR_REQUEST_MATCHER); - } - - - @Test - @Order(7) - void testUserImport() throws Exception { - this.checkUserList(); - //测试用户数据导入。 每个导入文件都有10条数据,不同文件出错的数据不同。 - int importSuccessData = 10;//应该导入成功的数据数量 - int[] errorDataIndex = {};//出错数据的行数 - 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, UserParamUtils.getFileBytes(filePath)); - ExcelParseDTO userImportReportDTOByFile = userService.getUserExcelParseDTO(file); - 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) { - LOG_CHECK_LIST.add( - new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT) - ); - } - - //导入空文件. 应当导入成功的数据为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, UserParamUtils.getFileBytes(filePath)); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(UserRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class); - importSuccessData = 0; - errorDataIndex = new int[]{}; - UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex); - - - //导入中文文件 - importSuccessData = 19; - filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/user_import_cn_success.xls")).getPath(); - file = new MockMultipartFile("file", "userImportCn.xls", MediaType.APPLICATION_OCTET_STREAM_VALUE, UserParamUtils.getFileBytes(filePath)); - userImportReportDTOByFile = userService.getUserExcelParseDTO(file); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(UserRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class); - UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值 - userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 - for (UserDTO item : userDTOList) { - LOG_CHECK_LIST.add( - new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT) - ); - } - - - //文件内没有一条合格数据 应当导入成功的数据为0 - importSuccessData = 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, 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}; - 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, UserParamUtils.getFileBytes(filePath)); - userImportReportDTOByFile = userService.getUserExcelParseDTO(file); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(UserRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class); - importSuccessData = 8; - errorDataIndex = new int[]{1, 7}; - UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex); - userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 - for (UserDTO item : userDTOList) { - LOG_CHECK_LIST.add( - new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT) - ); - } - - //文件内邮箱重复 应当导入成功的数据为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, UserParamUtils.getFileBytes(filePath)); - userImportReportDTOByFile = userService.getUserExcelParseDTO(file); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(UserRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class); - errorDataIndex = new int[]{9, 10}; - UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex); - userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 - for (UserDTO item : userDTOList) { - LOG_CHECK_LIST.add( - new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT) - ); - } - - //文件不符合规范 应当导入成功的数据为0 - filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("file/abcde.gif")).getPath(); - 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[]{}; - 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, UserParamUtils.getFileBytes(filePath)); - userImportReportDTOByFile = userService.getUserExcelParseDTO(file); - response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responseFile(UserRequestUtils.URL_USER_IMPORT, file), UserImportResponse.class); - importSuccessData = 10;//应该导入成功的数据数量 - errorDataIndex = new int[]{};//出错数据的行数 - UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值 - userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 - for (UserDTO item : userDTOList) { - LOG_CHECK_LIST.add( - new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT) - ); - } - } - - @Test - @Order(8) - void testUserResetPasswordError() throws Exception { - //用户不存在 - { - TableBatchProcessDTO request = new TableBatchProcessDTO(); - request.setSelectIds(Collections.singletonList("none user")); - this.requestPostAndReturn(UserRequestUtils.URL_USER_RESET_PASSWORD, request, ERROR_REQUEST_MATCHER); - } - } - - @Test - @Order(1) - void testAddError() throws Exception { - if (CollectionUtils.isEmpty(USER_ROLE_LIST)) { - this.testGetGlobalSystemUserRoleSuccess(); - } - UserBatchCreateRequest userMaintainRequest; - List errorUserList = new ArrayList<>() {{ - add(new UserCreateInfo() {{ - setName("tianyang.error.1"); - setEmail("tianyang.error.name.1@126.com"); - }}); - add(new UserCreateInfo() {{ - setName("tianyang.error.2"); - setEmail("tianyang.error.name.2@126.com"); - }}); - }}; - - /* - * 校验参数不合法的反例 - * 每一次校验,使用getErrorUserCreateDTO方法重新获取参数,避免上一步的参数干扰 - */ - //所有参数都为空 - userMaintainRequest = UserParamUtils.getUserCreateDTO(null, null); - this.requestPost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - //用户组ID为空 - userMaintainRequest = UserParamUtils.getUserCreateDTO( - null, - errorUserList); - this.requestPost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - //没有用户 - userMaintainRequest = UserParamUtils.getUserCreateDTO( - USER_ROLE_LIST, - null); - this.requestPost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - //用户组含有null - userMaintainRequest = UserParamUtils.getUserCreateDTO( - USER_ROLE_LIST, - errorUserList); - userMaintainRequest.getUserRoleIdList().add(null); - userMaintainRequest.getUserRoleIdList().add(""); - this.requestPost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - //含有用户名称为空的数据 - userMaintainRequest = UserParamUtils.getUserCreateDTO( - USER_ROLE_LIST, - new ArrayList<>() - ); - userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{ - setEmail("tianyang.name.empty@126.com"); - }}); - this.requestPost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - //含有用户邮箱为空的数据 - userMaintainRequest = UserParamUtils.getUserCreateDTO( - USER_ROLE_LIST, - new ArrayList<>() - ); - userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{ - setName("tianyang.email.empty"); - }}); - this.requestPost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - //用户邮箱不符合标准 - userMaintainRequest = UserParamUtils.getUserCreateDTO( - USER_ROLE_LIST, - new ArrayList<>() - ); - userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{ - setName("用户邮箱放飞自我"); - setEmail("用户邮箱放飞自我"); - }}); - this.requestPost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest).andExpect(BAD_REQUEST_MATCHER); - /* - * 校验业务判断出错的反例 (500 error) - * 需要保证数据库有正常数据 - */ - this.checkUserList(); - //含有非法用户组 - userMaintainRequest = UserParamUtils.getUserCreateDTO( - new ArrayList<>() {{ - this.add(new UserSelectOption() {{ - this.setId("not system global user role id"); - }}); - }}, - errorUserList); - this.requestPost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest).andExpect(ERROR_REQUEST_MATCHER); - //含有重复的用户邮箱 - userMaintainRequest = UserParamUtils.getUserCreateDTO( - USER_ROLE_LIST, - errorUserList - ); - String firstUserEmail = userMaintainRequest.getUserInfoList().getFirst().getEmail(); - userMaintainRequest.getUserInfoList().add(new UserCreateInfo() {{ - setName("tianyang.no.error4"); - setEmail(firstUserEmail); - }}); - MvcResult errorEmailResult = this.requestPostWithOkAndReturn(UserRequestUtils.URL_USER_CREATE, userMaintainRequest); - ResultHolder errorEmailResultHolder = JSON.parseObject(errorEmailResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class); - UserBatchCreateResponse errorEmailResponse = JSON.parseObject(JSON.toJSONString(errorEmailResultHolder.getData()), UserBatchCreateResponse.class); - Assertions.assertTrue(MapUtils.isNotEmpty(errorEmailResponse.getErrorEmails())); - //测试请求参数中含有数据库中已存在的邮箱情况 - userMaintainRequest = UserParamUtils.getUserCreateDTO( - USER_ROLE_LIST, - errorUserList - ); - userMaintainRequest.setUserInfoList( - new ArrayList<>() {{ - add(new UserCreateInfo() {{ - setName("tianyang.repeat.email.db"); - setEmail(USER_DEFAULT_EMAIL); - }}); - }} - ); - errorEmailResult = this.requestPostWithOkAndReturn(UserRequestUtils.URL_USER_CREATE, userMaintainRequest); - errorEmailResultHolder = JSON.parseObject(errorEmailResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class); - errorEmailResponse = JSON.parseObject(JSON.toJSONString(errorEmailResultHolder.getData()), UserBatchCreateResponse.class); - Assertions.assertTrue(MapUtils.isNotEmpty(errorEmailResponse.getErrorEmails())); - } - - @Test - @Order(8) - void testUserResetPasswordSuccess() throws Exception { - this.checkUserList(); - //重置admin的密码 - { - TableBatchProcessDTO request = new TableBatchProcessDTO(); - request.setSelectIds(Collections.singletonList("admin")); - this.requestPostAndReturn(UserRequestUtils.URL_USER_RESET_PASSWORD, request); - //检查数据库 - UserExample userExample = new UserExample(); - userExample.createCriteria().andIdEqualTo("admin").andPasswordEqualTo(CodingUtils.md5("metersphere")); - Assertions.assertEquals(1, userMapper.countByExample(userExample)); - LOG_CHECK_LIST.add( - new CheckLogModel("admin", OperationLogType.UPDATE, UserRequestUtils.URL_USER_RESET_PASSWORD) - ); - } - //重置普通用户密码 - { - User paramUser = new User(); - String userId = USER_LIST.getFirst().getId(); - paramUser.setId(userId); - paramUser.setPassword("I can't say any dirty words"); - Assertions.assertEquals(1, userMapper.updateByPrimaryKeySelective(paramUser)); - TableBatchProcessDTO request = new TableBatchProcessDTO(); - request.setSelectIds(Collections.singletonList(userId)); - TableBatchProcessResponse response = userRequestUtils.parseObjectFromMvcResult( - this.requestPostAndReturn(UserRequestUtils.URL_USER_RESET_PASSWORD, request), - TableBatchProcessResponse.class - ); - Assertions.assertEquals(response.getTotalCount(), response.getSuccessCount(), 1); - List userList = userToolService.selectByIdList(Collections.singletonList(userId)); - for (User checkUser : userList) { - UserExample userExample = new UserExample(); - userExample.createCriteria().andIdEqualTo(checkUser.getId()).andPasswordEqualTo(CodingUtils.md5(checkUser.getEmail())); - Assertions.assertEquals(1, userMapper.countByExample(userExample)); - LOG_CHECK_LIST.add( - new CheckLogModel(checkUser.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_RESET_PASSWORD) - ); - } - } - //重置非Admin用户的密码 - { - TableBatchProcessDTO request = new TableBatchProcessDTO(); - request.setExcludeIds(Collections.singletonList("admin")); - request.setSelectAll(true); - TableBatchProcessResponse response = userRequestUtils.parseObjectFromMvcResult( - this.requestPostAndReturn(UserRequestUtils.URL_USER_RESET_PASSWORD, request), - TableBatchProcessResponse.class - ); - UserExample example = new UserExample(); - example.createCriteria().andIdNotEqualTo("admin"); - long count = userMapper.countByExample(example); - Assertions.assertEquals(response.getTotalCount(), response.getSuccessCount(), count); - - example.clear(); - example.createCriteria().andIdNotEqualTo("admin"); - List userList = userMapper.selectByExample(example); - for (User checkUser : userList) { - UserExample userExample = new UserExample(); - userExample.createCriteria().andIdEqualTo(checkUser.getId()).andPasswordEqualTo(CodingUtils.md5(checkUser.getEmail())); - Assertions.assertEquals(1, userMapper.countByExample(userExample)); - LOG_CHECK_LIST.add( - new CheckLogModel(checkUser.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_RESET_PASSWORD) - ); - } - } - } - - @Test - @Order(9) - void testUserRoleRelationSuccess() throws Exception { - //UserList中的部分角色是没有添加到某权限中的 - if (USER_LIST.size() < 50) { - this.testAddSuccess(); - } - List last50Users = USER_LIST.subList(USER_LIST.size() - 50, USER_LIST.size()); - //测试添加角色权限。 预期数据:每个用户都会增加对应的权限 - UserRoleBatchRelationRequest request = new UserRoleBatchRelationRequest(); - request.setSelectIds(last50Users.stream().map(UserCreateInfo::getId).toList()); - request.setRoleIds(USER_ROLE_LIST.stream().map(UserSelectOption::getId).toList()); - userRequestUtils.requestPost(UserRequestUtils.URL_USER_ROLE_RELATION, request, null); - //检查有权限的数据量是否一致 - Assertions.assertEquals( - globalUserRoleRelationService.selectByUserIdAndRuleId(request.getSelectIds(), request.getRoleIds()).size(), - request.getSelectIds().size() * request.getRoleIds().size() - ); - //检查日志 - for (String userID : request.getSelectIds()) { - LOG_CHECK_LIST.add( - new CheckLogModel(userID, OperationLogType.UPDATE, UserRequestUtils.URL_USER_ROLE_RELATION) - ); - } - - //测试重复添加用户权限。预期结果:不会额外增加数据 - userRequestUtils.requestPost(UserRequestUtils.URL_USER_ROLE_RELATION, request, null); - //检查有权限的数据量是否一致 - Assertions.assertEquals( - globalUserRoleRelationService.selectByUserIdAndRuleId(request.getSelectIds(), request.getRoleIds()).size(), - request.getSelectIds().size() * request.getRoleIds().size() - ); - } - - @Test - @Order(9) - 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为空 - UserRoleBatchRelationRequest request = new UserRoleBatchRelationRequest(); - request.setSelectIds(new ArrayList<>()); - request.setRoleIds(USER_ROLE_LIST.stream().map(UserSelectOption::getId).toList()); - userRequestUtils.requestPost(UserRequestUtils.URL_USER_ROLE_RELATION, request, ERROR_REQUEST_MATCHER); - // 角色id为空 - request = new UserRoleBatchRelationRequest(); - request.setSelectIds(last50Users.stream().map(UserCreateInfo::getId).toList()); - request.setRoleIds(new ArrayList<>()); - userRequestUtils.requestPost(UserRequestUtils.URL_USER_ROLE_RELATION, request, ERROR_REQUEST_MATCHER); - // 用户ID含有不存在的 - request = new UserRoleBatchRelationRequest(); - request.setSelectIds(last50Users.stream().map(UserCreateInfo::getId).collect(Collectors.toList())); - request.getSelectIds().add("none user"); - request.setRoleIds(USER_ROLE_LIST.stream().map(UserSelectOption::getId).toList()); - userRequestUtils.requestPost(UserRequestUtils.URL_USER_ROLE_RELATION, request, ERROR_REQUEST_MATCHER); - // 角色ID含有不存在的 - request = new UserRoleBatchRelationRequest(); - request.setSelectIds(last50Users.stream().map(UserCreateInfo::getId).toList()); - request.setRoleIds(USER_ROLE_LIST.stream().map(UserSelectOption::getId).collect(Collectors.toList())); - request.getRoleIds().add("none role"); - userRequestUtils.requestPost(UserRequestUtils.URL_USER_ROLE_RELATION, request, ERROR_REQUEST_MATCHER); - } - - @Test - @Order(9) - void testGetEmptyProject() throws Exception { - //测试如果没有项目系统不会报错 - List allProjectList = projectMapper.selectByExample(null); - projectMapper.deleteByExample(null); - String str = userRequestUtils.responseGet(UserRequestUtils.URL_GET_PROJECT).getResponse().getContentAsString(StandardCharsets.UTF_8); - ResultHolder rh = JSON.parseObject(str, ResultHolder.class); - List userTreeSelectOptions = JSON.parseArray( - JSON.toJSONString(rh.getData()), - BaseTreeNode.class); - Assertions.assertTrue(CollectionUtils.isEmpty(userTreeSelectOptions)); - //还原数据 - for (Project project : allProjectList) { - projectMapper.insert(project); - } - - //开始正常获取数据。 有可能在整体运行单元测试的过程中,会被默认插入了项目测试数据。所以这里根据上面数据库查到的来做判断 - str = userRequestUtils.responseGet(UserRequestUtils.URL_GET_PROJECT).getResponse().getContentAsString(StandardCharsets.UTF_8); - ResultHolder resultHolder = JSON.parseObject(str, ResultHolder.class); - userTreeSelectOptions = JSON.parseArray( - JSON.toJSONString(resultHolder.getData()), - BaseTreeNode.class); - Assertions.assertEquals(CollectionUtils.isEmpty(userTreeSelectOptions), CollectionUtils.isEmpty(allProjectList)); - } - - @Test - @Order(10) - @Sql(scripts = {"/dml/init_user_org_project.sql"}, - config = @SqlConfig(encoding = "utf-8", transactionMode = SqlConfig.TransactionMode.ISOLATED), - executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) - void testGetProjectAndOrganization() throws Exception { - String str = userRequestUtils.responseGet(UserRequestUtils.URL_GET_PROJECT).getResponse().getContentAsString(StandardCharsets.UTF_8); - ResultHolder rh = JSON.parseObject(str, ResultHolder.class); - List userTreeSelectOptions = JSON.parseArray( - JSON.toJSONString(rh.getData()), - BaseTreeNode.class); - //返回值不为空 - Assertions.assertTrue(CollectionUtils.isNotEmpty(userTreeSelectOptions)); - - userTreeSelectOptions.forEach(item -> PROJECT_LIST.addAll(item.getChildren())); - - List userSelectOptions = JSON.parseArray( - JSON.toJSONString( - JSON.parseObject( - userRequestUtils.responseGet(UserRequestUtils.URL_GET_ORGANIZATION).getResponse().getContentAsString(StandardCharsets.UTF_8), - ResultHolder.class).getData()), - UserSelectOption.class); - ORG_LIST.addAll(userSelectOptions); - } - - @Test - @Order(11) - void testAddProjectMember() throws Exception { - //UserList中的部分角色是没有添加到某权限中的 - if (CollectionUtils.isEmpty(USER_LIST)) { - this.testAddSuccess(); - } - if (CollectionUtils.isEmpty(PROJECT_LIST) || CollectionUtils.isEmpty(ORG_LIST)) { - this.testGetProjectAndOrganization(); - } - - List userIds = this.selectUserTableIds(100); - - UserRoleBatchRelationRequest request = new UserRoleBatchRelationRequest(); - request.setSelectIds(userIds); - request.setRoleIds(PROJECT_LIST.stream().map(BaseTreeNode::getId).toList()); - this.requestPostWithOk(UserRequestUtils.URL_ADD_PROJECT_MEMBER, request); - //检查有权限的数据量是否一致 - UserRoleRelationExample checkExample = new UserRoleRelationExample(); - - for (String projectId : request.getRoleIds()) { - Project project = projectMapper.selectByPrimaryKey(projectId); - String orgId = project.getOrganizationId(); - for (String userId : request.getSelectIds()) { - checkExample.createCriteria().andUserIdEqualTo(userId).andSourceIdEqualTo(projectId); - //检查是否在对应的项目下 - Assertions.assertEquals( - userRoleRelationMapper.countByExample(checkExample), 1 - ); - checkExample.clear(); - //检查是否在对应的组织下 - checkExample.createCriteria().andUserIdEqualTo(userId).andSourceIdEqualTo(orgId); - Assertions.assertEquals( - userRoleRelationMapper.countByExample(checkExample), 1 - ); - } - } - //检查日志 - for (String userID : request.getSelectIds()) { - LOG_CHECK_LIST.add( - new CheckLogModel(userID, OperationLogType.UPDATE, UserRequestUtils.URL_ADD_PROJECT_MEMBER) - ); - } - //获取用户信息 - for (String userID : request.getSelectIds()) { - userService.getPersonalById(userID); - } - - //检查用户表格不会加载出来非全局用户组 - this.testPageSuccess(); - } - - @Test - @Order(13) - void testAddOrganization() throws Exception { - //UserList中的部分角色是没有添加到某权限中的 - if (CollectionUtils.isEmpty(USER_LIST)) { - this.testAddSuccess(); - } - if (CollectionUtils.isEmpty(PROJECT_LIST) || CollectionUtils.isEmpty(ORG_LIST)) { - this.testGetProjectAndOrganization(); - } - - List userIds = this.selectUserTableIds(50); - - UserRoleBatchRelationRequest request = new UserRoleBatchRelationRequest(); - request.setSelectIds(userIds); - request.setRoleIds(ORG_LIST.stream().map(UserSelectOption::getId).toList()); - this.requestPostWithOk(UserRequestUtils.URL_ADD_ORGANIZATION_MEMBER, request); - //检查有权限的数据量是否一致 - UserRoleRelationExample checkExample = new UserRoleRelationExample(); - for (String orgId : request.getRoleIds()) { - for (String userId : request.getSelectIds()) { - checkExample.clear(); - //检查是否在对应的组织下 - checkExample.createCriteria().andUserIdEqualTo(userId).andSourceIdEqualTo(orgId); - Assertions.assertEquals( - userRoleRelationMapper.countByExample(checkExample), 1 - ); - } - } - //检查日志 - for (String userID : request.getSelectIds()) { - LOG_CHECK_LIST.add( - new CheckLogModel(userID, OperationLogType.UPDATE, UserRequestUtils.URL_ADD_ORGANIZATION_MEMBER) - ); - } - - //获取用户信息 - for (String userID : request.getSelectIds()) { - userService.getPersonalById(userID); - } - //检查用户表格加载组织 - this.testPageSuccess(); - } - - @Test - @Order(11) - void testAddToOrgOrProjectError() throws Exception { - if (CollectionUtils.isEmpty(PROJECT_LIST) || CollectionUtils.isEmpty(ORG_LIST)) { - this.testGetProjectAndOrganization(); - } - // 用户ID为空 - UserRoleBatchRelationRequest addToProjectRequest = new UserRoleBatchRelationRequest(); - addToProjectRequest.setSelectIds(new ArrayList<>()); - addToProjectRequest.setRoleIds(PROJECT_LIST.stream().map(BaseTreeNode::getId).toList()); - userRequestUtils.requestPost(UserRequestUtils.URL_ADD_PROJECT_MEMBER, addToProjectRequest, ERROR_REQUEST_MATCHER); - // 项目为空 - addToProjectRequest = new UserRoleBatchRelationRequest(); - addToProjectRequest.setSelectIds(USER_LIST.stream().map(UserCreateInfo::getId).toList()); - addToProjectRequest.setRoleIds(new ArrayList<>()); - userRequestUtils.requestPost(UserRequestUtils.URL_ADD_PROJECT_MEMBER, addToProjectRequest, BAD_REQUEST_MATCHER); - // 用户ID含有不存在的 - addToProjectRequest = new UserRoleBatchRelationRequest(); - addToProjectRequest.setSelectIds(Collections.singletonList("none user")); - addToProjectRequest.setRoleIds(PROJECT_LIST.stream().map(BaseTreeNode::getId).toList()); - userRequestUtils.requestPost(UserRequestUtils.URL_ADD_PROJECT_MEMBER, addToProjectRequest, ERROR_REQUEST_MATCHER); - // 项目ID含有不存在的 - addToProjectRequest = new UserRoleBatchRelationRequest(); - addToProjectRequest.setSelectIds(USER_LIST.stream().map(UserCreateInfo::getId).toList()); - addToProjectRequest.setRoleIds(Collections.singletonList("none role")); - userRequestUtils.requestPost(UserRequestUtils.URL_ADD_PROJECT_MEMBER, addToProjectRequest, ERROR_REQUEST_MATCHER); - - - // 用户ID为空 - UserRoleBatchRelationRequest orgRequest = new UserRoleBatchRelationRequest(); - orgRequest.setSelectIds(new ArrayList<>()); - orgRequest.setRoleIds(ORG_LIST.stream().map(UserSelectOption::getId).toList()); - userRequestUtils.requestPost(UserRequestUtils.URL_ADD_PROJECT_MEMBER, orgRequest, ERROR_REQUEST_MATCHER); - // 项目为空 - orgRequest = new UserRoleBatchRelationRequest(); - orgRequest.setSelectIds(USER_LIST.stream().map(UserCreateInfo::getId).toList()); - orgRequest.setRoleIds(new ArrayList<>()); - userRequestUtils.requestPost(UserRequestUtils.URL_ADD_PROJECT_MEMBER, orgRequest, BAD_REQUEST_MATCHER); - // 用户ID含有不存在的 - orgRequest = new UserRoleBatchRelationRequest(); - orgRequest.setSelectIds(Collections.singletonList("none user")); - orgRequest.setRoleIds(ORG_LIST.stream().map(UserSelectOption::getId).toList()); - userRequestUtils.requestPost(UserRequestUtils.URL_ADD_PROJECT_MEMBER, orgRequest, ERROR_REQUEST_MATCHER); - // 项目ID含有不存在的 - orgRequest = new UserRoleBatchRelationRequest(); - orgRequest.setSelectIds(USER_LIST.stream().map(UserCreateInfo::getId).toList()); - orgRequest.setRoleIds(Collections.singletonList("none role")); - userRequestUtils.requestPost(UserRequestUtils.URL_ADD_PROJECT_MEMBER, orgRequest, ERROR_REQUEST_MATCHER); - } - - @Test - @Order(12) - void testUserInvite() throws Exception { - if (CollectionUtils.isEmpty(USER_LIST)) { - this.testAddSuccess(); - } - this.testUserInviteSuccess(); - this.testUserInviteError(); - } - - @Test - @Order(13) - void testUserRegister() throws Exception { - if (CollectionUtils.isEmpty(INVITE_RECORD_ID_LIST)) { - this.testUserInvite(); - } - this.testUserRegisterSuccess(); - this.testUserRegisterError(); - } - - @Test - @Order(14) - void testGetKey() throws Exception { - this.requestGetWithOk("/get-key"); - } - - //本测试类中会用到很多次用户数据。所以测试删除的方法放于最后 - @Test - @Order(99) - void testUserDeleteSuccess() throws Exception { - this.checkUserList(); - - //先使用要操作的用户登录,用于检查会不会把账户踢出 - UserCreateInfo userInfo = USER_LIST.getFirst(); - MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/login") - .content(String.format("{\"username\":\"%s\",\"password\":\"%s\"}", userInfo.getEmail(), userInfo.getEmail())) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); - String sessionId = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.sessionId"); - String csrfToken = JsonPath.read(mvcResult.getResponse().getContentAsString(), "$.data.csrfToken"); - //检查该用户状态登录中 - MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/is-login"); - requestBuilder - .header(SessionConstants.HEADER_TOKEN, sessionId) - .header(SessionConstants.CSRF_TOKEN, csrfToken) - .header(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN"); - MvcResult loginResult = mockMvc.perform(requestBuilder).andReturn(); - ResultHolder checkLoginHolder = JSON.parseObject(loginResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class); - Assertions.assertNotNull(checkLoginHolder.getData()); - - //删除USER_LIST用户 - TableBatchProcessDTO request = new TableBatchProcessDTO(); - request.setSelectIds(USER_LIST.stream().map(UserCreateInfo::getId).toList()); - TableBatchProcessResponse response = userRequestUtils.parseObjectFromMvcResult( - userRequestUtils.responsePost(UserRequestUtils.URL_USER_DELETE, request), TableBatchProcessResponse.class); - Assertions.assertEquals(request.getSelectIds().size(), response.getTotalCount()); - Assertions.assertEquals(request.getSelectIds().size(), response.getSuccessCount()); - - //检查该用户被踢出 - requestBuilder = MockMvcRequestBuilders.get("/is-login"); - requestBuilder - .header(SessionConstants.HEADER_TOKEN, sessionId) - .header(SessionConstants.CSRF_TOKEN, csrfToken) - .header(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN"); - loginResult = mockMvc.perform(requestBuilder).andReturn(); - checkLoginHolder = JSON.parseObject(loginResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class); - Assertions.assertNull(checkLoginHolder.getData()); - - //检查数据库 - List removeList = new ArrayList<>(); - for (UserCreateInfo deleteUser : USER_LIST) { - User user = userMapper.selectByPrimaryKey(deleteUser.getId()); - Assertions.assertTrue(user.getDeleted()); - //检查日志 - LOG_CHECK_LIST.add( - new CheckLogModel(deleteUser.getId(), OperationLogType.DELETE, UserRequestUtils.URL_USER_DELETE) - ); - removeList.add(deleteUser); - } - USER_LIST.removeAll(removeList); - } - - //删除失败的方法要放在删除成功方法后面执行 - @Test - @Order(100) - void testUserDeleteError() throws Exception { - //参数为空 - TableBatchProcessDTO request = new TableBatchProcessDTO(); - this.requestPost(UserRequestUtils.URL_USER_DELETE, request).andExpect(ERROR_REQUEST_MATCHER); - //用户不存在 - request.setSelectIds(Collections.singletonList("none user")); - this.requestPost(UserRequestUtils.URL_USER_DELETE, request).andExpect(ERROR_REQUEST_MATCHER); - //测试用户已经被删除的 - if (CollectionUtils.isEmpty(DELETED_USER_ID_LIST)) { - this.testUserDeleteSuccess(); - } - request.setSelectIds(DELETED_USER_ID_LIST); - this.requestPost(UserRequestUtils.URL_USER_DELETE, request).andExpect(ERROR_REQUEST_MATCHER); - - //测试包含Admin用户 - request = new TableBatchProcessDTO(); - request.setSelectAll(true); - this.requestPost(UserRequestUtils.URL_USER_DELETE, request).andExpect(ERROR_REQUEST_MATCHER); - } - - - @Test - @Order(101) - void testLog() throws Exception { - Thread.sleep(5000); - for (CheckLogModel checkLogModel : LOG_CHECK_LIST) { - if (StringUtils.isEmpty(checkLogModel.getUrl())) { - this.checkLog(checkLogModel.getResourceId(), checkLogModel.getOperationType()); - } else { - this.checkLog(checkLogModel.getResourceId(), checkLogModel.getOperationType(), checkLogModel.getUrl()); - } - } - } - - //记录查询到的组织信息 - 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()), UserSelectOption.class); - //返回值不为空 - Assertions.assertTrue(CollectionUtils.isNotEmpty(userRoleList)); - USER_ROLE_LIST.addAll(userRoleList); - } - - //查找表格用户信息的ID - private List selectUserTableIds(int pageSize) throws Exception { - BasePageRequest basePageRequest = UserParamUtils.getDefaultPageRequest(); - basePageRequest.setPageSize(pageSize); - Pager returnPager = userRequestUtils.selectUserPage(basePageRequest); - //用户组不存在非全局用户组 - List userList = JSON.parseArray(JSON.toJSONString(returnPager.getList()), UserTableResponse.class); - return userList.stream().map(User::getId).toList(); - } - - //成功入库的用户保存内存中,其他用例会使用到 - private void addUser2List(MvcResult mvcResult) { - UserBatchCreateResponse userMaintainRequest = userRequestUtils.parseObjectFromMvcResult(mvcResult, UserBatchCreateResponse.class); - for (UserCreateInfo item : userMaintainRequest.getSuccessList()) { - LOG_CHECK_LIST.add( - new CheckLogModel(item.getId(), OperationLogType.ADD, null) - ); - } - //返回值不为空 - Assertions.assertNotNull(userMaintainRequest); - USER_LIST.addAll(userMaintainRequest.getSuccessList()); - } - - 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()); - Assertions.assertNotNull(userDTO); - returnList.add(userDTO); - } - return returnList; - } - - void testUserInviteSuccess() throws Exception { - UserInviteRequest userInviteRequest = UserParamUtils.getUserInviteRequest( - USER_ROLE_LIST, - new ArrayList<>() {{ - add("tianyang.song.invite.1@test.email"); - add("tianyang.song.invite.2@test.email"); - }} - ); - //这里无法测试邮箱是否发出,所以不针对结果进行校验 - this.requestPost(UserRequestUtils.URL_INVITE, userInviteRequest); - - List inviteList = userInviteService.batchInsert(userInviteRequest.getInviteEmails(), "admin", userInviteRequest.getUserRoleIds()); - UserInviteResponse response = new UserInviteResponse(inviteList); - INVITE_RECORD_ID_LIST.addAll(response.getInviteIds()); - } - - @Resource - private UserInviteService userInviteService; - - void testUserInviteError() throws Exception { - List inviteEmailList = new ArrayList<>() {{ - add("tianyang.song.invite.error.1@test.email"); - add("tianyang.song.invite.error.2@test.email"); - }}; - //400-用户角色为空 - UserInviteRequest userInviteRequest = UserParamUtils.getUserInviteRequest( - new ArrayList<>(), - inviteEmailList - ); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE, userInviteRequest, BAD_REQUEST_MATCHER); - userInviteRequest.setUserRoleIds(null); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE, userInviteRequest, BAD_REQUEST_MATCHER); - - //400-邀请用户为空 - userInviteRequest = UserParamUtils.getUserInviteRequest( - USER_ROLE_LIST, - new ArrayList<>() - ); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE, userInviteRequest, BAD_REQUEST_MATCHER); - userInviteRequest.setInviteEmails(null); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE, userInviteRequest, BAD_REQUEST_MATCHER); - - //400-邀请邮箱又非正确的格式的 - userInviteRequest = UserParamUtils.getUserInviteRequest( - USER_ROLE_LIST, - new ArrayList<>() {{ - this.addAll(inviteEmailList); - this.add("tianyang.song.invite.error.3"); - }} - ); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE, userInviteRequest, BAD_REQUEST_MATCHER); - - //500-包含无效权限 - userInviteRequest = UserParamUtils.getUserInviteRequest( - USER_ROLE_LIST, - inviteEmailList - ); - userInviteRequest.getUserRoleIds().add("none role"); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE, userInviteRequest, ERROR_REQUEST_MATCHER); - - //500-用户邮箱数据内重复 - userInviteRequest = UserParamUtils.getUserInviteRequest( - USER_ROLE_LIST, - inviteEmailList - ); - userInviteRequest.getInviteEmails().addAll(inviteEmailList); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE, userInviteRequest, ERROR_REQUEST_MATCHER); - - //500-用户邮箱在数据库中已存在 - userInviteRequest = UserParamUtils.getUserInviteRequest( - USER_ROLE_LIST, - inviteEmailList - ); - userInviteRequest.getInviteEmails().add(USER_LIST.getFirst().getEmail()); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE, userInviteRequest, ERROR_REQUEST_MATCHER); - } - - private void testUserRegisterSuccess() throws Exception { - String inviteId = INVITE_RECORD_ID_LIST.getFirst(); - UserRegisterRequest request = new UserRegisterRequest(); - request.setInviteId(inviteId); - request.setPassword(RsaUtils.publicEncrypt("Cao..12138", RsaUtils.getRsaKey().getPublicKey())); - - //先测试反例:名称超过255 - StringBuilder overSizeName = new StringBuilder(); - while (overSizeName.length() < 256) { - overSizeName.append("i"); - } - request.setName(overSizeName.toString()); - this.requestPost(UserRequestUtils.URL_INVITE_REGISTER, request).andExpect(BAD_REQUEST_MATCHER); - - //测试正常创建 - this.requestGetWithOk("/system/user/check-invite/" + request.getInviteId()); - request.setName("建国通过邮箱邀请"); - MvcResult mvcResult = userRequestUtils.responsePost(UserRequestUtils.URL_INVITE_REGISTER, request); - String resultHolderStr = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8); - ResultHolder resultHolder = JSON.parseObject(resultHolderStr, ResultHolder.class); - - //检查日志 此处日志的资源是邀请的用户,即admin - LOG_CHECK_LIST.add( - new CheckLogModel(resultHolder.getData().toString(), OperationLogType.ADD, UserRequestUtils.URL_INVITE_REGISTER) - ); - - - } - - private void testUserRegisterError() throws Exception { - if (INVITE_RECORD_ID_LIST.isEmpty()) { - this.testUserInviteSuccess(); - } - String inviteId = INVITE_RECORD_ID_LIST.get(1); - - //400-用户名为空 - UserRegisterRequest request = new UserRegisterRequest(); - request.setInviteId(inviteId); - request.setPassword(IDGenerator.nextStr()); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE_REGISTER, request, BAD_REQUEST_MATCHER); - request.setName(""); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE_REGISTER, request, BAD_REQUEST_MATCHER); - //400-用户密码为空 - request = new UserRegisterRequest(); - request.setInviteId(inviteId); - request.setName("建国通过邮箱邀请2"); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE_REGISTER, request, BAD_REQUEST_MATCHER); - request.setPassword(""); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE_REGISTER, request, BAD_REQUEST_MATCHER); - - //400-邀请ID为空 - request = new UserRegisterRequest(); - request.setName("建国通过邮箱邀请2"); - request.setPassword(IDGenerator.nextStr()); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE_REGISTER, request, BAD_REQUEST_MATCHER); - request.setInviteId(""); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE_REGISTER, request, BAD_REQUEST_MATCHER); - - //500-邀请ID不存在 - request = new UserRegisterRequest(); - request.setInviteId(IDGenerator.nextStr()); - request.setName("建国通过邮箱邀请2"); - request.setPassword(IDGenerator.nextStr()); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE_REGISTER, request, ERROR_REQUEST_MATCHER); - this.requestGet("/system/user/check-invite/" + request.getInviteId()).andExpect(ERROR_REQUEST_MATCHER); - - //500-邀请ID已过期,且暂未删除 (同时校验邀请检测接口) - UserInvite invite = userInviteMapper.selectByPrimaryKey(inviteId); - invite.setInviteTime(invite.getInviteTime() - 1000 * 60 * 60 * 24); - userInviteMapper.updateByPrimaryKeySelective(invite); - - request = new UserRegisterRequest(); - request.setInviteId(inviteId); - request.setName("建国通过邮箱邀请2"); - request.setPassword(IDGenerator.nextStr()); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE_REGISTER, request, ERROR_REQUEST_MATCHER); - this.requestGet("/system/user/check-invite/" + inviteId).andExpect(ERROR_REQUEST_MATCHER); - - //500-用户邮箱在用户注册之前已经被注册过了 - //首先还原邀请时间 - invite = userInviteMapper.selectByPrimaryKey(inviteId); - invite.setInviteTime(System.currentTimeMillis()); - userInviteMapper.updateByPrimaryKeySelective(invite); - - String insertEmail = invite.getEmail(); - UserBatchCreateRequest userMaintainRequest = UserParamUtils.getUserCreateDTO( - USER_ROLE_LIST, - new ArrayList<>() {{ - add(new UserCreateInfo() {{ - setName(insertEmail); - setEmail(insertEmail); - }}); - }} - ); - userRequestUtils.responsePost(UserRequestUtils.URL_USER_CREATE, userMaintainRequest); - - //测试 - request = new UserRegisterRequest(); - request.setInviteId(inviteId); - request.setName("建国通过邮箱邀请2"); - request.setPassword(IDGenerator.nextStr()); - userRequestUtils.requestPost(UserRequestUtils.URL_INVITE_REGISTER, request, ERROR_REQUEST_MATCHER); - } -} - -@Data -@AllArgsConstructor -class CheckLogModel { - private String resourceId; - private OperationLogType operationType; - private String url; -} diff --git a/backend/services/test-plan/src/main/java/io/metersphere/plan/service/TestPlanReportService.java b/backend/services/test-plan/src/main/java/io/metersphere/plan/service/TestPlanReportService.java index 5c9122d452..14239c0894 100644 --- a/backend/services/test-plan/src/main/java/io/metersphere/plan/service/TestPlanReportService.java +++ b/backend/services/test-plan/src/main/java/io/metersphere/plan/service/TestPlanReportService.java @@ -24,7 +24,7 @@ import io.metersphere.system.dto.sdk.OptionDTO; import io.metersphere.system.mapper.BaseUserMapper; import io.metersphere.system.mapper.UserMapper; import io.metersphere.system.notice.constants.NoticeConstants; -import io.metersphere.system.service.UserService; +import io.metersphere.system.service.NormalUserService; import io.metersphere.system.uid.IDGenerator; import jakarta.annotation.Resource; import org.apache.commons.collections4.CollectionUtils; @@ -47,7 +47,7 @@ public class TestPlanReportService { @Resource private UserMapper userMapper; @Resource - private UserService userService; + private NormalUserService normalUserService; @Resource private SqlSessionFactory sqlSessionFactory; @Resource @@ -91,7 +91,7 @@ public class TestPlanReportService { return new ArrayList<>(); } List distinctUserIds = reportList.stream().map(TestPlanReportPageResponse::getCreateUser).distinct().toList(); - Map userMap = userService.getUserMapByIds(distinctUserIds); + Map userMap = normalUserService.getUserMapByIds(distinctUserIds); reportList.forEach(report -> report.setCreateUserName(userMap.get(report.getCreateUser()))); return reportList; }