Merge branch 'master' of https://gitee.com/zhijiantianya/yudao-cloud into feat/springdoc

# Conflicts:
#	yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/errorcode/ErrorCodeApi.java
#	yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/tenant/TenantApi.java
#	yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/user/AdminUserApi.java
#	yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/auth/AuthController.java
#	yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dept/DeptController.java
#	yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/dept/PostController.java
#	yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/user/UserController.java
pull/25/head
gaibu 2023-02-05 21:28:49 +08:00
commit 65ee76a79f
63 changed files with 1670 additions and 605 deletions

View File

@ -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();
}
}
}

View File

@ -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()));
}
}

View File

@ -49,7 +49,7 @@ public class ErrorCodeAutoGeneratorImpl implements ErrorCodeAutoGenerator {
log.info("[execute][解析到错误码数量为 ({}) 个]", autoGenerateDTOs.size()); log.info("[execute][解析到错误码数量为 ({}) 个]", autoGenerateDTOs.size());
// 第二步,写入到 system 服务 // 第二步,写入到 system 服务
errorCodeApi.autoGenerateErrorCodes(autoGenerateDTOs).checkError(); errorCodeApi.autoGenerateErrorCodeList(autoGenerateDTOs).checkError();
log.info("[execute][写入到 system 组件完成]"); log.info("[execute][写入到 system 组件完成]");
} }

View File

@ -30,7 +30,7 @@ public class TenantFrameworkServiceImpl implements TenantFrameworkService {
@Override @Override
public List<Long> load(Object key) { public List<Long> load(Object key) {
return tenantApi.getTenantIds().getCheckedData(); return tenantApi.getTenantIdList().getCheckedData();
} }
}); });

View File

@ -220,7 +220,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {
} else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.POST.getType())) { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.POST.getType())) {
postApi.validPostList(options); postApi.validPostList(options);
} else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER.getType())) { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER.getType())) {
adminUserApi.validUsers(options); adminUserApi.validUserList(options);
} else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER_GROUP.getType())) { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.USER_GROUP.getType())) {
userGroupService.validUserGroups(options); userGroupService.validUserGroups(options);
} else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.SCRIPT.getType())) { } else if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.SCRIPT.getType())) {
@ -288,7 +288,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {
} }
private Set<Long> calculateTaskCandidateUsersByDeptMember(BpmTaskAssignRuleDO rule) { private Set<Long> calculateTaskCandidateUsersByDeptMember(BpmTaskAssignRuleDO rule) {
List<AdminUserRespDTO> users = adminUserApi.getUsersByDeptIds(rule.getOptions()).getCheckedData(); List<AdminUserRespDTO> users = adminUserApi.getUserListByDeptIds(rule.getOptions()).getCheckedData();
return convertSet(users, AdminUserRespDTO::getId); return convertSet(users, AdminUserRespDTO::getId);
} }
@ -298,7 +298,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {
} }
private Set<Long> calculateTaskCandidateUsersByPost(BpmTaskAssignRuleDO rule) { private Set<Long> calculateTaskCandidateUsersByPost(BpmTaskAssignRuleDO rule) {
List<AdminUserRespDTO> users = adminUserApi.getUsersByPostIds(rule.getOptions()).getCheckedData(); List<AdminUserRespDTO> users = adminUserApi.getUserListByPostIds(rule.getOptions()).getCheckedData();
return convertSet(users, AdminUserRespDTO::getId); return convertSet(users, AdminUserRespDTO::getId);
} }

View File

@ -87,7 +87,7 @@ public class BpmTaskAssignRuleServiceImplTest extends BaseDbUnitTest {
// mock 方法 // mock 方法
List<AdminUserRespDTO> users = CollectionUtils.convertList(asSet(11L, 22L), List<AdminUserRespDTO> users = CollectionUtils.convertList(asSet(11L, 22L),
id -> new AdminUserRespDTO().setId(id)); 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)); mockGetUserMap(asSet(11L, 22L));
// 调用 // 调用
@ -121,7 +121,7 @@ public class BpmTaskAssignRuleServiceImplTest extends BaseDbUnitTest {
// mock 方法 // mock 方法
List<AdminUserRespDTO> users = CollectionUtils.convertList(asSet(11L, 22L), List<AdminUserRespDTO> users = CollectionUtils.convertList(asSet(11L, 22L),
id -> new AdminUserRespDTO().setId(id)); 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)); mockGetUserMap(asSet(11L, 22L));
// 调用 // 调用

View File

