补全用户与岗位的关联的单元测试,简化相关的实现代码

pull/2/head
YunaiV 2022-05-02 15:59:38 +08:00
parent c845f3f012
commit cf3cfdd2d6
6 changed files with 85 additions and 100 deletions

View File

@ -1,7 +1,7 @@
package cn.iocoder.yudao.module.system.dal.dataobject.dept;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import com.baomidou.mybatisplus.annotation.DbType;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
@ -14,6 +14,7 @@ import lombok.EqualsAndHashCode;
* @author ruoyi
*/
@TableName("system_user_post")
@KeySequence("system_user_post_seq") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。
@Data
@EqualsAndHashCode(callSuper = true)
public class UserPostDO extends BaseDO {
@ -25,10 +26,14 @@ public class UserPostDO extends BaseDO {
private Long id;
/**
* ID
*
* {@link AdminUserDO#getId()}
*/
private Long userId;
/**
* ID
*
* {@link PostDO#getId()}
*/
private Long postId;

View File

@ -12,9 +12,9 @@ import java.util.List;
@Mapper
public interface UserPostMapper extends BaseMapperX<UserPostDO> {
default List<UserPostDO> selectIdList(Long id) {
default List<UserPostDO> selectListByUserId(Long userId) {
return selectList(new LambdaQueryWrapperX<UserPostDO>()
.eq(UserPostDO::getUserId, id));
.eq(UserPostDO::getUserId, userId));
}
default void deleteByUserIdAndPostId(Long userId, Collection<Long> postIds) {

View File

@ -11,12 +11,7 @@ import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserExportReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserImportExcelVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserImportRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserUpdateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.*;
import cn.iocoder.yudao.module.system.convert.user.UserConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.UserPostDO;
@ -36,25 +31,12 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.*;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_COUNT_MAX;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_EMAIL_EXISTS;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_IMPORT_LIST_IS_EMPTY;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_IS_DISABLE;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_MOBILE_EXISTS;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_NOT_EXISTS;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_PASSWORD_FAILED;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_USERNAME_EXISTS;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
/**
* Service
@ -98,22 +80,17 @@ public class AdminUserServiceImpl implements AdminUserService {
}
});
// 校验正确性
this.checkCreateOrUpdate(null, reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(),
checkCreateOrUpdate(null, reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(),
reqVO.getDeptId(), reqVO.getPostIds());
// 插入用户
AdminUserDO user = UserConvert.INSTANCE.convert(reqVO);
user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
user.setPassword(passwordEncoder.encode(reqVO.getPassword())); // 加密密码
userMapper.insert(user);
Set<Long> postIds = user.getPostIds();
if (CollectionUtil.isNotEmpty(postIds)) {
List<UserPostDO> insertUserPostList = CollectionUtils.convertList(postIds, postId -> {
UserPostDO entity = new UserPostDO();
entity.setUserId(user.getId());
entity.setPostId(postId);
return entity;
});
userPostMapper.insertBatch(insertUserPostList);
// 插入关联岗位
if (CollectionUtil.isNotEmpty(user.getPostIds())) {
userPostMapper.insertBatch(convertList(user.getPostIds(),
postId -> new UserPostDO().setUserId(user.getId()).setPostId(postId)));
}
return user.getId();
}
@ -122,48 +99,32 @@ public class AdminUserServiceImpl implements AdminUserService {
@Transactional(rollbackFor = Exception.class)
public void updateUser(UserUpdateReqVO reqVO) {
// 校验正确性
this.checkCreateOrUpdate(reqVO.getId(), reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(),
checkCreateOrUpdate(reqVO.getId(), reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(),
reqVO.getDeptId(), reqVO.getPostIds());
// 更新用户
AdminUserDO updateObj = UserConvert.INSTANCE.convert(reqVO);
userMapper.updateById(updateObj);
// 更新岗位
updateUserPost(reqVO, updateObj);
}
private void updateUserPost(UserUpdateReqVO reqVO, AdminUserDO updateObj) {
Set<Long> postIds = updateObj.getPostIds();
Long userId = reqVO.getId();
List<Long> dbPostIds = userPostMapper.selectIdList(userId)
.stream()
.map(UserPostDO::getPostId)
.collect(Collectors.toList());
Set<Long> dbPostIds = convertSet(userPostMapper.selectListByUserId(userId), UserPostDO::getPostId);
// 计算新增和删除的岗位编号
Set<Long> postIds = updateObj.getPostIds();
Collection<Long> createPostIds = CollUtil.subtract(postIds, dbPostIds);
Collection<Long> deletePostIds = CollUtil.subtract(dbPostIds, postIds);
// 执行新增和删除。对于已经授权的菜单,不用做任何处理
if (!CollectionUtil.isEmpty(createPostIds)) {
List<UserPostDO> list = createUserPost(userId, createPostIds);
userPostMapper.insertBatch(list);
userPostMapper.insertBatch(convertList(createPostIds,
postId -> new UserPostDO().setUserId(userId).setPostId(postId)));
}
if (!CollectionUtil.isEmpty(deletePostIds)) {
userPostMapper.deleteByUserIdAndPostId(userId, deletePostIds);
}
}
private List<UserPostDO> createUserPost(Long userId, Collection<Long> createPostIds) {
return createPostIds
.stream()
.map(postId -> {
UserPostDO entity = new UserPostDO();
entity.setUserId(userId);
entity.setPostId(postId);
return entity;
})
.collect(Collectors.toList());
}
@Override
public void updateUserLogin(Long id, String loginIp) {
userMapper.updateById(new AdminUserDO().setId(id).setLoginIp(loginIp).setLoginDate(new Date()));
@ -172,9 +133,9 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override
public void updateUserProfile(Long id, UserProfileUpdateReqVO reqVO) {
// 校验正确性
this.checkUserExists(id);
this.checkEmailUnique(id, reqVO.getEmail());
this.checkMobileUnique(id, reqVO.getMobile());
checkUserExists(id);
checkEmailUnique(id, reqVO.getEmail());
checkMobileUnique(id, reqVO.getMobile());
// 执行更新
userMapper.updateById(UserConvert.INSTANCE.convert(reqVO).setId(id));
}
@ -182,7 +143,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override
public void updateUserPassword(Long id, UserProfileUpdatePasswordReqVO reqVO) {
// 校验旧密码密码
this.checkOldPassword(id, reqVO.getOldPassword());
checkOldPassword(id, reqVO.getOldPassword());
// 执行更新
AdminUserDO updateObj = new AdminUserDO().setId(id);
updateObj.setPassword(passwordEncoder.encode(reqVO.getNewPassword())); // 加密密码
@ -191,7 +152,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override
public String updateUserAvatar(Long id, InputStream avatarFile) throws Exception {
this.checkUserExists(id);
checkUserExists(id);
// 存储文件
String avatar = fileApi.createFile(IoUtil.readBytes(avatarFile));
// 更新路径
@ -205,7 +166,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override
public void updateUserPassword(Long id, String password) {
// 校验用户存在
this.checkUserExists(id);
checkUserExists(id);
// 更新密码
AdminUserDO updateObj = new AdminUserDO();
updateObj.setId(id);
@ -216,7 +177,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override
public void updateUserStatus(Long id, Integer status) {
// 校验用户存在
this.checkUserExists(id);
checkUserExists(id);
// 更新状态
AdminUserDO updateObj = new AdminUserDO();
updateObj.setId(id);
@ -228,7 +189,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Transactional(rollbackFor = Exception.class)
public void deleteUser(Long id) {
// 校验用户存在
this.checkUserExists(id);
checkUserExists(id);
// 删除用户
userMapper.deleteById(id);
// 删除用户关联数据
@ -244,7 +205,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override
public PageResult<AdminUserDO> getUserPage(UserPageReqVO reqVO) {
return userMapper.selectPage(reqVO, this.getDeptCondition(reqVO.getDeptId()));
return userMapper.selectPage(reqVO, getDeptCondition(reqVO.getDeptId()));
}
@Override
@ -265,15 +226,11 @@ public class AdminUserServiceImpl implements AdminUserService {
if (CollUtil.isEmpty(postIds)) {
return Collections.emptyList();
}
List<Long> userIdList = userPostMapper.selectListByPostIds(postIds)
.stream()
.map(UserPostDO::getUserId)
.distinct()
.collect(Collectors.toList());;
if (userIdList.isEmpty()) {
Set<Long> userIds = convertSet(userPostMapper.selectListByPostIds(postIds), UserPostDO::getUserId);
if (CollUtil.isEmpty(userIds)) {
return Collections.emptyList();
}
return userMapper.selectBatchIds(userIdList);
return userMapper.selectBatchIds(userIds);
}
@Override
@ -306,7 +263,7 @@ public class AdminUserServiceImpl implements AdminUserService {
@Override
public List<AdminUserDO> getUsers(UserExportReqVO reqVO) {
return userMapper.selectList(reqVO, this.getDeptCondition(reqVO.getDeptId()));
return userMapper.selectList(reqVO, getDeptCondition(reqVO.getDeptId()));
}
@Override
@ -328,7 +285,7 @@ public class AdminUserServiceImpl implements AdminUserService {
if (deptId == null) {
return Collections.emptySet();
}
Set<Long> deptIds = CollectionUtils.convertSet(deptService.getDeptsByParentIdFromCache(
Set<Long> deptIds = convertSet(deptService.getDeptsByParentIdFromCache(
deptId, true), DeptDO::getId);
deptIds.add(deptId); // 包括自身
return deptIds;
@ -337,13 +294,13 @@ public class AdminUserServiceImpl implements AdminUserService {
private void checkCreateOrUpdate(Long id, String username, String mobile, String email,
Long deptId, Set<Long> postIds) {
// 校验用户存在
this.checkUserExists(id);
checkUserExists(id);
// 校验用户名唯一
this.checkUsernameUnique(id, username);
checkUsernameUnique(id, username);
// 校验手机号唯一
this.checkMobileUnique(id, mobile);
checkMobileUnique(id, mobile);
// 校验邮箱唯一
this.checkEmailUnique(id, email);
checkEmailUnique(id, email);
// 校验部门处于开启状态
deptService.validDepts(CollectionUtils.singleton(deptId));
// 校验岗位处于开启状态

View File

@ -7,21 +7,23 @@ import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.ObjectUtils;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdatePasswordReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.*;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.PostDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.UserPostDO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.dept.UserPostMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.yudao.module.system.enums.common.SexEnum;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.dept.PostService;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.tenant.TenantService;
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
import org.junit.jupiter.api.Test;
import org.mockito.stubbing.Answer;
import org.springframework.boot.test.mock.mockito.MockBean;
@ -30,16 +32,19 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import static cn.hutool.core.util.RandomUtil.randomBytes;
import static cn.hutool.core.util.RandomUtil.randomEle;
import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.buildTime;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
import static java.util.Collections.singleton;
import static org.assertj.core.util.Lists.newArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@ -47,13 +52,15 @@ import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@Import(AdminUserServiceImpl.class)
public class UserServiceImplTest extends BaseDbUnitTest {
public class AdminUserServiceImplTest extends BaseDbUnitTest {
@Resource
private AdminUserServiceImpl userService;
@Resource
private AdminUserMapper userMapper;
@Resource
private UserPostMapper userPostMapper;
@MockBean
private DeptService deptService;
@ -74,6 +81,7 @@ public class UserServiceImplTest extends BaseDbUnitTest {
UserCreateReqVO reqVO = randomPojo(UserCreateReqVO.class, o -> {
o.setSex(RandomUtil.randomEle(SexEnum.values()).getSex());
o.setMobile(randomString());
o.setPostIds(asSet(1L, 2L));
});
// mock 账户额度充足
TenantDO tenant = randomPojo(TenantDO.class, o -> o.setAccountCount(1));
@ -104,6 +112,10 @@ public class UserServiceImplTest extends BaseDbUnitTest {
assertPojoEquals(reqVO, user, "password");
assertEquals("yudaoyuanma", user.getPassword());
assertEquals(CommonStatusEnum.ENABLE.getStatus(), user.getStatus());
// 断言关联岗位
List<UserPostDO> userPosts = userPostMapper.selectListByUserId(user.getId());
assertEquals(1L, userPosts.get(0).getPostId());
assertEquals(2L, userPosts.get(1).getPostId());
}
@Test
@ -124,13 +136,16 @@ public class UserServiceImplTest extends BaseDbUnitTest {
@Test
public void testUpdateUser_success() {
// mock 数据
AdminUserDO dbUser = randomAdminUserDO();
AdminUserDO dbUser = randomAdminUserDO(o -> o.setPostIds(asSet(1L, 2L)));
userMapper.insert(dbUser);
userPostMapper.insert(new UserPostDO().setUserId(dbUser.getId()).setPostId(1L));
userPostMapper.insert(new UserPostDO().setUserId(dbUser.getId()).setPostId(2L));
// 准备参数
UserUpdateReqVO reqVO = randomPojo(UserUpdateReqVO.class, o -> {
o.setId(dbUser.getId());
o.setSex(RandomUtil.randomEle(SexEnum.values()).getSex());
o.setMobile(randomString());
o.setPostIds(asSet(2L, 3L));
});
// mock deptService 的方法
DeptDO dept = randomPojo(DeptDO.class, o -> {
@ -151,6 +166,10 @@ public class UserServiceImplTest extends BaseDbUnitTest {
// 断言
AdminUserDO user = userMapper.selectById(reqVO.getId());
assertPojoEquals(reqVO, user);
// 断言关联岗位
List<UserPostDO> userPosts = userPostMapper.selectListByUserId(user.getId());
assertEquals(2L, userPosts.get(0).getPostId());
assertEquals(3L, userPosts.get(1).getPostId());
}
@Test
@ -552,22 +571,26 @@ public class UserServiceImplTest extends BaseDbUnitTest {
verify(passwordEncoder, times(1)).matches(eq(oldPassword), eq(user.getPassword()));
}
// @Test //TODO jason 已经移到userCoreService.getUsersByPostIds
// public void testUsersByPostIds() {
// // 准备参数
// Collection<Long> postIds = asSet(10L, 20L);
// // mock 方法
// AdminUserDO user1 = randomAdminUserDO(o -> o.setPostIds(asSet(10L, 30L)));
// userMapper.insert(user1);
// AdminUserDO user2 = randomAdminUserDO(o -> o.setPostIds(singleton(100L)));
// userMapper.insert(user2);
//
// // 调用
// List<AdminUserDO> result = userService.getUsersByPostIds(postIds);
// // 断言
// assertEquals(1, result.size());
// assertEquals(user1, result.get(0));
// }
@Test
public void testUsersByPostIds() {
// 准备参数
Collection<Long> postIds = asSet(10L, 20L);
// mock user1 数据
AdminUserDO user1 = randomAdminUserDO(o -> o.setPostIds(asSet(10L, 30L)));
userMapper.insert(user1);
userPostMapper.insert(new UserPostDO().setUserId(user1.getId()).setPostId(10L));
userPostMapper.insert(new UserPostDO().setUserId(user1.getId()).setPostId(30L));
// mock user2 数据
AdminUserDO user2 = randomAdminUserDO(o -> o.setPostIds(singleton(100L)));
userMapper.insert(user2);
userPostMapper.insert(new UserPostDO().setUserId(user2.getId()).setPostId(100L));
// 调用
List<AdminUserDO> result = userService.getUsersByPostIds(postIds);
// 断言
assertEquals(1, result.size());
assertEquals(user1, result.get(0));
}
// ========== 随机对象 ==========

View File

@ -10,7 +10,7 @@ DELETE FROM "system_user_session";
DELETE FROM "system_post";
DELETE FROM "system_login_log";
DELETE FROM "system_operate_log";
DELETE FROM "system_user";
DELETE FROM "system_users";
DELETE FROM "system_sms_channel";
DELETE FROM "system_sms_template";
DELETE FROM "system_sms_log";

View File

@ -225,7 +225,7 @@ CREATE TABLE IF NOT EXISTS `system_operate_log` (
PRIMARY KEY (`id`)
) COMMENT ='';
CREATE TABLE IF NOT EXISTS "system_user" (
CREATE TABLE IF NOT EXISTS "system_users" (
"id" bigint not null GENERATED BY DEFAULT AS IDENTITY,
"username" varchar(30) not null,
"password" varchar(100) not null default '',