diff --git a/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/main/java/cn/iocoder/yudao/framework/datapermission/core/util/DataPermissionUtils.java b/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/main/java/cn/iocoder/yudao/framework/datapermission/core/util/DataPermissionUtils.java new file mode 100644 index 000000000..c154bd5f5 --- /dev/null +++ b/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/main/java/cn/iocoder/yudao/framework/datapermission/core/util/DataPermissionUtils.java @@ -0,0 +1,43 @@ +package cn.iocoder.yudao.framework.datapermission.core.util; + +import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission; +import cn.iocoder.yudao.framework.datapermission.core.aop.DataPermissionContextHolder; +import lombok.SneakyThrows; + +/** + * 数据权限 Util + * + * @author 芋道源码 + */ +public class DataPermissionUtils { + + private static DataPermission DATA_PERMISSION_DISABLE; + + @DataPermission(enable = false) + @SneakyThrows + private static DataPermission getDisableDataPermissionDisable() { + if (DATA_PERMISSION_DISABLE == null) { + DATA_PERMISSION_DISABLE = DataPermissionUtils.class + .getDeclaredMethod("getDisableDataPermissionDisable") + .getAnnotation(DataPermission.class); + } + return DATA_PERMISSION_DISABLE; + } + + /** + * 忽略数据权限,执行对应的逻辑 + * + * @param runnable 逻辑 + */ + public static void executeIgnore(Runnable runnable) { + DataPermission dataPermission = getDisableDataPermissionDisable(); + DataPermissionContextHolder.add(dataPermission); + try { + // 执行 runnable + runnable.run(); + } finally { + DataPermissionContextHolder.remove(); + } + } + +} diff --git a/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/test/java/cn/iocoder/yudao/framework/datapermission/core/utils/DataPermissionUtilsTest.java b/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/test/java/cn/iocoder/yudao/framework/datapermission/core/utils/DataPermissionUtilsTest.java new file mode 100644 index 000000000..234a9fe88 --- /dev/null +++ b/yudao-framework/yudao-spring-boot-starter-biz-data-permission/src/test/java/cn/iocoder/yudao/framework/datapermission/core/utils/DataPermissionUtilsTest.java @@ -0,0 +1,16 @@ +package cn.iocoder.yudao.framework.datapermission.core.utils; + +import cn.iocoder.yudao.framework.datapermission.core.aop.DataPermissionContextHolder; +import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class DataPermissionUtilsTest { + + @Test + public void testExecuteIgnore() { + DataPermissionUtils.executeIgnore(() -> assertFalse(DataPermissionContextHolder.get().enable())); + } + +} diff --git a/yudao-framework/yudao-spring-boot-starter-biz-error-code/src/main/java/cn/iocoder/yudao/framework/errorcode/core/generator/ErrorCodeAutoGeneratorImpl.java b/yudao-framework/yudao-spring-boot-starter-biz-error-code/src/main/java/cn/iocoder/yudao/framework/errorcode/core/generator/ErrorCodeAutoGeneratorImpl.java index 3ec761f80..fd175367c 100644 --- a/yudao-framework/yudao-spring-boot-starter-biz-error-code/src/main/java/cn/iocoder/yudao/framework/errorcode/core/generator/ErrorCodeAutoGeneratorImpl.java +++ b/yudao-framework/yudao-spring-boot-starter-biz-error-code/src/main/java/cn/iocoder/yudao/framework/errorcode/core/generator/ErrorCodeAutoGeneratorImpl.java @@ -49,7 +49,7 @@ public class ErrorCodeAutoGeneratorImpl implements ErrorCodeAutoGenerator { log.info("[execute][解析到错误码数量为 ({}) 个]", autoGenerateDTOs.size()); // 第二步,写入到 system 服务 - errorCodeApi.autoGenerateErrorCodes(autoGenerateDTOs).checkError(); + errorCodeApi.autoGenerateErrorCodeList(autoGenerateDTOs).checkError(); log.info("[execute][写入到 system 组件完成]"); } diff --git a/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/service/TenantFrameworkServiceImpl.java b/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/service/TenantFrameworkServiceImpl.java index aff8965b1..7877ae1e0 100644 --- a/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/service/TenantFrameworkServiceImpl.java +++ b/yudao-framework/yudao-spring-boot-starter-biz-tenant/src/main/java/cn/iocoder/yudao/framework/tenant/core/service/TenantFrameworkServiceImpl.java @@ -30,7 +30,7 @@ public class TenantFrameworkServiceImpl implements TenantFrameworkService { @Override public List load(Object key) { - return tenantApi.getTenantIds().getCheckedData(); + return tenantApi.getTenantIdList().getCheckedData(); } }); diff --git a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImpl.java b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImpl.java index b2c336745..1b3497303 100644 --- a/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImpl.java +++ b/yudao-module-bpm/yudao-module-bpm-biz/src/main/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImpl.java @@ -220,7 +220,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.POST.getType())) { postApi.validPostList(options); } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER.getType())) { - adminUserApi.validUsers(options); + adminUserApi.validUserList(options); } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER_GROUP.getType())) { userGroupService.validUserGroups(options); } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.SCRIPT.getType())) { @@ -288,7 +288,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService { } private Set calculateTaskCandidateUsersByDeptMember(BpmTaskAssignRuleDO rule) { - List users = adminUserApi.getUsersByDeptIds(rule.getOptions()).getCheckedData(); + List users = adminUserApi.getUserListByDeptIds(rule.getOptions()).getCheckedData(); return convertSet(users, AdminUserRespDTO::getId); } @@ -298,7 +298,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService { } private Set calculateTaskCandidateUsersByPost(BpmTaskAssignRuleDO rule) { - List users = adminUserApi.getUsersByPostIds(rule.getOptions()).getCheckedData(); + List users = adminUserApi.getUserListByPostIds(rule.getOptions()).getCheckedData(); return convertSet(users, AdminUserRespDTO::getId); } diff --git a/yudao-module-bpm/yudao-module-bpm-biz/src/test/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImplTest.java b/yudao-module-bpm/yudao-module-bpm-biz/src/test/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImplTest.java index 2d60ad97c..f0210d38c 100644 --- a/yudao-module-bpm/yudao-module-bpm-biz/src/test/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImplTest.java +++ b/yudao-module-bpm/yudao-module-bpm-biz/src/test/java/cn/iocoder/yudao/module/bpm/service/definition/BpmTaskAssignRuleServiceImplTest.java @@ -87,7 +87,7 @@ public class BpmTaskAssignRuleServiceImplTest extends BaseDbUnitTest { // mock 方法 List users = CollectionUtils.convertList(asSet(11L, 22L), id -> new AdminUserRespDTO().setId(id)); - when(adminUserApi.getUsersByDeptIds(eq(rule.getOptions()))).thenReturn(success(users)); + when(adminUserApi.getUserListByDeptIds(eq(rule.getOptions()))).thenReturn(success(users)); mockGetUserMap(asSet(11L, 22L)); // 调用 @@ -121,7 +121,7 @@ public class BpmTaskAssignRuleServiceImplTest extends BaseDbUnitTest { // mock 方法 List users = CollectionUtils.convertList(asSet(11L, 22L), id -> new AdminUserRespDTO().setId(id)); - when(adminUserApi.getUsersByPostIds(eq(rule.getOptions()))).thenReturn(success(users)); + when(adminUserApi.getUserListByPostIds(eq(rule.getOptions()))).thenReturn(success(users)); mockGetUserMap(asSet(11L, 22L)); // 调用 diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/config/ConfigController.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/config/ConfigController.java index cdeda3f1f..08d8b6f60 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/config/ConfigController.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/controller/admin/config/ConfigController.java @@ -1,6 +1,5 @@ package cn.iocoder.yudao.module.infra.controller.admin.config; -import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils; @@ -23,6 +22,7 @@ import javax.validation.Valid; import java.io.IOException; import java.util.List; +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT; @@ -76,7 +76,7 @@ public class ConfigController { return null; } if (!config.getVisible()) { - throw ServiceExceptionUtil.exception(ErrorCodeConstants.CONFIG_GET_VALUE_ERROR_IF_VISIBLE); + throw exception(ErrorCodeConstants.CONFIG_GET_VALUE_ERROR_IF_VISIBLE); } return success(config.getValue()); } @@ -93,8 +93,8 @@ public class ConfigController { @Operation(summary = "导出参数配置") @PreAuthorize("@ss.hasPermission('infra:config:export')") @OperateLog(type = EXPORT) - public void exportSysConfig(@Valid ConfigExportReqVO reqVO, - HttpServletResponse response) throws IOException { + public void exportConfig(@Valid ConfigExportReqVO reqVO, + HttpServletResponse response) throws IOException { List list = configService.getConfigList(reqVO); // 拼接数据 List datas = ConfigConvert.INSTANCE.convertList(list); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenColumnDO.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenColumnDO.java index f1990f3fc..368162214 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenColumnDO.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenColumnDO.java @@ -39,27 +39,38 @@ public class CodegenColumnDO extends BaseDO { /** * 字段名 + * + * 关联 {@link TableField#getName()} */ private String columnName; /** * 数据库字段类型 + * * 关联 {@link TableField.MetaInfo#getJdbcType()} */ private String dataType; /** * 字段描述 + * + * 关联 {@link TableField#getComment()} */ private String columnComment; /** * 是否允许为空 + * + * 关联 {@link TableField.MetaInfo#isNullable()} */ private Boolean nullable; /** * 是否主键 + * + * 关联 {@link TableField#isKeyFlag()} */ private Boolean primaryKey; /** * 是否自增 + * + * 关联 {@link TableField#isKeyIdentityFlag()} */ private Boolean autoIncrement; /** @@ -71,12 +82,16 @@ public class CodegenColumnDO extends BaseDO { /** * Java 属性类型 - *

+ * * 例如说 String、Boolean 等等 + * + * 关联 {@link TableField#getColumnType()} */ private String javaType; /** * Java 属性名 + * + * 关联 {@link TableField#getPropertyName()} */ private String javaField; /** diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenTableDO.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenTableDO.java index b821d210c..4f4a644a7 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenTableDO.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/dal/dataobject/codegen/CodegenTableDO.java @@ -6,6 +6,7 @@ import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import com.baomidou.mybatisplus.annotation.KeySequence; import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.generator.config.po.TableInfo; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; @@ -44,10 +45,14 @@ public class CodegenTableDO extends BaseDO { /** * 表名称 + * + * 关联 {@link TableInfo#getName()} */ private String tableName; /** * 表描述 + * + * 关联 {@link TableInfo#getComment()} */ private String tableComment; /** diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/CodegenServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/CodegenServiceImpl.java index b5103bc04..c4a9fb801 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/CodegenServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/codegen/CodegenServiceImpl.java @@ -28,6 +28,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.BiPredicate; import java.util.stream.Collectors; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; @@ -75,7 +76,7 @@ public class CodegenServiceImpl implements CodegenService { private Long createCodegen0(Long userId, Long dataSourceConfigId, TableInfo tableInfo) { // 校验导入的表和字段非空 - checkTableInfo(tableInfo); + validateTableInfo(tableInfo); // 校验是否已经存在 if (codegenTableMapper.selectByTableNameAndDataSourceConfigId(tableInfo.getName(), dataSourceConfigId) != null) { @@ -86,7 +87,7 @@ public class CodegenServiceImpl implements CodegenService { CodegenTableDO table = codegenBuilder.buildTable(tableInfo); table.setDataSourceConfigId(dataSourceConfigId); table.setScene(CodegenSceneEnum.ADMIN.getScene()); // 默认配置下,使用管理后台的模板 - table.setAuthor(userApi.getUser(userId).getData().getNickname()); + table.setAuthor(userApi.getUser(userId).getCheckedData().getNickname()); codegenTableMapper.insert(table); // 构建 CodegenColumnDO 数组,插入到 DB 中 @@ -99,7 +100,7 @@ public class CodegenServiceImpl implements CodegenService { return table.getId(); } - private void checkTableInfo(TableInfo tableInfo) { + private void validateTableInfo(TableInfo tableInfo) { if (tableInfo == null) { throw exception(CODEGEN_IMPORT_TABLE_NULL); } @@ -148,18 +149,33 @@ public class CodegenServiceImpl implements CodegenService { private void syncCodegen0(Long tableId, TableInfo tableInfo) { // 校验导入的表和字段非空 - checkTableInfo(tableInfo); + validateTableInfo(tableInfo); List tableFields = tableInfo.getFields(); // 构建 CodegenColumnDO 数组,只同步新增的字段 List codegenColumns = codegenColumnMapper.selectListByTableId(tableId); Set codegenColumnNames = CollectionUtils.convertSet(codegenColumns, CodegenColumnDO::getColumnName); + + //计算需要修改的字段,插入时重新插入,删除时将原来的删除 + BiPredicate pr = + (tableField, codegenColumn) -> tableField.getType().equals(codegenColumn.getDataType()) + && tableField.getMetaInfo().isNullable() == codegenColumn.getNullable() + && tableField.isKeyFlag() == codegenColumn.getPrimaryKey() + && tableField.getComment().equals(codegenColumn.getColumnComment()); + Map codegenColumnDOMap = CollectionUtils.convertMap(codegenColumns, CodegenColumnDO::getColumnName); + //需要修改的字段 + Set modifyFieldNames = tableFields.stream() + .filter(tableField -> codegenColumnDOMap.get(tableField.getColumnName()) != null + && !pr.test(tableField, codegenColumnDOMap.get(tableField.getColumnName()))) + .map(TableField::getColumnName) + .collect(Collectors.toSet()); // 计算需要删除的字段 Set tableFieldNames = CollectionUtils.convertSet(tableFields, TableField::getName); - Set deleteColumnIds = codegenColumns.stream().filter(column -> !tableFieldNames.contains(column.getColumnName())) + Set deleteColumnIds = codegenColumns.stream() + .filter(column -> (!tableFieldNames.contains(column.getColumnName())) || modifyFieldNames.contains(column.getColumnName())) .map(CodegenColumnDO::getId).collect(Collectors.toSet()); // 移除已经存在的字段 - tableFields.removeIf(column -> codegenColumnNames.contains(column.getColumnName())); + tableFields.removeIf(column -> codegenColumnNames.contains(column.getColumnName()) && (!modifyFieldNames.contains(column.getColumnName()))); if (CollUtil.isEmpty(tableFields) && CollUtil.isEmpty(deleteColumnIds)) { throw exception(CODEGEN_SYNC_NONE_CHANGE); } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImpl.java index 5c354c989..51c912be7 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImpl.java @@ -9,7 +9,6 @@ import cn.iocoder.yudao.module.infra.controller.admin.config.vo.ConfigUpdateReqV import cn.iocoder.yudao.module.infra.convert.config.ConfigConvert; import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO; import cn.iocoder.yudao.module.infra.dal.mysql.config.ConfigMapper; -import cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants; import cn.iocoder.yudao.module.infra.enums.config.ConfigTypeEnum; import com.google.common.annotations.VisibleForTesting; import lombok.extern.slf4j.Slf4j; @@ -20,6 +19,7 @@ import javax.annotation.Resource; import java.util.List; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; +import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; /** * 参数配置 Service 实现类 @@ -35,7 +35,7 @@ public class ConfigServiceImpl implements ConfigService { @Override public Long createConfig(ConfigCreateReqVO reqVO) { // 校验正确性 - checkCreateOrUpdate(null, reqVO.getKey()); + validateConfigForCreateOrUpdate(null, reqVO.getKey()); // 插入参数配置 ConfigDO config = ConfigConvert.INSTANCE.convert(reqVO); config.setType(ConfigTypeEnum.CUSTOM.getType()); @@ -46,19 +46,19 @@ public class ConfigServiceImpl implements ConfigService { @Override public void updateConfig(ConfigUpdateReqVO reqVO) { // 校验正确性 - checkCreateOrUpdate(reqVO.getId(), null); // 不允许更新 key + validateConfigForCreateOrUpdate(reqVO.getId(), null); // 不允许更新 key // 更新参数配置 ConfigDO updateObj = ConfigConvert.INSTANCE.convert(reqVO); - configMapper.updateById(updateObj);; + configMapper.updateById(updateObj); } @Override public void deleteConfig(Long id) { // 校验配置存在 - ConfigDO config = checkConfigExists(id); + ConfigDO config = validateConfigExists(id); // 内置配置,不允许删除 if (ConfigTypeEnum.SYSTEM.getType().equals(config.getType())) { - throw exception(ErrorCodeConstants.CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE); + throw exception(CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE); } // 删除 configMapper.deleteById(id); @@ -84,39 +84,39 @@ public class ConfigServiceImpl implements ConfigService { return configMapper.selectList(reqVO); } - private void checkCreateOrUpdate(Long id, String key) { + private void validateConfigForCreateOrUpdate(Long id, String key) { // 校验自己存在 - checkConfigExists(id); + validateConfigExists(id); // 校验参数配置 key 的唯一性 if (StrUtil.isNotEmpty(key)) { - checkConfigKeyUnique(id, key); + validateConfigKeyUnique(id, key); } } @VisibleForTesting - public ConfigDO checkConfigExists(Long id) { + public ConfigDO validateConfigExists(Long id) { if (id == null) { return null; } ConfigDO config = configMapper.selectById(id); if (config == null) { - throw exception(ErrorCodeConstants.CONFIG_NOT_EXISTS); + throw exception(CONFIG_NOT_EXISTS); } return config; } @VisibleForTesting - public void checkConfigKeyUnique(Long id, String key) { + public void validateConfigKeyUnique(Long id, String key) { ConfigDO config = configMapper.selectByKey(key); if (config == null) { return; } // 如果 id 为空,说明不用比较是否为相同 id 的参数配置 if (id == null) { - throw exception(ErrorCodeConstants.CONFIG_KEY_DUPLICATE); + throw exception(CONFIG_KEY_DUPLICATE); } if (!config.getId().equals(id)) { - throw exception(ErrorCodeConstants.CONFIG_KEY_DUPLICATE); + throw exception(CONFIG_KEY_DUPLICATE); } } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImpl.java index f2fd0a408..e4365c205 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImpl.java @@ -37,7 +37,7 @@ public class DataSourceConfigServiceImpl implements DataSourceConfigService { @Override public Long createDataSourceConfig(DataSourceConfigCreateReqVO createReqVO) { DataSourceConfigDO dataSourceConfig = DataSourceConfigConvert.INSTANCE.convert(createReqVO); - checkConnectionOK(dataSourceConfig); + validateConnectionOK(dataSourceConfig); // 插入 dataSourceConfigMapper.insert(dataSourceConfig); @@ -50,7 +50,7 @@ public class DataSourceConfigServiceImpl implements DataSourceConfigService { // 校验存在 validateDataSourceConfigExists(updateReqVO.getId()); DataSourceConfigDO updateObj = DataSourceConfigConvert.INSTANCE.convert(updateReqVO); - checkConnectionOK(updateObj); + validateConnectionOK(updateObj); // 更新 dataSourceConfigMapper.updateById(updateObj); @@ -88,7 +88,7 @@ public class DataSourceConfigServiceImpl implements DataSourceConfigService { return result; } - private void checkConnectionOK(DataSourceConfigDO config) { + private void validateConnectionOK(DataSourceConfigDO config) { boolean success = JdbcUtils.isConnectionOK(config.getUrl(), config.getUsername(), config.getPassword()); if (!success) { throw exception(DATA_SOURCE_CONFIG_NOT_OK); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImpl.java index cd3ddaba7..8bd2d5c93 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImpl.java @@ -41,7 +41,7 @@ public class DatabaseTableServiceImpl implements DatabaseTableService { return CollUtil.getFirst(getTableList0(dataSourceConfigId, name)); } - public List getTableList0(Long dataSourceConfigId, String name) { + private List getTableList0(Long dataSourceConfigId, String name) { // 获得数据源配置 DataSourceConfigDO config = dataSourceConfigService.getDataSourceConfig(dataSourceConfigId); Assert.notNull(config, "数据源({}) 不存在!", dataSourceConfigId); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigService.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigService.java index b3fc6bad2..43ab5bc68 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigService.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigService.java @@ -8,8 +8,6 @@ import cn.iocoder.yudao.module.infra.controller.admin.file.vo.config.FileConfigU import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileConfigDO; import javax.validation.Valid; -import java.util.Collection; -import java.util.List; /** * 文件配置 Service 接口 @@ -60,14 +58,6 @@ public interface FileConfigService { */ FileConfigDO getFileConfig(Long id); - /** - * 获得文件配置列表 - * - * @param ids 编号 - * @return 文件配置列表 - */ - List getFileConfigList(Collection ids); - /** * 获得文件配置分页 * diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImpl.java index e81be2e73..6236df6ff 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImpl.java @@ -27,7 +27,6 @@ import org.springframework.validation.annotation.Validated; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.validation.Validator; -import java.util.Collection; import java.util.List; import java.util.Map; @@ -95,7 +94,7 @@ public class FileConfigServiceImpl implements FileConfigService { @Override public void updateFileConfig(FileConfigUpdateReqVO updateReqVO) { // 校验存在 - FileConfigDO config = this.validateFileConfigExists(updateReqVO.getId()); + FileConfigDO config = validateFileConfigExists(updateReqVO.getId()); // 更新 FileConfigDO updateObj = FileConfigConvert.INSTANCE.convert(updateReqVO) .setConfig(parseClientConfig(config.getStorage(), updateReqVO.getConfig())); @@ -108,7 +107,7 @@ public class FileConfigServiceImpl implements FileConfigService { @Transactional(rollbackFor = Exception.class) public void updateFileConfigMaster(Long id) { // 校验存在 - this.validateFileConfigExists(id); + validateFileConfigExists(id); // 更新其它为非 master fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false)); // 更新 @@ -138,9 +137,9 @@ public class FileConfigServiceImpl implements FileConfigService { @Override public void deleteFileConfig(Long id) { // 校验存在 - FileConfigDO config = this.validateFileConfigExists(id); + FileConfigDO config = validateFileConfigExists(id); if (Boolean.TRUE.equals(config.getMaster())) { - throw exception(FILE_CONFIG_DELETE_FAIL_MASTER); + throw exception(FILE_CONFIG_DELETE_FAIL_MASTER); } // 删除 fileConfigMapper.deleteById(id); @@ -161,11 +160,6 @@ public class FileConfigServiceImpl implements FileConfigService { return fileConfigMapper.selectById(id); } - @Override - public List getFileConfigList(Collection ids) { - return fileConfigMapper.selectBatchIds(ids); - } - @Override public PageResult getFileConfigPage(FileConfigPageReqVO pageReqVO) { return fileConfigMapper.selectPage(pageReqVO); @@ -174,7 +168,7 @@ public class FileConfigServiceImpl implements FileConfigService { @Override public String testFileConfig(Long id) throws Exception { // 校验存在 - this.validateFileConfigExists(id); + validateFileConfigExists(id); // 上传文件 byte[] content = ResourceUtil.readBytes("file/erweima.jpg"); return fileClientFactory.getFileClient(id).upload(content, IdUtil.fastSimpleUUID() + ".jpg", "image/jpeg"); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java index 2226e7bae..0732765d8 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImpl.java @@ -69,7 +69,7 @@ public class FileServiceImpl implements FileService { @Override public void deleteFile(Long id) throws Exception { // 校验存在 - FileDO file = this.validateFileExists(id); + FileDO file = validateFileExists(id); // 从文件存储器中删除 FileClient client = fileConfigService.getFileClient(file.getConfigId()); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImpl.java index 6d79f8754..c0f9252af 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImpl.java @@ -1,17 +1,13 @@ package cn.iocoder.yudao.module.infra.service.logger; -import cn.iocoder.yudao.framework.apilog.core.service.ApiErrorLog; +import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.module.infra.api.logger.dto.ApiErrorLogCreateReqDTO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogExportReqVO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogPageReqVO; import cn.iocoder.yudao.module.infra.convert.logger.ApiErrorLogConvert; import cn.iocoder.yudao.module.infra.dal.dataobject.logger.ApiErrorLogDO; import cn.iocoder.yudao.module.infra.dal.mysql.logger.ApiErrorLogMapper; -import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; -import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants; import cn.iocoder.yudao.module.infra.enums.logger.ApiErrorLogProcessStatusEnum; -import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; @@ -19,6 +15,10 @@ import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.List; +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; +import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.API_ERROR_LOG_NOT_FOUND; +import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.API_ERROR_LOG_PROCESSED; + /** * API 错误日志 Service 实现类 * @@ -33,8 +33,8 @@ public class ApiErrorLogServiceImpl implements ApiErrorLogService { @Override public void createApiErrorLog(ApiErrorLogCreateReqDTO createDTO) { - ApiErrorLogDO apiErrorLog = ApiErrorLogConvert.INSTANCE.convert(createDTO); - apiErrorLog.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); + ApiErrorLogDO apiErrorLog = ApiErrorLogConvert.INSTANCE.convert(createDTO) + .setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); apiErrorLogMapper.insert(apiErrorLog); } @@ -52,10 +52,10 @@ public class ApiErrorLogServiceImpl implements ApiErrorLogService { public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) { ApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id); if (errorLog == null) { - throw ServiceExceptionUtil.exception(ErrorCodeConstants.API_ERROR_LOG_NOT_FOUND); + throw exception(API_ERROR_LOG_NOT_FOUND); } if (!ApiErrorLogProcessStatusEnum.INIT.getStatus().equals(errorLog.getProcessStatus())) { - throw ServiceExceptionUtil.exception(ErrorCodeConstants.API_ERROR_LOG_PROCESSED); + throw exception(API_ERROR_LOG_PROCESSED); } // 标记处理 apiErrorLogMapper.updateById(ApiErrorLogDO.builder().id(id).processStatus(processStatus) diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/test/TestDemoServiceImpl.java b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/test/TestDemoServiceImpl.java index 92153b022..f476b5a72 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/test/TestDemoServiceImpl.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/java/cn/iocoder/yudao/module/infra/service/test/TestDemoServiceImpl.java @@ -45,7 +45,7 @@ public class TestDemoServiceImpl implements TestDemoService { @CacheEvict(value = "test", key = "#updateReqVO.id") public void updateTestDemo(TestDemoUpdateReqVO updateReqVO) { // 校验存在 - this.validateTestDemoExists(updateReqVO.getId()); + validateTestDemoExists(updateReqVO.getId()); // 更新 TestDemoDO updateObj = TestDemoConvert.INSTANCE.convert(updateReqVO); testDemoMapper.updateById(updateObj); @@ -55,7 +55,7 @@ public class TestDemoServiceImpl implements TestDemoService { @CacheEvict(value = "test", key = "#id") public void deleteTestDemo(Long id) { // 校验存在 - this.validateTestDemoExists(id); + validateTestDemoExists(id); // 删除 testDemoMapper.deleteById(id); } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/service/serviceImpl.vm b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/service/serviceImpl.vm index 85dfa0aab..a732039ce 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/service/serviceImpl.vm +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/service/serviceImpl.vm @@ -39,7 +39,7 @@ public class ${table.className}ServiceImpl implements ${table.className}Service @Override public void update${simpleClassName}(${sceneEnum.prefixClass}${table.className}UpdateReqVO updateReqVO) { // 校验存在 - this.validate${simpleClassName}Exists(updateReqVO.getId()); + validate${simpleClassName}Exists(updateReqVO.getId()); // 更新 ${table.className}DO updateObj = ${table.className}Convert.INSTANCE.convert(updateReqVO); ${classNameVar}Mapper.updateById(updateObj); @@ -48,7 +48,7 @@ public class ${table.className}ServiceImpl implements ${table.className}Service @Override public void delete${simpleClassName}(${primaryColumn.javaType} id) { // 校验存在 - this.validate${simpleClassName}Exists(id); + validate${simpleClassName}Exists(id); // 删除 ${classNameVar}Mapper.deleteById(id); } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/test/serviceTest.vm b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/test/serviceTest.vm index e97fbb275..67a44e989 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/test/serviceTest.vm +++ b/yudao-module-infra/yudao-module-infra-biz/src/main/resources/codegen/java/test/serviceTest.vm @@ -52,7 +52,7 @@ import static org.mockito.Mockito.*; #if (${column.listOperation}) #set ($JavaField = $column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})##首字母大写 #if (${column.listOperationCondition} == "BETWEEN")## BETWEEN 的情况 - reqVO.set${JavaField}((new LocalDateTime[]{})); + reqVO.set${JavaField}(buildBetweenTime(2023, 2, 1, 2023, 2, 28)); #else reqVO.set$JavaField(null); #end diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImplTest.java similarity index 73% rename from yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceTest.java rename to yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImplTest.java index 5d7d74338..428b20522 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/config/ConfigServiceImplTest.java @@ -2,7 +2,6 @@ package cn.iocoder.yudao.module.infra.service.config; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.framework.test.core.util.RandomUtils; import cn.iocoder.yudao.module.infra.controller.admin.config.vo.ConfigCreateReqVO; @@ -12,27 +11,25 @@ import cn.iocoder.yudao.module.infra.controller.admin.config.vo.ConfigUpdateReqV import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO; import cn.iocoder.yudao.module.infra.dal.mysql.config.ConfigMapper; import cn.iocoder.yudao.module.infra.enums.config.ConfigTypeEnum; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.List; import java.util.function.Consumer; import static cn.hutool.core.util.RandomUtil.randomEle; -import static cn.iocoder.yudao.framework.common.util.date.DateUtils.buildLocalDateTime; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; @Import(ConfigServiceImpl.class) -public class ConfigServiceTest extends BaseDbUnitTest { +public class ConfigServiceImplTest extends BaseDbUnitTest { @Resource private ConfigServiceImpl configService; @@ -52,7 +49,7 @@ public class ConfigServiceTest extends BaseDbUnitTest { // 校验记录的属性是否正确 ConfigDO config = configMapper.selectById(configId); assertPojoEquals(reqVO, config); - Assertions.assertEquals(ConfigTypeEnum.CUSTOM.getType(), config.getType()); + assertEquals(ConfigTypeEnum.CUSTOM.getType(), config.getType()); } @Test @@ -103,40 +100,40 @@ public class ConfigServiceTest extends BaseDbUnitTest { } @Test - public void testCheckConfigExists_success() { + public void testValidateConfigExists_success() { // mock 数据 ConfigDO dbConfigDO = randomConfigDO(); configMapper.insert(dbConfigDO);// @Sql: 先插入出一条存在的数据 // 调用成功 - configService.checkConfigExists(dbConfigDO.getId()); + configService.validateConfigExists(dbConfigDO.getId()); } @Test - public void testCheckConfigExist_notExists() { - assertServiceException(() -> configService.checkConfigExists(randomLongId()), CONFIG_NOT_EXISTS); + public void testValidateConfigExist_notExists() { + assertServiceException(() -> configService.validateConfigExists(randomLongId()), CONFIG_NOT_EXISTS); } @Test - public void testCheckConfigKeyUnique_success() { + public void testValidateConfigKeyUnique_success() { // 调用,成功 - configService.checkConfigKeyUnique(randomLongId(), randomString()); + configService.validateConfigKeyUnique(randomLongId(), randomString()); } @Test - public void testCheckConfigKeyUnique_keyDuplicateForCreate() { + public void testValidateConfigKeyUnique_keyDuplicateForCreate() { // 准备参数 String key = randomString(); // mock 数据 configMapper.insert(randomConfigDO(o -> o.setConfigKey(key))); // 调用,校验异常 - assertServiceException(() -> configService.checkConfigKeyUnique(null, key), + assertServiceException(() -> configService.validateConfigKeyUnique(null, key), CONFIG_KEY_DUPLICATE); } @Test - public void testCheckConfigKeyUnique_keyDuplicateForUpdate() { + public void testValidateConfigKeyUnique_keyDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String key = randomString(); @@ -144,7 +141,7 @@ public class ConfigServiceTest extends BaseDbUnitTest { configMapper.insert(randomConfigDO(o -> o.setConfigKey(key))); // 调用,校验异常 - assertServiceException(() -> configService.checkConfigKeyUnique(id, key), + assertServiceException(() -> configService.validateConfigKeyUnique(id, key), CONFIG_KEY_DUPLICATE); } @@ -155,23 +152,23 @@ public class ConfigServiceTest extends BaseDbUnitTest { o.setName("芋艿"); o.setConfigKey("yunai"); o.setType(ConfigTypeEnum.SYSTEM.getType()); - o.setCreateTime(buildLocalDateTime(2021, 2, 1)); + o.setCreateTime(buildTime(2021, 2, 1)); }); configMapper.insert(dbConfig); // 测试 name 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setName("土豆"))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setName("土豆"))); // 测试 key 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou"))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou"))); // 测试 type 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType()))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType()))); // 测试 createTime 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setCreateTime(buildLocalDateTime(2021, 1, 1)))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setCreateTime(buildTime(2021, 1, 1)))); // 准备参数 ConfigPageReqVO reqVO = new ConfigPageReqVO(); reqVO.setName("艿"); reqVO.setKey("nai"); reqVO.setType(ConfigTypeEnum.SYSTEM.getType()); - reqVO.setCreateTime((new LocalDateTime[]{buildLocalDateTime(2021, 1, 15),buildLocalDateTime(2021, 2, 15)})); + reqVO.setCreateTime(buildBetweenTime(2021, 1, 15, 2021, 2, 15)); // 调用 PageResult pageResult = configService.getConfigPage(reqVO); @@ -188,23 +185,23 @@ public class ConfigServiceTest extends BaseDbUnitTest { o.setName("芋艿"); o.setConfigKey("yunai"); o.setType(ConfigTypeEnum.SYSTEM.getType()); - o.setCreateTime(buildLocalDateTime(2021, 2, 1)); + o.setCreateTime(buildTime(2021, 2, 1)); }); configMapper.insert(dbConfig); // 测试 name 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setName("土豆"))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setName("土豆"))); // 测试 key 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou"))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou"))); // 测试 type 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType()))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType()))); // 测试 createTime 不匹配 - configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setCreateTime(buildLocalDateTime(2021, 1, 1)))); + configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setCreateTime(buildTime(2021, 1, 1)))); // 准备参数 ConfigExportReqVO reqVO = new ConfigExportReqVO(); reqVO.setName("艿"); reqVO.setKey("nai"); reqVO.setType(ConfigTypeEnum.SYSTEM.getType()); - reqVO.setCreateTime((new LocalDateTime[]{buildLocalDateTime(2021, 1, 15),buildLocalDateTime(2021, 2, 15)})); + reqVO.setCreateTime(buildBetweenTime(2021, 1, 15, 2021, 2, 15)); // 调用 List list = configService.getConfigList(reqVO); @@ -213,6 +210,21 @@ public class ConfigServiceTest extends BaseDbUnitTest { assertPojoEquals(dbConfig, list.get(0)); } + @Test + public void testGetConfig() { + // mock 数据 + ConfigDO dbConfig = randomConfigDO(); + configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据 + // 准备参数 + Long id = dbConfig.getId(); + + // 调用 + ConfigDO config = configService.getConfig(id); + // 断言 + assertNotNull(config); + assertPojoEquals(dbConfig, config); + } + @Test public void testGetConfigByKey() { // mock 数据 diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImplTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImplTest.java index e1c997f7b..b5ef46c46 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImplTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DataSourceConfigServiceImplTest.java @@ -1,5 +1,6 @@ package cn.iocoder.yudao.module.infra.service.db; +import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.ReflectUtil; import cn.hutool.crypto.symmetric.AES; import cn.iocoder.yudao.framework.mybatis.core.type.EncryptTypeHandler; @@ -9,6 +10,7 @@ import cn.iocoder.yudao.module.infra.controller.admin.db.vo.DataSourceConfigCrea import cn.iocoder.yudao.module.infra.controller.admin.db.vo.DataSourceConfigUpdateReqVO; import cn.iocoder.yudao.module.infra.dal.dataobject.db.DataSourceConfigDO; import cn.iocoder.yudao.module.infra.dal.mysql.db.DataSourceConfigMapper; +import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty; import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,14 +20,14 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; +import java.util.List; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.DATA_SOURCE_CONFIG_NOT_EXISTS; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mockStatic; @@ -57,6 +59,11 @@ public class DataSourceConfigServiceImplTest extends BaseDbUnitTest { ReflectUtil.setFieldValue(EncryptTypeHandler.class, "aes", aes); when(aes.encryptBase64(anyString())).then((Answer) invocation -> invocation.getArgument(0)); when(aes.decryptStr(anyString())).then((Answer) invocation -> invocation.getArgument(0)); + + // mock DynamicDataSourceProperties + when(dynamicDataSourceProperties.getPrimary()).thenReturn("primary"); + when(dynamicDataSourceProperties.getDatasource()).thenReturn(MapUtil.of("primary", + new DataSourceProperty().setUrl("http://localhost:3306").setUsername("yunai").setPassword("tudou"))); } @Test @@ -89,7 +96,6 @@ public class DataSourceConfigServiceImplTest extends BaseDbUnitTest { o.setId(dbDataSourceConfig.getId()); // 设置更新的 ID }); // mock 方法 -// when(stringEncryptor.encrypt(eq(reqVO.getPassword()))).thenReturn("123456"); databaseUtilsMock.when(() -> JdbcUtils.isConnectionOK(eq(reqVO.getUrl()), eq(reqVO.getUsername()), eq(reqVO.getPassword()))).thenReturn(true); @@ -142,7 +148,58 @@ public class DataSourceConfigServiceImplTest extends BaseDbUnitTest { // 调用 DataSourceConfigDO result = dataSourceConfigMapper.selectOne(DataSourceConfigDO::getPassword, EncryptTypeHandler.encrypt(dbDataSourceConfig.getPassword())); - System.out.println(result); + assertPojoEquals(dbDataSourceConfig, result); + } + + @Test + public void testGetDataSourceConfig_master() { + // 准备参数 + Long id = 0L; + // mock 方法 + + // 调用 + DataSourceConfigDO dataSourceConfig = dataSourceConfigService.getDataSourceConfig(id); + // 断言 + assertEquals(id, dataSourceConfig.getId()); + assertEquals("primary", dataSourceConfig.getName()); + assertEquals("http://localhost:3306", dataSourceConfig.getUrl()); + assertEquals("yunai", dataSourceConfig.getUsername()); + assertEquals("tudou", dataSourceConfig.getPassword()); + } + + @Test + public void testGetDataSourceConfig_normal() { + // mock 数据 + DataSourceConfigDO dbDataSourceConfig = randomPojo(DataSourceConfigDO.class); + dataSourceConfigMapper.insert(dbDataSourceConfig);// @Sql: 先插入出一条存在的数据 + // 准备参数 + Long id = dbDataSourceConfig.getId(); + + // 调用 + DataSourceConfigDO dataSourceConfig = dataSourceConfigService.getDataSourceConfig(id); + // 断言 + assertPojoEquals(dbDataSourceConfig, dataSourceConfig); + } + + @Test + public void testGetDataSourceConfigList() { + // mock 数据 + DataSourceConfigDO dbDataSourceConfig = randomPojo(DataSourceConfigDO.class); + dataSourceConfigMapper.insert(dbDataSourceConfig);// @Sql: 先插入出一条存在的数据 + // 准备参数 + + // 调用 + List dataSourceConfigList = dataSourceConfigService.getDataSourceConfigList(); + // 断言 + assertEquals(2, dataSourceConfigList.size()); + // master + assertEquals(0L, dataSourceConfigList.get(0).getId()); + assertEquals("primary", dataSourceConfigList.get(0).getName()); + assertEquals("http://localhost:3306", dataSourceConfigList.get(0).getUrl()); + assertEquals("yunai", dataSourceConfigList.get(0).getUsername()); + assertEquals("tudou", dataSourceConfigList.get(0).getPassword()); + // normal + assertPojoEquals(dbDataSourceConfig, dataSourceConfigList.get(1)); } } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImplTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImplTest.java new file mode 100644 index 000000000..6ce8c7d41 --- /dev/null +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/db/DatabaseTableServiceImplTest.java @@ -0,0 +1,89 @@ +package cn.iocoder.yudao.module.infra.service.db; + +import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; +import cn.iocoder.yudao.module.infra.dal.dataobject.db.DataSourceConfigDO; +import com.baomidou.mybatisplus.generator.config.po.TableField; +import com.baomidou.mybatisplus.generator.config.po.TableInfo; +import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; +import org.apache.ibatis.type.JdbcType; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; + +import javax.annotation.Resource; +import java.util.List; + +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@Import(DatabaseTableServiceImpl.class) +public class DatabaseTableServiceImplTest extends BaseDbUnitTest { + + @Resource + private DatabaseTableServiceImpl databaseTableService; + + @MockBean + private DataSourceConfigService dataSourceConfigService; + + @Test + public void testGetTableList() { + // 准备参数 + Long dataSourceConfigId = randomLongId(); + // mock 方法 + DataSourceConfigDO dataSourceConfig = new DataSourceConfigDO().setUsername("sa").setPassword("") + .setUrl("jdbc:h2:mem:testdb"); + when(dataSourceConfigService.getDataSourceConfig(eq(dataSourceConfigId))) + .thenReturn(dataSourceConfig); + + // 调用 + List tables = databaseTableService.getTableList(dataSourceConfigId, + "config", "参数"); + // 断言 + assertEquals(1, tables.size()); + assertTableInfo(tables.get(0)); + } + + @Test + public void testGetTable() { + // 准备参数 + Long dataSourceConfigId = randomLongId(); + // mock 方法 + DataSourceConfigDO dataSourceConfig = new DataSourceConfigDO().setUsername("sa").setPassword("") + .setUrl("jdbc:h2:mem:testdb"); + when(dataSourceConfigService.getDataSourceConfig(eq(dataSourceConfigId))) + .thenReturn(dataSourceConfig); + + // 调用 + TableInfo tableInfo = databaseTableService.getTable(dataSourceConfigId, "infra_config"); + // 断言 + assertTableInfo(tableInfo); + } + + private void assertTableInfo(TableInfo tableInfo) { + assertEquals("infra_config", tableInfo.getName()); + assertEquals("参数配置表", tableInfo.getComment()); + assertEquals(13, tableInfo.getFields().size()); + // id 字段 + TableField idField = tableInfo.getFields().get(0); + assertEquals("id", idField.getName()); + assertEquals(JdbcType.BIGINT, idField.getMetaInfo().getJdbcType()); + assertEquals("编号", idField.getComment()); + assertFalse(idField.getMetaInfo().isNullable()); + assertTrue(idField.isKeyFlag()); + assertTrue(idField.isKeyIdentityFlag()); + assertEquals(DbColumnType.LONG, idField.getColumnType()); + assertEquals("id", idField.getPropertyName()); + // name 字段 + TableField nameField = tableInfo.getFields().get(3); + assertEquals("name", nameField.getName()); + assertEquals(JdbcType.VARCHAR, nameField.getMetaInfo().getJdbcType()); + assertEquals("名字", nameField.getComment()); + assertFalse(nameField.getMetaInfo().isNullable()); + assertFalse(nameField.isKeyFlag()); + assertFalse(nameField.isKeyIdentityFlag()); + assertEquals(DbColumnType.STRING, nameField.getColumnType()); + assertEquals("name", nameField.getPropertyName()); + } +} diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImplTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImplTest.java index 56261576b..656955194 100755 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImplTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileConfigServiceImplTest.java @@ -7,6 +7,7 @@ import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.file.core.client.FileClient; import cn.iocoder.yudao.framework.file.core.client.FileClientConfig; import cn.iocoder.yudao.framework.file.core.client.FileClientFactory; +import cn.iocoder.yudao.framework.file.core.client.local.LocalFileClient; import cn.iocoder.yudao.framework.file.core.client.local.LocalFileClientConfig; import cn.iocoder.yudao.framework.file.core.enums.FileStorageEnum; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; @@ -41,10 +42,10 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; /** - * {@link FileConfigServiceImpl} 的单元测试类 - * - * @author 芋道源码 - */ +* {@link FileConfigServiceImpl} 的单元测试类 +* +* @author 芋道源码 +*/ @Import(FileConfigServiceImpl.class) public class FileConfigServiceImplTest extends BaseDbUnitTest { @@ -171,8 +172,8 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest { // 调用 fileConfigService.deleteFileConfig(id); - // 校验数据不存在了 - assertNull(fileConfigMapper.selectById(id)); + // 校验数据不存在了 + assertNull(fileConfigMapper.selectById(id)); // verify 调用 verify(fileConfigProducer).sendFileConfigRefreshMessage(); } @@ -200,30 +201,30 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest { @Test public void testGetFileConfigPage() { - // mock 数据 - FileConfigDO dbFileConfig = randomFileConfigDO().setName("芋道源码") - .setStorage(FileStorageEnum.LOCAL.getStorage()); - dbFileConfig.setCreateTime(LocalDateTimeUtil.parse("2020-01-23", DatePattern.NORM_DATE_PATTERN));// 等会查询到 - fileConfigMapper.insert(dbFileConfig); - // 测试 name 不匹配 - fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setName("源码"))); - // 测试 storage 不匹配 - fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setStorage(FileStorageEnum.DB.getStorage()))); - // 测试 createTime 不匹配 - fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setCreateTime(LocalDateTimeUtil.parse("2020-11-23", DatePattern.NORM_DATE_PATTERN)))); - // 准备参数 - FileConfigPageReqVO reqVO = new FileConfigPageReqVO(); - reqVO.setName("芋道"); - reqVO.setStorage(FileStorageEnum.LOCAL.getStorage()); - reqVO.setCreateTime((new LocalDateTime[]{buildTime(2020, 1, 1), - buildTime(2020, 1, 24)})); + // mock 数据 + FileConfigDO dbFileConfig = randomFileConfigDO().setName("芋道源码") + .setStorage(FileStorageEnum.LOCAL.getStorage()); + dbFileConfig.setCreateTime(LocalDateTimeUtil.parse("2020-01-23", DatePattern.NORM_DATE_PATTERN));// 等会查询到 + fileConfigMapper.insert(dbFileConfig); + // 测试 name 不匹配 + fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setName("源码"))); + // 测试 storage 不匹配 + fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setStorage(FileStorageEnum.DB.getStorage()))); + // 测试 createTime 不匹配 + fileConfigMapper.insert(cloneIgnoreId(dbFileConfig, o -> o.setCreateTime(LocalDateTimeUtil.parse("2020-11-23", DatePattern.NORM_DATE_PATTERN)))); + // 准备参数 + FileConfigPageReqVO reqVO = new FileConfigPageReqVO(); + reqVO.setName("芋道"); + reqVO.setStorage(FileStorageEnum.LOCAL.getStorage()); + reqVO.setCreateTime((new LocalDateTime[]{buildTime(2020, 1, 1), + buildTime(2020, 1, 24)})); - // 调用 - PageResult pageResult = fileConfigService.getFileConfigPage(reqVO); - // 断言 - assertEquals(1, pageResult.getTotal()); - assertEquals(1, pageResult.getList().size()); - assertPojoEquals(dbFileConfig, pageResult.getList().get(0)); + // 调用 + PageResult pageResult = fileConfigService.getFileConfigPage(reqVO); + // 断言 + assertEquals(1, pageResult.getTotal()); + assertEquals(1, pageResult.getList().size()); + assertPojoEquals(dbFileConfig, pageResult.getList().get(0)); } @Test @@ -242,6 +243,30 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest { assertEquals("https://www.iocoder.cn", fileConfigService.testFileConfig(id)); } + @Test + public void testGetFileConfig() { + // mock 数据 + FileConfigDO dbFileConfig = randomFileConfigDO().setMaster(false); + fileConfigMapper.insert(dbFileConfig);// @Sql: 先插入出一条存在的数据 + // 准备参数 + Long id = dbFileConfig.getId(); + + // 调用,并断言 + assertPojoEquals(dbFileConfig, fileConfigService.getFileConfig(id)); + } + + @Test + public void testGetFileClient() { + // 准备参数 + Long id = randomLongId(); + // mock 获得 Client + FileClient fileClient = new LocalFileClient(id, new LocalFileClientConfig()); + when(fileClientFactory.getFileClient(eq(id))).thenReturn(fileClient); + + // 调用,并断言 + assertSame(fileClient, fileConfigService.getFileClient(id)); + } + private FileConfigDO randomFileConfigDO() { return randomPojo(FileConfigDO.class).setStorage(randomEle(FileStorageEnum.values()).getStorage()) .setConfig(new EmptyFileClientConfig()); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImplTest.java similarity index 92% rename from yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceTest.java rename to yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImplTest.java index 1261d0a99..fe5f6fb1e 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/file/FileServiceImplTest.java @@ -16,7 +16,7 @@ import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.time.LocalDateTime; -import static cn.iocoder.yudao.framework.common.util.date.DateUtils.buildLocalDateTime; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_NOT_EXISTS; @@ -25,7 +25,7 @@ import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.*; @Import({FileServiceImpl.class}) -public class FileServiceTest extends BaseDbUnitTest { +public class FileServiceImplTest extends BaseDbUnitTest { @Resource private FileService fileService; @@ -42,7 +42,7 @@ public class FileServiceTest extends BaseDbUnitTest { FileDO dbFile = randomPojo(FileDO.class, o -> { // 等会查询到 o.setPath("yunai"); o.setType("image/jpg"); - o.setCreateTime(buildLocalDateTime(2021, 1, 15)); + o.setCreateTime(buildTime(2021, 1, 15)); }); fileMapper.insert(dbFile); // 测试 path 不匹配 @@ -53,13 +53,13 @@ public class FileServiceTest extends BaseDbUnitTest { })); // 测试 createTime 不匹配 fileMapper.insert(ObjectUtils.cloneIgnoreId(dbFile, o -> { - o.setCreateTime(buildLocalDateTime(2020, 1, 15)); + o.setCreateTime(buildTime(2020, 1, 15)); })); // 准备参数 FilePageReqVO reqVO = new FilePageReqVO(); reqVO.setPath("yunai"); reqVO.setType("jp"); - reqVO.setCreateTime((new LocalDateTime[]{buildLocalDateTime(2021, 1, 10), buildLocalDateTime(2021, 1, 20)})); + reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 1, 10), buildTime(2021, 1, 20)})); // 调用 PageResult pageResult = fileService.getFilePage(reqVO); diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiAccessLogServiceImplTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiAccessLogServiceImplTest.java index cb1e52b23..8ff2dd9bf 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiAccessLogServiceImplTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiAccessLogServiceImplTest.java @@ -1,12 +1,9 @@ package cn.iocoder.yudao.module.infra.service.logger; -import cn.hutool.core.util.RandomUtil; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; -import cn.iocoder.yudao.framework.test.core.util.RandomUtils; import cn.iocoder.yudao.module.infra.api.logger.dto.ApiAccessLogCreateReqDTO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apiaccesslog.ApiAccessLogExportReqVO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apiaccesslog.ApiAccessLogPageReqVO; @@ -16,149 +13,121 @@ import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.List; -import static cn.iocoder.yudao.framework.common.util.date.DateUtils.buildLocalDateTime; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; @Import(ApiAccessLogServiceImpl.class) public class ApiAccessLogServiceImplTest extends BaseDbUnitTest { @Resource - private ApiAccessLogService apiAccessLogService; + private ApiAccessLogServiceImpl apiAccessLogService; @Resource private ApiAccessLogMapper apiAccessLogMapper; @Test public void testGetApiAccessLogPage() { - // 构造测试数据 - long userId = 2233L; - int userType = UserTypeEnum.ADMIN.getValue(); - String applicationName = "yudao-test"; - String requestUrl = "foo"; - LocalDateTime beginTime = buildLocalDateTime(2021, 3, 13); - int duration = 1000; - int resultCode = GlobalErrorCodeConstants.SUCCESS.getCode(); - - ApiAccessLogDO infApiAccessLogDO = RandomUtils.randomPojo(ApiAccessLogDO.class, dto -> { - dto.setUserId(userId); - dto.setUserType(userType); - dto.setApplicationName(applicationName); - dto.setRequestUrl(requestUrl); - dto.setBeginTime(beginTime); - dto.setDuration(duration); - dto.setResultCode(resultCode); + ApiAccessLogDO apiAccessLogDO = randomPojo(ApiAccessLogDO.class, o -> { + o.setUserId(2233L); + o.setUserType(UserTypeEnum.ADMIN.getValue()); + o.setApplicationName("yudao-test"); + o.setRequestUrl("foo"); + o.setBeginTime(buildTime(2021, 3, 13)); + o.setDuration(1000); + o.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()); }); - apiAccessLogMapper.insert(infApiAccessLogDO); - - // 下面几个都是不匹配的数据 - // userId 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserId(3344L))); - // userType - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); - // applicationName 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setApplicationName("test"))); - // requestUrl 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setRequestUrl("bar"))); - // 构造一个早期时间 2021-02-06 00:00:00 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setBeginTime(buildLocalDateTime(2021, 2, 6)))); - // duration 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setDuration(100))); - // resultCode 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setResultCode(2))); - - // 构造调用参数 + apiAccessLogMapper.insert(apiAccessLogDO); + // 测试 userId 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserId(3344L))); + // 测试 userType 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserType(UserTypeEnum.MEMBER.getValue()))); + // 测试 applicationName 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setApplicationName("test"))); + // 测试 requestUrl 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setRequestUrl("bar"))); + // 测试 beginTime 不匹配:构造一个早期时间 2021-02-06 00:00:00 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setBeginTime(buildTime(2021, 2, 6)))); + // 测试 duration 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setDuration(100))); + // 测试 resultCode 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setResultCode(2))); + // 准备参数 ApiAccessLogPageReqVO reqVO = new ApiAccessLogPageReqVO(); - reqVO.setUserId(userId); - reqVO.setUserType(userType); - reqVO.setApplicationName(applicationName); - reqVO.setRequestUrl(requestUrl); - reqVO.setBeginTime((new LocalDateTime[]{buildLocalDateTime(2021, 3, 12),buildLocalDateTime(2021, 3, 14)})); - reqVO.setDuration(duration); - reqVO.setResultCode(resultCode); + reqVO.setUserId(2233L); + reqVO.setUserType(UserTypeEnum.ADMIN.getValue()); + reqVO.setApplicationName("yudao-test"); + reqVO.setRequestUrl("foo"); + reqVO.setBeginTime(buildBetweenTime(2021, 3, 13, 2021, 3, 13)); + reqVO.setDuration(1000); + reqVO.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()); - // 调用service方法 + // 调用 PageResult pageResult = apiAccessLogService.getApiAccessLogPage(reqVO); - // 断言,只查到了一条符合条件的 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); - assertPojoEquals(infApiAccessLogDO, pageResult.getList().get(0)); + assertPojoEquals(apiAccessLogDO, pageResult.getList().get(0)); } @Test public void testGetApiAccessLogList() { - // 构造测试数据 - long userId = 2233L; - int userType = UserTypeEnum.ADMIN.getValue(); - String applicationName = "yudao-test"; - String requestUrl = "foo"; - LocalDateTime beginTime = buildLocalDateTime(2021, 3, 13); - int duration = 1000; - int resultCode = GlobalErrorCodeConstants.SUCCESS.getCode(); - - ApiAccessLogDO infApiAccessLogDO = RandomUtils.randomPojo(ApiAccessLogDO.class, dto -> { - dto.setUserId(userId); - dto.setUserType(userType); - dto.setApplicationName(applicationName); - dto.setRequestUrl(requestUrl); - dto.setBeginTime(beginTime); - dto.setDuration(duration); - dto.setResultCode(resultCode); + ApiAccessLogDO apiAccessLogDO = randomPojo(ApiAccessLogDO.class, o -> { + o.setUserId(2233L); + o.setUserType(UserTypeEnum.ADMIN.getValue()); + o.setApplicationName("yudao-test"); + o.setRequestUrl("foo"); + o.setBeginTime(buildTime(2021, 3, 13)); + o.setDuration(1000); + o.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()); }); - apiAccessLogMapper.insert(infApiAccessLogDO); - - // 下面几个都是不匹配的数据 - // userId 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserId(3344L))); - // userType - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); - // applicationName 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setApplicationName("test"))); - // requestUrl 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setRequestUrl("bar"))); - // 构造一个早期时间 2021-02-06 00:00:00 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setBeginTime(buildLocalDateTime(2021, 2, 6)))); - // duration 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setDuration(100))); - // resultCode 不同的 - apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setResultCode(2))); - - // 构造调用参数 + apiAccessLogMapper.insert(apiAccessLogDO); + // 测试 userId 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserId(3344L))); + // 测试 userType 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserType(UserTypeEnum.MEMBER.getValue()))); + // 测试 applicationName 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setApplicationName("test"))); + // 测试 requestUrl 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setRequestUrl("bar"))); + // 测试 beginTime 不匹配:构造一个早期时间 2021-02-06 00:00:00 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setBeginTime(buildTime(2021, 2, 6)))); + // 测试 duration 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setDuration(100))); + // 测试 resultCode 不匹配 + apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setResultCode(2))); + // 准备参数 ApiAccessLogExportReqVO reqVO = new ApiAccessLogExportReqVO(); - reqVO.setUserId(userId); - reqVO.setUserType(userType); - reqVO.setApplicationName(applicationName); - reqVO.setRequestUrl(requestUrl); - reqVO.setBeginTime((new LocalDateTime[]{buildLocalDateTime(2021, 3, 12),buildLocalDateTime(2021, 3, 14)})); - reqVO.setDuration(duration); - reqVO.setResultCode(resultCode); + reqVO.setUserId(2233L); + reqVO.setUserType(UserTypeEnum.ADMIN.getValue()); + reqVO.setApplicationName("yudao-test"); + reqVO.setRequestUrl("foo"); + reqVO.setBeginTime(buildBetweenTime(2021, 3, 13, 2021, 3, 13)); + reqVO.setDuration(1000); + reqVO.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode()); - // 调用service方法 + // 调用 List list = apiAccessLogService.getApiAccessLogList(reqVO); - // 断言,只查到了一条符合条件的 assertEquals(1, list.size()); - assertPojoEquals(infApiAccessLogDO, list.get(0)); + assertPojoEquals(apiAccessLogDO, list.get(0)); } @Test - public void testCreateApiAccessLogAsync() { + public void testCreateApiAccessLog() { // 准备参数 - ApiAccessLogCreateReqDTO createDTO = RandomUtils.randomPojo(ApiAccessLogCreateReqDTO.class, - dto -> dto.setUserType(RandomUtil.randomEle(UserTypeEnum.values()).getValue())); + ApiAccessLogCreateReqDTO createDTO = randomPojo(ApiAccessLogCreateReqDTO.class); // 调用 apiAccessLogService.createApiAccessLog(createDTO); // 断言 - ApiAccessLogDO infApiAccessLogDO = apiAccessLogMapper.selectOne(null); - assertNotNull(infApiAccessLogDO); - assertPojoEquals(createDTO, infApiAccessLogDO); + ApiAccessLogDO apiAccessLogDO = apiAccessLogMapper.selectOne(null); + assertPojoEquals(createDTO, apiAccessLogDO); } - } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImplTest.java b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImplTest.java index bffdf46e8..86e55f5d1 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImplTest.java +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/java/cn/iocoder/yudao/module/infra/service/logger/ApiErrorLogServiceImplTest.java @@ -1,28 +1,28 @@ package cn.iocoder.yudao.module.infra.service.logger; -import cn.hutool.core.util.RandomUtil; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.pojo.PageResult; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; -import cn.iocoder.yudao.framework.test.core.util.RandomUtils; import cn.iocoder.yudao.module.infra.api.logger.dto.ApiErrorLogCreateReqDTO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogExportReqVO; import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogPageReqVO; import cn.iocoder.yudao.module.infra.dal.dataobject.logger.ApiErrorLogDO; import cn.iocoder.yudao.module.infra.dal.mysql.logger.ApiErrorLogMapper; import cn.iocoder.yudao.module.infra.enums.logger.ApiErrorLogProcessStatusEnum; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.Import; import javax.annotation.Resource; -import java.time.LocalDateTime; import java.util.List; -import static cn.iocoder.yudao.framework.common.util.date.DateUtils.buildLocalDateTime; +import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.API_ERROR_LOG_NOT_FOUND; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.API_ERROR_LOG_PROCESSED; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -35,161 +35,150 @@ public class ApiErrorLogServiceImplTest extends BaseDbUnitTest { private ApiErrorLogServiceImpl apiErrorLogService; @Resource - private ApiErrorLogMapper infApiErrorLogMapper; + private ApiErrorLogMapper apiErrorLogMapper; @Test public void testGetApiErrorLogPage() { - // 构造测试数据 - long userId = 2233L; - int userType = UserTypeEnum.ADMIN.getValue(); - String applicationName = "yudao-test"; - String requestUrl = "foo"; - LocalDateTime beginTime = buildLocalDateTime(2021, 3, 13); - int progressStatus = ApiErrorLogProcessStatusEnum.INIT.getStatus(); - - ApiErrorLogDO infApiErrorLogDO = RandomUtils.randomPojo(ApiErrorLogDO.class, logDO -> { - logDO.setUserId(userId); - logDO.setUserType(userType); - logDO.setApplicationName(applicationName); - logDO.setRequestUrl(requestUrl); - logDO.setExceptionTime(beginTime); - logDO.setProcessStatus(progressStatus); + // mock 数据 + ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class, o -> { + o.setUserId(2233L); + o.setUserType(UserTypeEnum.ADMIN.getValue()); + o.setApplicationName("yudao-test"); + o.setRequestUrl("foo"); + o.setExceptionTime(buildTime(2021, 3, 13)); + o.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); }); - infApiErrorLogMapper.insert(infApiErrorLogDO); - - // 下面几个都是不匹配的数据 - // userId 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserId(3344L))); - // userType - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); - // applicationName 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setApplicationName("test"))); - // requestUrl 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setRequestUrl("bar"))); - // 构造一个早期时间 2021-02-06 00:00:00 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setExceptionTime(buildLocalDateTime(2021, 2, 6)))); - // progressStatus 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()))); - - // 构造调用参数 + apiErrorLogMapper.insert(apiErrorLogDO); + // 测试 userId 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, o -> o.setUserId(3344L))); + // 测试 userType 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); + // 测试 applicationName 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setApplicationName("test"))); + // 测试 requestUrl 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setRequestUrl("bar"))); + // 测试 exceptionTime 不匹配:构造一个早期时间 2021-02-06 00:00:00 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setExceptionTime(buildTime(2021, 2, 6)))); + // 测试 progressStatus 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()))); + // 准备参数 ApiErrorLogPageReqVO reqVO = new ApiErrorLogPageReqVO(); - reqVO.setUserId(userId); - reqVO.setUserType(userType); - reqVO.setApplicationName(applicationName); - reqVO.setRequestUrl(requestUrl); - reqVO.setExceptionTime((new LocalDateTime[]{buildLocalDateTime(2021, 3, 12),buildLocalDateTime(2021, 3, 14)})); - reqVO.setProcessStatus(progressStatus); + reqVO.setUserId(2233L); + reqVO.setUserType(UserTypeEnum.ADMIN.getValue()); + reqVO.setApplicationName("yudao-test"); + reqVO.setRequestUrl("foo"); + reqVO.setExceptionTime(buildBetweenTime(2021, 3, 1, 2021, 3, 31)); + reqVO.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); - // 调用service方法 + // 调用 PageResult pageResult = apiErrorLogService.getApiErrorLogPage(reqVO); - // 断言,只查到了一条符合条件的 assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getList().size()); - assertPojoEquals(infApiErrorLogDO, pageResult.getList().get(0)); + assertPojoEquals(apiErrorLogDO, pageResult.getList().get(0)); } @Test public void testGetApiErrorLogList() { - // 构造测试数据 - long userId = 2233L; - int userType = UserTypeEnum.ADMIN.getValue(); - String applicationName = "yudao-test"; - String requestUrl = "foo"; - LocalDateTime beginTime = buildLocalDateTime(2021, 3, 13); - int progressStatus = ApiErrorLogProcessStatusEnum.INIT.getStatus(); - - ApiErrorLogDO infApiErrorLogDO = RandomUtils.randomPojo(ApiErrorLogDO.class, logDO -> { - logDO.setUserId(userId); - logDO.setUserType(userType); - logDO.setApplicationName(applicationName); - logDO.setRequestUrl(requestUrl); - logDO.setExceptionTime(beginTime); - logDO.setProcessStatus(progressStatus); + // mock 数据 + ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class, o -> { + o.setUserId(2233L); + o.setUserType(UserTypeEnum.ADMIN.getValue()); + o.setApplicationName("yudao-test"); + o.setRequestUrl("foo"); + o.setExceptionTime(buildTime(2021, 3, 13)); + o.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); }); - infApiErrorLogMapper.insert(infApiErrorLogDO); - - // 下面几个都是不匹配的数据 - // userId 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserId(3344L))); - // userType - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); - // applicationName 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setApplicationName("test"))); - // requestUrl 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setRequestUrl("bar"))); - // 构造一个早期时间 2021-02-06 00:00:00 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setExceptionTime(buildLocalDateTime(2021, 2, 6)))); - // progressStatus 不同的 - infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()))); - - // 构造调用参数 + apiErrorLogMapper.insert(apiErrorLogDO); + // 测试 userId 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, o -> o.setUserId(3344L))); + // 测试 userType 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); + // 测试 applicationName 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setApplicationName("test"))); + // 测试 requestUrl 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setRequestUrl("bar"))); + // 测试 exceptionTime 不匹配:构造一个早期时间 2021-02-06 00:00:00 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setExceptionTime(buildTime(2021, 2, 6)))); + // 测试 progressStatus 不匹配 + apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()))); + // 准备参数 ApiErrorLogExportReqVO reqVO = new ApiErrorLogExportReqVO(); - reqVO.setUserId(userId); - reqVO.setUserType(userType); - reqVO.setApplicationName(applicationName); - reqVO.setRequestUrl(requestUrl); - reqVO.setExceptionTime((new LocalDateTime[]{buildLocalDateTime(2021, 3, 12),buildLocalDateTime(2021, 3, 14)})); - reqVO.setProcessStatus(progressStatus); + reqVO.setUserId(2233L); + reqVO.setUserType(UserTypeEnum.ADMIN.getValue()); + reqVO.setApplicationName("yudao-test"); + reqVO.setRequestUrl("foo"); + reqVO.setExceptionTime(buildBetweenTime(2021, 3, 1, 2021, 3, 31)); + reqVO.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); - // 调用service方法 + // 调用 List list = apiErrorLogService.getApiErrorLogList(reqVO); - // 断言,只查到了一条符合条件的 assertEquals(1, list.size()); - assertPojoEquals(infApiErrorLogDO, list.get(0)); - } - - - // TODO 芋艿:单元测试,可以拆小一点 - @Test - public void testUpdateApiErrorLogProcess() { - // 先构造两条数据,第一条用于抛出异常,第二条用于正常的执行update操作 - Long processUserId = 2233L; - - ApiErrorLogDO first = RandomUtils.randomPojo(ApiErrorLogDO.class, logDO -> { - logDO.setProcessUserId(processUserId); - logDO.setUserType(UserTypeEnum.ADMIN.getValue()); - logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus()); - }); - infApiErrorLogMapper.insert(first); - - ApiErrorLogDO second = RandomUtils.randomPojo(ApiErrorLogDO.class, logDO -> { - logDO.setProcessUserId(1122L); - logDO.setUserType(UserTypeEnum.ADMIN.getValue()); - logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); - }); - infApiErrorLogMapper.insert(second); - - Long firstId = first.getId(); - Long secondId = second.getId(); - - // 执行正常的 update 操作 - apiErrorLogService.updateApiErrorLogProcess(secondId, ApiErrorLogProcessStatusEnum.DONE.getStatus(), processUserId); - ApiErrorLogDO secondSelect = infApiErrorLogMapper.selectOne("id", secondId); - - // id 为 0 查询不到,应该抛出异常 API_ERROR_LOG_NOT_FOUND - assertServiceException(() -> apiErrorLogService.updateApiErrorLogProcess(0L, ApiErrorLogProcessStatusEnum.DONE.getStatus(), processUserId), API_ERROR_LOG_NOT_FOUND); - // id 为 first 的 progressStatus 为 DONE ,应该抛出 API_ERROR_LOG_PROCESSED - assertServiceException(() -> apiErrorLogService.updateApiErrorLogProcess(firstId, ApiErrorLogProcessStatusEnum.DONE.getStatus(), processUserId), API_ERROR_LOG_PROCESSED); - // 验证 progressStatus 是否修改成功 - Assertions.assertEquals(ApiErrorLogProcessStatusEnum.DONE.getStatus(), secondSelect.getProcessStatus()); - // 验证 progressUserId 是否修改成功 - Assertions.assertEquals(processUserId, secondSelect.getProcessUserId()); + assertPojoEquals(apiErrorLogDO, list.get(0)); } @Test - public void testCreateApiErrorLogAsync() { + public void testCreateApiErrorLog() { // 准备参数 - ApiErrorLogCreateReqDTO createDTO = RandomUtils.randomPojo(ApiErrorLogCreateReqDTO.class, - dto -> dto.setUserType(RandomUtil.randomEle(UserTypeEnum.values()).getValue())); + ApiErrorLogCreateReqDTO createDTO = randomPojo(ApiErrorLogCreateReqDTO.class); // 调用 apiErrorLogService.createApiErrorLog(createDTO); // 断言 - ApiErrorLogDO infApiErrorLogDO = infApiErrorLogMapper.selectOne(null); - assertNotNull(infApiErrorLogDO); - assertPojoEquals(createDTO, infApiErrorLogDO); + ApiErrorLogDO apiErrorLogDO = apiErrorLogMapper.selectOne(null); + assertPojoEquals(createDTO, apiErrorLogDO); + assertEquals(ApiErrorLogProcessStatusEnum.INIT.getStatus(), apiErrorLogDO.getProcessStatus()); + } + + @Test + public void testUpdateApiErrorLogProcess_success() { + // 准备参数 + ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class, + o -> o.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus())); + apiErrorLogMapper.insert(apiErrorLogDO); + // 准备参数 + Long id = apiErrorLogDO.getId(); + Integer processStatus = randomEle(ApiErrorLogProcessStatusEnum.values()).getStatus(); + Long processUserId = randomLongId(); + + // 调用 + apiErrorLogService.updateApiErrorLogProcess(id, processStatus, processUserId); + // 断言 + ApiErrorLogDO dbApiErrorLogDO = apiErrorLogMapper.selectById(apiErrorLogDO.getId()); + assertEquals(processStatus, dbApiErrorLogDO.getProcessStatus()); + assertEquals(processUserId, dbApiErrorLogDO.getProcessUserId()); + assertNotNull(dbApiErrorLogDO.getProcessTime()); + } + + @Test + public void testUpdateApiErrorLogProcess_processed() { + // 准备参数 + ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class, + o -> o.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus())); + apiErrorLogMapper.insert(apiErrorLogDO); + // 准备参数 + Long id = apiErrorLogDO.getId(); + Integer processStatus = randomEle(ApiErrorLogProcessStatusEnum.values()).getStatus(); + Long processUserId = randomLongId(); + + // 调用,并断言异常 + assertServiceException(() -> + apiErrorLogService.updateApiErrorLogProcess(id, processStatus, processUserId), + API_ERROR_LOG_PROCESSED); + } + + @Test + public void testUpdateApiErrorLogProcess_notFound() { + // 准备参数 + Long id = randomLongId(); + Integer processStatus = randomEle(ApiErrorLogProcessStatusEnum.values()).getStatus(); + Long processUserId = randomLongId(); + + // 调用,并断言异常 + assertServiceException(() -> + apiErrorLogService.updateApiErrorLogProcess(id, processStatus, processUserId), + API_ERROR_LOG_NOT_FOUND); } } diff --git a/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/create_tables.sql b/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/create_tables.sql index 5825e0fef..9d4e57e67 100644 --- a/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/create_tables.sql +++ b/yudao-module-infra/yudao-module-infra-biz/src/test/resources/sql/create_tables.sql @@ -1,9 +1,9 @@ CREATE TABLE IF NOT EXISTS "infra_config" ( - "id" bigint(20) NOT NULL GENERATED BY DEFAULT AS IDENTITY, + "id" bigint(20) NOT NULL GENERATED BY DEFAULT AS IDENTITY COMMENT '编号', "category" varchar(50) NOT NULL, "type" tinyint NOT NULL, - "name" varchar(100) NOT NULL DEFAULT '', + "name" varchar(100) NOT NULL DEFAULT '' COMMENT '名字', "config_key" varchar(100) NOT NULL DEFAULT '', "value" varchar(500) NOT NULL DEFAULT '', "visible" bit NOT NULL, diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApiImpl.java index 0b2c731cc..5ec9f3109 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApiImpl.java @@ -24,7 +24,7 @@ public class ErrorCodeApiImpl implements ErrorCodeApi { private ErrorCodeService errorCodeService; @Override - public CommonResult autoGenerateErrorCodes(List autoGenerateDTOs) { + public CommonResult autoGenerateErrorCodeList(List autoGenerateDTOs) { errorCodeService.autoGenerateErrorCodes(autoGenerateDTOs); return success(true); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApiImpl.java index 3a082e780..008104388 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApiImpl.java @@ -21,8 +21,8 @@ public class TenantApiImpl implements TenantApi { private TenantService tenantService; @Override - public CommonResult> getTenantIds() { - return success(tenantService.getTenantIds()); + public CommonResult> getTenantIdList() { + return success(tenantService.getTenantIdList()); } @Override diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApiImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApiImpl.java index 0351c94fd..eb9adba11 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApiImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApiImpl.java @@ -33,26 +33,26 @@ public class AdminUserApiImpl implements AdminUserApi { } @Override - public CommonResult> getUsers(Collection ids) { - List users = userService.getUsers(ids); + public CommonResult> getUserList(Collection ids) { + List users = userService.getUserList(ids); return success(UserConvert.INSTANCE.convertList4(users)); } @Override - public CommonResult> getUsersByDeptIds(Collection deptIds) { - List users = userService.getUsersByDeptIds(deptIds); + public CommonResult> getUserListByDeptIds(Collection deptIds) { + List users = userService.getUserListByDeptIds(deptIds); return success(UserConvert.INSTANCE.convertList4(users)); } @Override - public CommonResult> getUsersByPostIds(Collection postIds) { - List users = userService.getUsersByPostIds(postIds); + public CommonResult> getUserListByPostIds(Collection postIds) { + List users = userService.getUserListByPostIds(postIds); return success(UserConvert.INSTANCE.convertList4(users)); } @Override - public CommonResult validUsers(Set ids) { - userService.validUsers(ids); + public CommonResult validUserList(Set ids) { + userService.validateUserList(ids); return success(true); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictDataController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictDataController.java index 145520acb..e47814b23 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictDataController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictDataController.java @@ -61,7 +61,7 @@ public class DictDataController { @GetMapping("/list-all-simple") @Operation(summary = "获得全部字典数据列表", description = "一般用于管理后台缓存字典数据在本地") // 无需添加权限认证,因为前端全局都需要 - public CommonResult> getSimpleDictDatas() { + public CommonResult> getSimpleDictDataList() { List list = dictDataService.getDictDataList(); return success(DictDataConvert.INSTANCE.convertList(list)); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictTypeController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictTypeController.java index de0098c9a..eee4d95bc 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictTypeController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dict/DictTypeController.java @@ -76,7 +76,7 @@ public class DictTypeController { @GetMapping("/list-all-simple") @Operation(summary = "获得全部字典类型列表", description = "包括开启 + 禁用的字典类型,主要用于前端的下拉选项") // 无需添加权限认证,因为前端全局都需要 - public CommonResult> listSimpleDictTypes() { + public CommonResult> getSimpleDictTypeList() { List list = dictTypeService.getDictTypeList(); return success(DictTypeConvert.INSTANCE.convertList(list)); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sensitiveword/SensitiveWordController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sensitiveword/SensitiveWordController.java index ccc3dd7fc..60b8a8285 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sensitiveword/SensitiveWordController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/sensitiveword/SensitiveWordController.java @@ -90,8 +90,8 @@ public class SensitiveWordController { @GetMapping("/get-tags") @Operation(summary = "获取所有敏感词的标签数组") @PreAuthorize("@ss.hasPermission('system:sensitive-word:query')") - public CommonResult> getSensitiveWordTags() throws IOException { - return success(sensitiveWordService.getSensitiveWordTags()); + public CommonResult> getSensitiveWordTagSet() { + return success(sensitiveWordService.getSensitiveWordTagSet()); } @GetMapping("/validate-text") diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserProfileController.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserProfileController.java index 2ea0eef0e..1dfc9bc3c 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserProfileController.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserProfileController.java @@ -31,6 +31,7 @@ import javax.annotation.Resource; import javax.validation.Valid; import java.util.List; +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_IS_EMPTY; @@ -99,7 +100,7 @@ public class UserProfileController { @Operation(summary = "上传用户个人头像") public CommonResult updateUserAvatar(@RequestParam("avatarFile") MultipartFile file) throws Exception { if (file.isEmpty()) { - throw ServiceExceptionUtil.exception(FILE_IS_EMPTY); + throw exception(FILE_IS_EMPTY); } String avatar = userService.updateUserAvatar(getLoginUserId(), file.getInputStream()); return success(avatar); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/UserPostMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/UserPostMapper.java index 9d74a7beb..addc67d43 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/UserPostMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dept/UserPostMapper.java @@ -13,8 +13,7 @@ import java.util.List; public interface UserPostMapper extends BaseMapperX { default List selectListByUserId(Long userId) { - return selectList(new LambdaQueryWrapperX() - .eq(UserPostDO::getUserId, userId)); + return selectList(UserPostDO::getUserId, userId); } default void deleteByUserIdAndPostId(Long userId, Collection postIds) { @@ -24,8 +23,7 @@ public interface UserPostMapper extends BaseMapperX { } default List selectListByPostIds(Collection postIds) { - return selectList(new LambdaQueryWrapperX() - .in(UserPostDO::getPostId, postIds)); + return selectList(UserPostDO::getPostId, postIds); } default void deleteByUserId(Long userId) { diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/social/SocialUserBindMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/social/SocialUserBindMapper.java index 88d0c9227..28619ca51 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/social/SocialUserBindMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/social/SocialUserBindMapper.java @@ -24,9 +24,8 @@ public interface SocialUserBindMapper extends BaseMapperX { } default SocialUserBindDO selectByUserTypeAndSocialUserId(Integer userType, Long socialUserId) { - return selectOne(new LambdaQueryWrapperX() - .eq(SocialUserBindDO::getUserType, userType) - .eq(SocialUserBindDO::getSocialUserId, socialUserId)); + return selectOne(SocialUserBindDO::getUserType, userType, + SocialUserBindDO::getSocialUserId, socialUserId); } default List selectListByUserIdAndUserType(Long userId, Integer userType) { diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/user/AdminUserMapper.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/user/AdminUserMapper.java index e6713bacb..4e0827210 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/user/AdminUserMapper.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/user/AdminUserMapper.java @@ -6,7 +6,6 @@ import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserPageReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import org.apache.ibatis.annotations.Mapper; import java.util.Collection; @@ -16,15 +15,15 @@ import java.util.List; public interface AdminUserMapper extends BaseMapperX { default AdminUserDO selectByUsername(String username) { - return selectOne(new LambdaQueryWrapper().eq(AdminUserDO::getUsername, username)); + return selectOne(AdminUserDO::getUsername, username); } default AdminUserDO selectByEmail(String email) { - return selectOne(new LambdaQueryWrapper().eq(AdminUserDO::getEmail, email)); + return selectOne(AdminUserDO::getEmail, email); } default AdminUserDO selectByMobile(String mobile) { - return selectOne(new LambdaQueryWrapper().eq(AdminUserDO::getMobile, mobile)); + return selectOne(AdminUserDO::getMobile, mobile); } default PageResult selectPage(UserPageReqVO reqVO, Collection deptIds) { @@ -50,10 +49,6 @@ public interface AdminUserMapper extends BaseMapperX { return selectList(new LambdaQueryWrapperX().like(AdminUserDO::getNickname, nickname)); } - default List selectListByUsername(String username) { - return selectList(new LambdaQueryWrapperX().like(AdminUserDO::getUsername, username)); - } - default List selectListByStatus(Integer status) { return selectList(AdminUserDO::getStatus, status); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImpl.java index fbf983b43..c899696ac 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImpl.java @@ -49,7 +49,7 @@ public class OperateLogServiceImpl implements OperateLogService { // 处理基于用户昵称的查询 Collection userIds = null; if (StrUtil.isNotEmpty(reqVO.getUserNickname())) { - userIds = convertSet(userService.getUsersByNickname(reqVO.getUserNickname()), AdminUserDO::getId); + userIds = convertSet(userService.getUserListByNickname(reqVO.getUserNickname()), AdminUserDO::getId); if (CollUtil.isEmpty(userIds)) { return PageResult.empty(); } @@ -63,7 +63,7 @@ public class OperateLogServiceImpl implements OperateLogService { // 处理基于用户昵称的查询 Collection userIds = null; if (StrUtil.isNotEmpty(reqVO.getUserNickname())) { - userIds = convertSet(userService.getUsersByNickname(reqVO.getUserNickname()), AdminUserDO::getId); + userIds = convertSet(userService.getUserListByNickname(reqVO.getUserNickname()), AdminUserDO::getId); if (CollUtil.isEmpty(userIds)) { return Collections.emptyList(); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImpl.java index 40db4ee0f..72da3cf89 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImpl.java @@ -3,7 +3,6 @@ package cn.iocoder.yudao.module.system.service.mail; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.mail.MailAccount; import cn.hutool.extra.mail.MailUtil; -import cn.iocoder.yudao.framework.common.core.KeyValue; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.module.system.convert.mail.MailAccountConvert; @@ -20,15 +19,13 @@ import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.annotation.Resource; -import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; /** - * 邮箱模版 服务实现类 + * 邮箱发送 Service 实现类 * * @author wangjingyi * @since 2022-03-21 @@ -82,14 +79,13 @@ public class MailSendServiceImpl implements MailSendService { public Long sendSingleMail(String mail, Long userId, Integer userType, String templateCode, Map templateParams) { // 校验邮箱模版是否合法 - MailTemplateDO template = checkMailTemplateValid(templateCode); + MailTemplateDO template = validateMailTemplate(templateCode); // 校验邮箱账号是否合法 - MailAccountDO account = checkMailAccountValid(template.getAccountId()); + MailAccountDO account = validateMailAccount(template.getAccountId()); // 校验邮箱是否存在 - mail = checkMail(mail); - // 校验参数模版 - checkTemplateParams(template, templateParams); + mail = validateMail(mail); + validateTemplateParams(template, templateParams); // 创建发送日志。如果模板被禁用,则不发送短信,只记录日志 Boolean isSend = CommonStatusEnum.ENABLE.getStatus().equals(template.getStatus()); @@ -107,7 +103,7 @@ public class MailSendServiceImpl implements MailSendService { @Override public void doSendMail(MailSendMessage message) { // 1. 创建发送账号 - MailAccountDO account = checkMailAccountValid(message.getAccountId()); + MailAccountDO account = validateMailAccount(message.getAccountId()); MailAccount mailAccount = MailAccountConvert.INSTANCE.convert(account, message.getNickname()); // 2. 发送邮件 try { @@ -122,7 +118,7 @@ public class MailSendServiceImpl implements MailSendService { } @VisibleForTesting - public MailTemplateDO checkMailTemplateValid(String templateCode) { + MailTemplateDO validateMailTemplate(String templateCode) { // 获得邮件模板。考虑到效率,从缓存中获取 MailTemplateDO template = mailTemplateService.getMailTemplateByCodeFromCache(templateCode); // 邮件模板不存在 @@ -133,7 +129,7 @@ public class MailSendServiceImpl implements MailSendService { } @VisibleForTesting - public MailAccountDO checkMailAccountValid(Long accountId) { + MailAccountDO validateMailAccount(Long accountId) { // 获得邮箱账号。考虑到效率,从缓存中获取 MailAccountDO account = mailAccountService.getMailAccountFromCache(accountId); // 邮箱账号不存在 @@ -144,7 +140,7 @@ public class MailSendServiceImpl implements MailSendService { } @VisibleForTesting - public String checkMail(String mail) { + String validateMail(String mail) { if (StrUtil.isEmpty(mail)) { throw exception(MAIL_SEND_MAIL_NOT_EXISTS); } @@ -152,13 +148,13 @@ public class MailSendServiceImpl implements MailSendService { } /** - * 校验参数模板 + * 校验邮件参数是否确实 * * @param template 邮箱模板 - * @param templateParams 原始参数 + * @param templateParams 参数列表 */ @VisibleForTesting - public void checkTemplateParams(MailTemplateDO template, Map templateParams) { + void validateTemplateParams(MailTemplateDO template, Map templateParams) { template.getParams().forEach(key -> { Object value = templateParams.get(key); if (value == null) { diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImpl.java index 39e685fd5..8d360dead 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImpl.java @@ -13,7 +13,8 @@ import java.util.Map; import java.util.Objects; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; -import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.NOTICE_NOT_FOUND; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.NOTIFY_SEND_TEMPLATE_PARAM_MISS; /** * 站内信发送 Service 实现类 @@ -44,13 +45,13 @@ public class NotifySendServiceImpl implements NotifySendService { @Override public Long sendSingleNotify(Long userId, Integer userType, String templateCode, Map templateParams) { // 校验模版 - NotifyTemplateDO template = checkNotifyTemplateValid(templateCode); + NotifyTemplateDO template = validateNotifyTemplate(templateCode); if (Objects.equals(template.getStatus(), CommonStatusEnum.DISABLE.getStatus())) { log.info("[sendSingleNotify][模版({})已经关闭,无法给用户({}/{})发送]", templateCode, userId, userType); return null; } // 校验参数 - checkTemplateParams(template, templateParams); + validateTemplateParams(template, templateParams); // 发送站内信 String content = notifyTemplateService.formatNotifyTemplateContent(template.getContent(), templateParams); @@ -58,7 +59,7 @@ public class NotifySendServiceImpl implements NotifySendService { } @VisibleForTesting - public NotifyTemplateDO checkNotifyTemplateValid(String templateCode) { + public NotifyTemplateDO validateNotifyTemplate(String templateCode) { // 获得站内信模板。考虑到效率,从缓存中获取 NotifyTemplateDO template = notifyTemplateService.getNotifyTemplateByCodeFromCache(templateCode); // 站内信模板不存在 @@ -75,7 +76,7 @@ public class NotifySendServiceImpl implements NotifySendService { * @param templateParams 参数列表 */ @VisibleForTesting - public void checkTemplateParams(NotifyTemplateDO template, Map templateParams) { + public void validateTemplateParams(NotifyTemplateDO template, Map templateParams) { template.getParams().forEach(key -> { Object value = templateParams.get(key); if (value == null) { diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImpl.java index 5ee8b4bbc..5b63ac720 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImpl.java @@ -76,7 +76,7 @@ public class NotifyTemplateServiceImpl implements NotifyTemplateService { @Override public Long createNotifyTemplate(NotifyTemplateCreateReqVO createReqVO) { // 校验站内信编码是否重复 - checkNotifyTemplateCodeDuplicate(null, createReqVO.getCode()); + validateNotifyTemplateCodeDuplicate(null, createReqVO.getCode()); // 插入 NotifyTemplateDO notifyTemplate = NotifyTemplateConvert.INSTANCE.convert(createReqVO); @@ -93,7 +93,7 @@ public class NotifyTemplateServiceImpl implements NotifyTemplateService { // 校验存在 validateNotifyTemplateExists(updateReqVO.getId()); // 校验站内信编码是否重复 - checkNotifyTemplateCodeDuplicate(updateReqVO.getId(), updateReqVO.getCode()); + validateNotifyTemplateCodeDuplicate(updateReqVO.getId(), updateReqVO.getCode()); // 更新 NotifyTemplateDO updateObj = NotifyTemplateConvert.INSTANCE.convert(updateReqVO); @@ -136,7 +136,7 @@ public class NotifyTemplateServiceImpl implements NotifyTemplateService { } @VisibleForTesting - public void checkNotifyTemplateCodeDuplicate(Long id, String code) { + public void validateNotifyTemplateCodeDuplicate(Long id, String code) { NotifyTemplateDO template = notifyTemplateMapper.selectByCode(code); if (template == null) { return; diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImpl.java index ee7fdc91a..ac6d94a49 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImpl.java @@ -31,6 +31,7 @@ import javax.annotation.Resource; import java.util.*; import java.util.stream.Collectors; +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO.ID_ROOT; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; @@ -118,7 +119,7 @@ public class MenuServiceImpl implements MenuService { public void updateMenu(MenuUpdateReqVO reqVO) { // 校验更新的菜单是否存在 if (menuMapper.selectById(reqVO.getId()) == null) { - throw ServiceExceptionUtil.exception(MENU_NOT_EXISTS); + throw exception(MENU_NOT_EXISTS); } // 校验父菜单存在 validateParentMenu(reqVO.getParentId(), reqVO.getId()); @@ -138,11 +139,11 @@ public class MenuServiceImpl implements MenuService { public void deleteMenu(Long menuId) { // 校验是否还有子菜单 if (menuMapper.selectCountByParentId(menuId) > 0) { - throw ServiceExceptionUtil.exception(MENU_EXISTS_CHILDREN); + throw exception(MENU_EXISTS_CHILDREN); } // 校验删除的菜单是否存在 if (menuMapper.selectById(menuId) == null) { - throw ServiceExceptionUtil.exception(MENU_NOT_EXISTS); + throw exception(MENU_NOT_EXISTS); } // 标记删除 menuMapper.deleteById(menuId); @@ -229,17 +230,17 @@ public class MenuServiceImpl implements MenuService { } // 不能设置自己为父菜单 if (parentId.equals(childId)) { - throw ServiceExceptionUtil.exception(MENU_PARENT_ERROR); + throw exception(MENU_PARENT_ERROR); } MenuDO menu = menuMapper.selectById(parentId); // 父菜单不存在 if (menu == null) { - throw ServiceExceptionUtil.exception(MENU_PARENT_NOT_EXISTS); + throw exception(MENU_PARENT_NOT_EXISTS); } // 父菜单必须是目录或者菜单类型 if (!MenuTypeEnum.DIR.getType().equals(menu.getType()) && !MenuTypeEnum.MENU.getType().equals(menu.getType())) { - throw ServiceExceptionUtil.exception(MENU_PARENT_NOT_DIR_OR_MENU); + throw exception(MENU_PARENT_NOT_DIR_OR_MENU); } } @@ -260,10 +261,10 @@ public class MenuServiceImpl implements MenuService { } // 如果 id 为空,说明不用比较是否为相同 id 的菜单 if (id == null) { - throw ServiceExceptionUtil.exception(MENU_NAME_DUPLICATE); + throw exception(MENU_NAME_DUPLICATE); } if (!menu.getId().equals(id)) { - throw ServiceExceptionUtil.exception(MENU_NAME_DUPLICATE); + throw exception(MENU_NAME_DUPLICATE); } } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordService.java index 29cd55e6e..a852ec9cf 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordService.java @@ -81,7 +81,7 @@ public interface SensitiveWordService { * * @return 标签数组 */ - Set getSensitiveWordTags(); + Set getSensitiveWordTagSet(); /** * 获得文本所包含的不合法的敏感词数组 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImpl.java index 868ef6f6f..b82807855 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImpl.java @@ -182,7 +182,7 @@ public class SensitiveWordServiceImpl implements SensitiveWordService { } @Override - public Set getSensitiveWordTags() { + public Set getSensitiveWordTagSet() { return sensitiveWordTagsCache; } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImpl.java index f2502924a..c9edac2f8 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImpl.java @@ -39,7 +39,6 @@ import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; * 短信模板 Service 实现类 * * @author zzf - * @date 2021/1/25 9:25 */ @Service @Slf4j @@ -105,11 +104,11 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { @Override public Long createSmsTemplate(SmsTemplateCreateReqVO createReqVO) { // 校验短信渠道 - SmsChannelDO channelDO = checkSmsChannel(createReqVO.getChannelId()); + SmsChannelDO channelDO = validateSmsChannel(createReqVO.getChannelId()); // 校验短信编码是否重复 - checkSmsTemplateCodeDuplicate(null, createReqVO.getCode()); + validateSmsTemplateCodeDuplicate(null, createReqVO.getCode()); // 校验短信模板 - checkApiTemplate(createReqVO.getChannelId(), createReqVO.getApiTemplateId()); + validateApiTemplate(createReqVO.getChannelId(), createReqVO.getApiTemplateId()); // 插入 SmsTemplateDO template = SmsTemplateConvert.INSTANCE.convert(createReqVO); @@ -127,11 +126,11 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { // 校验存在 validateSmsTemplateExists(updateReqVO.getId()); // 校验短信渠道 - SmsChannelDO channelDO = checkSmsChannel(updateReqVO.getChannelId()); + SmsChannelDO channelDO = validateSmsChannel(updateReqVO.getChannelId()); // 校验短信编码是否重复 - checkSmsTemplateCodeDuplicate(updateReqVO.getId(), updateReqVO.getCode()); + validateSmsTemplateCodeDuplicate(updateReqVO.getId(), updateReqVO.getCode()); // 校验短信模板 - checkApiTemplate(updateReqVO.getChannelId(), updateReqVO.getApiTemplateId()); + validateApiTemplate(updateReqVO.getChannelId(), updateReqVO.getApiTemplateId()); // 更新 SmsTemplateDO updateObj = SmsTemplateConvert.INSTANCE.convert(updateReqVO); @@ -184,7 +183,7 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { } @VisibleForTesting - public SmsChannelDO checkSmsChannel(Long channelId) { + public SmsChannelDO validateSmsChannel(Long channelId) { SmsChannelDO channelDO = smsChannelService.getSmsChannel(channelId); if (channelDO == null) { throw exception(SMS_CHANNEL_NOT_EXISTS); @@ -196,7 +195,7 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { } @VisibleForTesting - public void checkSmsTemplateCodeDuplicate(Long id, String code) { + public void validateSmsTemplateCodeDuplicate(Long id, String code) { SmsTemplateDO template = smsTemplateMapper.selectByCode(code); if (template == null) { return; @@ -217,7 +216,7 @@ public class SmsTemplateServiceImpl implements SmsTemplateService { * @param apiTemplateId API 模板编号 */ @VisibleForTesting - public void checkApiTemplate(Long channelId, String apiTemplateId) { + public void validateApiTemplate(Long channelId, String apiTemplateId) { // 获得短信模板 SmsClient smsClient = smsClientFactory.getSmsClient(channelId); Assert.notNull(smsClient, String.format("短信客户端(%d) 不存在", channelId)); diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantService.java index b56134e75..3dacfefe7 100755 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantService.java @@ -2,7 +2,6 @@ package cn.iocoder.yudao.module.system.service.tenant; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; -import cn.iocoder.yudao.framework.tenant.core.service.TenantFrameworkService; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantPageReqVO; @@ -121,7 +120,7 @@ public interface TenantService { * * @return 租户编号数组 */ - List getTenantIds(); + List getTenantIdList(); /** * 校验租户是否合法 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImpl.java index 3045e7573..3a70d31b9 100755 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImpl.java @@ -75,7 +75,7 @@ public class TenantServiceImpl implements TenantService { private PermissionService permissionService; @Override - public List getTenantIds() { + public List getTenantIdList() { List tenants = tenantMapper.selectList(); return CollectionUtils.convertList(tenants, TenantDO::getId); } diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserService.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserService.java index ae3245de2..e10b9e997 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserService.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserService.java @@ -127,7 +127,7 @@ public interface AdminUserService { * @param deptIds 部门数组 * @return 用户数组 */ - List getUsersByDeptIds(Collection deptIds); + List getUserListByDeptIds(Collection deptIds); /** * 获得指定岗位的用户数组 @@ -135,7 +135,7 @@ public interface AdminUserService { * @param postIds 岗位数组 * @return 用户数组 */ - List getUsersByPostIds(Collection postIds); + List getUserListByPostIds(Collection postIds); /** * 获得用户列表 @@ -143,7 +143,7 @@ public interface AdminUserService { * @param ids 用户编号数组 * @return 用户列表 */ - List getUsers(Collection ids); + List getUserList(Collection ids); /** * 校验用户们是否有效。如下情况,视为无效: @@ -152,7 +152,7 @@ public interface AdminUserService { * * @param ids 用户编号数组 */ - void validUsers(Set ids); + void validateUserList(Collection ids); /** * 获得用户 Map @@ -164,7 +164,7 @@ public interface AdminUserService { if (CollUtil.isEmpty(ids)) { return new HashMap<>(); } - return CollectionUtils.convertMap(getUsers(ids), AdminUserDO::getId); + return CollectionUtils.convertMap(getUserList(ids), AdminUserDO::getId); } /** @@ -173,7 +173,7 @@ public interface AdminUserService { * @param reqVO 列表请求 * @return 用户列表 */ - List getUsers(UserExportReqVO reqVO); + List getUserList(UserExportReqVO reqVO); /** * 获得用户列表,基于昵称模糊匹配 @@ -181,15 +181,7 @@ public interface AdminUserService { * @param nickname 昵称 * @return 用户列表 */ - List getUsersByNickname(String nickname); - - /** - * 获得用户列表,基于用户账号模糊匹配 - * - * @param username 用户账号 - * @return 用户列表 - */ - List getUsersByUsername(String username); + List getUserListByNickname(String nickname); /** * 批量导入用户 @@ -198,7 +190,7 @@ public interface AdminUserService { * @param isUpdateSupport 是否支持更新 * @return 导入结果 */ - UserImportRespVO importUsers(List importUsers, boolean isUpdateSupport); + UserImportRespVO importUserList(List importUsers, boolean isUpdateSupport); /** * 获得指定状态的用户们 @@ -206,7 +198,7 @@ public interface AdminUserService { * @param status 状态 * @return 用户们 */ - List getUsersByStatus(Integer status); + List getUserListByStatus(Integer status); /** * 判断密码是否匹配 diff --git a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImpl.java b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImpl.java index 843c9d919..74948bbf0 100644 --- a/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImpl.java +++ b/yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImpl.java @@ -8,7 +8,7 @@ import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.exception.ServiceException; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; -import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission; +import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils; import cn.iocoder.yudao.module.infra.api.file.FileApi; import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO; import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO; @@ -43,6 +43,7 @@ import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; /** * 后台用户 Service 实现类 + * * @author 芋道源码 */ @Service("adminUserService") @@ -73,10 +74,6 @@ public class AdminUserServiceImpl implements AdminUserService { @Resource private FileApi fileApi; - @Resource - @Lazy // 循环依赖(自己依赖自己),避免报错 - private AdminUserServiceImpl self; - @Override @Transactional(rollbackFor = Exception.class) public Long createUser(UserCreateReqVO reqVO) { @@ -88,12 +85,12 @@ public class AdminUserServiceImpl implements AdminUserService { } }); // 校验正确性 - self.checkCreateOrUpdate(null, reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), + validateUserForCreateOrUpdate(null, reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), reqVO.getDeptId(), reqVO.getPostIds()); // 插入用户 AdminUserDO user = UserConvert.INSTANCE.convert(reqVO); user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启 - user.setPassword(passwordEncoder.encode(reqVO.getPassword())); // 加密密码 + user.setPassword(encodePassword(reqVO.getPassword())); // 加密密码 userMapper.insert(user); // 插入关联岗位 if (CollectionUtil.isNotEmpty(user.getPostIds())) { @@ -107,7 +104,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Transactional(rollbackFor = Exception.class) public void updateUser(UserUpdateReqVO reqVO) { // 校验正确性 - self.checkCreateOrUpdate(reqVO.getId(), reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), + validateUserForCreateOrUpdate(reqVO.getId(), reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), reqVO.getDeptId(), reqVO.getPostIds()); // 更新用户 AdminUserDO updateObj = UserConvert.INSTANCE.convert(reqVO); @@ -141,9 +138,9 @@ public class AdminUserServiceImpl implements AdminUserService { @Override public void updateUserProfile(Long id, UserProfileUpdateReqVO reqVO) { // 校验正确性 - checkUserExists(id); - checkEmailUnique(id, reqVO.getEmail()); - checkMobileUnique(id, reqVO.getMobile()); + validateUserExists(id); + validateEmailUnique(id, reqVO.getEmail()); + validateMobileUnique(id, reqVO.getMobile()); // 执行更新 userMapper.updateById(UserConvert.INSTANCE.convert(reqVO).setId(id)); } @@ -151,7 +148,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Override public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) { // 校验旧密码密码 - checkOldPassword(id, reqVO.getOldPassword()); + validateOldPassword(id, reqVO.getOldPassword()); // 执行更新 AdminUserDO updateObj = new AdminUserDO().setId(id); updateObj.setPassword(encodePassword(reqVO.getNewPassword())); // 加密密码 @@ -160,7 +157,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Override public String updateUserAvatar(Long id, InputStream avatarFile) throws Exception { - checkUserExists(id); + validateUserExists(id); // 存储文件 String avatar = fileApi.createFile(IoUtil.readBytes(avatarFile)); // 更新路径 @@ -174,7 +171,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Override public void updateUserPassword(Long id, String password) { // 校验用户存在 - checkUserExists(id); + validateUserExists(id); // 更新密码 AdminUserDO updateObj = new AdminUserDO(); updateObj.setId(id); @@ -185,7 +182,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Override public void updateUserStatus(Long id, Integer status) { // 校验用户存在 - checkUserExists(id); + validateUserExists(id); // 更新状态 AdminUserDO updateObj = new AdminUserDO(); updateObj.setId(id); @@ -197,7 +194,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Transactional(rollbackFor = Exception.class) public void deleteUser(Long id) { // 校验用户存在 - checkUserExists(id); + validateUserExists(id); // 删除用户 userMapper.deleteById(id); // 删除用户关联数据 @@ -227,7 +224,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public List getUsersByDeptIds(Collection deptIds) { + public List getUserListByDeptIds(Collection deptIds) { if (CollUtil.isEmpty(deptIds)) { return Collections.emptyList(); } @@ -235,7 +232,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public List getUsersByPostIds(Collection postIds) { + public List getUserListByPostIds(Collection postIds) { if (CollUtil.isEmpty(postIds)) { return Collections.emptyList(); } @@ -247,7 +244,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public List getUsers(Collection ids) { + public List getUserList(Collection ids) { if (CollUtil.isEmpty(ids)) { return Collections.emptyList(); } @@ -255,7 +252,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public void validUsers(Set ids) { + public void validateUserList(Collection ids) { if (CollUtil.isEmpty(ids)) { return; } @@ -275,20 +272,15 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public List getUsers(UserExportReqVO reqVO) { + public List getUserList(UserExportReqVO reqVO) { return userMapper.selectList(reqVO, getDeptCondition(reqVO.getDeptId())); } @Override - public List getUsersByNickname(String nickname) { + public List getUserListByNickname(String nickname) { return userMapper.selectListByNickname(nickname); } - @Override - public List getUsersByUsername(String username) { - return userMapper.selectListByUsername(username); - } - /** * 获得部门条件:查询指定部门的子部门编号们,包括自身 * @param deptId 部门编号 @@ -304,25 +296,27 @@ public class AdminUserServiceImpl implements AdminUserService { return deptIds; } - @DataPermission(enable = false) // 关闭数据权限,避免因为没有数据权限,查询不到数据,进而导致唯一校验不正确 - public void checkCreateOrUpdate(Long id, String username, String mobile, String email, - Long deptId, Set postIds) { - // 校验用户存在 - checkUserExists(id); - // 校验用户名唯一 - checkUsernameUnique(id, username); - // 校验手机号唯一 - checkMobileUnique(id, mobile); - // 校验邮箱唯一 - checkEmailUnique(id, email); - // 校验部门处于开启状态 - deptService.validateDeptList(CollectionUtils.singleton(deptId)); - // 校验岗位处于开启状态 - postService.validatePostList(postIds); + private void validateUserForCreateOrUpdate(Long id, String username, String mobile, String email, + Long deptId, Set postIds) { + // 关闭数据权限,避免因为没有数据权限,查询不到数据,进而导致唯一校验不正确 + DataPermissionUtils.executeIgnore(() -> { + // 校验用户存在 + validateUserExists(id); + // 校验用户名唯一 + validateUsernameUnique(id, username); + // 校验手机号唯一 + validateMobileUnique(id, mobile); + // 校验邮箱唯一 + validateEmailUnique(id, email); + // 校验部门处于开启状态 + deptService.validateDeptList(CollectionUtils.singleton(deptId)); + // 校验岗位处于开启状态 + postService.validatePostList(postIds); + }); } @VisibleForTesting - public void checkUserExists(Long id) { + void validateUserExists(Long id) { if (id == null) { return; } @@ -333,7 +327,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @VisibleForTesting - public void checkUsernameUnique(Long id, String username) { + void validateUsernameUnique(Long id, String username) { if (StrUtil.isBlank(username)) { return; } @@ -351,7 +345,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @VisibleForTesting - public void checkEmailUnique(Long id, String email) { + void validateEmailUnique(Long id, String email) { if (StrUtil.isBlank(email)) { return; } @@ -369,7 +363,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @VisibleForTesting - public void checkMobileUnique(Long id, String mobile) { + void validateMobileUnique(Long id, String mobile) { if (StrUtil.isBlank(mobile)) { return; } @@ -392,7 +386,7 @@ public class AdminUserServiceImpl implements AdminUserService { * @param oldPassword 旧密码 */ @VisibleForTesting - public void checkOldPassword(Long id, String oldPassword) { + void validateOldPassword(Long id, String oldPassword) { AdminUserDO user = userMapper.selectById(id); if (user == null) { throw exception(USER_NOT_EXISTS); @@ -404,7 +398,7 @@ public class AdminUserServiceImpl implements AdminUserService { @Override @Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入 - public UserImportRespVO importUsers(List importUsers, boolean isUpdateSupport) { + public UserImportRespVO importUserList(List importUsers, boolean isUpdateSupport) { if (CollUtil.isEmpty(importUsers)) { throw exception(USER_IMPORT_LIST_IS_EMPTY); } @@ -413,7 +407,7 @@ public class AdminUserServiceImpl implements AdminUserService { importUsers.forEach(importUser -> { // 校验,判断是否有不符合的原因 try { - checkCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail(), + validateUserForCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail(), importUser.getDeptId(), null); } catch (ServiceException ex) { respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage()); @@ -441,7 +435,7 @@ public class AdminUserServiceImpl implements AdminUserService { } @Override - public List getUsersByStatus(Integer status) { + public List getUserListByStatus(Integer status) { return userMapper.selectListByStatus(status); } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImplTest.java index cb1085d3a..14b007e25 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/logger/OperateLogServiceImplTest.java @@ -64,7 +64,7 @@ public class OperateLogServiceImplTest extends BaseDbUnitTest { o.setNickname("wang"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); }); - when(userService.getUsersByNickname("wang")).thenReturn(Collections.singletonList(user)); + when(userService.getUserListByNickname("wang")).thenReturn(Collections.singletonList(user)); Long userId = user.getId(); // 构造操作日志 @@ -112,7 +112,7 @@ public class OperateLogServiceImplTest extends BaseDbUnitTest { o.setNickname("wang"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); }); - when(userService.getUsersByNickname("wang")).thenReturn(Collections.singletonList(user)); + when(userService.getUserListByNickname("wang")).thenReturn(Collections.singletonList(user)); Long userId = user.getId(); // 构造操作日志 diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailAccountServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailAccountServiceImplTest.java index 64634bf30..a0e41f75c 100755 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailAccountServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailAccountServiceImplTest.java @@ -13,6 +13,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; +import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; @@ -21,7 +22,9 @@ import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServic import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.MAIL_ACCOUNT_NOT_EXISTS; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * {@link MailAccountServiceImpl} 的单元测试类 @@ -107,6 +110,8 @@ public class MailAccountServiceImplTest extends BaseDbUnitTest { mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbMailAccount.getId(); + // mock 方法(无关联模版) + when(mailTemplateService.countByAccountId(eq(id))).thenReturn(0L); // 调用 mailAccountService.deleteMailAccount(id); @@ -115,6 +120,21 @@ public class MailAccountServiceImplTest extends BaseDbUnitTest { verify(mailProducer).sendMailAccountRefreshMessage(); } + @Test + public void testGetMailAccountFromCache() { + // mock 数据 + MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class); + mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据 + mailAccountService.initLocalCache(); + // 准备参数 + Long id = dbMailAccount.getId(); + + // 调用 + MailAccountDO mailAccount = mailAccountService.getMailAccountFromCache(id); + // 断言 + assertPojoEquals(dbMailAccount, mailAccount); + } + @Test public void testDeleteMailAccount_notExists() { // 准备参数 @@ -149,4 +169,35 @@ public class MailAccountServiceImplTest extends BaseDbUnitTest { assertPojoEquals(dbMailAccount, pageResult.getList().get(0)); } + @Test + public void testGetMailAccount() { + // mock 数据 + MailAccountDO dbMailAccount = randomPojo(MailAccountDO.class); + mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据 + // 准备参数 + Long id = dbMailAccount.getId(); + + // 调用 + MailAccountDO mailAccount = mailAccountService.getMailAccount(id); + // 断言 + assertPojoEquals(dbMailAccount, mailAccount); + } + + @Test + public void testGetMailAccountList() { + // mock 数据 + MailAccountDO dbMailAccount01 = randomPojo(MailAccountDO.class); + mailAccountMapper.insert(dbMailAccount01); + MailAccountDO dbMailAccount02 = randomPojo(MailAccountDO.class); + mailAccountMapper.insert(dbMailAccount02); + // 准备参数 + + // 调用 + List list = mailAccountService.getMailAccountList(); + // 断言 + assertEquals(2, list.size()); + assertPojoEquals(dbMailAccount01, list.get(0)); + assertPojoEquals(dbMailAccount02, list.get(1)); + } + } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailLogServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailLogServiceImplTest.java index ccf4ba737..53acd0ef0 100755 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailLogServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailLogServiceImplTest.java @@ -116,6 +116,20 @@ public class MailLogServiceImplTest extends BaseDbUnitTest { assertEquals("NullPointerException: 测试异常", dbLog.getSendException()); } + @Test + public void testGetMailLog() { + // mock 数据 + MailLogDO dbMailLog = randomPojo(MailLogDO.class, o -> o.setTemplateParams(randomTemplateParams())); + mailLogMapper.insert(dbMailLog); + // 准备参数 + Long id = dbMailLog.getId(); + + // 调用 + MailLogDO mailLog = mailLogService.getMailLog(id); + // 断言 + assertPojoEquals(dbMailLog, mailLog); + } + @Test public void testGetMailLogPage() { // mock 数据 diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImplTest.java index 2d9dc2b65..911e91c89 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailSendServiceImplTest.java @@ -6,14 +6,20 @@ import cn.hutool.extra.mail.MailUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest; +import cn.iocoder.yudao.framework.test.core.util.RandomUtils; import cn.iocoder.yudao.module.system.dal.dataobject.mail.MailAccountDO; import cn.iocoder.yudao.module.system.dal.dataobject.mail.MailTemplateDO; +import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; +import cn.iocoder.yudao.module.system.mq.message.mail.MailSendMessage; import cn.iocoder.yudao.module.system.mq.producer.mail.MailProducer; +import cn.iocoder.yudao.module.system.service.member.MemberService; +import cn.iocoder.yudao.module.system.service.user.AdminUserService; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.MockedStatic; import java.util.HashMap; import java.util.Map; @@ -23,6 +29,7 @@ import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServic import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; @@ -31,6 +38,10 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { @InjectMocks private MailSendServiceImpl mailSendService; + @Mock + private AdminUserService adminUserService; + @Mock + private MemberService memberService; @Mock private MailAccountService mailAccountService; @Mock @@ -55,6 +66,82 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { System.out.println("发送结果:" + messageId); } + @Test + public void testSendSingleMailToAdmin() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = RandomUtils.randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock adminUserService 的方法 + AdminUserDO user = randomPojo(AdminUserDO.class, o -> o.setMobile("15601691300")); + when(adminUserService.getUser(eq(userId))).thenReturn(user); + + // mock MailTemplateService 的方法 + MailTemplateDO template = randomPojo(MailTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = RandomUtils.randomString(); + when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock MailAccountService 的方法 + MailAccountDO account = randomPojo(MailAccountDO.class); + when(mailAccountService.getMailAccountFromCache(eq(template.getAccountId()))).thenReturn(account); + // mock MailLogService 的方法 + Long mailLogId = randomLongId(); + when(mailLogService.createMailLog(eq(userId), eq(UserTypeEnum.ADMIN.getValue()), eq(user.getEmail()), + eq(account), eq(template), eq(content), eq(templateParams), eq(true))).thenReturn(mailLogId); + + // 调用 + Long resultMailLogId = mailSendService.sendSingleMailToAdmin(null, userId, templateCode, templateParams); + // 断言 + assertEquals(mailLogId, resultMailLogId); + // 断言调用 + verify(mailProducer).sendMailSendMessage(eq(mailLogId), eq(user.getEmail()), + eq(account.getId()), eq(template.getNickname()), eq(template.getTitle()), eq(content)); + } + + @Test + public void testSendSingleMailToMember() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = RandomUtils.randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock memberService 的方法 + String mail = randomEmail(); + when(memberService.getMemberUserEmail(eq(userId))).thenReturn(mail); + + // mock MailTemplateService 的方法 + MailTemplateDO template = randomPojo(MailTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = RandomUtils.randomString(); + when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock MailAccountService 的方法 + MailAccountDO account = randomPojo(MailAccountDO.class); + when(mailAccountService.getMailAccountFromCache(eq(template.getAccountId()))).thenReturn(account); + // mock MailLogService 的方法 + Long mailLogId = randomLongId(); + when(mailLogService.createMailLog(eq(userId), eq(UserTypeEnum.MEMBER.getValue()), eq(mail), + eq(account), eq(template), eq(content), eq(templateParams), eq(true))).thenReturn(mailLogId); + + // 调用 + Long resultMailLogId = mailSendService.sendSingleMailToMember(null, userId, templateCode, templateParams); + // 断言 + assertEquals(mailLogId, resultMailLogId); + // 断言调用 + verify(mailProducer).sendMailSendMessage(eq(mailLogId), eq(mail), + eq(account.getId()), eq(template.getNickname()), eq(template.getTitle()), eq(content)); + } + /** * 发送成功,当短信模板开启时 */ @@ -64,7 +151,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { String mail = randomEmail(); Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); - String templateCode = randomString(); + String templateCode = RandomUtils.randomString(); Map templateParams = MapUtil.builder().put("code", "1234") .put("op", "login").build(); // mock MailTemplateService 的方法 @@ -74,7 +161,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { o.setParams(Lists.newArrayList("code", "op")); }); when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); - String content = randomString(); + String content = RandomUtils.randomString(); when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams))) .thenReturn(content); // mock MailAccountService 的方法 @@ -103,7 +190,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { String mail = randomEmail(); Long userId = randomLongId(); Integer userType = randomEle(UserTypeEnum.values()).getValue(); - String templateCode = randomString(); + String templateCode = RandomUtils.randomString(); Map templateParams = MapUtil.builder().put("code", "1234") .put("op", "login").build(); // mock MailTemplateService 的方法 @@ -113,7 +200,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { o.setParams(Lists.newArrayList("code", "op")); }); when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); - String content = randomString(); + String content = RandomUtils.randomString(); when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams))) .thenReturn(content); // mock MailAccountService 的方法 @@ -134,18 +221,18 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { } @Test - public void testCheckMailTemplateValid_notExists() { + public void testValidateMailTemplateValid_notExists() { // 准备参数 - String templateCode = randomString(); + String templateCode = RandomUtils.randomString(); // mock 方法 // 调用,并断言异常 - assertServiceException(() -> mailSendService.checkMailTemplateValid(templateCode), + assertServiceException(() -> mailSendService.validateMailTemplate(templateCode), MAIL_TEMPLATE_NOT_EXISTS); } @Test - public void testBuildTemplateParams_paramMiss() { + public void testValidateTemplateParams_paramMiss() { // 准备参数 MailTemplateDO template = randomPojo(MailTemplateDO.class, o -> o.setParams(Lists.newArrayList("code"))); @@ -153,18 +240,80 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest { // mock 方法 // 调用,并断言异常 - assertServiceException(() -> mailSendService.checkTemplateParams(template, templateParams), + assertServiceException(() -> mailSendService.validateTemplateParams(template, templateParams), MAIL_SEND_TEMPLATE_PARAM_MISS, "code"); } @Test - public void testCheckMail_notExists() { + public void testValidateMail_notExists() { // 准备参数 // mock 方法 // 调用,并断言异常 - assertServiceException(() -> mailSendService.checkMail(null), + assertServiceException(() -> mailSendService.validateMail(null), MAIL_SEND_MAIL_NOT_EXISTS); } + @Test + public void testDoSendMail_success() { + try (MockedStatic mailUtilMock = mockStatic(MailUtil.class)) { + // 准备参数 + MailSendMessage message = randomPojo(MailSendMessage.class, o -> o.setNickname("芋艿")); + // mock 方法(获得邮箱账号) + MailAccountDO account = randomPojo(MailAccountDO.class, o -> o.setMail("7685@qq.com")); + when(mailAccountService.getMailAccountFromCache(eq(message.getAccountId()))) + .thenReturn(account); + + // mock 方法(发送邮件) + String messageId = randomString(); + mailUtilMock.when(() -> MailUtil.send(argThat(mailAccount -> { + assertEquals("芋艿 <7685@qq.com>", mailAccount.getFrom()); + assertTrue(mailAccount.isAuth()); + assertEquals(account.getUsername(), mailAccount.getUser()); + assertEquals(account.getPassword(), mailAccount.getPass()); + assertEquals(account.getHost(), mailAccount.getHost()); + assertEquals(account.getPort(), mailAccount.getPort()); + assertEquals(account.getSslEnable(), mailAccount.isSslEnable()); + return true; + }), eq(message.getMail()), eq(message.getTitle()), eq(message.getContent()), eq(true))) + .thenReturn(messageId); + + // 调用 + mailSendService.doSendMail(message); + // 断言 + verify(mailLogService).updateMailSendResult(eq(message.getLogId()), eq(messageId), isNull()); + } + } + + @Test + public void testDoSendMail_exception() { + try (MockedStatic mailUtilMock = mockStatic(MailUtil.class)) { + // 准备参数 + MailSendMessage message = randomPojo(MailSendMessage.class, o -> o.setNickname("芋艿")); + // mock 方法(获得邮箱账号) + MailAccountDO account = randomPojo(MailAccountDO.class, o -> o.setMail("7685@qq.com")); + when(mailAccountService.getMailAccountFromCache(eq(message.getAccountId()))) + .thenReturn(account); + + // mock 方法(发送邮件) + Exception e = new NullPointerException("啦啦啦"); + mailUtilMock.when(() -> MailUtil.send(argThat(mailAccount -> { + assertEquals("芋艿 <7685@qq.com>", mailAccount.getFrom()); + assertTrue(mailAccount.isAuth()); + assertEquals(account.getUsername(), mailAccount.getUser()); + assertEquals(account.getPassword(), mailAccount.getPass()); + assertEquals(account.getHost(), mailAccount.getHost()); + assertEquals(account.getPort(), mailAccount.getPort()); + assertEquals(account.getSslEnable(), mailAccount.isSslEnable()); + return true; + }), eq(message.getMail()), eq(message.getTitle()), eq(message.getContent()), eq(true))) + .thenThrow(e); + + // 调用 + mailSendService.doSendMail(message); + // 断言 + verify(mailLogService).updateMailSendResult(eq(message.getLogId()), isNull(), same(e)); + } + } + } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailTemplateServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailTemplateServiceImplTest.java index a133fadab..83f23e92e 100755 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailTemplateServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/mail/MailTemplateServiceImplTest.java @@ -14,6 +14,8 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; +import java.util.HashMap; +import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; @@ -25,6 +27,7 @@ import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.MAIL_TEMPLATE_NOT_EXISTS; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.verify; /** * {@link MailTemplateServiceImpl} 的单元测试类 @@ -70,6 +73,7 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest { // 校验记录的属性是否正确 MailTemplateDO mailTemplate = mailTemplateMapper.selectById(mailTemplateId); assertPojoEquals(reqVO, mailTemplate); + verify(mailProducer).sendMailTemplateRefreshMessage(); } @Test @@ -87,6 +91,7 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest { // 校验是否更新正确 MailTemplateDO mailTemplate = mailTemplateMapper.selectById(reqVO.getId()); // 获取最新的 assertPojoEquals(reqVO, mailTemplate); + verify(mailProducer).sendMailTemplateRefreshMessage(); } @Test @@ -108,8 +113,9 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest { // 调用 mailTemplateService.deleteMailTemplate(id); - // 校验数据不存在了 - assertNull(mailTemplateMapper.selectById(id)); + // 校验数据不存在了 + assertNull(mailTemplateMapper.selectById(id)); + verify(mailProducer).sendMailTemplateRefreshMessage(); } @Test @@ -158,4 +164,77 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest { assertPojoEquals(dbMailTemplate, pageResult.getList().get(0)); } + @Test + public void testGetMailTemplateList() { + // mock 数据 + MailTemplateDO dbMailTemplate01 = randomPojo(MailTemplateDO.class); + mailTemplateMapper.insert(dbMailTemplate01); + MailTemplateDO dbMailTemplate02 = randomPojo(MailTemplateDO.class); + mailTemplateMapper.insert(dbMailTemplate02); + + // 调用 + List list = mailTemplateService.getMailTemplateList(); + // 断言 + assertEquals(2, list.size()); + assertEquals(dbMailTemplate01, list.get(0)); + assertEquals(dbMailTemplate02, list.get(1)); + } + + @Test + public void testGetMailTemplate() { + // mock 数据 + MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class); + mailTemplateMapper.insert(dbMailTemplate); + // 准备参数 + Long id = dbMailTemplate.getId(); + + // 调用 + MailTemplateDO mailTemplate = mailTemplateService.getMailTemplate(id); + // 断言 + assertPojoEquals(dbMailTemplate, mailTemplate); + } + + @Test + public void testGetMailTemplateByCodeFromCache() { + // mock 数据 + MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class); + mailTemplateMapper.insert(dbMailTemplate); + mailTemplateService.initLocalCache(); + // 准备参数 + String code = dbMailTemplate.getCode(); + + // 调用 + MailTemplateDO mailTemplate = mailTemplateService.getMailTemplateByCodeFromCache(code); + // 断言 + assertPojoEquals(dbMailTemplate, mailTemplate); + } + + @Test + public void testFormatMailTemplateContent() { + // 准备参数 + Map params = new HashMap<>(); + params.put("name", "小红"); + params.put("what", "饭"); + + // 调用,并断言 + assertEquals("小红,你好,饭吃了吗?", + mailTemplateService.formatMailTemplateContent("{name},你好,{what}吃了吗?", params)); + } + + @Test + public void testCountByAccountId() { + // mock 数据 + MailTemplateDO dbMailTemplate = randomPojo(MailTemplateDO.class); + mailTemplateMapper.insert(dbMailTemplate); + // 测试 accountId 不匹配 + mailTemplateMapper.insert(cloneIgnoreId(dbMailTemplate, o -> o.setAccountId(2L))); + // 准备参数 + Long accountId = dbMailTemplate.getAccountId(); + + // 调用 + long count = mailTemplateService.countByAccountId(accountId); + // 断言 + assertEquals(1, count); + } + } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyMessageServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyMessageServiceImplTest.java index 1087918cc..9e2158da1 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyMessageServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyMessageServiceImplTest.java @@ -108,6 +108,20 @@ public class NotifyMessageServiceImplTest extends BaseDbUnitTest { assertPojoEquals(dbNotifyMessage, pageResult.getList().get(0)); } + @Test + public void testGetNotifyMessage() { + // mock 数据 + NotifyMessageDO dbNotifyMessage = randomPojo(NotifyMessageDO.class, + o -> o.setTemplateParams(randomTemplateParams())); + notifyMessageMapper.insert(dbNotifyMessage); + // 准备参数 + Long id = dbNotifyMessage.getId(); + + // 调用 + NotifyMessageDO notifyMessage = notifyMessageService.getNotifyMessage(id); + assertPojoEquals(dbNotifyMessage, notifyMessage); + } + @Test public void testGetMyNotifyMessagePage() { // mock 数据 diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImplTest.java index ddc214443..7c5078330 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifySendServiceImplTest.java @@ -33,6 +33,62 @@ class NotifySendServiceImplTest extends BaseMockitoUnitTest { @Mock private NotifyMessageService notifyMessageService; + @Test + public void testSendSingleNotifyToAdmin() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock NotifyTemplateService 的方法 + NotifyTemplateDO template = randomPojo(NotifyTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(notifyTemplateService.getNotifyTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = randomString(); + when(notifyTemplateService.formatNotifyTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock NotifyMessageService 的方法 + Long messageId = randomLongId(); + when(notifyMessageService.createNotifyMessage(eq(userId), eq(UserTypeEnum.ADMIN.getValue()), + eq(template), eq(content), eq(templateParams))).thenReturn(messageId); + + // 调用 + Long resultMessageId = notifySendService.sendSingleNotifyToAdmin(userId, templateCode, templateParams); + // 断言 + assertEquals(messageId, resultMessageId); + } + + @Test + public void testSendSingleNotifyToMember() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock NotifyTemplateService 的方法 + NotifyTemplateDO template = randomPojo(NotifyTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(notifyTemplateService.getNotifyTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = randomString(); + when(notifyTemplateService.formatNotifyTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock NotifyMessageService 的方法 + Long messageId = randomLongId(); + when(notifyMessageService.createNotifyMessage(eq(userId), eq(UserTypeEnum.MEMBER.getValue()), + eq(template), eq(content), eq(templateParams))).thenReturn(messageId); + + // 调用 + Long resultMessageId = notifySendService.sendSingleNotifyToMember(userId, templateCode, templateParams); + // 断言 + assertEquals(messageId, resultMessageId); + } + /** * 发送成功,当短信模板开启时 */ @@ -99,7 +155,7 @@ class NotifySendServiceImplTest extends BaseMockitoUnitTest { // mock 方法 // 调用,并断言异常 - assertServiceException(() -> notifySendService.checkNotifyTemplateValid(templateCode), + assertServiceException(() -> notifySendService.validateNotifyTemplate(templateCode), NOTICE_NOT_FOUND); } @@ -112,7 +168,7 @@ class NotifySendServiceImplTest extends BaseMockitoUnitTest { // mock 方法 // 调用,并断言异常 - assertServiceException(() -> notifySendService.checkTemplateParams(template, templateParams), + assertServiceException(() -> notifySendService.validateTemplateParams(template, templateParams), NOTIFY_SEND_TEMPLATE_PARAM_MISS, "code"); } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImplTest.java index 5a6f5a508..28f6f9a38 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/notify/NotifyTemplateServiceImplTest.java @@ -14,6 +14,8 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; +import java.util.HashMap; +import java.util.Map; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; @@ -143,4 +145,44 @@ public class NotifyTemplateServiceImplTest extends BaseDbUnitTest { assertPojoEquals(dbNotifyTemplate, pageResult.getList().get(0)); } + @Test + public void testGetNotifyTemplate() { + // mock 数据 + NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class); + notifyTemplateMapper.insert(dbNotifyTemplate); + // 准备参数 + Long id = dbNotifyTemplate.getId(); + + // 调用 + NotifyTemplateDO notifyTemplate = notifyTemplateService.getNotifyTemplate(id); + // 断言 + assertPojoEquals(dbNotifyTemplate, notifyTemplate); + } + + @Test + public void testGetNotifyTemplateByCodeFromCache() { + // mock 数据 + NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class); + notifyTemplateMapper.insert(dbNotifyTemplate); + notifyTemplateService.initLocalCache(); + // 准备参数 + String code = dbNotifyTemplate.getCode(); + + // 调用 + NotifyTemplateDO notifyTemplate = notifyTemplateService.getNotifyTemplateByCodeFromCache(code); + // 断言 + assertPojoEquals(dbNotifyTemplate, notifyTemplate); + } + + @Test + public void testFormatNotifyTemplateContent() { + // 准备参数 + Map params = new HashMap<>(); + params.put("name", "小红"); + params.put("what", "饭"); + + // 调用,并断言 + assertEquals("小红,你好,饭吃了吗?", + notifyTemplateService.formatNotifyTemplateContent("{name},你好,{what}吃了吗?", params)); + } } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImplTest.java index 40a080b6a..141236987 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sensitiveword/SensitiveWordServiceImplTest.java @@ -60,7 +60,7 @@ public class SensitiveWordServiceImplTest extends BaseDbUnitTest { // 调用 sensitiveWordService.initLocalCache(); // 断言 sensitiveWordTagsCache 缓存 - assertEquals(SetUtils.asSet("论坛", "蔬菜"), sensitiveWordService.getSensitiveWordTags()); + assertEquals(SetUtils.asSet("论坛", "蔬菜"), sensitiveWordService.getSensitiveWordTagSet()); // 断言 tagSensitiveWordTries 缓存 assertNotNull(sensitiveWordService.getDefaultSensitiveWordTrie()); assertEquals(2, sensitiveWordService.getTagSensitiveWordTries().size()); diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceImplTest.java new file mode 100644 index 000000000..0f7d0f9b7 --- /dev/null +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsSendServiceImplTest.java @@ -0,0 +1,288 @@ +package cn.iocoder.yudao.module.system.service.sms; + +import cn.hutool.core.map.MapUtil; +import cn.iocoder.yudao.framework.common.core.KeyValue; +import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; +import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; +import cn.iocoder.yudao.framework.sms.core.client.SmsClient; +import cn.iocoder.yudao.framework.sms.core.client.SmsClientFactory; +import cn.iocoder.yudao.framework.sms.core.client.SmsCommonResult; +import cn.iocoder.yudao.framework.sms.core.client.dto.SmsReceiveRespDTO; +import cn.iocoder.yudao.framework.sms.core.client.dto.SmsSendRespDTO; +import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest; +import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsChannelDO; +import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsTemplateDO; +import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; +import cn.iocoder.yudao.module.system.mq.message.sms.SmsSendMessage; +import cn.iocoder.yudao.module.system.mq.producer.sms.SmsProducer; +import cn.iocoder.yudao.module.system.service.member.MemberService; +import cn.iocoder.yudao.module.system.service.user.AdminUserService; +import org.assertj.core.util.Lists; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static cn.hutool.core.util.RandomUtil.randomEle; +import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; +import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; +import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +public class SmsSendServiceImplTest extends BaseMockitoUnitTest { + + @InjectMocks + private SmsSendServiceImpl smsService; + + @Mock + private AdminUserService adminUserService; + @Mock + private MemberService memberService; + @Mock + private SmsChannelService smsChannelService; + @Mock + private SmsTemplateService smsTemplateService; + @Mock + private SmsLogService smsLogService; + @Mock + private SmsProducer smsProducer; + + @Mock + private SmsClientFactory smsClientFactory; + + @Test + public void testSendSingleSmsToAdmin() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock adminUserService 的方法 + AdminUserDO user = randomPojo(AdminUserDO.class, o -> o.setMobile("15601691300")); + when(adminUserService.getUser(eq(userId))).thenReturn(user); + + // mock SmsTemplateService 的方法 + SmsTemplateDO template = randomPojo(SmsTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(smsTemplateService.getSmsTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = randomString(); + when(smsTemplateService.formatSmsTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock SmsChannelService 的方法 + SmsChannelDO smsChannel = randomPojo(SmsChannelDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + when(smsChannelService.getSmsChannel(eq(template.getChannelId()))).thenReturn(smsChannel); + // mock SmsLogService 的方法 + Long smsLogId = randomLongId(); + when(smsLogService.createSmsLog(eq(user.getMobile()), eq(userId), eq(UserTypeEnum.ADMIN.getValue()), eq(Boolean.TRUE), eq(template), + eq(content), eq(templateParams))).thenReturn(smsLogId); + + // 调用 + Long resultSmsLogId = smsService.sendSingleSmsToAdmin(null, userId, templateCode, templateParams); + // 断言 + assertEquals(smsLogId, resultSmsLogId); + // 断言调用 + verify(smsProducer).sendSmsSendMessage(eq(smsLogId), eq(user.getMobile()), + eq(template.getChannelId()), eq(template.getApiTemplateId()), + eq(Lists.newArrayList(new KeyValue<>("code", "1234"), new KeyValue<>("op", "login")))); + } + + @Test + public void testSendSingleSmsToUser() { + // 准备参数 + Long userId = randomLongId(); + String templateCode = randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock memberService 的方法 + String mobile = "15601691300"; + when(memberService.getMemberUserMobile(eq(userId))).thenReturn(mobile); + + // mock SmsTemplateService 的方法 + SmsTemplateDO template = randomPojo(SmsTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(smsTemplateService.getSmsTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = randomString(); + when(smsTemplateService.formatSmsTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock SmsChannelService 的方法 + SmsChannelDO smsChannel = randomPojo(SmsChannelDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + when(smsChannelService.getSmsChannel(eq(template.getChannelId()))).thenReturn(smsChannel); + // mock SmsLogService 的方法 + Long smsLogId = randomLongId(); + when(smsLogService.createSmsLog(eq(mobile), eq(userId), eq(UserTypeEnum.MEMBER.getValue()), eq(Boolean.TRUE), eq(template), + eq(content), eq(templateParams))).thenReturn(smsLogId); + + // 调用 + Long resultSmsLogId = smsService.sendSingleSmsToMember(null, userId, templateCode, templateParams); + // 断言 + assertEquals(smsLogId, resultSmsLogId); + // 断言调用 + verify(smsProducer).sendSmsSendMessage(eq(smsLogId), eq(mobile), + eq(template.getChannelId()), eq(template.getApiTemplateId()), + eq(Lists.newArrayList(new KeyValue<>("code", "1234"), new KeyValue<>("op", "login")))); + } + + /** + * 发送成功,当短信模板开启时 + */ + @Test + public void testSendSingleSms_successWhenSmsTemplateEnable() { + // 准备参数 + String mobile = randomString(); + Long userId = randomLongId(); + Integer userType = randomEle(UserTypeEnum.values()).getValue(); + String templateCode = randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock SmsTemplateService 的方法 + SmsTemplateDO template = randomPojo(SmsTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.ENABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(smsTemplateService.getSmsTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = randomString(); + when(smsTemplateService.formatSmsTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock SmsChannelService 的方法 + SmsChannelDO smsChannel = randomPojo(SmsChannelDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + when(smsChannelService.getSmsChannel(eq(template.getChannelId()))).thenReturn(smsChannel); + // mock SmsLogService 的方法 + Long smsLogId = randomLongId(); + when(smsLogService.createSmsLog(eq(mobile), eq(userId), eq(userType), eq(Boolean.TRUE), eq(template), + eq(content), eq(templateParams))).thenReturn(smsLogId); + + // 调用 + Long resultSmsLogId = smsService.sendSingleSms(mobile, userId, userType, templateCode, templateParams); + // 断言 + assertEquals(smsLogId, resultSmsLogId); + // 断言调用 + verify(smsProducer).sendSmsSendMessage(eq(smsLogId), eq(mobile), + eq(template.getChannelId()), eq(template.getApiTemplateId()), + eq(Lists.newArrayList(new KeyValue<>("code", "1234"), new KeyValue<>("op", "login")))); + } + + /** + * 发送成功,当短信模板关闭时 + */ + @Test + public void testSendSingleSms_successWhenSmsTemplateDisable() { + // 准备参数 + String mobile = randomString(); + Long userId = randomLongId(); + Integer userType = randomEle(UserTypeEnum.values()).getValue(); + String templateCode = randomString(); + Map templateParams = MapUtil.builder().put("code", "1234") + .put("op", "login").build(); + // mock SmsTemplateService 的方法 + SmsTemplateDO template = randomPojo(SmsTemplateDO.class, o -> { + o.setStatus(CommonStatusEnum.DISABLE.getStatus()); + o.setContent("验证码为{code}, 操作为{op}"); + o.setParams(Lists.newArrayList("code", "op")); + }); + when(smsTemplateService.getSmsTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); + String content = randomString(); + when(smsTemplateService.formatSmsTemplateContent(eq(template.getContent()), eq(templateParams))) + .thenReturn(content); + // mock SmsChannelService 的方法 + SmsChannelDO smsChannel = randomPojo(SmsChannelDO.class, o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus())); + when(smsChannelService.getSmsChannel(eq(template.getChannelId()))).thenReturn(smsChannel); + // mock SmsLogService 的方法 + Long smsLogId = randomLongId(); + when(smsLogService.createSmsLog(eq(mobile), eq(userId), eq(userType), eq(Boolean.FALSE), eq(template), + eq(content), eq(templateParams))).thenReturn(smsLogId); + + // 调用 + Long resultSmsLogId = smsService.sendSingleSms(mobile, userId, userType, templateCode, templateParams); + // 断言 + assertEquals(smsLogId, resultSmsLogId); + // 断言调用 + verify(smsProducer, times(0)).sendSmsSendMessage(anyLong(), anyString(), + anyLong(), any(), anyList()); + } + + @Test + public void testCheckSmsTemplateValid_notExists() { + // 准备参数 + String templateCode = randomString(); + // mock 方法 + + // 调用,并断言异常 + assertServiceException(() -> smsService.validateSmsTemplate(templateCode), + SMS_SEND_TEMPLATE_NOT_EXISTS); + } + + @Test + public void testBuildTemplateParams_paramMiss() { + // 准备参数 + SmsTemplateDO template = randomPojo(SmsTemplateDO.class, + o -> o.setParams(Lists.newArrayList("code"))); + Map templateParams = new HashMap<>(); + // mock 方法 + + // 调用,并断言异常 + assertServiceException(() -> smsService.buildTemplateParams(template, templateParams), + SMS_SEND_MOBILE_TEMPLATE_PARAM_MISS, "code"); + } + + @Test + public void testCheckMobile_notExists() { + // 准备参数 + // mock 方法 + + // 调用,并断言异常 + assertServiceException(() -> smsService.validateMobile(null), + SMS_SEND_MOBILE_NOT_EXISTS); + } + + @Test + @SuppressWarnings("unchecked") + public void testDoSendSms() { + // 准备参数 + SmsSendMessage message = randomPojo(SmsSendMessage.class); + // mock SmsClientFactory 的方法 + SmsClient smsClient = spy(SmsClient.class); + when(smsClientFactory.getSmsClient(eq(message.getChannelId()))).thenReturn(smsClient); + // mock SmsClient 的方法 + SmsCommonResult sendResult = randomPojo(SmsCommonResult.class, SmsSendRespDTO.class); + when(smsClient.sendSms(eq(message.getLogId()), eq(message.getMobile()), eq(message.getApiTemplateId()), + eq(message.getTemplateParams()))).thenReturn(sendResult); + + // 调用 + smsService.doSendSms(message); + // 断言 + verify(smsLogService).updateSmsSendResult(eq(message.getLogId()), + eq(sendResult.getCode()), eq(sendResult.getMsg()), eq(sendResult.getApiCode()), + eq(sendResult.getApiMsg()), eq(sendResult.getApiRequestId()), eq(sendResult.getData().getSerialNo())); + } + + @Test + public void testReceiveSmsStatus() throws Throwable { + // 准备参数 + String channelCode = randomString(); + String text = randomString(); + // mock SmsClientFactory 的方法 + SmsClient smsClient = spy(SmsClient.class); + when(smsClientFactory.getSmsClient(eq(channelCode))).thenReturn(smsClient); + // mock SmsClient 的方法 + List receiveResults = randomPojoList(SmsReceiveRespDTO.class); + + // 调用 + smsService.receiveSmsStatus(channelCode, text); + // 断言 + receiveResults.forEach(result -> smsLogService.updateSmsReceiveResult(eq(result.getLogId()), eq(result.getSuccess()), + eq(result.getReceiveTime()), eq(result.getErrorCode()), eq(result.getErrorCode()))); + } + +} diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImplTest.java index f0c4df40a..3b9b577a2 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImplTest.java @@ -279,7 +279,7 @@ public class SmsTemplateServiceImplTest extends BaseDbUnitTest { } @Test - public void testCheckSmsChannel_success() { + public void testValidateSmsChannel_success() { // 准备参数 Long channelId = randomLongId(); // mock 方法 @@ -290,23 +290,23 @@ public class SmsTemplateServiceImplTest extends BaseDbUnitTest { when(smsChannelService.getSmsChannel(eq(channelId))).thenReturn(channelDO); // 调用 - SmsChannelDO returnChannelDO = smsTemplateService.checkSmsChannel(channelId); + SmsChannelDO returnChannelDO = smsTemplateService.validateSmsChannel(channelId); // 断言 assertPojoEquals(returnChannelDO, channelDO); } @Test - public void testCheckSmsChannel_notExists() { + public void testValidateSmsChannel_notExists() { // 准备参数 Long channelId = randomLongId(); // 调用,校验异常 - assertServiceException(() -> smsTemplateService.checkSmsChannel(channelId), + assertServiceException(() -> smsTemplateService.validateSmsChannel(channelId), SMS_CHANNEL_NOT_EXISTS); } @Test - public void testCheckSmsChannel_disable() { + public void testValidateSmsChannel_disable() { // 准备参数 Long channelId = randomLongId(); // mock 方法 @@ -317,30 +317,30 @@ public class SmsTemplateServiceImplTest extends BaseDbUnitTest { when(smsChannelService.getSmsChannel(eq(channelId))).thenReturn(channelDO); // 调用,校验异常 - assertServiceException(() -> smsTemplateService.checkSmsChannel(channelId), + assertServiceException(() -> smsTemplateService.validateSmsChannel(channelId), SMS_CHANNEL_DISABLE); } @Test - public void testCheckDictDataValueUnique_success() { + public void testValidateDictDataValueUnique_success() { // 调用,成功 - smsTemplateService.checkSmsTemplateCodeDuplicate(randomLongId(), randomString()); + smsTemplateService.validateSmsTemplateCodeDuplicate(randomLongId(), randomString()); } @Test - public void testCheckSmsTemplateCodeDuplicate_valueDuplicateForCreate() { + public void testValidateSmsTemplateCodeDuplicate_valueDuplicateForCreate() { // 准备参数 String code = randomString(); // mock 数据 smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code))); // 调用,校验异常 - assertServiceException(() -> smsTemplateService.checkSmsTemplateCodeDuplicate(null, code), + assertServiceException(() -> smsTemplateService.validateSmsTemplateCodeDuplicate(null, code), SMS_TEMPLATE_CODE_DUPLICATE, code); } @Test - public void testCheckDictDataValueUnique_valueDuplicateForUpdate() { + public void testValidateDictDataValueUnique_valueDuplicateForUpdate() { // 准备参数 Long id = randomLongId(); String code = randomString(); @@ -348,7 +348,7 @@ public class SmsTemplateServiceImplTest extends BaseDbUnitTest { smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code))); // 调用,校验异常 - assertServiceException(() -> smsTemplateService.checkSmsTemplateCodeDuplicate(id, code), + assertServiceException(() -> smsTemplateService.validateSmsTemplateCodeDuplicate(id, code), SMS_TEMPLATE_CODE_DUPLICATE, code); } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java index 9e33f87fa..f181f177c 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/tenant/TenantServiceImplTest.java @@ -81,13 +81,13 @@ public class TenantServiceImplTest extends BaseDbUnitTest { } @Test - public void testGetTenantIds() { + public void testGetTenantIdList() { // mock 数据 TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L)); tenantMapper.insert(tenant); // 调用,并断言业务异常 - List result = tenantService.getTenantIds(); + List result = tenantService.getTenantIdList(); assertEquals(Collections.singletonList(1L), result); } diff --git a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImplTest.java b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImplTest.java index e881d04e3..a5e0183a4 100644 --- a/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImplTest.java +++ b/yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/user/AdminUserServiceImplTest.java @@ -6,7 +6,6 @@ import cn.iocoder.yudao.framework.common.exception.ServiceException; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; -import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.infra.api.file.FileApi; import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO; @@ -32,23 +31,25 @@ import org.springframework.security.crypto.password.PasswordEncoder; import javax.annotation.Resource; import java.io.ByteArrayInputStream; -import java.time.LocalDateTime; import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.function.Consumer; import static cn.hutool.core.util.RandomUtil.randomBytes; import static cn.hutool.core.util.RandomUtil.randomEle; import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet; -import static cn.iocoder.yudao.framework.common.util.date.DateUtils.buildLocalDateTime; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; +import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; +import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static java.util.Collections.singleton; +import static java.util.Collections.singletonList; import static org.assertj.core.util.Lists.newArrayList; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; @@ -173,6 +174,23 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { assertEquals(3L, userPosts.get(1).getPostId()); } + @Test + public void testUpdateUserLogin() { + // mock 数据 + AdminUserDO user = randomAdminUserDO(o -> o.setLoginDate(null)); + userMapper.insert(user); + // 准备参数 + Long id = user.getId(); + String loginIp = randomString(); + + // 调用 + userService.updateUserLogin(id, loginIp); + // 断言 + AdminUserDO dbUser = userMapper.selectById(id); + assertEquals(loginIp, dbUser.getLoginIp()); + assertNotNull(dbUser.getLoginDate()); + } + @Test public void testUpdateUserProfile_success() { // mock 数据 @@ -286,6 +304,34 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { verify(permissionService, times(1)).processUserDeleted(eq(userId)); } + @Test + public void testGetUserByUsername() { + // mock 数据 + AdminUserDO dbUser = randomAdminUserDO(); + userMapper.insert(dbUser); + // 准备参数 + String username = dbUser.getUsername(); + + // 调用 + AdminUserDO user = userService.getUserByUsername(username); + // 断言 + assertPojoEquals(dbUser, user); + } + + @Test + public void testGetUserByMobile() { + // mock 数据 + AdminUserDO dbUser = randomAdminUserDO(); + userMapper.insert(dbUser); + // 准备参数 + String mobile = dbUser.getMobile(); + + // 调用 + AdminUserDO user = userService.getUserByMobile(mobile); + // 断言 + assertPojoEquals(dbUser, user); + } + @Test public void testGetUserPage() { // mock 数据 @@ -295,8 +341,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { reqVO.setUsername("tu"); reqVO.setMobile("1560"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildLocalDateTime(2020, 12, 1), - buildLocalDateTime(2020, 12, 24)})); + reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24)); reqVO.setDeptId(1L); // 其中,1L 是 2L 的父部门 // mock 方法 List deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L))); @@ -311,7 +356,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { } @Test - public void testGetUsers() { + public void testGetUserList_export() { // mock 数据 AdminUserDO dbUser = initGetUserPageData(); // 准备参数 @@ -319,15 +364,14 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { reqVO.setUsername("tu"); reqVO.setMobile("1560"); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); - reqVO.setCreateTime((new LocalDateTime[]{buildLocalDateTime(2020, 12, 1), - buildLocalDateTime(2020, 12, 24)})); + reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24)); reqVO.setDeptId(1L); // 其中,1L 是 2L 的父部门 // mock 方法 List deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L))); when(deptService.getDeptListByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList); // 调用 - List list = userService.getUsers(reqVO); + List list = userService.getUserList(reqVO); // 断言 assertEquals(1, list.size()); assertPojoEquals(dbUser, list.get(0)); @@ -342,28 +386,59 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { o.setUsername("tudou"); o.setMobile("15601691300"); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); - o.setCreateTime(buildLocalDateTime(2020, 12, 12)); + o.setCreateTime(buildTime(2020, 12, 12)); o.setDeptId(2L); }); userMapper.insert(dbUser); // 测试 username 不匹配 - userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setUsername("dou"))); + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setUsername("dou"))); // 测试 mobile 不匹配 - userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setMobile("18818260888"))); + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setMobile("18818260888"))); // 测试 status 不匹配 - userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 测试 createTime 不匹配 - userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setCreateTime(buildLocalDateTime(2020, 11, 11)))); + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setCreateTime(buildTime(2020, 11, 11)))); // 测试 dept 不匹配 - userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setDeptId(0L))); + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setDeptId(0L))); return dbUser; } + @Test + public void testGetUser() { + // mock 数据 + AdminUserDO dbUser = randomAdminUserDO(); + userMapper.insert(dbUser); + // 准备参数 + Long userId = dbUser.getId(); + + // 调用 + AdminUserDO user = userService.getUser(userId); + // 断言 + assertPojoEquals(dbUser, user); + } + + @Test + public void testGetUserListByDeptIds() { + // mock 数据 + AdminUserDO dbUser = randomAdminUserDO(o -> o.setDeptId(1L)); + userMapper.insert(dbUser); + // 测试 deptId 不匹配 + userMapper.insert(cloneIgnoreId(dbUser, o -> o.setDeptId(2L))); + // 准备参数 + Collection deptIds = singleton(1L); + + // 调用 + List list = userService.getUserListByDeptIds(deptIds); + // 断言 + assertEquals(1, list.size()); + assertEquals(dbUser, list.get(0)); + } + /** * 情况一,校验不通过,导致插入失败 */ @Test - public void testImportUsers_01() { + public void testImportUserList_01() { // 准备参数 UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { }); @@ -371,7 +446,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { doThrow(new ServiceException(DEPT_NOT_FOUND)).when(deptService).validateDeptList(any()); // 调用 - UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true); + UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true); // 断言 assertEquals(0, respVO.getCreateUsernames().size()); assertEquals(0, respVO.getUpdateUsernames().size()); @@ -383,7 +458,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { * 情况二,不存在,进行插入 */ @Test - public void testImportUsers_02() { + public void testImportUserList_02() { // 准备参数 UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 @@ -399,7 +474,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { when(passwordEncoder.encode(eq("yudaoyuanma"))).thenReturn("java"); // 调用 - UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true); + UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true); // 断言 assertEquals(1, respVO.getCreateUsernames().size()); AdminUserDO user = userMapper.selectByUsername(respVO.getCreateUsernames().get(0)); @@ -413,7 +488,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { * 情况三,存在,但是不强制更新 */ @Test - public void testImportUsers_03() { + public void testImportUserList_03() { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(); userMapper.insert(dbUser); @@ -431,7 +506,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { when(deptService.getDept(eq(dept.getId()))).thenReturn(dept); // 调用 - UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), false); + UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), false); // 断言 assertEquals(0, respVO.getCreateUsernames().size()); assertEquals(0, respVO.getUpdateUsernames().size()); @@ -443,7 +518,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { * 情况四,存在,强制更新 */ @Test - public void testImportUsers_04() { + public void testImportUserList_04() { // mock 数据 AdminUserDO dbUser = randomAdminUserDO(); userMapper.insert(dbUser); @@ -461,7 +536,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { when(deptService.getDept(eq(dept.getId()))).thenReturn(dept); // 调用 - UserImportRespVO respVO = userService.importUsers(newArrayList(importUser), true); + UserImportRespVO respVO = userService.importUserList(newArrayList(importUser), true); // 断言 assertEquals(0, respVO.getCreateUsernames().size()); assertEquals(1, respVO.getUpdateUsernames().size()); @@ -471,24 +546,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { } @Test - public void testCheckUserExists_notExists() { - assertServiceException(() -> userService.checkUserExists(randomLongId()), USER_NOT_EXISTS); + public void testValidateUserExists_notExists() { + assertServiceException(() -> userService.validateUserExists(randomLongId()), USER_NOT_EXISTS); } @Test - public void testCheckUsernameUnique_usernameExistsForCreate() { + public void testValidateUsernameUnique_usernameExistsForCreate() { // 准备参数 String username = randomString(); // mock 数据 userMapper.insert(randomAdminUserDO(o -> o.setUsername(username))); // 调用,校验异常 - assertServiceException(() -> userService.checkUsernameUnique(null, username), + assertServiceException(() -> userService.validateUsernameUnique(null, username), USER_USERNAME_EXISTS); } @Test - public void testCheckUsernameUnique_usernameExistsForUpdate() { + public void testValidateUsernameUnique_usernameExistsForUpdate() { // 准备参数 Long id = randomLongId(); String username = randomString(); @@ -496,24 +571,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { userMapper.insert(randomAdminUserDO(o -> o.setUsername(username))); // 调用,校验异常 - assertServiceException(() -> userService.checkUsernameUnique(id, username), + assertServiceException(() -> userService.validateUsernameUnique(id, username), USER_USERNAME_EXISTS); } @Test - public void testCheckEmailUnique_emailExistsForCreate() { + public void testValidateEmailUnique_emailExistsForCreate() { // 准备参数 String email = randomString(); // mock 数据 userMapper.insert(randomAdminUserDO(o -> o.setEmail(email))); // 调用,校验异常 - assertServiceException(() -> userService.checkEmailUnique(null, email), + assertServiceException(() -> userService.validateEmailUnique(null, email), USER_EMAIL_EXISTS); } @Test - public void testCheckEmailUnique_emailExistsForUpdate() { + public void testValidateEmailUnique_emailExistsForUpdate() { // 准备参数 Long id = randomLongId(); String email = randomString(); @@ -521,24 +596,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { userMapper.insert(randomAdminUserDO(o -> o.setEmail(email))); // 调用,校验异常 - assertServiceException(() -> userService.checkEmailUnique(id, email), + assertServiceException(() -> userService.validateEmailUnique(id, email), USER_EMAIL_EXISTS); } @Test - public void testCheckMobileUnique_mobileExistsForCreate() { + public void testValidateMobileUnique_mobileExistsForCreate() { // 准备参数 String mobile = randomString(); // mock 数据 userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile))); // 调用,校验异常 - assertServiceException(() -> userService.checkMobileUnique(null, mobile), + assertServiceException(() -> userService.validateMobileUnique(null, mobile), USER_MOBILE_EXISTS); } @Test - public void testCheckMobileUnique_mobileExistsForUpdate() { + public void testValidateMobileUnique_mobileExistsForUpdate() { // 准备参数 Long id = randomLongId(); String mobile = randomString(); @@ -546,18 +621,18 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile))); // 调用,校验异常 - assertServiceException(() -> userService.checkMobileUnique(id, mobile), + assertServiceException(() -> userService.validateMobileUnique(id, mobile), USER_MOBILE_EXISTS); } @Test - public void testCheckOldPassword_notExists() { - assertServiceException(() -> userService.checkOldPassword(randomLongId(), randomString()), + public void testValidateOldPassword_notExists() { + assertServiceException(() -> userService.validateOldPassword(randomLongId(), randomString()), USER_NOT_EXISTS); } @Test - public void testCheckOldPassword_passwordFailed() { + public void testValidateOldPassword_passwordFailed() { // mock 数据 AdminUserDO user = randomAdminUserDO(); userMapper.insert(user); @@ -566,14 +641,14 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { String oldPassword = user.getPassword(); // 调用,校验异常 - assertServiceException(() -> userService.checkOldPassword(id, oldPassword), + assertServiceException(() -> userService.validateOldPassword(id, oldPassword), USER_PASSWORD_FAILED); // 校验调用 verify(passwordEncoder, times(1)).matches(eq(oldPassword), eq(user.getPassword())); } @Test - public void testUsersByPostIds() { + public void testUserListByPostIds() { // 准备参数 Collection postIds = asSet(10L, 20L); // mock user1 数据 @@ -587,12 +662,114 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest { userPostMapper.insert(new UserPostDO().setUserId(user2.getId()).setPostId(100L)); // 调用 - List result = userService.getUsersByPostIds(postIds); + List result = userService.getUserListByPostIds(postIds); // 断言 assertEquals(1, result.size()); assertEquals(user1, result.get(0)); } + @Test + public void testGetUserList() { + // mock 数据 + AdminUserDO user = randomAdminUserDO(); + userMapper.insert(user); + // 测试 id 不匹配 + userMapper.insert(randomAdminUserDO()); + // 准备参数 + Collection ids = singleton(user.getId()); + + // 调用 + List result = userService.getUserList(ids); + // 断言 + assertEquals(1, result.size()); + assertEquals(user, result.get(0)); + } + + @Test + public void testGetUserMap() { + // mock 数据 + AdminUserDO user = randomAdminUserDO(); + userMapper.insert(user); + // 测试 id 不匹配 + userMapper.insert(randomAdminUserDO()); + // 准备参数 + Collection ids = singleton(user.getId()); + + // 调用 + Map result = userService.getUserMap(ids); + // 断言 + assertEquals(1, result.size()); + assertEquals(user, result.get(user.getId())); + } + + @Test + public void testGetUserListByNickname() { + // mock 数据 + AdminUserDO user = randomAdminUserDO(o -> o.setNickname("芋头")); + userMapper.insert(user); + // 测试 nickname 不匹配 + userMapper.insert(randomAdminUserDO(o -> o.setNickname("源码"))); + // 准备参数 + String nickname = "芋"; + + // 调用 + List result = userService.getUserListByNickname(nickname); + // 断言 + assertEquals(1, result.size()); + assertEquals(user, result.get(0)); + } + + @Test + public void testGetUserListByStatus() { + // mock 数据 + AdminUserDO user = randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())); + userMapper.insert(user); + // 测试 status 不匹配 + userMapper.insert(randomAdminUserDO(o -> o.setStatus(CommonStatusEnum.ENABLE.getStatus()))); + // 准备参数 + Integer status = CommonStatusEnum.DISABLE.getStatus(); + + // 调用 + List result = userService.getUserListByStatus(status); + // 断言 + assertEquals(1, result.size()); + assertEquals(user, result.get(0)); + } + + @Test + public void testValidateUserList_success() { + // mock 数据 + AdminUserDO userDO = randomAdminUserDO().setStatus(CommonStatusEnum.ENABLE.getStatus()); + userMapper.insert(userDO); + // 准备参数 + List ids = singletonList(userDO.getId()); + + // 调用,无需断言 + userService.validateUserList(ids); + } + + @Test + public void testValidateUserList_notFound() { + // 准备参数 + List ids = singletonList(randomLongId()); + + // 调用, 并断言异常 + assertServiceException(() -> userService.validateUserList(ids), USER_NOT_EXISTS); + } + + @Test + public void testValidateUserList_notEnable() { + // mock 数据 + AdminUserDO userDO = randomAdminUserDO().setStatus(CommonStatusEnum.DISABLE.getStatus()); + userMapper.insert(userDO); + // 准备参数 + List ids = singletonList(userDO.getId()); + + // 调用, 并断言异常 + assertServiceException(() -> userService.validateUserList(ids), USER_IS_DISABLE, + userDO.getNickname()); + } + // ========== 随机对象 ========== @SafeVarargs