@ -1,6 +1,5 @@
package cn.iocoder.yudao.module.infra.controller.admin.config; 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.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils; import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
@ -23,6 +22,7 @@ import javax.validation.Valid;
import java.io.IOException; import java.io.IOException;
import java.util.List; 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.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT; import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
@ -76,7 +76,7 @@ public class ConfigController {
return null; return null;
} }
if (!config.getVisible()) { 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()); return success(config.getValue());
} }
@ -93,7 +93,7 @@ public class ConfigController {
@Operation(summary = "导出参数配置") @Operation(summary = "导出参数配置")
@PreAuthorize("@ss.hasPermission('infra:config:export')") @PreAuthorize("@ss.hasPermission('infra:config:export')")
@OperateLog(type = EXPORT) @OperateLog(type = EXPORT)
public void exportSysConfig(@Valid ConfigExportReqVO reqVO, public void exportConfig(@Valid ConfigExportReqVO reqVO,
HttpServletResponse response) throws IOException { HttpServletResponse response) throws IOException {
List<ConfigDO> list = configService.getConfigList(reqVO); List<ConfigDO> list = configService.getConfigList(reqVO);
// 拼接数据 // 拼接数据

View File

@ -39,27 +39,38 @@ public class CodegenColumnDO extends BaseDO {
/** /**
* *
*
* {@link TableField#getName()}
*/ */
private String columnName; private String columnName;
/** /**
* *
*
* {@link TableField.MetaInfo#getJdbcType()} * {@link TableField.MetaInfo#getJdbcType()}
*/ */
private String dataType; private String dataType;
/** /**
* *
*
* {@link TableField#getComment()}
*/ */
private String columnComment; private String columnComment;
/** /**
* *
*
* {@link TableField.MetaInfo#isNullable()}
*/ */
private Boolean nullable; private Boolean nullable;
/** /**
* *
*
* {@link TableField#isKeyFlag()}
*/ */
private Boolean primaryKey; private Boolean primaryKey;
/** /**
* *
*
* {@link TableField#isKeyIdentityFlag()}
*/ */
private Boolean autoIncrement; private Boolean autoIncrement;
/** /**
@ -71,12 +82,16 @@ public class CodegenColumnDO extends BaseDO {
/** /**
* Java * Java
* <p> *
* StringBoolean * StringBoolean
*
* {@link TableField#getColumnType()}
*/ */
private String javaType; private String javaType;
/** /**
* Java * Java
*
* {@link TableField#getPropertyName()}
*/ */
private String javaField; private String javaField;
/** /**

View File

@ -6,6 +6,7 @@ import cn.iocoder.yudao.module.infra.enums.codegen.CodegenSceneEnum;
import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum; import cn.iocoder.yudao.module.infra.enums.codegen.CodegenTemplateTypeEnum;
import com.baomidou.mybatisplus.annotation.KeySequence; import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
@ -44,10 +45,14 @@ public class CodegenTableDO extends BaseDO {
/** /**
* *
*
* {@link TableInfo#getName()}
*/ */
private String tableName; private String tableName;
/** /**
* *
*
* {@link TableInfo#getComment()}
*/ */
private String tableComment; private String tableComment;
/** /**

View File

@ -28,6 +28,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.BiPredicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; 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) { private Long createCodegen0(Long userId, Long dataSourceConfigId, TableInfo tableInfo) {
// 校验导入的表和字段非空 // 校验导入的表和字段非空
checkTableInfo(tableInfo); validateTableInfo(tableInfo);
// 校验是否已经存在 // 校验是否已经存在
if (codegenTableMapper.selectByTableNameAndDataSourceConfigId(tableInfo.getName(), if (codegenTableMapper.selectByTableNameAndDataSourceConfigId(tableInfo.getName(),
dataSourceConfigId) != null) { dataSourceConfigId) != null) {
@ -86,7 +87,7 @@ public class CodegenServiceImpl implements CodegenService {
CodegenTableDO table = codegenBuilder.buildTable(tableInfo); CodegenTableDO table = codegenBuilder.buildTable(tableInfo);
table.setDataSourceConfigId(dataSourceConfigId); table.setDataSourceConfigId(dataSourceConfigId);
table.setScene(CodegenSceneEnum.ADMIN.getScene()); // 默认配置下,使用管理后台的模板 table.setScene(CodegenSceneEnum.ADMIN.getScene()); // 默认配置下,使用管理后台的模板
table.setAuthor(userApi.getUser(userId).getData().getNickname()); table.setAuthor(userApi.getUser(userId).getCheckedData().getNickname());
codegenTableMapper.insert(table); codegenTableMapper.insert(table);
// 构建 CodegenColumnDO 数组,插入到 DB 中 // 构建 CodegenColumnDO 数组,插入到 DB 中
@ -99,7 +100,7 @@ public class CodegenServiceImpl implements CodegenService {
return table.getId(); return table.getId();
} }
private void checkTableInfo(TableInfo tableInfo) { private void validateTableInfo(TableInfo tableInfo) {
if (tableInfo == null) { if (tableInfo == null) {
throw exception(CODEGEN_IMPORT_TABLE_NULL); throw exception(CODEGEN_IMPORT_TABLE_NULL);
} }
@ -148,18 +149,33 @@ public class CodegenServiceImpl implements CodegenService {
private void syncCodegen0(Long tableId, TableInfo tableInfo) { private void syncCodegen0(Long tableId, TableInfo tableInfo) {
// 校验导入的表和字段非空 // 校验导入的表和字段非空
checkTableInfo(tableInfo); validateTableInfo(tableInfo);
List<TableField> tableFields = tableInfo.getFields(); List<TableField> tableFields = tableInfo.getFields();
// 构建 CodegenColumnDO 数组,只同步新增的字段 // 构建 CodegenColumnDO 数组,只同步新增的字段
List<CodegenColumnDO> codegenColumns = codegenColumnMapper.selectListByTableId(tableId); List<CodegenColumnDO> codegenColumns = codegenColumnMapper.selectListByTableId(tableId);
Set<String> codegenColumnNames = CollectionUtils.convertSet(codegenColumns, CodegenColumnDO::getColumnName); Set<String> codegenColumnNames = CollectionUtils.convertSet(codegenColumns, CodegenColumnDO::getColumnName);
//计算需要修改的字段,插入时重新插入,删除时将原来的删除
BiPredicate<TableField, CodegenColumnDO> pr =
(tableField, codegenColumn) -> tableField.getType().equals(codegenColumn.getDataType())
&& tableField.getMetaInfo().isNullable() == codegenColumn.getNullable()
&& tableField.isKeyFlag() == codegenColumn.getPrimaryKey()
&& tableField.getComment().equals(codegenColumn.getColumnComment());
Map<String, CodegenColumnDO> codegenColumnDOMap = CollectionUtils.convertMap(codegenColumns, CodegenColumnDO::getColumnName);
//需要修改的字段
Set<String> modifyFieldNames = tableFields.stream()
.filter(tableField -> codegenColumnDOMap.get(tableField.getColumnName()) != null
&& !pr.test(tableField, codegenColumnDOMap.get(tableField.getColumnName())))
.map(TableField::getColumnName)
.collect(Collectors.toSet());
// 计算需要删除的字段 // 计算需要删除的字段
Set<String> tableFieldNames = CollectionUtils.convertSet(tableFields, TableField::getName); Set<String> tableFieldNames = CollectionUtils.convertSet(tableFields, TableField::getName);
Set<Long> deleteColumnIds = codegenColumns.stream().filter(column -> !tableFieldNames.contains(column.getColumnName())) Set<Long> deleteColumnIds = codegenColumns.stream()
.filter(column -> (!tableFieldNames.contains(column.getColumnName())) || modifyFieldNames.contains(column.getColumnName()))
.map(CodegenColumnDO::getId).collect(Collectors.toSet()); .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)) { if (CollUtil.isEmpty(tableFields) && CollUtil.isEmpty(deleteColumnIds)) {
throw exception(CODEGEN_SYNC_NONE_CHANGE); throw exception(CODEGEN_SYNC_NONE_CHANGE);
} }

View File

@ -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.convert.config.ConfigConvert;
import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO; 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.dal.mysql.config.ConfigMapper;
import cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.infra.enums.config.ConfigTypeEnum; import cn.iocoder.yudao.module.infra.enums.config.ConfigTypeEnum;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -20,6 +19,7 @@ import javax.annotation.Resource;
import java.util.List; import java.util.List;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*;
/** /**
* Service * Service
@ -35,7 +35,7 @@ public class ConfigServiceImpl implements ConfigService {
@Override @Override
public Long createConfig(ConfigCreateReqVO reqVO) { public Long createConfig(ConfigCreateReqVO reqVO) {
// 校验正确性 // 校验正确性
checkCreateOrUpdate(null, reqVO.getKey()); validateConfigForCreateOrUpdate(null, reqVO.getKey());
// 插入参数配置 // 插入参数配置
ConfigDO config = ConfigConvert.INSTANCE.convert(reqVO); ConfigDO config = ConfigConvert.INSTANCE.convert(reqVO);
config.setType(ConfigTypeEnum.CUSTOM.getType()); config.setType(ConfigTypeEnum.CUSTOM.getType());
@ -46,19 +46,19 @@ public class ConfigServiceImpl implements ConfigService {
@Override @Override
public void updateConfig(ConfigUpdateReqVO reqVO) { public void updateConfig(ConfigUpdateReqVO reqVO) {
// 校验正确性 // 校验正确性
checkCreateOrUpdate(reqVO.getId(), null); // 不允许更新 key validateConfigForCreateOrUpdate(reqVO.getId(), null); // 不允许更新 key
// 更新参数配置 // 更新参数配置
ConfigDO updateObj = ConfigConvert.INSTANCE.convert(reqVO); ConfigDO updateObj = ConfigConvert.INSTANCE.convert(reqVO);
configMapper.updateById(updateObj);; configMapper.updateById(updateObj);
} }
@Override @Override
public void deleteConfig(Long id) { public void deleteConfig(Long id) {
// 校验配置存在 // 校验配置存在
ConfigDO config = checkConfigExists(id); ConfigDO config = validateConfigExists(id);
// 内置配置,不允许删除 // 内置配置,不允许删除
if (ConfigTypeEnum.SYSTEM.getType().equals(config.getType())) { 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); configMapper.deleteById(id);
@ -84,39 +84,39 @@ public class ConfigServiceImpl implements ConfigService {
return configMapper.selectList(reqVO); return configMapper.selectList(reqVO);
} }
private void checkCreateOrUpdate(Long id, String key) { private void validateConfigForCreateOrUpdate(Long id, String key) {
// 校验自己存在 // 校验自己存在
checkConfigExists(id); validateConfigExists(id);
// 校验参数配置 key 的唯一性 // 校验参数配置 key 的唯一性
if (StrUtil.isNotEmpty(key)) { if (StrUtil.isNotEmpty(key)) {
checkConfigKeyUnique(id, key); validateConfigKeyUnique(id, key);
} }
} }
@VisibleForTesting @VisibleForTesting
public ConfigDO checkConfigExists(Long id) { public ConfigDO validateConfigExists(Long id) {
if (id == null) { if (id == null) {
return null; return null;
} }
ConfigDO config = configMapper.selectById(id); ConfigDO config = configMapper.selectById(id);
if (config == null) { if (config == null) {
throw exception(ErrorCodeConstants.CONFIG_NOT_EXISTS); throw exception(CONFIG_NOT_EXISTS);
} }
return config; return config;
} }
@VisibleForTesting @VisibleForTesting
public void checkConfigKeyUnique(Long id, String key) { public void validateConfigKeyUnique(Long id, String key) {
ConfigDO config = configMapper.selectByKey(key); ConfigDO config = configMapper.selectByKey(key);
if (config == null) { if (config == null) {
return; return;
} }
// 如果 id 为空,说明不用比较是否为相同 id 的参数配置 // 如果 id 为空,说明不用比较是否为相同 id 的参数配置
if (id == null) { if (id == null) {
throw exception(ErrorCodeConstants.CONFIG_KEY_DUPLICATE); throw exception(CONFIG_KEY_DUPLICATE);
} }
if (!config.getId().equals(id)) { if (!config.getId().equals(id)) {
throw exception(ErrorCodeConstants.CONFIG_KEY_DUPLICATE); throw exception(CONFIG_KEY_DUPLICATE);
} }
} }

View File

@ -37,7 +37,7 @@ public class DataSourceConfigServiceImpl implements DataSourceConfigService {
@Override @Override
public Long createDataSourceConfig(DataSourceConfigCreateReqVO createReqVO) { public Long createDataSourceConfig(DataSourceConfigCreateReqVO createReqVO) {
DataSourceConfigDO dataSourceConfig = DataSourceConfigConvert.INSTANCE.convert(createReqVO); DataSourceConfigDO dataSourceConfig = DataSourceConfigConvert.INSTANCE.convert(createReqVO);
checkConnectionOK(dataSourceConfig); validateConnectionOK(dataSourceConfig);
// 插入 // 插入
dataSourceConfigMapper.insert(dataSourceConfig); dataSourceConfigMapper.insert(dataSourceConfig);
@ -50,7 +50,7 @@ public class DataSourceConfigServiceImpl implements DataSourceConfigService {
// 校验存在 // 校验存在
validateDataSourceConfigExists(updateReqVO.getId()); validateDataSourceConfigExists(updateReqVO.getId());
DataSourceConfigDO updateObj = DataSourceConfigConvert.INSTANCE.convert(updateReqVO); DataSourceConfigDO updateObj = DataSourceConfigConvert.INSTANCE.convert(updateReqVO);
checkConnectionOK(updateObj); validateConnectionOK(updateObj);
// 更新 // 更新
dataSourceConfigMapper.updateById(updateObj); dataSourceConfigMapper.updateById(updateObj);
@ -88,7 +88,7 @@ public class DataSourceConfigServiceImpl implements DataSourceConfigService {
return result; return result;
} }
private void checkConnectionOK(DataSourceConfigDO config) { private void validateConnectionOK(DataSourceConfigDO config) {
boolean success = JdbcUtils.isConnectionOK(config.getUrl(), config.getUsername(), config.getPassword()); boolean success = JdbcUtils.isConnectionOK(config.getUrl(), config.getUsername(), config.getPassword());
if (!success) { if (!success) {
throw exception(DATA_SOURCE_CONFIG_NOT_OK); throw exception(DATA_SOURCE_CONFIG_NOT_OK);

View File

@ -41,7 +41,7 @@ public class DatabaseTableServiceImpl implements DatabaseTableService {
return CollUtil.getFirst(getTableList0(dataSourceConfigId, name)); return CollUtil.getFirst(getTableList0(dataSourceConfigId, name));
} }
public List<TableInfo> getTableList0(Long dataSourceConfigId, String name) { private List<TableInfo> getTableList0(Long dataSourceConfigId, String name) {
// 获得数据源配置 // 获得数据源配置
DataSourceConfigDO config = dataSourceConfigService.getDataSourceConfig(dataSourceConfigId); DataSourceConfigDO config = dataSourceConfigService.getDataSourceConfig(dataSourceConfigId);
Assert.notNull(config, "数据源({}) 不存在!", dataSourceConfigId); Assert.notNull(config, "数据源({}) 不存在!", dataSourceConfigId);

View File

@ -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 cn.iocoder.yudao.module.infra.dal.dataobject.file.FileConfigDO;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.Collection;
import java.util.List;
/** /**
* Service * Service
@ -60,14 +58,6 @@ public interface FileConfigService {
*/ */
FileConfigDO getFileConfig(Long id); FileConfigDO getFileConfig(Long id);
/**
*
*
* @param ids
* @return
*/
List<FileConfigDO> getFileConfigList(Collection<Long> ids);
/** /**
* *
* *

View File

@ -27,7 +27,6 @@ import org.springframework.validation.annotation.Validated;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.validation.Validator; import javax.validation.Validator;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -95,7 +94,7 @@ public class FileConfigServiceImpl implements FileConfigService {
@Override @Override
public void updateFileConfig(FileConfigUpdateReqVO updateReqVO) { public void updateFileConfig(FileConfigUpdateReqVO updateReqVO) {
// 校验存在 // 校验存在
FileConfigDO config = this.validateFileConfigExists(updateReqVO.getId()); FileConfigDO config = validateFileConfigExists(updateReqVO.getId());
// 更新 // 更新
FileConfigDO updateObj = FileConfigConvert.INSTANCE.convert(updateReqVO) FileConfigDO updateObj = FileConfigConvert.INSTANCE.convert(updateReqVO)
.setConfig(parseClientConfig(config.getStorage(), updateReqVO.getConfig())); .setConfig(parseClientConfig(config.getStorage(), updateReqVO.getConfig()));
@ -108,7 +107,7 @@ public class FileConfigServiceImpl implements FileConfigService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void updateFileConfigMaster(Long id) { public void updateFileConfigMaster(Long id) {
// 校验存在 // 校验存在
this.validateFileConfigExists(id); validateFileConfigExists(id);
// 更新其它为非 master // 更新其它为非 master
fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false)); fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false));
// 更新 // 更新
@ -138,7 +137,7 @@ public class FileConfigServiceImpl implements FileConfigService {
@Override @Override
public void deleteFileConfig(Long id) { public void deleteFileConfig(Long id) {
// 校验存在 // 校验存在
FileConfigDO config = this.validateFileConfigExists(id); FileConfigDO config = validateFileConfigExists(id);
if (Boolean.TRUE.equals(config.getMaster())) { if (Boolean.TRUE.equals(config.getMaster())) {
throw exception(FILE_CONFIG_DELETE_FAIL_MASTER); throw exception(FILE_CONFIG_DELETE_FAIL_MASTER);
} }
@ -161,11 +160,6 @@ public class FileConfigServiceImpl implements FileConfigService {
return fileConfigMapper.selectById(id); return fileConfigMapper.selectById(id);
} }
@Override
public List<FileConfigDO> getFileConfigList(Collection<Long> ids) {
return fileConfigMapper.selectBatchIds(ids);
}
@Override @Override
public PageResult<FileConfigDO> getFileConfigPage(FileConfigPageReqVO pageReqVO) { public PageResult<FileConfigDO> getFileConfigPage(FileConfigPageReqVO pageReqVO) {
return fileConfigMapper.selectPage(pageReqVO); return fileConfigMapper.selectPage(pageReqVO);
@ -174,7 +168,7 @@ public class FileConfigServiceImpl implements FileConfigService {
@Override @Override
public String testFileConfig(Long id) throws Exception { public String testFileConfig(Long id) throws Exception {
// 校验存在 // 校验存在
this.validateFileConfigExists(id); validateFileConfigExists(id);
// 上传文件 // 上传文件
byte[] content = ResourceUtil.readBytes("file/erweima.jpg"); byte[] content = ResourceUtil.readBytes("file/erweima.jpg");
return fileClientFactory.getFileClient(id).upload(content, IdUtil.fastSimpleUUID() + ".jpg", "image/jpeg"); return fileClientFactory.getFileClient(id).upload(content, IdUtil.fastSimpleUUID() + ".jpg", "image/jpeg");

View File

@ -69,7 +69,7 @@ public class FileServiceImpl implements FileService {
@Override @Override
public void deleteFile(Long id) throws Exception { public void deleteFile(Long id) throws Exception {
// 校验存在 // 校验存在
FileDO file = this.validateFileExists(id); FileDO file = validateFileExists(id);
// 从文件存储器中删除 // 从文件存储器中删除
FileClient client = fileConfigService.getFileClient(file.getConfigId()); FileClient client = fileConfigService.getFileClient(file.getConfigId());

View File

@ -1,17 +1,13 @@
package cn.iocoder.yudao.module.infra.service.logger; 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.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.ApiErrorLogExportReqVO;
import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogPageReqVO; 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.convert.logger.ApiErrorLogConvert;
import cn.iocoder.yudao.module.infra.dal.dataobject.logger.ApiErrorLogDO; 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.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 cn.iocoder.yudao.module.infra.enums.logger.ApiErrorLogProcessStatusEnum;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
@ -19,6 +15,10 @@ import javax.annotation.Resource;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; 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 * API Service
* *
@ -33,8 +33,8 @@ public class ApiErrorLogServiceImpl implements ApiErrorLogService {
@Override @Override
public void createApiErrorLog(ApiErrorLogCreateReqDTO createDTO) { public void createApiErrorLog(ApiErrorLogCreateReqDTO createDTO) {
ApiErrorLogDO apiErrorLog = ApiErrorLogConvert.INSTANCE.convert(createDTO); ApiErrorLogDO apiErrorLog = ApiErrorLogConvert.INSTANCE.convert(createDTO)
apiErrorLog.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus()); .setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus());
apiErrorLogMapper.insert(apiErrorLog); apiErrorLogMapper.insert(apiErrorLog);
} }
@ -52,10 +52,10 @@ public class ApiErrorLogServiceImpl implements ApiErrorLogService {
public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) { public void updateApiErrorLogProcess(Long id, Integer processStatus, Long processUserId) {
ApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id); ApiErrorLogDO errorLog = apiErrorLogMapper.selectById(id);
if (errorLog == null) { 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())) { 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) apiErrorLogMapper.updateById(ApiErrorLogDO.builder().id(id).processStatus(processStatus)

View File

@ -45,7 +45,7 @@ public class TestDemoServiceImpl implements TestDemoService {
@CacheEvict(value = "test", key = "#updateReqVO.id") @CacheEvict(value = "test", key = "#updateReqVO.id")
public void updateTestDemo(TestDemoUpdateReqVO updateReqVO) { public void updateTestDemo(TestDemoUpdateReqVO updateReqVO) {
// 校验存在 // 校验存在
this.validateTestDemoExists(updateReqVO.getId()); validateTestDemoExists(updateReqVO.getId());
// 更新 // 更新
TestDemoDO updateObj = TestDemoConvert.INSTANCE.convert(updateReqVO); TestDemoDO updateObj = TestDemoConvert.INSTANCE.convert(updateReqVO);
testDemoMapper.updateById(updateObj); testDemoMapper.updateById(updateObj);
@ -55,7 +55,7 @@ public class TestDemoServiceImpl implements TestDemoService {
@CacheEvict(value = "test", key = "#id") @CacheEvict(value = "test", key = "#id")
public void deleteTestDemo(Long id) { public void deleteTestDemo(Long id) {
// 校验存在 // 校验存在
this.validateTestDemoExists(id); validateTestDemoExists(id);
// 删除 // 删除
testDemoMapper.deleteById(id); testDemoMapper.deleteById(id);
} }

View File

@ -39,7 +39,7 @@ public class ${table.className}ServiceImpl implements ${table.className}Service
@Override @Override
public void update${simpleClassName}(${sceneEnum.prefixClass}${table.className}UpdateReqVO updateReqVO) { 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); ${table.className}DO updateObj = ${table.className}Convert.INSTANCE.convert(updateReqVO);
${classNameVar}Mapper.updateById(updateObj); ${classNameVar}Mapper.updateById(updateObj);
@ -48,7 +48,7 @@ public class ${table.className}ServiceImpl implements ${table.className}Service
@Override @Override
public void delete${simpleClassName}(${primaryColumn.javaType} id) { public void delete${simpleClassName}(${primaryColumn.javaType} id) {
// 校验存在 // 校验存在
this.validate${simpleClassName}Exists(id); validate${simpleClassName}Exists(id);
// 删除 // 删除
${classNameVar}Mapper.deleteById(id); ${classNameVar}Mapper.deleteById(id);
} }

View File

@ -52,7 +52,7 @@ import static org.mockito.Mockito.*;
#if (${column.listOperation}) #if (${column.listOperation})
#set ($JavaField = $column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})##首字母大写 #set ($JavaField = $column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})##首字母大写
#if (${column.listOperationCondition} == "BETWEEN")## BETWEEN 的情况 #if (${column.listOperationCondition} == "BETWEEN")## BETWEEN 的情况
reqVO.set${JavaField}((new LocalDateTime[]{})); reqVO.set${JavaField}(buildBetweenTime(2023, 2, 1, 2023, 2, 28));
#else #else
reqVO.set$JavaField(null); reqVO.set$JavaField(null);
#end #end

View File

@ -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.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; 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.ut.BaseDbUnitTest;
import cn.iocoder.yudao.framework.test.core.util.RandomUtils; import cn.iocoder.yudao.framework.test.core.util.RandomUtils;
import cn.iocoder.yudao.module.infra.controller.admin.config.vo.ConfigCreateReqVO; 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.dataobject.config.ConfigDO;
import cn.iocoder.yudao.module.infra.dal.mysql.config.ConfigMapper; import cn.iocoder.yudao.module.infra.dal.mysql.config.ConfigMapper;
import cn.iocoder.yudao.module.infra.enums.config.ConfigTypeEnum; import cn.iocoder.yudao.module.infra.enums.config.ConfigTypeEnum;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import static cn.hutool.core.util.RandomUtil.randomEle; 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.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; 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.framework.test.core.util.RandomUtils.*;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.*;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@Import(ConfigServiceImpl.class) @Import(ConfigServiceImpl.class)
public class ConfigServiceTest extends BaseDbUnitTest { public class ConfigServiceImplTest extends BaseDbUnitTest {
@Resource @Resource
private ConfigServiceImpl configService; private ConfigServiceImpl configService;
@ -52,7 +49,7 @@ public class ConfigServiceTest extends BaseDbUnitTest {
// 校验记录的属性是否正确 // 校验记录的属性是否正确
ConfigDO config = configMapper.selectById(configId); ConfigDO config = configMapper.selectById(configId);
assertPojoEquals(reqVO, config); assertPojoEquals(reqVO, config);
Assertions.assertEquals(ConfigTypeEnum.CUSTOM.getType(), config.getType()); assertEquals(ConfigTypeEnum.CUSTOM.getType(), config.getType());
} }
@Test @Test
@ -103,40 +100,40 @@ public class ConfigServiceTest extends BaseDbUnitTest {
} }
@Test @Test
public void testCheckConfigExists_success() { public void testValidateConfigExists_success() {
// mock 数据 // mock 数据
ConfigDO dbConfigDO = randomConfigDO(); ConfigDO dbConfigDO = randomConfigDO();
configMapper.insert(dbConfigDO);// @Sql: 先插入出一条存在的数据 configMapper.insert(dbConfigDO);// @Sql: 先插入出一条存在的数据
// 调用成功 // 调用成功
configService.checkConfigExists(dbConfigDO.getId()); configService.validateConfigExists(dbConfigDO.getId());
} }
@Test @Test
public void testCheckConfigExist_notExists() { public void testValidateConfigExist_notExists() {
assertServiceException(() -> configService.checkConfigExists(randomLongId()), CONFIG_NOT_EXISTS); assertServiceException(() -> configService.validateConfigExists(randomLongId()), CONFIG_NOT_EXISTS);
} }
@Test @Test
public void testCheckConfigKeyUnique_success() { public void testValidateConfigKeyUnique_success() {
// 调用,成功 // 调用,成功
configService.checkConfigKeyUnique(randomLongId(), randomString()); configService.validateConfigKeyUnique(randomLongId(), randomString());
} }
@Test @Test
public void testCheckConfigKeyUnique_keyDuplicateForCreate() { public void testValidateConfigKeyUnique_keyDuplicateForCreate() {
// 准备参数 // 准备参数
String key = randomString(); String key = randomString();
// mock 数据 // mock 数据
configMapper.insert(randomConfigDO(o -> o.setConfigKey(key))); configMapper.insert(randomConfigDO(o -> o.setConfigKey(key)));
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> configService.checkConfigKeyUnique(null, key), assertServiceException(() -> configService.validateConfigKeyUnique(null, key),
CONFIG_KEY_DUPLICATE); CONFIG_KEY_DUPLICATE);
} }
@Test @Test
public void testCheckConfigKeyUnique_keyDuplicateForUpdate() { public void testValidateConfigKeyUnique_keyDuplicateForUpdate() {
// 准备参数 // 准备参数
Long id = randomLongId(); Long id = randomLongId();
String key = randomString(); String key = randomString();
@ -144,7 +141,7 @@ public class ConfigServiceTest extends BaseDbUnitTest {
configMapper.insert(randomConfigDO(o -> o.setConfigKey(key))); configMapper.insert(randomConfigDO(o -> o.setConfigKey(key)));
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> configService.checkConfigKeyUnique(id, key), assertServiceException(() -> configService.validateConfigKeyUnique(id, key),
CONFIG_KEY_DUPLICATE); CONFIG_KEY_DUPLICATE);
} }
@ -155,23 +152,23 @@ public class ConfigServiceTest extends BaseDbUnitTest {
o.setName("芋艿"); o.setName("芋艿");
o.setConfigKey("yunai"); o.setConfigKey("yunai");
o.setType(ConfigTypeEnum.SYSTEM.getType()); o.setType(ConfigTypeEnum.SYSTEM.getType());
o.setCreateTime(buildLocalDateTime(2021, 2, 1)); o.setCreateTime(buildTime(2021, 2, 1));
}); });
configMapper.insert(dbConfig); configMapper.insert(dbConfig);
// 测试 name 不匹配 // 测试 name 不匹配
configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setName("土豆"))); configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setName("土豆")));
// 测试 key 不匹配 // 测试 key 不匹配
configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou"))); configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou")));
// 测试 type 不匹配 // 测试 type 不匹配
configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType()))); configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType())));
// 测试 createTime 不匹配 // 测试 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(); ConfigPageReqVO reqVO = new ConfigPageReqVO();
reqVO.setName("艿"); reqVO.setName("艿");
reqVO.setKey("nai"); reqVO.setKey("nai");
reqVO.setType(ConfigTypeEnum.SYSTEM.getType()); 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<ConfigDO> pageResult = configService.getConfigPage(reqVO); PageResult<ConfigDO> pageResult = configService.getConfigPage(reqVO);
@ -188,23 +185,23 @@ public class ConfigServiceTest extends BaseDbUnitTest {
o.setName("芋艿"); o.setName("芋艿");
o.setConfigKey("yunai"); o.setConfigKey("yunai");
o.setType(ConfigTypeEnum.SYSTEM.getType()); o.setType(ConfigTypeEnum.SYSTEM.getType());
o.setCreateTime(buildLocalDateTime(2021, 2, 1)); o.setCreateTime(buildTime(2021, 2, 1));
}); });
configMapper.insert(dbConfig); configMapper.insert(dbConfig);
// 测试 name 不匹配 // 测试 name 不匹配
configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setName("土豆"))); configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setName("土豆")));
// 测试 key 不匹配 // 测试 key 不匹配
configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou"))); configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setConfigKey("tudou")));
// 测试 type 不匹配 // 测试 type 不匹配
configMapper.insert(ObjectUtils.cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType()))); configMapper.insert(cloneIgnoreId(dbConfig, o -> o.setType(ConfigTypeEnum.CUSTOM.getType())));
// 测试 createTime 不匹配 // 测试 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(); ConfigExportReqVO reqVO = new ConfigExportReqVO();
reqVO.setName("艿"); reqVO.setName("艿");
reqVO.setKey("nai"); reqVO.setKey("nai");
reqVO.setType(ConfigTypeEnum.SYSTEM.getType()); 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<ConfigDO> list = configService.getConfigList(reqVO); List<ConfigDO> list = configService.getConfigList(reqVO);
@ -213,6 +210,21 @@ public class ConfigServiceTest extends BaseDbUnitTest {
assertPojoEquals(dbConfig, list.get(0)); 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 @Test
public void testGetConfigByKey() { public void testGetConfigByKey() {
// mock 数据 // mock 数据

View File

@ -1,5 +1,6 @@
package cn.iocoder.yudao.module.infra.service.db; package cn.iocoder.yudao.module.infra.service.db;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import cn.hutool.crypto.symmetric.AES; import cn.hutool.crypto.symmetric.AES;
import cn.iocoder.yudao.framework.mybatis.core.type.EncryptTypeHandler; 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.controller.admin.db.vo.DataSourceConfigUpdateReqVO;
import cn.iocoder.yudao.module.infra.dal.dataobject.db.DataSourceConfigDO; import cn.iocoder.yudao.module.infra.dal.dataobject.db.DataSourceConfigDO;
import cn.iocoder.yudao.module.infra.dal.mysql.db.DataSourceConfigMapper; 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 com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; 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 org.springframework.context.annotation.Import;
import javax.annotation.Resource; 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.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; 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.randomLongId;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo; 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 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.*;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.mockStatic;
@ -57,6 +59,11 @@ public class DataSourceConfigServiceImplTest extends BaseDbUnitTest {
ReflectUtil.setFieldValue(EncryptTypeHandler.class, "aes", aes); ReflectUtil.setFieldValue(EncryptTypeHandler.class, "aes", aes);
when(aes.encryptBase64(anyString())).then((Answer<String>) invocation -> invocation.getArgument(0)); when(aes.encryptBase64(anyString())).then((Answer<String>) invocation -> invocation.getArgument(0));
when(aes.decryptStr(anyString())).then((Answer<String>) invocation -> invocation.getArgument(0)); when(aes.decryptStr(anyString())).then((Answer<String>) 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 @Test
@ -89,7 +96,6 @@ public class DataSourceConfigServiceImplTest extends BaseDbUnitTest {
o.setId(dbDataSourceConfig.getId()); // 设置更新的 ID o.setId(dbDataSourceConfig.getId()); // 设置更新的 ID
}); });
// mock 方法 // mock 方法
// when(stringEncryptor.encrypt(eq(reqVO.getPassword()))).thenReturn("123456");
databaseUtilsMock.when(() -> JdbcUtils.isConnectionOK(eq(reqVO.getUrl()), databaseUtilsMock.when(() -> JdbcUtils.isConnectionOK(eq(reqVO.getUrl()),
eq(reqVO.getUsername()), eq(reqVO.getPassword()))).thenReturn(true); eq(reqVO.getUsername()), eq(reqVO.getPassword()))).thenReturn(true);
@ -142,7 +148,58 @@ public class DataSourceConfigServiceImplTest extends BaseDbUnitTest {
// 调用 // 调用
DataSourceConfigDO result = dataSourceConfigMapper.selectOne(DataSourceConfigDO::getPassword, DataSourceConfigDO result = dataSourceConfigMapper.selectOne(DataSourceConfigDO::getPassword,
EncryptTypeHandler.encrypt(dbDataSourceConfig.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<DataSourceConfigDO> 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));
} }
} }

View File

@ -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<TableInfo> 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());
}
}

View File

@ -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.FileClient;
import cn.iocoder.yudao.framework.file.core.client.FileClientConfig; 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.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.client.local.LocalFileClientConfig;
import cn.iocoder.yudao.framework.file.core.enums.FileStorageEnum; import cn.iocoder.yudao.framework.file.core.enums.FileStorageEnum;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
@ -41,10 +42,10 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
/** /**
* {@link FileConfigServiceImpl} * {@link FileConfigServiceImpl}
* *
* @author * @author
*/ */
@Import(FileConfigServiceImpl.class) @Import(FileConfigServiceImpl.class)
public class FileConfigServiceImplTest extends BaseDbUnitTest { public class FileConfigServiceImplTest extends BaseDbUnitTest {
@ -242,6 +243,30 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest {
assertEquals("https://www.iocoder.cn", fileConfigService.testFileConfig(id)); 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() { private FileConfigDO randomFileConfigDO() {
return randomPojo(FileConfigDO.class).setStorage(randomEle(FileStorageEnum.values()).getStorage()) return randomPojo(FileConfigDO.class).setStorage(randomEle(FileStorageEnum.values()).getStorage())
.setConfig(new EmptyFileClientConfig()); .setConfig(new EmptyFileClientConfig());

View File

@ -16,7 +16,7 @@ import org.springframework.context.annotation.Import;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.LocalDateTime; 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.AssertUtils.assertServiceException;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_NOT_EXISTS; 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 static org.mockito.Mockito.*;
@Import({FileServiceImpl.class}) @Import({FileServiceImpl.class})
public class FileServiceTest extends BaseDbUnitTest { public class FileServiceImplTest extends BaseDbUnitTest {
@Resource @Resource
private FileService fileService; private FileService fileService;
@ -42,7 +42,7 @@ public class FileServiceTest extends BaseDbUnitTest {
FileDO dbFile = randomPojo(FileDO.class, o -> { // 等会查询到 FileDO dbFile = randomPojo(FileDO.class, o -> { // 等会查询到
o.setPath("yunai"); o.setPath("yunai");
o.setType("image/jpg"); o.setType("image/jpg");
o.setCreateTime(buildLocalDateTime(2021, 1, 15)); o.setCreateTime(buildTime(2021, 1, 15));
}); });
fileMapper.insert(dbFile); fileMapper.insert(dbFile);
// 测试 path 不匹配 // 测试 path 不匹配
@ -53,13 +53,13 @@ public class FileServiceTest extends BaseDbUnitTest {
})); }));
// 测试 createTime 不匹配 // 测试 createTime 不匹配
fileMapper.insert(ObjectUtils.cloneIgnoreId(dbFile, o -> { fileMapper.insert(ObjectUtils.cloneIgnoreId(dbFile, o -> {
o.setCreateTime(buildLocalDateTime(2020, 1, 15)); o.setCreateTime(buildTime(2020, 1, 15));
})); }));
// 准备参数 // 准备参数
FilePageReqVO reqVO = new FilePageReqVO(); FilePageReqVO reqVO = new FilePageReqVO();
reqVO.setPath("yunai"); reqVO.setPath("yunai");
reqVO.setType("jp"); 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<FileDO> pageResult = fileService.getFilePage(reqVO); PageResult<FileDO> pageResult = fileService.getFilePage(reqVO);

View File

@ -1,12 +1,9 @@
package cn.iocoder.yudao.module.infra.service.logger; 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.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants; import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.pojo.PageResult; 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.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.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.ApiAccessLogExportReqVO;
import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apiaccesslog.ApiAccessLogPageReqVO; 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 org.springframework.context.annotation.Import;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List; 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.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.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@Import(ApiAccessLogServiceImpl.class) @Import(ApiAccessLogServiceImpl.class)
public class ApiAccessLogServiceImplTest extends BaseDbUnitTest { public class ApiAccessLogServiceImplTest extends BaseDbUnitTest {
@Resource @Resource
private ApiAccessLogService apiAccessLogService; private ApiAccessLogServiceImpl apiAccessLogService;
@Resource @Resource
private ApiAccessLogMapper apiAccessLogMapper; private ApiAccessLogMapper apiAccessLogMapper;
@Test @Test
public void testGetApiAccessLogPage() { public void testGetApiAccessLogPage() {
// 构造测试数据 ApiAccessLogDO apiAccessLogDO = randomPojo(ApiAccessLogDO.class, o -> {
long userId = 2233L; o.setUserId(2233L);
int userType = UserTypeEnum.ADMIN.getValue(); o.setUserType(UserTypeEnum.ADMIN.getValue());
String applicationName = "yudao-test"; o.setApplicationName("yudao-test");
String requestUrl = "foo"; o.setRequestUrl("foo");
LocalDateTime beginTime = buildLocalDateTime(2021, 3, 13); o.setBeginTime(buildTime(2021, 3, 13));
int duration = 1000; o.setDuration(1000);
int resultCode = GlobalErrorCodeConstants.SUCCESS.getCode(); o.setResultCode(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);
}); });
apiAccessLogMapper.insert(infApiAccessLogDO); apiAccessLogMapper.insert(apiAccessLogDO);
// 测试 userId 不匹配
// 下面几个都是不匹配的数据 apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserId(3344L)));
// userId 不同的 // 测试 userType 不匹配
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserId(3344L))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserType(UserTypeEnum.MEMBER.getValue())));
// userType // 测试 applicationName 不匹配
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setApplicationName("test")));
// applicationName 不同的 // 测试 requestUrl 不匹配
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setApplicationName("test"))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setRequestUrl("bar")));
// requestUrl 不同的 // 测试 beginTime 不匹配:构造一个早期时间 2021-02-06 00:00:00
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setRequestUrl("bar"))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setBeginTime(buildTime(2021, 2, 6))));
// 构造一个早期时间 2021-02-06 00:00:00 // 测试 duration 不匹配
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setBeginTime(buildLocalDateTime(2021, 2, 6)))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setDuration(100)));
// duration 不同的 // 测试 resultCode 不匹配
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setDuration(100))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setResultCode(2)));
// resultCode 不同的 // 准备参数
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setResultCode(2)));
// 构造调用参数
ApiAccessLogPageReqVO reqVO = new ApiAccessLogPageReqVO(); ApiAccessLogPageReqVO reqVO = new ApiAccessLogPageReqVO();
reqVO.setUserId(userId); reqVO.setUserId(2233L);
reqVO.setUserType(userType); reqVO.setUserType(UserTypeEnum.ADMIN.getValue());
reqVO.setApplicationName(applicationName); reqVO.setApplicationName("yudao-test");
reqVO.setRequestUrl(requestUrl); reqVO.setRequestUrl("foo");
reqVO.setBeginTime((new LocalDateTime[]{buildLocalDateTime(2021, 3, 12),buildLocalDateTime(2021, 3, 14)})); reqVO.setBeginTime(buildBetweenTime(2021, 3, 13, 2021, 3, 13));
reqVO.setDuration(duration); reqVO.setDuration(1000);
reqVO.setResultCode(resultCode); reqVO.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode());
// 调用service方法 // 调用
PageResult<ApiAccessLogDO> pageResult = apiAccessLogService.getApiAccessLogPage(reqVO); PageResult<ApiAccessLogDO> pageResult = apiAccessLogService.getApiAccessLogPage(reqVO);
// 断言,只查到了一条符合条件的 // 断言,只查到了一条符合条件的
assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size()); assertEquals(1, pageResult.getList().size());
assertPojoEquals(infApiAccessLogDO, pageResult.getList().get(0)); assertPojoEquals(apiAccessLogDO, pageResult.getList().get(0));
} }
@Test @Test
public void testGetApiAccessLogList() { public void testGetApiAccessLogList() {
// 构造测试数据 ApiAccessLogDO apiAccessLogDO = randomPojo(ApiAccessLogDO.class, o -> {
long userId = 2233L; o.setUserId(2233L);
int userType = UserTypeEnum.ADMIN.getValue(); o.setUserType(UserTypeEnum.ADMIN.getValue());
String applicationName = "yudao-test"; o.setApplicationName("yudao-test");
String requestUrl = "foo"; o.setRequestUrl("foo");
LocalDateTime beginTime = buildLocalDateTime(2021, 3, 13); o.setBeginTime(buildTime(2021, 3, 13));
int duration = 1000; o.setDuration(1000);
int resultCode = GlobalErrorCodeConstants.SUCCESS.getCode(); o.setResultCode(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);
}); });
apiAccessLogMapper.insert(infApiAccessLogDO); apiAccessLogMapper.insert(apiAccessLogDO);
// 测试 userId 不匹配
// 下面几个都是不匹配的数据 apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserId(3344L)));
// userId 不同的 // 测试 userType 不匹配
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserId(3344L))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setUserType(UserTypeEnum.MEMBER.getValue())));
// userType // 测试 applicationName 不匹配
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setApplicationName("test")));
// applicationName 不同的 // 测试 requestUrl 不匹配
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setApplicationName("test"))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setRequestUrl("bar")));
// requestUrl 不同的 // 测试 beginTime 不匹配:构造一个早期时间 2021-02-06 00:00:00
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setRequestUrl("bar"))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setBeginTime(buildTime(2021, 2, 6))));
// 构造一个早期时间 2021-02-06 00:00:00 // 测试 duration 不匹配
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setBeginTime(buildLocalDateTime(2021, 2, 6)))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setDuration(100)));
// duration 不同的 // 测试 resultCode 不匹配
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setDuration(100))); apiAccessLogMapper.insert(cloneIgnoreId(apiAccessLogDO, o -> o.setResultCode(2)));
// resultCode 不同的 // 准备参数
apiAccessLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiAccessLogDO, logDO -> logDO.setResultCode(2)));
// 构造调用参数
ApiAccessLogExportReqVO reqVO = new ApiAccessLogExportReqVO(); ApiAccessLogExportReqVO reqVO = new ApiAccessLogExportReqVO();
reqVO.setUserId(userId); reqVO.setUserId(2233L);
reqVO.setUserType(userType); reqVO.setUserType(UserTypeEnum.ADMIN.getValue());
reqVO.setApplicationName(applicationName); reqVO.setApplicationName("yudao-test");
reqVO.setRequestUrl(requestUrl); reqVO.setRequestUrl("foo");
reqVO.setBeginTime((new LocalDateTime[]{buildLocalDateTime(2021, 3, 12),buildLocalDateTime(2021, 3, 14)})); reqVO.setBeginTime(buildBetweenTime(2021, 3, 13, 2021, 3, 13));
reqVO.setDuration(duration); reqVO.setDuration(1000);
reqVO.setResultCode(resultCode); reqVO.setResultCode(GlobalErrorCodeConstants.SUCCESS.getCode());
// 调用service方法 // 调用
List<ApiAccessLogDO> list = apiAccessLogService.getApiAccessLogList(reqVO); List<ApiAccessLogDO> list = apiAccessLogService.getApiAccessLogList(reqVO);
// 断言,只查到了一条符合条件的 // 断言,只查到了一条符合条件的
assertEquals(1, list.size()); assertEquals(1, list.size());
assertPojoEquals(infApiAccessLogDO, list.get(0)); assertPojoEquals(apiAccessLogDO, list.get(0));
} }
@Test @Test
public void testCreateApiAccessLogAsync() { public void testCreateApiAccessLog() {
// 准备参数 // 准备参数
ApiAccessLogCreateReqDTO createDTO = RandomUtils.randomPojo(ApiAccessLogCreateReqDTO.class, ApiAccessLogCreateReqDTO createDTO = randomPojo(ApiAccessLogCreateReqDTO.class);
dto -> dto.setUserType(RandomUtil.randomEle(UserTypeEnum.values()).getValue()));
// 调用 // 调用
apiAccessLogService.createApiAccessLog(createDTO); apiAccessLogService.createApiAccessLog(createDTO);
// 断言 // 断言
ApiAccessLogDO infApiAccessLogDO = apiAccessLogMapper.selectOne(null); ApiAccessLogDO apiAccessLogDO = apiAccessLogMapper.selectOne(null);
assertNotNull(infApiAccessLogDO); assertPojoEquals(createDTO, apiAccessLogDO);
assertPojoEquals(createDTO, infApiAccessLogDO);
} }
} }

View File

@ -1,28 +1,28 @@
package cn.iocoder.yudao.module.infra.service.logger; 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.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult; 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.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.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.ApiErrorLogExportReqVO;
import cn.iocoder.yudao.module.infra.controller.admin.logger.vo.apierrorlog.ApiErrorLogPageReqVO; 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.dataobject.logger.ApiErrorLogDO;
import cn.iocoder.yudao.module.infra.dal.mysql.logger.ApiErrorLogMapper; import cn.iocoder.yudao.module.infra.dal.mysql.logger.ApiErrorLogMapper;
import cn.iocoder.yudao.module.infra.enums.logger.ApiErrorLogProcessStatusEnum; import cn.iocoder.yudao.module.infra.enums.logger.ApiErrorLogProcessStatusEnum;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List; 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.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; 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_NOT_FOUND;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.API_ERROR_LOG_PROCESSED; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.API_ERROR_LOG_PROCESSED;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@ -35,161 +35,150 @@ public class ApiErrorLogServiceImplTest extends BaseDbUnitTest {
private ApiErrorLogServiceImpl apiErrorLogService; private ApiErrorLogServiceImpl apiErrorLogService;
@Resource @Resource
private ApiErrorLogMapper infApiErrorLogMapper; private ApiErrorLogMapper apiErrorLogMapper;
@Test @Test
public void testGetApiErrorLogPage() { public void testGetApiErrorLogPage() {
// 构造测试数据 // mock 数据
long userId = 2233L; ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class, o -> {
int userType = UserTypeEnum.ADMIN.getValue(); o.setUserId(2233L);
String applicationName = "yudao-test"; o.setUserType(UserTypeEnum.ADMIN.getValue());
String requestUrl = "foo"; o.setApplicationName("yudao-test");
LocalDateTime beginTime = buildLocalDateTime(2021, 3, 13); o.setRequestUrl("foo");
int progressStatus = ApiErrorLogProcessStatusEnum.INIT.getStatus(); o.setExceptionTime(buildTime(2021, 3, 13));
o.setProcessStatus(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);
}); });
infApiErrorLogMapper.insert(infApiErrorLogDO); apiErrorLogMapper.insert(apiErrorLogDO);
// 测试 userId 不匹配
// 下面几个都是不匹配的数据 apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, o -> o.setUserId(3344L)));
// userId 不同的 // 测试 userType 不匹配
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserId(3344L))); apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue())));
// userType // 测试 applicationName 不匹配
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setApplicationName("test")));
// applicationName 不同的 // 测试 requestUrl 不匹配
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setApplicationName("test"))); apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setRequestUrl("bar")));
// requestUrl 不同的 // 测试 exceptionTime 不匹配:构造一个早期时间 2021-02-06 00:00:00
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setRequestUrl("bar"))); apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setExceptionTime(buildTime(2021, 2, 6))));
// 构造一个早期时间 2021-02-06 00:00:00 // 测试 progressStatus 不匹配
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setExceptionTime(buildLocalDateTime(2021, 2, 6)))); apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus())));
// progressStatus 不同的 // 准备参数
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus())));
// 构造调用参数
ApiErrorLogPageReqVO reqVO = new ApiErrorLogPageReqVO(); ApiErrorLogPageReqVO reqVO = new ApiErrorLogPageReqVO();
reqVO.setUserId(userId); reqVO.setUserId(2233L);
reqVO.setUserType(userType); reqVO.setUserType(UserTypeEnum.ADMIN.getValue());
reqVO.setApplicationName(applicationName); reqVO.setApplicationName("yudao-test");
reqVO.setRequestUrl(requestUrl); reqVO.setRequestUrl("foo");
reqVO.setExceptionTime((new LocalDateTime[]{buildLocalDateTime(2021, 3, 12),buildLocalDateTime(2021, 3, 14)})); reqVO.setExceptionTime(buildBetweenTime(2021, 3, 1, 2021, 3, 31));
reqVO.setProcessStatus(progressStatus); reqVO.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus());
// 调用service方法 // 调用
PageResult<ApiErrorLogDO> pageResult = apiErrorLogService.getApiErrorLogPage(reqVO); PageResult<ApiErrorLogDO> pageResult = apiErrorLogService.getApiErrorLogPage(reqVO);
// 断言,只查到了一条符合条件的 // 断言,只查到了一条符合条件的
assertEquals(1, pageResult.getTotal()); assertEquals(1, pageResult.getTotal());
assertEquals(1, pageResult.getList().size()); assertEquals(1, pageResult.getList().size());
assertPojoEquals(infApiErrorLogDO, pageResult.getList().get(0)); assertPojoEquals(apiErrorLogDO, pageResult.getList().get(0));
} }
@Test @Test
public void testGetApiErrorLogList() { public void testGetApiErrorLogList() {
// 构造测试数据 // mock 数据
long userId = 2233L; ApiErrorLogDO apiErrorLogDO = randomPojo(ApiErrorLogDO.class, o -> {
int userType = UserTypeEnum.ADMIN.getValue(); o.setUserId(2233L);
String applicationName = "yudao-test"; o.setUserType(UserTypeEnum.ADMIN.getValue());
String requestUrl = "foo"; o.setApplicationName("yudao-test");
LocalDateTime beginTime = buildLocalDateTime(2021, 3, 13); o.setRequestUrl("foo");
int progressStatus = ApiErrorLogProcessStatusEnum.INIT.getStatus(); o.setExceptionTime(buildTime(2021, 3, 13));
o.setProcessStatus(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);
}); });
infApiErrorLogMapper.insert(infApiErrorLogDO); apiErrorLogMapper.insert(apiErrorLogDO);
// 测试 userId 不匹配
// 下面几个都是不匹配的数据 apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, o -> o.setUserId(3344L)));
// userId 不同的 // 测试 userType 不匹配
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserId(3344L))); apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue())));
// userType // 测试 applicationName 不匹配
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setUserType(UserTypeEnum.MEMBER.getValue()))); apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setApplicationName("test")));
// applicationName 不同的 // 测试 requestUrl 不匹配
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setApplicationName("test"))); apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setRequestUrl("bar")));
// requestUrl 不同的 // 测试 exceptionTime 不匹配:构造一个早期时间 2021-02-06 00:00:00
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setRequestUrl("bar"))); apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setExceptionTime(buildTime(2021, 2, 6))));
// 构造一个早期时间 2021-02-06 00:00:00 // 测试 progressStatus 不匹配
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setExceptionTime(buildLocalDateTime(2021, 2, 6)))); apiErrorLogMapper.insert(cloneIgnoreId(apiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus())));
// progressStatus 不同的 // 准备参数
infApiErrorLogMapper.insert(ObjectUtils.cloneIgnoreId(infApiErrorLogDO, logDO -> logDO.setProcessStatus(ApiErrorLogProcessStatusEnum.DONE.getStatus())));
// 构造调用参数
ApiErrorLogExportReqVO reqVO = new ApiErrorLogExportReqVO(); ApiErrorLogExportReqVO reqVO = new ApiErrorLogExportReqVO();
reqVO.setUserId(userId); reqVO.setUserId(2233L);
reqVO.setUserType(userType); reqVO.setUserType(UserTypeEnum.ADMIN.getValue());
reqVO.setApplicationName(applicationName); reqVO.setApplicationName("yudao-test");
reqVO.setRequestUrl(requestUrl); reqVO.setRequestUrl("foo");
reqVO.setExceptionTime((new LocalDateTime[]{buildLocalDateTime(2021, 3, 12),buildLocalDateTime(2021, 3, 14)})); reqVO.setExceptionTime(buildBetweenTime(2021, 3, 1, 2021, 3, 31));
reqVO.setProcessStatus(progressStatus); reqVO.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus());
// 调用service方法 // 调用
List<ApiErrorLogDO> list = apiErrorLogService.getApiErrorLogList(reqVO); List<ApiErrorLogDO> list = apiErrorLogService.getApiErrorLogList(reqVO);
// 断言,只查到了一条符合条件的 // 断言,只查到了一条符合条件的
assertEquals(1, list.size()); assertEquals(1, list.size());
assertPojoEquals(infApiErrorLogDO, list.get(0)); assertPojoEquals(apiErrorLogDO, 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());
} }
@Test @Test
public void testCreateApiErrorLogAsync() { public void testCreateApiErrorLog() {
// 准备参数 // 准备参数
ApiErrorLogCreateReqDTO createDTO = RandomUtils.randomPojo(ApiErrorLogCreateReqDTO.class, ApiErrorLogCreateReqDTO createDTO = randomPojo(ApiErrorLogCreateReqDTO.class);
dto -> dto.setUserType(RandomUtil.randomEle(UserTypeEnum.values()).getValue()));
// 调用 // 调用
apiErrorLogService.createApiErrorLog(createDTO); apiErrorLogService.createApiErrorLog(createDTO);
// 断言 // 断言
ApiErrorLogDO infApiErrorLogDO = infApiErrorLogMapper.selectOne(null); ApiErrorLogDO apiErrorLogDO = apiErrorLogMapper.selectOne(null);
assertNotNull(infApiErrorLogDO); assertPojoEquals(createDTO, apiErrorLogDO);
assertPojoEquals(createDTO, infApiErrorLogDO); 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);
} }
} }

View File

@ -1,9 +1,9 @@
CREATE TABLE IF NOT EXISTS "infra_config" ( 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, "category" varchar(50) NOT NULL,
"type" tinyint 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 '', "config_key" varchar(100) NOT NULL DEFAULT '',
"value" varchar(500) NOT NULL DEFAULT '', "value" varchar(500) NOT NULL DEFAULT '',
"visible" bit NOT NULL, "visible" bit NOT NULL,

View File

@ -24,7 +24,7 @@ public class ErrorCodeApiImpl implements ErrorCodeApi {
private ErrorCodeService errorCodeService; private ErrorCodeService errorCodeService;
@Override @Override
public CommonResult<Boolean> autoGenerateErrorCodes(List<ErrorCodeAutoGenerateReqDTO> autoGenerateDTOs) { public CommonResult<Boolean> autoGenerateErrorCodeList(List<ErrorCodeAutoGenerateReqDTO> autoGenerateDTOs) {
errorCodeService.autoGenerateErrorCodes(autoGenerateDTOs); errorCodeService.autoGenerateErrorCodes(autoGenerateDTOs);
return success(true); return success(true);
} }

View File

@ -21,8 +21,8 @@ public class TenantApiImpl implements TenantApi {
private TenantService tenantService; private TenantService tenantService;
@Override @Override
public CommonResult<List<Long>> getTenantIds() { public CommonResult<List<Long>> getTenantIdList() {
return success(tenantService.getTenantIds()); return success(tenantService.getTenantIdList());
} }
@Override @Override

View File

@ -33,26 +33,26 @@ public class AdminUserApiImpl implements AdminUserApi {
} }
@Override @Override
public CommonResult<List<AdminUserRespDTO>> getUsers(Collection<Long> ids) { public CommonResult<List<AdminUserRespDTO>> getUserList(Collection<Long> ids) {
List<AdminUserDO> users = userService.getUsers(ids); List<AdminUserDO> users = userService.getUserList(ids);
return success(UserConvert.INSTANCE.convertList4(users)); return success(UserConvert.INSTANCE.convertList4(users));
} }
@Override @Override
public CommonResult<List<AdminUserRespDTO>> getUsersByDeptIds(Collection<Long> deptIds) { public CommonResult<List<AdminUserRespDTO>> getUserListByDeptIds(Collection<Long> deptIds) {
List<AdminUserDO> users = userService.getUsersByDeptIds(deptIds); List<AdminUserDO> users = userService.getUserListByDeptIds(deptIds);
return success(UserConvert.INSTANCE.convertList4(users)); return success(UserConvert.INSTANCE.convertList4(users));
} }
@Override @Override
public CommonResult<List<AdminUserRespDTO>> getUsersByPostIds(Collection<Long> postIds) { public CommonResult<List<AdminUserRespDTO>> getUserListByPostIds(Collection<Long> postIds) {
List<AdminUserDO> users = userService.getUsersByPostIds(postIds); List<AdminUserDO> users = userService.getUserListByPostIds(postIds);
return success(UserConvert.INSTANCE.convertList4(users)); return success(UserConvert.INSTANCE.convertList4(users));
} }
@Override @Override
public CommonResult<Boolean> validUsers(Set<Long> ids) { public CommonResult<Boolean> validUserList(Set<Long> ids) {
userService.validUsers(ids); userService.validateUserList(ids);
return success(true); return success(true);
} }

View File

@ -61,7 +61,7 @@ public class DictDataController {
@GetMapping("/list-all-simple") @GetMapping("/list-all-simple")
@Operation(summary = "获得全部字典数据列表", description = "一般用于管理后台缓存字典数据在本地") @Operation(summary = "获得全部字典数据列表", description = "一般用于管理后台缓存字典数据在本地")
// 无需添加权限认证,因为前端全局都需要 // 无需添加权限认证,因为前端全局都需要
public CommonResult<List<DictDataSimpleRespVO>> getSimpleDictDatas() { public CommonResult<List<DictDataSimpleRespVO>> getSimpleDictDataList() {
List<DictDataDO> list = dictDataService.getDictDataList(); List<DictDataDO> list = dictDataService.getDictDataList();
return success(DictDataConvert.INSTANCE.convertList(list)); return success(DictDataConvert.INSTANCE.convertList(list));
} }

View File

@ -76,7 +76,7 @@ public class DictTypeController {
@GetMapping("/list-all-simple") @GetMapping("/list-all-simple")
@Operation(summary = "获得全部字典类型列表", description = "包括开启 + 禁用的字典类型,主要用于前端的下拉选项") @Operation(summary = "获得全部字典类型列表", description = "包括开启 + 禁用的字典类型,主要用于前端的下拉选项")
// 无需添加权限认证,因为前端全局都需要 // 无需添加权限认证,因为前端全局都需要
public CommonResult<List<DictTypeSimpleRespVO>> listSimpleDictTypes() { public CommonResult<List<DictTypeSimpleRespVO>> getSimpleDictTypeList() {
List<DictTypeDO> list = dictTypeService.getDictTypeList(); List<DictTypeDO> list = dictTypeService.getDictTypeList();
return success(DictTypeConvert.INSTANCE.convertList(list)); return success(DictTypeConvert.INSTANCE.convertList(list));
} }

View File

@ -90,8 +90,8 @@ public class SensitiveWordController {
@GetMapping("/get-tags") @GetMapping("/get-tags")
@Operation(summary = "获取所有敏感词的标签数组") @Operation(summary = "获取所有敏感词的标签数组")
@PreAuthorize("@ss.hasPermission('system:sensitive-word:query')") @PreAuthorize("@ss.hasPermission('system:sensitive-word:query')")
public CommonResult<Set<String>> getSensitiveWordTags() throws IOException { public CommonResult<Set<String>> getSensitiveWordTagSet() {
return success(sensitiveWordService.getSensitiveWordTags()); return success(sensitiveWordService.getSensitiveWordTagSet());
} }
@GetMapping("/validate-text") @GetMapping("/validate-text")

View File

@ -31,6 +31,7 @@ import javax.annotation.Resource;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.List; 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.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId; import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_IS_EMPTY; import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_IS_EMPTY;
@ -99,7 +100,7 @@ public class UserProfileController {
@Operation(summary = "上传用户个人头像") @Operation(summary = "上传用户个人头像")
public CommonResult<String> updateUserAvatar(@RequestParam("avatarFile") MultipartFile file) throws Exception { public CommonResult<String> updateUserAvatar(@RequestParam("avatarFile") MultipartFile file) throws Exception {
if (file.isEmpty()) { if (file.isEmpty()) {
throw ServiceExceptionUtil.exception(FILE_IS_EMPTY); throw exception(FILE_IS_EMPTY);
} }
String avatar = userService.updateUserAvatar(getLoginUserId(), file.getInputStream()); String avatar = userService.updateUserAvatar(getLoginUserId(), file.getInputStream());
return success(avatar); return success(avatar);

View File

@ -13,8 +13,7 @@ import java.util.List;
public interface UserPostMapper extends BaseMapperX<UserPostDO> { public interface UserPostMapper extends BaseMapperX<UserPostDO> {
default List<UserPostDO> selectListByUserId(Long userId) { default List<UserPostDO> selectListByUserId(Long userId) {
return selectList(new LambdaQueryWrapperX<UserPostDO>() return selectList(UserPostDO::getUserId, userId);
.eq(UserPostDO::getUserId, userId));
} }
default void deleteByUserIdAndPostId(Long userId, Collection<Long> postIds) { default void deleteByUserIdAndPostId(Long userId, Collection<Long> postIds) {
@ -24,8 +23,7 @@ public interface UserPostMapper extends BaseMapperX<UserPostDO> {
} }
default List<UserPostDO> selectListByPostIds(Collection<Long> postIds) { default List<UserPostDO> selectListByPostIds(Collection<Long> postIds) {
return selectList(new LambdaQueryWrapperX<UserPostDO>() return selectList(UserPostDO::getPostId, postIds);
.in(UserPostDO::getPostId, postIds));
} }
default void deleteByUserId(Long userId) { default void deleteByUserId(Long userId) {

View File

@ -24,9 +24,8 @@ public interface SocialUserBindMapper extends BaseMapperX<SocialUserBindDO> {
} }
default SocialUserBindDO selectByUserTypeAndSocialUserId(Integer userType, Long socialUserId) { default SocialUserBindDO selectByUserTypeAndSocialUserId(Integer userType, Long socialUserId) {
return selectOne(new LambdaQueryWrapperX<SocialUserBindDO>() return selectOne(SocialUserBindDO::getUserType, userType,
.eq(SocialUserBindDO::getUserType, userType) SocialUserBindDO::getSocialUserId, socialUserId);
.eq(SocialUserBindDO::getSocialUserId, socialUserId));
} }
default List<SocialUserBindDO> selectListByUserIdAndUserType(Long userId, Integer userType) { default List<SocialUserBindDO> selectListByUserIdAndUserType(Long userId, Integer userType) {

View File

@ -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.UserExportReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserPageReqVO; import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; 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 org.apache.ibatis.annotations.Mapper;
import java.util.Collection; import java.util.Collection;
@ -16,15 +15,15 @@ import java.util.List;
public interface AdminUserMapper extends BaseMapperX<AdminUserDO> { public interface AdminUserMapper extends BaseMapperX<AdminUserDO> {
default AdminUserDO selectByUsername(String username) { default AdminUserDO selectByUsername(String username) {
return selectOne(new LambdaQueryWrapper<AdminUserDO>().eq(AdminUserDO::getUsername, username)); return selectOne(AdminUserDO::getUsername, username);
} }
default AdminUserDO selectByEmail(String email) { default AdminUserDO selectByEmail(String email) {
return selectOne(new LambdaQueryWrapper<AdminUserDO>().eq(AdminUserDO::getEmail, email)); return selectOne(AdminUserDO::getEmail, email);
} }
default AdminUserDO selectByMobile(String mobile) { default AdminUserDO selectByMobile(String mobile) {
return selectOne(new LambdaQueryWrapper<AdminUserDO>().eq(AdminUserDO::getMobile, mobile)); return selectOne(AdminUserDO::getMobile, mobile);
} }
default PageResult<AdminUserDO> selectPage(UserPageReqVO reqVO, Collection<Long> deptIds) { default PageResult<AdminUserDO> selectPage(UserPageReqVO reqVO, Collection<Long> deptIds) {
@ -50,10 +49,6 @@ public interface AdminUserMapper extends BaseMapperX<AdminUserDO> {
return selectList(new LambdaQueryWrapperX<AdminUserDO>().like(AdminUserDO::getNickname, nickname)); return selectList(new LambdaQueryWrapperX<AdminUserDO>().like(AdminUserDO::getNickname, nickname));
} }
default List<AdminUserDO> selectListByUsername(String username) {
return selectList(new LambdaQueryWrapperX<AdminUserDO>().like(AdminUserDO::getUsername, username));
}
default List<AdminUserDO> selectListByStatus(Integer status) { default List<AdminUserDO> selectListByStatus(Integer status) {
return selectList(AdminUserDO::getStatus, status); return selectList(AdminUserDO::getStatus, status);
} }

View File

@ -49,7 +49,7 @@ public class OperateLogServiceImpl implements OperateLogService {
// 处理基于用户昵称的查询 // 处理基于用户昵称的查询
Collection<Long> userIds = null; Collection<Long> userIds = null;
if (StrUtil.isNotEmpty(reqVO.getUserNickname())) { 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)) { if (CollUtil.isEmpty(userIds)) {
return PageResult.empty(); return PageResult.empty();
} }
@ -63,7 +63,7 @@ public class OperateLogServiceImpl implements OperateLogService {
// 处理基于用户昵称的查询 // 处理基于用户昵称的查询
Collection<Long> userIds = null; Collection<Long> userIds = null;
if (StrUtil.isNotEmpty(reqVO.getUserNickname())) { 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)) { if (CollUtil.isEmpty(userIds)) {
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -3,7 +3,6 @@ package cn.iocoder.yudao.module.system.service.mail;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount; import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil; 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.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.module.system.convert.mail.MailAccountConvert; 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 org.springframework.validation.annotation.Validated;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.List;
import java.util.Map; 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.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
/** /**
* * Service
* *
* @author wangjingyi * @author wangjingyi
* @since 2022-03-21 * @since 2022-03-21
@ -82,14 +79,13 @@ public class MailSendServiceImpl implements MailSendService {
public Long sendSingleMail(String mail, Long userId, Integer userType, public Long sendSingleMail(String mail, Long userId, Integer userType,
String templateCode, Map<String, Object> templateParams) { String templateCode, Map<String, Object> templateParams) {
// 校验邮箱模版是否合法 // 校验邮箱模版是否合法
MailTemplateDO template = checkMailTemplateValid(templateCode); MailTemplateDO template = validateMailTemplate(templateCode);
// 校验邮箱账号是否合法 // 校验邮箱账号是否合法
MailAccountDO account = checkMailAccountValid(template.getAccountId()); MailAccountDO account = validateMailAccount(template.getAccountId());
// 校验邮箱是否存在 // 校验邮箱是否存在
mail = checkMail(mail); mail = validateMail(mail);
// 校验参数模版 validateTemplateParams(template, templateParams);
checkTemplateParams(template, templateParams);
// 创建发送日志。如果模板被禁用,则不发送短信,只记录日志 // 创建发送日志。如果模板被禁用,则不发送短信,只记录日志
Boolean isSend = CommonStatusEnum.ENABLE.getStatus().equals(template.getStatus()); Boolean isSend = CommonStatusEnum.ENABLE.getStatus().equals(template.getStatus());
@ -107,7 +103,7 @@ public class MailSendServiceImpl implements MailSendService {
@Override @Override
public void doSendMail(MailSendMessage message) { public void doSendMail(MailSendMessage message) {
// 1. 创建发送账号 // 1. 创建发送账号
MailAccountDO account = checkMailAccountValid(message.getAccountId()); MailAccountDO account = validateMailAccount(message.getAccountId());
MailAccount mailAccount = MailAccountConvert.INSTANCE.convert(account, message.getNickname()); MailAccount mailAccount = MailAccountConvert.INSTANCE.convert(account, message.getNickname());
// 2. 发送邮件 // 2. 发送邮件
try { try {
@ -122,7 +118,7 @@ public class MailSendServiceImpl implements MailSendService {
} }
@VisibleForTesting @VisibleForTesting
public MailTemplateDO checkMailTemplateValid(String templateCode) { MailTemplateDO validateMailTemplate(String templateCode) {
// 获得邮件模板。考虑到效率,从缓存中获取 // 获得邮件模板。考虑到效率,从缓存中获取
MailTemplateDO template = mailTemplateService.getMailTemplateByCodeFromCache(templateCode); MailTemplateDO template = mailTemplateService.getMailTemplateByCodeFromCache(templateCode);
// 邮件模板不存在 // 邮件模板不存在
@ -133,7 +129,7 @@ public class MailSendServiceImpl implements MailSendService {
} }
@VisibleForTesting @VisibleForTesting
public MailAccountDO checkMailAccountValid(Long accountId) { MailAccountDO validateMailAccount(Long accountId) {
// 获得邮箱账号。考虑到效率,从缓存中获取 // 获得邮箱账号。考虑到效率,从缓存中获取
MailAccountDO account = mailAccountService.getMailAccountFromCache(accountId); MailAccountDO account = mailAccountService.getMailAccountFromCache(accountId);
// 邮箱账号不存在 // 邮箱账号不存在
@ -144,7 +140,7 @@ public class MailSendServiceImpl implements MailSendService {
} }
@VisibleForTesting @VisibleForTesting
public String checkMail(String mail) { String validateMail(String mail) {
if (StrUtil.isEmpty(mail)) { if (StrUtil.isEmpty(mail)) {
throw exception(MAIL_SEND_MAIL_NOT_EXISTS); throw exception(MAIL_SEND_MAIL_NOT_EXISTS);
} }
@ -152,13 +148,13 @@ public class MailSendServiceImpl implements MailSendService {
} }
/** /**
* *
* *
* @param template * @param template
* @param templateParams * @param templateParams
*/ */
@VisibleForTesting @VisibleForTesting
public void checkTemplateParams(MailTemplateDO template, Map<String, Object> templateParams) { void validateTemplateParams(MailTemplateDO template, Map<String, Object> templateParams) {
template.getParams().forEach(key -> { template.getParams().forEach(key -> {
Object value = templateParams.get(key); Object value = templateParams.get(key);
if (value == null) { if (value == null) {

View File

@ -13,7 +13,8 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; 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 * Service
@ -44,13 +45,13 @@ public class NotifySendServiceImpl implements NotifySendService {
@Override @Override
public Long sendSingleNotify(Long userId, Integer userType, String templateCode, Map<String, Object> templateParams) { public Long sendSingleNotify(Long userId, Integer userType, String templateCode, Map<String, Object> templateParams) {
// 校验模版 // 校验模版
NotifyTemplateDO template = checkNotifyTemplateValid(templateCode); NotifyTemplateDO template = validateNotifyTemplate(templateCode);
if (Objects.equals(template.getStatus(), CommonStatusEnum.DISABLE.getStatus())) { if (Objects.equals(template.getStatus(), CommonStatusEnum.DISABLE.getStatus())) {
log.info("[sendSingleNotify][模版({})已经关闭,无法给用户({}/{})发送]", templateCode, userId, userType); log.info("[sendSingleNotify][模版({})已经关闭,无法给用户({}/{})发送]", templateCode, userId, userType);
return null; return null;
} }
// 校验参数 // 校验参数
checkTemplateParams(template, templateParams); validateTemplateParams(template, templateParams);
// 发送站内信 // 发送站内信
String content = notifyTemplateService.formatNotifyTemplateContent(template.getContent(), templateParams); String content = notifyTemplateService.formatNotifyTemplateContent(template.getContent(), templateParams);
@ -58,7 +59,7 @@ public class NotifySendServiceImpl implements NotifySendService {
} }
@VisibleForTesting @VisibleForTesting
public NotifyTemplateDO checkNotifyTemplateValid(String templateCode) { public NotifyTemplateDO validateNotifyTemplate(String templateCode) {
// 获得站内信模板。考虑到效率,从缓存中获取 // 获得站内信模板。考虑到效率,从缓存中获取
NotifyTemplateDO template = notifyTemplateService.getNotifyTemplateByCodeFromCache(templateCode); NotifyTemplateDO template = notifyTemplateService.getNotifyTemplateByCodeFromCache(templateCode);
// 站内信模板不存在 // 站内信模板不存在
@ -75,7 +76,7 @@ public class NotifySendServiceImpl implements NotifySendService {
* @param templateParams * @param templateParams
*/ */
@VisibleForTesting @VisibleForTesting
public void checkTemplateParams(NotifyTemplateDO template, Map<String, Object> templateParams) { public void validateTemplateParams(NotifyTemplateDO template, Map<String, Object> templateParams) {
template.getParams().forEach(key -> { template.getParams().forEach(key -> {
Object value = templateParams.get(key); Object value = templateParams.get(key);
if (value == null) { if (value == null) {

View File

@ -76,7 +76,7 @@ public class NotifyTemplateServiceImpl implements NotifyTemplateService {
@Override @Override
public Long createNotifyTemplate(NotifyTemplateCreateReqVO createReqVO) { public Long createNotifyTemplate(NotifyTemplateCreateReqVO createReqVO) {
// 校验站内信编码是否重复 // 校验站内信编码是否重复
checkNotifyTemplateCodeDuplicate(null, createReqVO.getCode()); validateNotifyTemplateCodeDuplicate(null, createReqVO.getCode());
// 插入 // 插入
NotifyTemplateDO notifyTemplate = NotifyTemplateConvert.INSTANCE.convert(createReqVO); NotifyTemplateDO notifyTemplate = NotifyTemplateConvert.INSTANCE.convert(createReqVO);
@ -93,7 +93,7 @@ public class NotifyTemplateServiceImpl implements NotifyTemplateService {
// 校验存在 // 校验存在
validateNotifyTemplateExists(updateReqVO.getId()); validateNotifyTemplateExists(updateReqVO.getId());
// 校验站内信编码是否重复 // 校验站内信编码是否重复
checkNotifyTemplateCodeDuplicate(updateReqVO.getId(), updateReqVO.getCode()); validateNotifyTemplateCodeDuplicate(updateReqVO.getId(), updateReqVO.getCode());
// 更新 // 更新
NotifyTemplateDO updateObj = NotifyTemplateConvert.INSTANCE.convert(updateReqVO); NotifyTemplateDO updateObj = NotifyTemplateConvert.INSTANCE.convert(updateReqVO);
@ -136,7 +136,7 @@ public class NotifyTemplateServiceImpl implements NotifyTemplateService {
} }
@VisibleForTesting @VisibleForTesting
public void checkNotifyTemplateCodeDuplicate(Long id, String code) { public void validateNotifyTemplateCodeDuplicate(Long id, String code) {
NotifyTemplateDO template = notifyTemplateMapper.selectByCode(code); NotifyTemplateDO template = notifyTemplateMapper.selectByCode(code);
if (template == null) { if (template == null) {
return; return;

View File

@ -31,6 +31,7 @@ import javax.annotation.Resource;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; 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.dal.dataobject.permission.MenuDO.ID_ROOT;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
@ -118,7 +119,7 @@ public class MenuServiceImpl implements MenuService {
public void updateMenu(MenuUpdateReqVO reqVO) { public void updateMenu(MenuUpdateReqVO reqVO) {
// 校验更新的菜单是否存在 // 校验更新的菜单是否存在
if (menuMapper.selectById(reqVO.getId()) == null) { if (menuMapper.selectById(reqVO.getId()) == null) {
throw ServiceExceptionUtil.exception(MENU_NOT_EXISTS); throw exception(MENU_NOT_EXISTS);
} }
// 校验父菜单存在 // 校验父菜单存在
validateParentMenu(reqVO.getParentId(), reqVO.getId()); validateParentMenu(reqVO.getParentId(), reqVO.getId());
@ -138,11 +139,11 @@ public class MenuServiceImpl implements MenuService {
public void deleteMenu(Long menuId) { public void deleteMenu(Long menuId) {
// 校验是否还有子菜单 // 校验是否还有子菜单
if (menuMapper.selectCountByParentId(menuId) > 0) { if (menuMapper.selectCountByParentId(menuId) > 0) {
throw ServiceExceptionUtil.exception(MENU_EXISTS_CHILDREN); throw exception(MENU_EXISTS_CHILDREN);
} }
// 校验删除的菜单是否存在 // 校验删除的菜单是否存在
if (menuMapper.selectById(menuId) == null) { if (menuMapper.selectById(menuId) == null) {
throw ServiceExceptionUtil.exception(MENU_NOT_EXISTS); throw exception(MENU_NOT_EXISTS);
} }
// 标记删除 // 标记删除
menuMapper.deleteById(menuId); menuMapper.deleteById(menuId);
@ -229,17 +230,17 @@ public class MenuServiceImpl implements MenuService {
} }
// 不能设置自己为父菜单 // 不能设置自己为父菜单
if (parentId.equals(childId)) { if (parentId.equals(childId)) {
throw ServiceExceptionUtil.exception(MENU_PARENT_ERROR); throw exception(MENU_PARENT_ERROR);
} }
MenuDO menu = menuMapper.selectById(parentId); MenuDO menu = menuMapper.selectById(parentId);
// 父菜单不存在 // 父菜单不存在
if (menu == null) { if (menu == null) {
throw ServiceExceptionUtil.exception(MENU_PARENT_NOT_EXISTS); throw exception(MENU_PARENT_NOT_EXISTS);
} }
// 父菜单必须是目录或者菜单类型 // 父菜单必须是目录或者菜单类型
if (!MenuTypeEnum.DIR.getType().equals(menu.getType()) if (!MenuTypeEnum.DIR.getType().equals(menu.getType())
&& !MenuTypeEnum.MENU.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 的菜单 // 如果 id 为空,说明不用比较是否为相同 id 的菜单
if (id == null) { if (id == null) {
throw ServiceExceptionUtil.exception(MENU_NAME_DUPLICATE); throw exception(MENU_NAME_DUPLICATE);
} }
if (!menu.getId().equals(id)) { if (!menu.getId().equals(id)) {
throw ServiceExceptionUtil.exception(MENU_NAME_DUPLICATE); throw exception(MENU_NAME_DUPLICATE);
} }
} }

View File

@ -81,7 +81,7 @@ public interface SensitiveWordService {
* *
* @return * @return
*/ */
Set<String> getSensitiveWordTags(); Set<String> getSensitiveWordTagSet();
/** /**
* *

View File

@ -182,7 +182,7 @@ public class SensitiveWordServiceImpl implements SensitiveWordService {
} }
@Override @Override
public Set<String> getSensitiveWordTags() { public Set<String> getSensitiveWordTagSet() {
return sensitiveWordTagsCache; return sensitiveWordTagsCache;
} }

View File

@ -39,7 +39,6 @@ import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
* Service * Service
* *
* @author zzf * @author zzf
* @date 2021/1/25 9:25
*/ */
@Service @Service
@Slf4j @Slf4j
@ -105,11 +104,11 @@ public class SmsTemplateServiceImpl implements SmsTemplateService {
@Override @Override
public Long createSmsTemplate(SmsTemplateCreateReqVO createReqVO) { 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); SmsTemplateDO template = SmsTemplateConvert.INSTANCE.convert(createReqVO);
@ -127,11 +126,11 @@ public class SmsTemplateServiceImpl implements SmsTemplateService {
// 校验存在 // 校验存在
validateSmsTemplateExists(updateReqVO.getId()); 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); SmsTemplateDO updateObj = SmsTemplateConvert.INSTANCE.convert(updateReqVO);
@ -184,7 +183,7 @@ public class SmsTemplateServiceImpl implements SmsTemplateService {
} }
@VisibleForTesting @VisibleForTesting
public SmsChannelDO checkSmsChannel(Long channelId) { public SmsChannelDO validateSmsChannel(Long channelId) {
SmsChannelDO channelDO = smsChannelService.getSmsChannel(channelId); SmsChannelDO channelDO = smsChannelService.getSmsChannel(channelId);
if (channelDO == null) { if (channelDO == null) {
throw exception(SMS_CHANNEL_NOT_EXISTS); throw exception(SMS_CHANNEL_NOT_EXISTS);
@ -196,7 +195,7 @@ public class SmsTemplateServiceImpl implements SmsTemplateService {
} }
@VisibleForTesting @VisibleForTesting
public void checkSmsTemplateCodeDuplicate(Long id, String code) { public void validateSmsTemplateCodeDuplicate(Long id, String code) {
SmsTemplateDO template = smsTemplateMapper.selectByCode(code); SmsTemplateDO template = smsTemplateMapper.selectByCode(code);
if (template == null) { if (template == null) {
return; return;
@ -217,7 +216,7 @@ public class SmsTemplateServiceImpl implements SmsTemplateService {
* @param apiTemplateId API * @param apiTemplateId API
*/ */
@VisibleForTesting @VisibleForTesting
public void checkApiTemplate(Long channelId, String apiTemplateId) { public void validateApiTemplate(Long channelId, String apiTemplateId) {
// 获得短信模板 // 获得短信模板
SmsClient smsClient = smsClientFactory.getSmsClient(channelId); SmsClient smsClient = smsClientFactory.getSmsClient(channelId);
Assert.notNull(smsClient, String.format("短信客户端(%d) 不存在", channelId)); Assert.notNull(smsClient, String.format("短信客户端(%d) 不存在", channelId));

View File

@ -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.common.pojo.PageResult;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; 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.TenantCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantExportReqVO;
import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantPageReqVO; import cn.iocoder.yudao.module.system.controller.admin.tenant.vo.tenant.TenantPageReqVO;
@ -121,7 +120,7 @@ public interface TenantService {
* *
* @return * @return
*/ */
List<Long> getTenantIds(); List<Long> getTenantIdList();
/** /**
* *

View File

@ -75,7 +75,7 @@ public class TenantServiceImpl implements TenantService {
private PermissionService permissionService; private PermissionService permissionService;
@Override @Override
public List<Long> getTenantIds() { public List<Long> getTenantIdList() {
List<TenantDO> tenants = tenantMapper.selectList(); List<TenantDO> tenants = tenantMapper.selectList();
return CollectionUtils.convertList(tenants, TenantDO::getId); return CollectionUtils.convertList(tenants, TenantDO::getId);
} }

View File

@ -127,7 +127,7 @@ public interface AdminUserService {
* @param deptIds * @param deptIds
* @return * @return
*/ */
List<AdminUserDO> getUsersByDeptIds(Collection<Long> deptIds); List<AdminUserDO> getUserListByDeptIds(Collection<Long> deptIds);
/** /**
* *
@ -135,7 +135,7 @@ public interface AdminUserService {
* @param postIds * @param postIds
* @return * @return
*/ */
List<AdminUserDO> getUsersByPostIds(Collection<Long> postIds); List<AdminUserDO> getUserListByPostIds(Collection<Long> postIds);
/** /**
* *
@ -143,7 +143,7 @@ public interface AdminUserService {
* @param ids * @param ids
* @return * @return
*/ */
List<AdminUserDO> getUsers(Collection<Long> ids); List<AdminUserDO> getUserList(Collection<Long> ids);
/** /**
* *
@ -152,7 +152,7 @@ public interface AdminUserService {
* *
* @param ids * @param ids
*/ */
void validUsers(Set<Long> ids); void validateUserList(Collection<Long> ids);
/** /**
* Map * Map
@ -164,7 +164,7 @@ public interface AdminUserService {
if (CollUtil.isEmpty(ids)) { if (CollUtil.isEmpty(ids)) {
return new HashMap<>(); 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 * @param reqVO
* @return * @return
*/ */
List<AdminUserDO> getUsers(UserExportReqVO reqVO); List<AdminUserDO> getUserList(UserExportReqVO reqVO);
/** /**
* *
@ -181,15 +181,7 @@ public interface AdminUserService {
* @param nickname * @param nickname
* @return * @return
*/ */
List<AdminUserDO> getUsersByNickname(String nickname); List<AdminUserDO> getUserListByNickname(String nickname);
/**
*
*
* @param username
* @return
*/
List<AdminUserDO> getUsersByUsername(String username);
/** /**
* *
@ -198,7 +190,7 @@ public interface AdminUserService {
* @param isUpdateSupport * @param isUpdateSupport
* @return * @return
*/ */
UserImportRespVO importUsers(List<UserImportExcelVO> importUsers, boolean isUpdateSupport); UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport);
/** /**
* *
@ -206,7 +198,7 @@ public interface AdminUserService {
* @param status * @param status
* @return * @return
*/ */
List<AdminUserDO> getUsersByStatus(Integer status); List<AdminUserDO> getUserListByStatus(Integer status);
/** /**
* *

View File

@ -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.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; 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.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.UserProfileUpdatePasswordReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO; 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 * Service
*
* @author * @author
*/ */
@Service("adminUserService") @Service("adminUserService")
@ -73,10 +74,6 @@ public class AdminUserServiceImpl implements AdminUserService {
@Resource @Resource
private FileApi fileApi; private FileApi fileApi;
@Resource
@Lazy // 循环依赖(自己依赖自己),避免报错
private AdminUserServiceImpl self;
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public Long createUser(UserCreateReqVO reqVO) { 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()); reqVO.getDeptId(), reqVO.getPostIds());
// 插入用户 // 插入用户
AdminUserDO user = UserConvert.INSTANCE.convert(reqVO); AdminUserDO user = UserConvert.INSTANCE.convert(reqVO);
user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启 user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
user.setPassword(passwordEncoder.encode(reqVO.getPassword())); // 加密密码 user.setPassword(encodePassword(reqVO.getPassword())); // 加密密码
userMapper.insert(user); userMapper.insert(user);
// 插入关联岗位 // 插入关联岗位
if (CollectionUtil.isNotEmpty(user.getPostIds())) { if (CollectionUtil.isNotEmpty(user.getPostIds())) {
@ -107,7 +104,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void updateUser(UserUpdateReqVO reqVO) { 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()); reqVO.getDeptId(), reqVO.getPostIds());
// 更新用户 // 更新用户
AdminUserDO updateObj = UserConvert.INSTANCE.convert(reqVO); AdminUserDO updateObj = UserConvert.INSTANCE.convert(reqVO);
@ -141,9 +138,9 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
public void updateUserProfile(Long id, UserProfileUpdateReqVO reqVO) { public void updateUserProfile(Long id, UserProfileUpdateReqVO reqVO) {
// 校验正确性 // 校验正确性
checkUserExists(id); validateUserExists(id);
checkEmailUnique(id, reqVO.getEmail()); validateEmailUnique(id, reqVO.getEmail());
checkMobileUnique(id, reqVO.getMobile()); validateMobileUnique(id, reqVO.getMobile());
// 执行更新 // 执行更新
userMapper.updateById(UserConvert.INSTANCE.convert(reqVO).setId(id)); userMapper.updateById(UserConvert.INSTANCE.convert(reqVO).setId(id));
} }
@ -151,7 +148,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) { public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) {
// 校验旧密码密码 // 校验旧密码密码
checkOldPassword(id, reqVO.getOldPassword()); validateOldPassword(id, reqVO.getOldPassword());
// 执行更新 // 执行更新
AdminUserDO updateObj = new AdminUserDO().setId(id); AdminUserDO updateObj = new AdminUserDO().setId(id);
updateObj.setPassword(encodePassword(reqVO.getNewPassword())); // 加密密码 updateObj.setPassword(encodePassword(reqVO.getNewPassword())); // 加密密码
@ -160,7 +157,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
public String updateUserAvatar(Long id, InputStream avatarFile) throws Exception { public String updateUserAvatar(Long id, InputStream avatarFile) throws Exception {
checkUserExists(id); validateUserExists(id);
// 存储文件 // 存储文件
String avatar = fileApi.createFile(IoUtil.readBytes(avatarFile)); String avatar = fileApi.createFile(IoUtil.readBytes(avatarFile));
// 更新路径 // 更新路径
@ -174,7 +171,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
public void updateUserPassword(Long id, String password) { public void updateUserPassword(Long id, String password) {
// 校验用户存在 // 校验用户存在
checkUserExists(id); validateUserExists(id);
// 更新密码 // 更新密码
AdminUserDO updateObj = new AdminUserDO(); AdminUserDO updateObj = new AdminUserDO();
updateObj.setId(id); updateObj.setId(id);
@ -185,7 +182,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
public void updateUserStatus(Long id, Integer status) { public void updateUserStatus(Long id, Integer status) {
// 校验用户存在 // 校验用户存在
checkUserExists(id); validateUserExists(id);
// 更新状态 // 更新状态
AdminUserDO updateObj = new AdminUserDO(); AdminUserDO updateObj = new AdminUserDO();
updateObj.setId(id); updateObj.setId(id);
@ -197,7 +194,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void deleteUser(Long id) { public void deleteUser(Long id) {
// 校验用户存在 // 校验用户存在
checkUserExists(id); validateUserExists(id);
// 删除用户 // 删除用户
userMapper.deleteById(id); userMapper.deleteById(id);
// 删除用户关联数据 // 删除用户关联数据
@ -227,7 +224,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public List<AdminUserDO> getUsersByDeptIds(Collection<Long> deptIds) { public List<AdminUserDO> getUserListByDeptIds(Collection<Long> deptIds) {
if (CollUtil.isEmpty(deptIds)) { if (CollUtil.isEmpty(deptIds)) {
return Collections.emptyList(); return Collections.emptyList();
} }
@ -235,7 +232,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public List<AdminUserDO> getUsersByPostIds(Collection<Long> postIds) { public List<AdminUserDO> getUserListByPostIds(Collection<Long> postIds) {
if (CollUtil.isEmpty(postIds)) { if (CollUtil.isEmpty(postIds)) {
return Collections.emptyList(); return Collections.emptyList();
} }
@ -247,7 +244,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public List<AdminUserDO> getUsers(Collection<Long> ids) { public List<AdminUserDO> getUserList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) { if (CollUtil.isEmpty(ids)) {
return Collections.emptyList(); return Collections.emptyList();
} }
@ -255,7 +252,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public void validUsers(Set<Long> ids) { public void validateUserList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) { if (CollUtil.isEmpty(ids)) {
return; return;
} }
@ -275,20 +272,15 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public List<AdminUserDO> getUsers(UserExportReqVO reqVO) { public List<AdminUserDO> getUserList(UserExportReqVO reqVO) {
return userMapper.selectList(reqVO, getDeptCondition(reqVO.getDeptId())); return userMapper.selectList(reqVO, getDeptCondition(reqVO.getDeptId()));
} }
@Override @Override
public List<AdminUserDO> getUsersByNickname(String nickname) { public List<AdminUserDO> getUserListByNickname(String nickname) {
return userMapper.selectListByNickname(nickname); return userMapper.selectListByNickname(nickname);
} }
@Override
public List<AdminUserDO> getUsersByUsername(String username) {
return userMapper.selectListByUsername(username);
}
/** /**
* *
* @param deptId * @param deptId
@ -304,25 +296,27 @@ public class AdminUserServiceImpl implements AdminUserService {
return deptIds; return deptIds;
} }
@DataPermission(enable = false) // 关闭数据权限,避免因为没有数据权限,查询不到数据,进而导致唯一校验不正确 private void validateUserForCreateOrUpdate(Long id, String username, String mobile, String email,
public void checkCreateOrUpdate(Long id, String username, String mobile, String email,
Long deptId, Set<Long> postIds) { Long deptId, Set<Long> postIds) {
// 关闭数据权限,避免因为没有数据权限,查询不到数据,进而导致唯一校验不正确
DataPermissionUtils.executeIgnore(() -> {
// 校验用户存在 // 校验用户存在
checkUserExists(id); validateUserExists(id);
// 校验用户名唯一 // 校验用户名唯一
checkUsernameUnique(id, username); validateUsernameUnique(id, username);
// 校验手机号唯一 // 校验手机号唯一
checkMobileUnique(id, mobile); validateMobileUnique(id, mobile);
// 校验邮箱唯一 // 校验邮箱唯一
checkEmailUnique(id, email); validateEmailUnique(id, email);
// 校验部门处于开启状态 // 校验部门处于开启状态
deptService.validateDeptList(CollectionUtils.singleton(deptId)); deptService.validateDeptList(CollectionUtils.singleton(deptId));
// 校验岗位处于开启状态 // 校验岗位处于开启状态
postService.validatePostList(postIds); postService.validatePostList(postIds);
});
} }
@VisibleForTesting @VisibleForTesting
public void checkUserExists(Long id) { void validateUserExists(Long id) {
if (id == null) { if (id == null) {
return; return;
} }
@ -333,7 +327,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@VisibleForTesting @VisibleForTesting
public void checkUsernameUnique(Long id, String username) { void validateUsernameUnique(Long id, String username) {
if (StrUtil.isBlank(username)) { if (StrUtil.isBlank(username)) {
return; return;
} }
@ -351,7 +345,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@VisibleForTesting @VisibleForTesting
public void checkEmailUnique(Long id, String email) { void validateEmailUnique(Long id, String email) {
if (StrUtil.isBlank(email)) { if (StrUtil.isBlank(email)) {
return; return;
} }
@ -369,7 +363,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@VisibleForTesting @VisibleForTesting
public void checkMobileUnique(Long id, String mobile) { void validateMobileUnique(Long id, String mobile) {
if (StrUtil.isBlank(mobile)) { if (StrUtil.isBlank(mobile)) {
return; return;
} }
@ -392,7 +386,7 @@ public class AdminUserServiceImpl implements AdminUserService {
* @param oldPassword * @param oldPassword
*/ */
@VisibleForTesting @VisibleForTesting
public void checkOldPassword(Long id, String oldPassword) { void validateOldPassword(Long id, String oldPassword) {
AdminUserDO user = userMapper.selectById(id); AdminUserDO user = userMapper.selectById(id);
if (user == null) { if (user == null) {
throw exception(USER_NOT_EXISTS); throw exception(USER_NOT_EXISTS);
@ -404,7 +398,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override @Override
@Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入 @Transactional(rollbackFor = Exception.class) // 添加事务,异常则回滚所有导入
public UserImportRespVO importUsers(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) { public UserImportRespVO importUserList(List<UserImportExcelVO> importUsers, boolean isUpdateSupport) {
if (CollUtil.isEmpty(importUsers)) { if (CollUtil.isEmpty(importUsers)) {
throw exception(USER_IMPORT_LIST_IS_EMPTY); throw exception(USER_IMPORT_LIST_IS_EMPTY);
} }
@ -413,7 +407,7 @@ public class AdminUserServiceImpl implements AdminUserService {
importUsers.forEach(importUser -> { importUsers.forEach(importUser -> {
// 校验,判断是否有不符合的原因 // 校验,判断是否有不符合的原因
try { try {
checkCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail(), validateUserForCreateOrUpdate(null, null, importUser.getMobile(), importUser.getEmail(),
importUser.getDeptId(), null); importUser.getDeptId(), null);
} catch (ServiceException ex) { } catch (ServiceException ex) {
respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage()); respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage());
@ -441,7 +435,7 @@ public class AdminUserServiceImpl implements AdminUserService {
} }
@Override @Override
public List<AdminUserDO> getUsersByStatus(Integer status) { public List<AdminUserDO> getUserListByStatus(Integer status) {
return userMapper.selectListByStatus(status); return userMapper.selectListByStatus(status);
} }

View File

@ -64,7 +64,7 @@ public class OperateLogServiceImplTest extends BaseDbUnitTest {
o.setNickname("wang"); o.setNickname("wang");
o.setStatus(CommonStatusEnum.ENABLE.getStatus()); 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(); Long userId = user.getId();
// 构造操作日志 // 构造操作日志
@ -112,7 +112,7 @@ public class OperateLogServiceImplTest extends BaseDbUnitTest {
o.setNickname("wang"); o.setNickname("wang");
o.setStatus(CommonStatusEnum.ENABLE.getStatus()); 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(); Long userId = user.getId();
// 构造操作日志 // 构造操作日志

View File

@ -13,6 +13,7 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.List;
import java.util.Map; import java.util.Map;
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId; 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.framework.test.core.util.RandomUtils.*;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.MAIL_ACCOUNT_NOT_EXISTS; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.MAIL_ACCOUNT_NOT_EXISTS;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** /**
* {@link MailAccountServiceImpl} * {@link MailAccountServiceImpl}
@ -107,6 +110,8 @@ public class MailAccountServiceImplTest extends BaseDbUnitTest {
mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据 mailAccountMapper.insert(dbMailAccount);// @Sql: 先插入出一条存在的数据
// 准备参数 // 准备参数
Long id = dbMailAccount.getId(); Long id = dbMailAccount.getId();
// mock 方法(无关联模版)
when(mailTemplateService.countByAccountId(eq(id))).thenReturn(0L);
// 调用 // 调用
mailAccountService.deleteMailAccount(id); mailAccountService.deleteMailAccount(id);
@ -115,6 +120,21 @@ public class MailAccountServiceImplTest extends BaseDbUnitTest {
verify(mailProducer).sendMailAccountRefreshMessage(); 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 @Test
public void testDeleteMailAccount_notExists() { public void testDeleteMailAccount_notExists() {
// 准备参数 // 准备参数
@ -149,4 +169,35 @@ public class MailAccountServiceImplTest extends BaseDbUnitTest {
assertPojoEquals(dbMailAccount, pageResult.getList().get(0)); 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<MailAccountDO> list = mailAccountService.getMailAccountList();
// 断言
assertEquals(2, list.size());
assertPojoEquals(dbMailAccount01, list.get(0));
assertPojoEquals(dbMailAccount02, list.get(1));
}
} }

View File

@ -116,6 +116,20 @@ public class MailLogServiceImplTest extends BaseDbUnitTest {
assertEquals("NullPointerException: 测试异常", dbLog.getSendException()); 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 @Test
public void testGetMailLogPage() { public void testGetMailLogPage() {
// mock 数据 // mock 数据

View File

@ -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.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest; 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.MailAccountDO;
import cn.iocoder.yudao.module.system.dal.dataobject.mail.MailTemplateDO; 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.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.assertj.core.util.Lists;
import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockedStatic;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; 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.framework.test.core.util.RandomUtils.*;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
import static org.junit.jupiter.api.Assertions.assertEquals; 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.ArgumentMatchers.eq;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -31,6 +38,10 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest {
@InjectMocks @InjectMocks
private MailSendServiceImpl mailSendService; private MailSendServiceImpl mailSendService;
@Mock
private AdminUserService adminUserService;
@Mock
private MemberService memberService;
@Mock @Mock
private MailAccountService mailAccountService; private MailAccountService mailAccountService;
@Mock @Mock
@ -55,6 +66,82 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest {
System.out.println("发送结果:" + messageId); System.out.println("发送结果:" + messageId);
} }
@Test
public void testSendSingleMailToAdmin() {
// 准备参数
Long userId = randomLongId();
String templateCode = RandomUtils.randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>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<String, Object> templateParams = MapUtil.<String, Object>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(); String mail = randomEmail();
Long userId = randomLongId(); Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue(); Integer userType = randomEle(UserTypeEnum.values()).getValue();
String templateCode = randomString(); String templateCode = RandomUtils.randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234") Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build(); .put("op", "login").build();
// mock MailTemplateService 的方法 // mock MailTemplateService 的方法
@ -74,7 +161,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest {
o.setParams(Lists.newArrayList("code", "op")); o.setParams(Lists.newArrayList("code", "op"));
}); });
when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template);
String content = randomString(); String content = RandomUtils.randomString();
when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams))) when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams)))
.thenReturn(content); .thenReturn(content);
// mock MailAccountService 的方法 // mock MailAccountService 的方法
@ -103,7 +190,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest {
String mail = randomEmail(); String mail = randomEmail();
Long userId = randomLongId(); Long userId = randomLongId();
Integer userType = randomEle(UserTypeEnum.values()).getValue(); Integer userType = randomEle(UserTypeEnum.values()).getValue();
String templateCode = randomString(); String templateCode = RandomUtils.randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234") Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build(); .put("op", "login").build();
// mock MailTemplateService 的方法 // mock MailTemplateService 的方法
@ -113,7 +200,7 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest {
o.setParams(Lists.newArrayList("code", "op")); o.setParams(Lists.newArrayList("code", "op"));
}); });
when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template); when(mailTemplateService.getMailTemplateByCodeFromCache(eq(templateCode))).thenReturn(template);
String content = randomString(); String content = RandomUtils.randomString();
when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams))) when(mailTemplateService.formatMailTemplateContent(eq(template.getContent()), eq(templateParams)))
.thenReturn(content); .thenReturn(content);
// mock MailAccountService 的方法 // mock MailAccountService 的方法
@ -134,18 +221,18 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest {
} }
@Test @Test
public void testCheckMailTemplateValid_notExists() { public void testValidateMailTemplateValid_notExists() {
// 准备参数 // 准备参数
String templateCode = randomString(); String templateCode = RandomUtils.randomString();
// mock 方法 // mock 方法
// 调用,并断言异常 // 调用,并断言异常
assertServiceException(() -> mailSendService.checkMailTemplateValid(templateCode), assertServiceException(() -> mailSendService.validateMailTemplate(templateCode),
MAIL_TEMPLATE_NOT_EXISTS); MAIL_TEMPLATE_NOT_EXISTS);
} }
@Test @Test
public void testBuildTemplateParams_paramMiss() { public void testValidateTemplateParams_paramMiss() {
// 准备参数 // 准备参数
MailTemplateDO template = randomPojo(MailTemplateDO.class, MailTemplateDO template = randomPojo(MailTemplateDO.class,
o -> o.setParams(Lists.newArrayList("code"))); o -> o.setParams(Lists.newArrayList("code")));
@ -153,18 +240,80 @@ class MailSendServiceImplTest extends BaseMockitoUnitTest {
// mock 方法 // mock 方法
// 调用,并断言异常 // 调用,并断言异常
assertServiceException(() -> mailSendService.checkTemplateParams(template, templateParams), assertServiceException(() -> mailSendService.validateTemplateParams(template, templateParams),
MAIL_SEND_TEMPLATE_PARAM_MISS, "code"); MAIL_SEND_TEMPLATE_PARAM_MISS, "code");
} }
@Test @Test
public void testCheckMail_notExists() { public void testValidateMail_notExists() {
// 准备参数 // 准备参数
// mock 方法 // mock 方法
// 调用,并断言异常 // 调用,并断言异常
assertServiceException(() -> mailSendService.checkMail(null), assertServiceException(() -> mailSendService.validateMail(null),
MAIL_SEND_MAIL_NOT_EXISTS); MAIL_SEND_MAIL_NOT_EXISTS);
} }
@Test
public void testDoSendMail_success() {
try (MockedStatic<MailUtil> 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<MailUtil> 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));
}
}
} }

View File

@ -14,6 +14,8 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map; 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.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.framework.test.core.util.RandomUtils.randomPojo;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.MAIL_TEMPLATE_NOT_EXISTS; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.MAIL_TEMPLATE_NOT_EXISTS;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.verify;
/** /**
* {@link MailTemplateServiceImpl} * {@link MailTemplateServiceImpl}
@ -70,6 +73,7 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest {
// 校验记录的属性是否正确 // 校验记录的属性是否正确
MailTemplateDO mailTemplate = mailTemplateMapper.selectById(mailTemplateId); MailTemplateDO mailTemplate = mailTemplateMapper.selectById(mailTemplateId);
assertPojoEquals(reqVO, mailTemplate); assertPojoEquals(reqVO, mailTemplate);
verify(mailProducer).sendMailTemplateRefreshMessage();
} }
@Test @Test
@ -87,6 +91,7 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest {
// 校验是否更新正确 // 校验是否更新正确
MailTemplateDO mailTemplate = mailTemplateMapper.selectById(reqVO.getId()); // 获取最新的 MailTemplateDO mailTemplate = mailTemplateMapper.selectById(reqVO.getId()); // 获取最新的
assertPojoEquals(reqVO, mailTemplate); assertPojoEquals(reqVO, mailTemplate);
verify(mailProducer).sendMailTemplateRefreshMessage();
} }
@Test @Test
@ -110,6 +115,7 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest {
mailTemplateService.deleteMailTemplate(id); mailTemplateService.deleteMailTemplate(id);
// 校验数据不存在了 // 校验数据不存在了
assertNull(mailTemplateMapper.selectById(id)); assertNull(mailTemplateMapper.selectById(id));
verify(mailProducer).sendMailTemplateRefreshMessage();
} }
@Test @Test
@ -158,4 +164,77 @@ public class MailTemplateServiceImplTest extends BaseDbUnitTest {
assertPojoEquals(dbMailTemplate, pageResult.getList().get(0)); 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<MailTemplateDO> 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<String, Object> 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);
}
} }

View File

@ -108,6 +108,20 @@ public class NotifyMessageServiceImplTest extends BaseDbUnitTest {
assertPojoEquals(dbNotifyMessage, pageResult.getList().get(0)); 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 @Test
public void testGetMyNotifyMessagePage() { public void testGetMyNotifyMessagePage() {
// mock 数据 // mock 数据

View File

@ -33,6 +33,62 @@ class NotifySendServiceImplTest extends BaseMockitoUnitTest {
@Mock @Mock
private NotifyMessageService notifyMessageService; private NotifyMessageService notifyMessageService;
@Test
public void testSendSingleNotifyToAdmin() {
// 准备参数
Long userId = randomLongId();
String templateCode = randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>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<String, Object> templateParams = MapUtil.<String, Object>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 方法 // mock 方法
// 调用,并断言异常 // 调用,并断言异常
assertServiceException(() -> notifySendService.checkNotifyTemplateValid(templateCode), assertServiceException(() -> notifySendService.validateNotifyTemplate(templateCode),
NOTICE_NOT_FOUND); NOTICE_NOT_FOUND);
} }
@ -112,7 +168,7 @@ class NotifySendServiceImplTest extends BaseMockitoUnitTest {
// mock 方法 // mock 方法
// 调用,并断言异常 // 调用,并断言异常
assertServiceException(() -> notifySendService.checkTemplateParams(template, templateParams), assertServiceException(() -> notifySendService.validateTemplateParams(template, templateParams),
NOTIFY_SEND_TEMPLATE_PARAM_MISS, "code"); NOTIFY_SEND_TEMPLATE_PARAM_MISS, "code");
} }

View File

@ -14,6 +14,8 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import javax.annotation.Resource; 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.buildBetweenTime;
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; 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)); 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<String, Object> params = new HashMap<>();
params.put("name", "小红");
params.put("what", "饭");
// 调用,并断言
assertEquals("小红,你好,饭吃了吗?",
notifyTemplateService.formatNotifyTemplateContent("{name},你好,{what}吃了吗?", params));
}
} }

View File

@ -60,7 +60,7 @@ public class SensitiveWordServiceImplTest extends BaseDbUnitTest {
// 调用 // 调用
sensitiveWordService.initLocalCache(); sensitiveWordService.initLocalCache();
// 断言 sensitiveWordTagsCache 缓存 // 断言 sensitiveWordTagsCache 缓存
assertEquals(SetUtils.asSet("论坛", "蔬菜"), sensitiveWordService.getSensitiveWordTags()); assertEquals(SetUtils.asSet("论坛", "蔬菜"), sensitiveWordService.getSensitiveWordTagSet());
// 断言 tagSensitiveWordTries 缓存 // 断言 tagSensitiveWordTries 缓存
assertNotNull(sensitiveWordService.getDefaultSensitiveWordTrie()); assertNotNull(sensitiveWordService.getDefaultSensitiveWordTrie());
assertEquals(2, sensitiveWordService.getTagSensitiveWordTries().size()); assertEquals(2, sensitiveWordService.getTagSensitiveWordTries().size());

View File

@ -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<String, Object> templateParams = MapUtil.<String, Object>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<String, Object> templateParams = MapUtil.<String, Object>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<String, Object> templateParams = MapUtil.<String, Object>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<String, Object> templateParams = MapUtil.<String, Object>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<String, Object> 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<SmsSendRespDTO> 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<SmsReceiveRespDTO> 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())));
}
}

View File

@ -279,7 +279,7 @@ public class SmsTemplateServiceImplTest extends BaseDbUnitTest {
} }
@Test @Test
public void testCheckSmsChannel_success() { public void testValidateSmsChannel_success() {
// 准备参数 // 准备参数
Long channelId = randomLongId(); Long channelId = randomLongId();
// mock 方法 // mock 方法
@ -290,23 +290,23 @@ public class SmsTemplateServiceImplTest extends BaseDbUnitTest {
when(smsChannelService.getSmsChannel(eq(channelId))).thenReturn(channelDO); when(smsChannelService.getSmsChannel(eq(channelId))).thenReturn(channelDO);
// 调用 // 调用
SmsChannelDO returnChannelDO = smsTemplateService.checkSmsChannel(channelId); SmsChannelDO returnChannelDO = smsTemplateService.validateSmsChannel(channelId);
// 断言 // 断言
assertPojoEquals(returnChannelDO, channelDO); assertPojoEquals(returnChannelDO, channelDO);
} }
@Test @Test
public void testCheckSmsChannel_notExists() { public void testValidateSmsChannel_notExists() {
// 准备参数 // 准备参数
Long channelId = randomLongId(); Long channelId = randomLongId();
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> smsTemplateService.checkSmsChannel(channelId), assertServiceException(() -> smsTemplateService.validateSmsChannel(channelId),
SMS_CHANNEL_NOT_EXISTS); SMS_CHANNEL_NOT_EXISTS);
} }
@Test @Test
public void testCheckSmsChannel_disable() { public void testValidateSmsChannel_disable() {
// 准备参数 // 准备参数
Long channelId = randomLongId(); Long channelId = randomLongId();
// mock 方法 // mock 方法
@ -317,30 +317,30 @@ public class SmsTemplateServiceImplTest extends BaseDbUnitTest {
when(smsChannelService.getSmsChannel(eq(channelId))).thenReturn(channelDO); when(smsChannelService.getSmsChannel(eq(channelId))).thenReturn(channelDO);
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> smsTemplateService.checkSmsChannel(channelId), assertServiceException(() -> smsTemplateService.validateSmsChannel(channelId),
SMS_CHANNEL_DISABLE); SMS_CHANNEL_DISABLE);
} }
@Test @Test
public void testCheckDictDataValueUnique_success() { public void testValidateDictDataValueUnique_success() {
// 调用,成功 // 调用,成功
smsTemplateService.checkSmsTemplateCodeDuplicate(randomLongId(), randomString()); smsTemplateService.validateSmsTemplateCodeDuplicate(randomLongId(), randomString());
} }
@Test @Test
public void testCheckSmsTemplateCodeDuplicate_valueDuplicateForCreate() { public void testValidateSmsTemplateCodeDuplicate_valueDuplicateForCreate() {
// 准备参数 // 准备参数
String code = randomString(); String code = randomString();
// mock 数据 // mock 数据
smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code))); smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code)));
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> smsTemplateService.checkSmsTemplateCodeDuplicate(null, code), assertServiceException(() -> smsTemplateService.validateSmsTemplateCodeDuplicate(null, code),
SMS_TEMPLATE_CODE_DUPLICATE, code); SMS_TEMPLATE_CODE_DUPLICATE, code);
} }
@Test @Test
public void testCheckDictDataValueUnique_valueDuplicateForUpdate() { public void testValidateDictDataValueUnique_valueDuplicateForUpdate() {
// 准备参数 // 准备参数
Long id = randomLongId(); Long id = randomLongId();
String code = randomString(); String code = randomString();
@ -348,7 +348,7 @@ public class SmsTemplateServiceImplTest extends BaseDbUnitTest {
smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code))); smsTemplateMapper.insert(randomSmsTemplateDO(o -> o.setCode(code)));
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> smsTemplateService.checkSmsTemplateCodeDuplicate(id, code), assertServiceException(() -> smsTemplateService.validateSmsTemplateCodeDuplicate(id, code),
SMS_TEMPLATE_CODE_DUPLICATE, code); SMS_TEMPLATE_CODE_DUPLICATE, code);
} }

View File

@ -81,13 +81,13 @@ public class TenantServiceImplTest extends BaseDbUnitTest {
} }
@Test @Test
public void testGetTenantIds() { public void testGetTenantIdList() {
// mock 数据 // mock 数据
TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L)); TenantDO tenant = randomPojo(TenantDO.class, o -> o.setId(1L));
tenantMapper.insert(tenant); tenantMapper.insert(tenant);
// 调用,并断言业务异常 // 调用,并断言业务异常
List<Long> result = tenantService.getTenantIds(); List<Long> result = tenantService.getTenantIdList();
assertEquals(Collections.singletonList(1L), result); assertEquals(Collections.singletonList(1L), result);
} }

View File

@ -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.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; 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.collection.CollectionUtils;
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.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.infra.api.file.FileApi; 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.UserProfileUpdatePasswordReqVO;
@ -32,23 +31,25 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.time.LocalDateTime;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.function.Consumer; import java.util.function.Consumer;
import static cn.hutool.core.util.RandomUtil.randomBytes; import static cn.hutool.core.util.RandomUtil.randomBytes;
import static cn.hutool.core.util.RandomUtil.randomEle; 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.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.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; 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.framework.test.core.util.RandomUtils.*;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
import static java.util.Collections.singleton; import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.assertj.core.util.Lists.newArrayList; import static org.assertj.core.util.Lists.newArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
@ -173,6 +174,23 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
assertEquals(3L, userPosts.get(1).getPostId()); 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 @Test
public void testUpdateUserProfile_success() { public void testUpdateUserProfile_success() {
// mock 数据 // mock 数据
@ -286,6 +304,34 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
verify(permissionService, times(1)).processUserDeleted(eq(userId)); 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 @Test
public void testGetUserPage() { public void testGetUserPage() {
// mock 数据 // mock 数据
@ -295,8 +341,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
reqVO.setUsername("tu"); reqVO.setUsername("tu");
reqVO.setMobile("1560"); reqVO.setMobile("1560");
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
reqVO.setCreateTime((new LocalDateTime[]{buildLocalDateTime(2020, 12, 1), reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24));
buildLocalDateTime(2020, 12, 24)}));
reqVO.setDeptId(1L); // 其中1L 是 2L 的父部门 reqVO.setDeptId(1L); // 其中1L 是 2L 的父部门
// mock 方法 // mock 方法
List<DeptDO> deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L))); List<DeptDO> deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L)));
@ -311,7 +356,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
} }
@Test @Test
public void testGetUsers() { public void testGetUserList_export() {
// mock 数据 // mock 数据
AdminUserDO dbUser = initGetUserPageData(); AdminUserDO dbUser = initGetUserPageData();
// 准备参数 // 准备参数
@ -319,15 +364,14 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
reqVO.setUsername("tu"); reqVO.setUsername("tu");
reqVO.setMobile("1560"); reqVO.setMobile("1560");
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
reqVO.setCreateTime((new LocalDateTime[]{buildLocalDateTime(2020, 12, 1), reqVO.setCreateTime(buildBetweenTime(2020, 12, 1, 2020, 12, 24));
buildLocalDateTime(2020, 12, 24)}));
reqVO.setDeptId(1L); // 其中1L 是 2L 的父部门 reqVO.setDeptId(1L); // 其中1L 是 2L 的父部门
// mock 方法 // mock 方法
List<DeptDO> deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L))); List<DeptDO> deptList = newArrayList(randomPojo(DeptDO.class, o -> o.setId(2L)));
when(deptService.getDeptListByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList); when(deptService.getDeptListByParentIdFromCache(eq(reqVO.getDeptId()), eq(true))).thenReturn(deptList);
// 调用 // 调用
List<AdminUserDO> list = userService.getUsers(reqVO); List<AdminUserDO> list = userService.getUserList(reqVO);
// 断言 // 断言
assertEquals(1, list.size()); assertEquals(1, list.size());
assertPojoEquals(dbUser, list.get(0)); assertPojoEquals(dbUser, list.get(0));
@ -342,28 +386,59 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
o.setUsername("tudou"); o.setUsername("tudou");
o.setMobile("15601691300"); o.setMobile("15601691300");
o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setStatus(CommonStatusEnum.ENABLE.getStatus());
o.setCreateTime(buildLocalDateTime(2020, 12, 12)); o.setCreateTime(buildTime(2020, 12, 12));
o.setDeptId(2L); o.setDeptId(2L);
}); });
userMapper.insert(dbUser); userMapper.insert(dbUser);
// 测试 username 不匹配 // 测试 username 不匹配
userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setUsername("dou"))); userMapper.insert(cloneIgnoreId(dbUser, o -> o.setUsername("dou")));
// 测试 mobile 不匹配 // 测试 mobile 不匹配
userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setMobile("18818260888"))); userMapper.insert(cloneIgnoreId(dbUser, o -> o.setMobile("18818260888")));
// 测试 status 不匹配 // 测试 status 不匹配
userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); userMapper.insert(cloneIgnoreId(dbUser, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
// 测试 createTime 不匹配 // 测试 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 不匹配 // 测试 dept 不匹配
userMapper.insert(ObjectUtils.cloneIgnoreId(dbUser, o -> o.setDeptId(0L))); userMapper.insert(cloneIgnoreId(dbUser, o -> o.setDeptId(0L)));
return dbUser; 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<Long> deptIds = singleton(1L);
// 调用
List<AdminUserDO> list = userService.getUserListByDeptIds(deptIds);
// 断言
assertEquals(1, list.size());
assertEquals(dbUser, list.get(0));
}
/** /**
* *
*/ */
@Test @Test
public void testImportUsers_01() { public void testImportUserList_01() {
// 准备参数 // 准备参数
UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { 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()); 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.getCreateUsernames().size());
assertEquals(0, respVO.getUpdateUsernames().size()); assertEquals(0, respVO.getUpdateUsernames().size());
@ -383,7 +458,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
* *
*/ */
@Test @Test
public void testImportUsers_02() { public void testImportUserList_02() {
// 准备参数 // 准备参数
UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> { UserImportExcelVO importUser = randomPojo(UserImportExcelVO.class, o -> {
o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围
@ -399,7 +474,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
when(passwordEncoder.encode(eq("yudaoyuanma"))).thenReturn("java"); 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()); assertEquals(1, respVO.getCreateUsernames().size());
AdminUserDO user = userMapper.selectByUsername(respVO.getCreateUsernames().get(0)); AdminUserDO user = userMapper.selectByUsername(respVO.getCreateUsernames().get(0));
@ -413,7 +488,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
* *
*/ */
@Test @Test
public void testImportUsers_03() { public void testImportUserList_03() {
// mock 数据 // mock 数据
AdminUserDO dbUser = randomAdminUserDO(); AdminUserDO dbUser = randomAdminUserDO();
userMapper.insert(dbUser); userMapper.insert(dbUser);
@ -431,7 +506,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
when(deptService.getDept(eq(dept.getId()))).thenReturn(dept); 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.getCreateUsernames().size());
assertEquals(0, respVO.getUpdateUsernames().size()); assertEquals(0, respVO.getUpdateUsernames().size());
@ -443,7 +518,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
* *
*/ */
@Test @Test
public void testImportUsers_04() { public void testImportUserList_04() {
// mock 数据 // mock 数据
AdminUserDO dbUser = randomAdminUserDO(); AdminUserDO dbUser = randomAdminUserDO();
userMapper.insert(dbUser); userMapper.insert(dbUser);
@ -461,7 +536,7 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
when(deptService.getDept(eq(dept.getId()))).thenReturn(dept); 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(0, respVO.getCreateUsernames().size());
assertEquals(1, respVO.getUpdateUsernames().size()); assertEquals(1, respVO.getUpdateUsernames().size());
@ -471,24 +546,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
} }
@Test @Test
public void testCheckUserExists_notExists() { public void testValidateUserExists_notExists() {
assertServiceException(() -> userService.checkUserExists(randomLongId()), USER_NOT_EXISTS); assertServiceException(() -> userService.validateUserExists(randomLongId()), USER_NOT_EXISTS);
} }
@Test @Test
public void testCheckUsernameUnique_usernameExistsForCreate() { public void testValidateUsernameUnique_usernameExistsForCreate() {
// 准备参数 // 准备参数
String username = randomString(); String username = randomString();
// mock 数据 // mock 数据
userMapper.insert(randomAdminUserDO(o -> o.setUsername(username))); userMapper.insert(randomAdminUserDO(o -> o.setUsername(username)));
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> userService.checkUsernameUnique(null, username), assertServiceException(() -> userService.validateUsernameUnique(null, username),
USER_USERNAME_EXISTS); USER_USERNAME_EXISTS);
} }
@Test @Test
public void testCheckUsernameUnique_usernameExistsForUpdate() { public void testValidateUsernameUnique_usernameExistsForUpdate() {
// 准备参数 // 准备参数
Long id = randomLongId(); Long id = randomLongId();
String username = randomString(); String username = randomString();
@ -496,24 +571,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
userMapper.insert(randomAdminUserDO(o -> o.setUsername(username))); userMapper.insert(randomAdminUserDO(o -> o.setUsername(username)));
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> userService.checkUsernameUnique(id, username), assertServiceException(() -> userService.validateUsernameUnique(id, username),
USER_USERNAME_EXISTS); USER_USERNAME_EXISTS);
} }
@Test @Test
public void testCheckEmailUnique_emailExistsForCreate() { public void testValidateEmailUnique_emailExistsForCreate() {
// 准备参数 // 准备参数
String email = randomString(); String email = randomString();
// mock 数据 // mock 数据
userMapper.insert(randomAdminUserDO(o -> o.setEmail(email))); userMapper.insert(randomAdminUserDO(o -> o.setEmail(email)));
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> userService.checkEmailUnique(null, email), assertServiceException(() -> userService.validateEmailUnique(null, email),
USER_EMAIL_EXISTS); USER_EMAIL_EXISTS);
} }
@Test @Test
public void testCheckEmailUnique_emailExistsForUpdate() { public void testValidateEmailUnique_emailExistsForUpdate() {
// 准备参数 // 准备参数
Long id = randomLongId(); Long id = randomLongId();
String email = randomString(); String email = randomString();
@ -521,24 +596,24 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
userMapper.insert(randomAdminUserDO(o -> o.setEmail(email))); userMapper.insert(randomAdminUserDO(o -> o.setEmail(email)));
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> userService.checkEmailUnique(id, email), assertServiceException(() -> userService.validateEmailUnique(id, email),
USER_EMAIL_EXISTS); USER_EMAIL_EXISTS);
} }
@Test @Test
public void testCheckMobileUnique_mobileExistsForCreate() { public void testValidateMobileUnique_mobileExistsForCreate() {
// 准备参数 // 准备参数
String mobile = randomString(); String mobile = randomString();
// mock 数据 // mock 数据
userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile))); userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile)));
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> userService.checkMobileUnique(null, mobile), assertServiceException(() -> userService.validateMobileUnique(null, mobile),
USER_MOBILE_EXISTS); USER_MOBILE_EXISTS);
} }
@Test @Test
public void testCheckMobileUnique_mobileExistsForUpdate() { public void testValidateMobileUnique_mobileExistsForUpdate() {
// 准备参数 // 准备参数
Long id = randomLongId(); Long id = randomLongId();
String mobile = randomString(); String mobile = randomString();
@ -546,18 +621,18 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile))); userMapper.insert(randomAdminUserDO(o -> o.setMobile(mobile)));
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> userService.checkMobileUnique(id, mobile), assertServiceException(() -> userService.validateMobileUnique(id, mobile),
USER_MOBILE_EXISTS); USER_MOBILE_EXISTS);
} }
@Test @Test
public void testCheckOldPassword_notExists() { public void testValidateOldPassword_notExists() {
assertServiceException(() -> userService.checkOldPassword(randomLongId(), randomString()), assertServiceException(() -> userService.validateOldPassword(randomLongId(), randomString()),
USER_NOT_EXISTS); USER_NOT_EXISTS);
} }
@Test @Test
public void testCheckOldPassword_passwordFailed() { public void testValidateOldPassword_passwordFailed() {
// mock 数据 // mock 数据
AdminUserDO user = randomAdminUserDO(); AdminUserDO user = randomAdminUserDO();
userMapper.insert(user); userMapper.insert(user);
@ -566,14 +641,14 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
String oldPassword = user.getPassword(); String oldPassword = user.getPassword();
// 调用,校验异常 // 调用,校验异常
assertServiceException(() -> userService.checkOldPassword(id, oldPassword), assertServiceException(() -> userService.validateOldPassword(id, oldPassword),
USER_PASSWORD_FAILED); USER_PASSWORD_FAILED);
// 校验调用 // 校验调用
verify(passwordEncoder, times(1)).matches(eq(oldPassword), eq(user.getPassword())); verify(passwordEncoder, times(1)).matches(eq(oldPassword), eq(user.getPassword()));
} }
@Test @Test
public void testUsersByPostIds() { public void testUserListByPostIds() {
// 准备参数 // 准备参数
Collection<Long> postIds = asSet(10L, 20L); Collection<Long> postIds = asSet(10L, 20L);
// mock user1 数据 // mock user1 数据
@ -587,12 +662,114 @@ public class AdminUserServiceImplTest extends BaseDbUnitTest {
userPostMapper.insert(new UserPostDO().setUserId(user2.getId()).setPostId(100L)); userPostMapper.insert(new UserPostDO().setUserId(user2.getId()).setPostId(100L));
// 调用 // 调用
List<AdminUserDO> result = userService.getUsersByPostIds(postIds); List<AdminUserDO> result = userService.getUserListByPostIds(postIds);
// 断言 // 断言
assertEquals(1, result.size()); assertEquals(1, result.size());
assertEquals(user1, result.get(0)); assertEquals(user1, result.get(0));
} }
@Test
public void testGetUserList() {
// mock 数据
AdminUserDO user = randomAdminUserDO();
userMapper.insert(user);
// 测试 id 不匹配
userMapper.insert(randomAdminUserDO());
// 准备参数
Collection<Long> ids = singleton(user.getId());
// 调用
List<AdminUserDO> 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<Long> ids = singleton(user.getId());
// 调用
Map<Long, AdminUserDO> 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<AdminUserDO> 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<AdminUserDO> 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<Long> ids = singletonList(userDO.getId());
// 调用,无需断言
userService.validateUserList(ids);
}
@Test
public void testValidateUserList_notFound() {
// 准备参数
List<Long> 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<Long> ids = singletonList(userDO.getId());
// 调用, 并断言异常
assertServiceException(() -> userService.validateUserList(ids), USER_IS_DISABLE,
userDO.getNickname());
}
// ========== 随机对象 ========== // ========== 随机对象 ==========
@SafeVarargs @SafeVarargs