提交 9185e5d2 authored 作者: YunaiV's avatar YunaiV

完善 RoleServiceImpl 单元测试

上级 71550a3c
......@@ -213,7 +213,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {
private void validTaskAssignRuleOptions(Integer type, Set<Long> options) {
if (Objects.equals(type, BpmTaskAssignRuleTypeEnum.ROLE.getType())) {
roleApi.validRoles(options);
roleApi.validRoleList(options);
} else if (ObjectUtils.equalsAny(type, BpmTaskAssignRuleTypeEnum.DEPT_MEMBER.getType(),
BpmTaskAssignRuleTypeEnum.DEPT_LEADER.getType())) {
deptApi.validateDeptList(options);
......
......@@ -20,6 +20,6 @@ public interface RoleApi {
@GetMapping(PREFIX + "/valid")
@ApiOperation("校验角色是否合法")
@ApiImplicitParam(name = "ids", value = "角色编号数组", example = "1,2", required = true, allowMultiple = true)
CommonResult<Boolean> validRoles(@RequestParam("ids") Collection<Long> ids);
CommonResult<Boolean> validRoleList(@RequestParam("ids") Collection<Long> ids);
}
package cn.iocoder.yudao.module.system.enums.permission;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Menu 编号枚举
*/
@Getter
@AllArgsConstructor
public enum MenuIdEnum {
/**
* 根节点
*/
ROOT(0L);
private final Long id;
}
......@@ -22,8 +22,8 @@ public class RoleApiImpl implements RoleApi {
private RoleService roleService;
@Override
public CommonResult<Boolean> validRoles(Collection<Long> ids) {
roleService.validRoles(ids);
public CommonResult<Boolean> validRoleList(Collection<Long> ids) {
roleService.validateRoleList(ids);
return success(true);
}
}
......@@ -98,7 +98,7 @@ public class AuthController {
}
// 获得角色列表
Set<Long> roleIds = permissionService.getUserRoleIdsFromCache(getLoginUserId(), singleton(CommonStatusEnum.ENABLE.getStatus()));
List<RoleDO> roleList = roleService.getRolesFromCache(roleIds);
List<RoleDO> roleList = roleService.getRoleListFromCache(roleIds);
// 获得菜单列表
List<MenuDO> menuList = permissionService.getRoleMenuListFromCache(roleIds,
SetUtils.asSet(MenuTypeEnum.DIR.getType(), MenuTypeEnum.MENU.getType(), MenuTypeEnum.BUTTON.getType()),
......
......@@ -20,12 +20,12 @@ import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static java.util.Collections.singleton;
@Api(tags = "管理后台 - 角色")
@RestController
......@@ -85,9 +85,9 @@ public class RoleController {
@GetMapping("/list-all-simple")
@ApiOperation(value = "获取角色精简信息列表", notes = "只包含被开启的角色,主要用于前端的下拉选项")
public CommonResult<List<RoleSimpleRespVO>> getSimpleRoles() {
public CommonResult<List<RoleSimpleRespVO>> getSimpleRoleList() {
// 获得角色列表,只要开启状态的
List<RoleDO> list = roleService.getRoles(Collections.singleton(CommonStatusEnum.ENABLE.getStatus()));
List<RoleDO> list = roleService.getRoleListByStatus(singleton(CommonStatusEnum.ENABLE.getStatus()));
// 排序后,返回给前端
list.sort(Comparator.comparing(RoleDO::getSort));
return success(RoleConvert.INSTANCE.convertList02(list));
......
......@@ -63,7 +63,7 @@ public class UserProfileController {
AdminUserDO user = userService.getUser(getLoginUserId());
UserProfileRespVO resp = UserConvert.INSTANCE.convert03(user);
// 获得用户角色
List<RoleDO> userRoles = roleService.getRolesFromCache(permissionService.getUserRoleIdListByUserId(user.getId()));
List<RoleDO> userRoles = roleService.getRoleListFromCache(permissionService.getUserRoleIdListByUserId(user.getId()));
resp.setRoles(UserConvert.INSTANCE.convertList(userRoles));
// 获得部门信息
if (user.getDeptId() != null) {
......
......@@ -9,13 +9,15 @@ import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.enums.permission.MenuIdEnum;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import org.slf4j.LoggerFactory;
import java.util.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO.ID_ROOT;
@Mapper
public interface AuthConvert {
......@@ -26,8 +28,8 @@ public interface AuthConvert {
default AuthPermissionInfoRespVO convert(AdminUserDO user, List<RoleDO> roleList, List<MenuDO> menuList) {
return AuthPermissionInfoRespVO.builder()
.user(AuthPermissionInfoRespVO.UserVO.builder().id(user.getId()).nickname(user.getNickname()).avatar(user.getAvatar()).build())
.roles(CollectionUtils.convertSet(roleList, RoleDO::getCode))
.permissions(CollectionUtils.convertSet(menuList, MenuDO::getPermission))
.roles(convertSet(roleList, RoleDO::getCode))
.permissions(convertSet(menuList, MenuDO::getPermission))
.build();
}
......@@ -47,7 +49,7 @@ public interface AuthConvert {
Map<Long, AuthMenuRespVO> treeNodeMap = new LinkedHashMap<>();
menuList.forEach(menu -> treeNodeMap.put(menu.getId(), AuthConvert.INSTANCE.convertTreeNode(menu)));
// 处理父子关系
treeNodeMap.values().stream().filter(node -> !node.getParentId().equals(MenuIdEnum.ROOT.getId())).forEach(childNode -> {
treeNodeMap.values().stream().filter(node -> !node.getParentId().equals(ID_ROOT)).forEach(childNode -> {
// 获得父节点
AuthMenuRespVO parentNode = treeNodeMap.get(childNode.getParentId());
if (parentNode == null) {
......@@ -62,7 +64,7 @@ public interface AuthConvert {
parentNode.getChildren().add(childNode);
});
// 获得到所有的根节点
return CollectionUtils.filterList(treeNodeMap.values(), node -> MenuIdEnum.ROOT.getId().equals(node.getParentId()));
return filterList(treeNodeMap.values(), node -> ID_ROOT.equals(node.getParentId()));
}
SocialUserBindReqDTO convert(Long userId, Integer userType, AuthSocialBindLoginReqVO reqVO);
......
......@@ -158,7 +158,7 @@ public class PermissionServiceImpl implements PermissionService {
}
// 判断角色是否包含超级管理员。如果是超级管理员,获取到全部
List<RoleDO> roleList = roleService.getRolesFromCache(roleIds);
List<RoleDO> roleList = roleService.getRoleListFromCache(roleIds);
if (roleService.hasAnySuperAdmin(roleList)) {
return menuService.getMenuListFromCache(menuTypes, menusStatuses);
}
......@@ -371,7 +371,7 @@ public class PermissionServiceImpl implements PermissionService {
if (roleService.hasAnySuperAdmin(roleIds)) {
return true;
}
Set<String> userRoles = convertSet(roleService.getRolesFromCache(roleIds),
Set<String> userRoles = convertSet(roleService.getRoleListFromCache(roleIds),
RoleDO::getCode);
return CollUtil.containsAny(userRoles, Sets.newHashSet(roles));
}
......@@ -388,7 +388,7 @@ public class PermissionServiceImpl implements PermissionService {
result.setSelf(true);
return result;
}
List<RoleDO> roles = roleService.getRolesFromCache(roleIds);
List<RoleDO> roles = roleService.getRoleListFromCache(roleIds);
// 获得用户的部门编号的缓存,通过 Guava 的 Suppliers 惰性求值,即有且仅有第一次发起 DB 的查询
Supplier<Long> userDeptIdCache = Suppliers.memoize(() -> userService.getUser(userId).getDeptId());
......
......@@ -79,7 +79,7 @@ public interface RoleService {
* @param statuses 筛选的状态。允许空,空时不筛选
* @return 角色列表
*/
List<RoleDO> getRoles(@Nullable Collection<Integer> statuses);
List<RoleDO> getRoleListByStatus(@Nullable Collection<Integer> statuses);
/**
* 获得角色数组,从缓存中
......@@ -87,7 +87,7 @@ public interface RoleService {
* @param ids 角色编号数组
* @return 角色数组
*/
List<RoleDO> getRolesFromCache(Collection<Long> ids);
List<RoleDO> getRoleListFromCache(Collection<Long> ids);
/**
* 判断角色数组中,是否有超级管理员
......@@ -104,7 +104,7 @@ public interface RoleService {
* @return 是否有管理员
*/
default boolean hasAnySuperAdmin(Set<Long> ids) {
return hasAnySuperAdmin(getRolesFromCache(ids));
return hasAnySuperAdmin(getRoleListFromCache(ids));
}
/**
......@@ -138,6 +138,6 @@ public interface RoleService {
*
* @param ids 角色编号数组
*/
void validRoles(Collection<Long> ids);
void validateRoleList(Collection<Long> ids);
}
......@@ -5,7 +5,6 @@ import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RoleCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.permission.vo.role.RoleExportReqVO;
......@@ -34,6 +33,7 @@ import java.util.*;
import java.util.stream.Collectors;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;
/**
......@@ -76,7 +76,7 @@ public class RoleServiceImpl implements RoleService {
log.info("[initLocalCache][缓存角色,数量为:{}]", roleList.size());
// 第二步:构建缓存
roleCache = CollectionUtils.convertMap(roleList, RoleDO::getId);
roleCache = convertMap(roleList, RoleDO::getId);
});
}
......@@ -84,7 +84,7 @@ public class RoleServiceImpl implements RoleService {
@Transactional
public Long createRole(RoleCreateReqVO reqVO, Integer type) {
// 校验角色
checkDuplicateRole(reqVO.getName(), reqVO.getCode(), null);
validateRoleDuplicate(reqVO.getName(), reqVO.getCode(), null);
// 插入到数据库
RoleDO role = RoleConvert.INSTANCE.convert(reqVO);
role.setType(ObjectUtil.defaultIfNull(type, RoleTypeEnum.CUSTOM.getType()));
......@@ -105,13 +105,13 @@ public class RoleServiceImpl implements RoleService {
@Override
public void updateRole(RoleUpdateReqVO reqVO) {
// 校验是否可以更新
checkUpdateRole(reqVO.getId());
validateRoleForUpdate(reqVO.getId());
// 校验角色的唯一字段是否重复
checkDuplicateRole(reqVO.getName(), reqVO.getCode(), reqVO.getId());
validateRoleDuplicate(reqVO.getName(), reqVO.getCode(), reqVO.getId());
// 更新到数据库
RoleDO updateObject = RoleConvert.INSTANCE.convert(reqVO);
roleMapper.updateById(updateObject);
RoleDO updateObj = RoleConvert.INSTANCE.convert(reqVO);
roleMapper.updateById(updateObj);
// 发送刷新消息
roleProducer.sendRoleRefreshMessage();
}
......@@ -119,12 +119,11 @@ public class RoleServiceImpl implements RoleService {
@Override
public void updateRoleStatus(Long id, Integer status) {
// 校验是否可以更新
checkUpdateRole(id);
validateRoleForUpdate(id);
// 更新状态
RoleDO updateObject = new RoleDO();
updateObject.setId(id);
updateObject.setStatus(status);
roleMapper.updateById(updateObject);
RoleDO updateObj = new RoleDO().setId(id).setStatus(status);
roleMapper.updateById(updateObj);
// 发送刷新消息
roleProducer.sendRoleRefreshMessage();
}
......@@ -132,7 +131,8 @@ public class RoleServiceImpl implements RoleService {
@Override
public void updateRoleDataScope(Long id, Integer dataScope, Set<Long> dataScopeDeptIds) {
// 校验是否可以更新
checkUpdateRole(id);
validateRoleForUpdate(id);
// 更新数据范围
RoleDO updateObject = new RoleDO();
updateObject.setId(id);
......@@ -147,7 +147,7 @@ public class RoleServiceImpl implements RoleService {
@Transactional(rollbackFor = Exception.class)
public void deleteRole(Long id) {
// 校验是否可以更新
this.checkUpdateRole(id);
validateRoleForUpdate(id);
// 标记删除
roleMapper.deleteById(id);
// 删除相关数据
......@@ -169,7 +169,7 @@ public class RoleServiceImpl implements RoleService {
}
@Override
public List<RoleDO> getRoles(@Nullable Collection<Integer> statuses) {
public List<RoleDO> getRoleListByStatus(@Nullable Collection<Integer> statuses) {
if (CollUtil.isEmpty(statuses)) {
return roleMapper.selectList();
}
......@@ -177,7 +177,7 @@ public class RoleServiceImpl implements RoleService {
}
@Override
public List<RoleDO> getRolesFromCache(Collection<Long> ids) {
public List<RoleDO> getRoleListFromCache(Collection<Long> ids) {
if (CollectionUtil.isEmpty(ids)) {
return Collections.emptyList();
}
......@@ -219,7 +219,7 @@ public class RoleServiceImpl implements RoleService {
* @param id 角色编号
*/
@VisibleForTesting
public void checkDuplicateRole(String name, String code, Long id) {
void validateRoleDuplicate(String name, String code, Long id) {
// 0. 超级管理员,不允许创建
if (RoleCodeEnum.isSuperAdmin(code)) {
throw exception(ROLE_ADMIN_CODE_ERROR, code);
......@@ -246,7 +246,7 @@ public class RoleServiceImpl implements RoleService {
* @param id 角色编号
*/
@VisibleForTesting
public void checkUpdateRole(Long id) {
void validateRoleForUpdate(Long id) {
RoleDO roleDO = roleMapper.selectById(id);
if (roleDO == null) {
throw exception(ROLE_NOT_EXISTS);
......@@ -258,13 +258,13 @@ public class RoleServiceImpl implements RoleService {
}
@Override
public void validRoles(Collection<Long> ids) {
public void validateRoleList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return;
}
// 获得角色信息
List<RoleDO> roles = roleMapper.selectBatchIds(ids);
Map<Long, RoleDO> roleMap = CollectionUtils.convertMap(roles, RoleDO::getId);
Map<Long, RoleDO> roleMap = convertMap(roles, RoleDO::getId);
// 校验
ids.forEach(id -> {
RoleDO role = roleMap.get(id);
......
......@@ -158,7 +158,7 @@ public class TenantServiceImpl implements TenantService {
public void updateTenantRoleMenu(Long tenantId, Set<Long> menuIds) {
TenantUtils.execute(tenantId, () -> {
// 获得所有角色
List<RoleDO> roles = roleService.getRoles(null);
List<RoleDO> roles = roleService.getRoleListByStatus(null);
roles.forEach(role -> Assert.isTrue(tenantId.equals(role.getTenantId()), "角色({}/{}) 租户不匹配",
role.getId(), role.getTenantId(), tenantId)); // 兜底校验
// 重新分配每个角色的权限
......
......@@ -106,7 +106,7 @@ public class PermissionServiceTest extends BaseDbUnitTest {
Collection<Integer> menusStatuses = asList(0, 1);
// mock 方法
List<RoleDO> roleList = singletonList(randomPojo(RoleDO.class, o -> o.setId(100L)));
when(roleService.getRolesFromCache(eq(roleIds))).thenReturn(roleList);
when(roleService.getRoleListFromCache(eq(roleIds))).thenReturn(roleList);
when(roleService.hasAnySuperAdmin(same(roleList))).thenReturn(true);
List<MenuDO> menuList = randomPojoList(MenuDO.class);
when(menuService.getMenuListFromCache(eq(menuTypes), eq(menusStatuses))).thenReturn(menuList);
......@@ -419,7 +419,7 @@ public class PermissionServiceTest extends BaseDbUnitTest {
.setStatus(CommonStatusEnum.ENABLE.getStatus()));
when(roleService.getRoleFromCache(eq(100L))).thenReturn(role);
// mock 其它方法
when(roleService.getRolesFromCache(eq(asSet(100L)))).thenReturn(singletonList(role));
when(roleService.getRoleListFromCache(eq(asSet(100L)))).thenReturn(singletonList(role));
// 调用
boolean has = permissionService.hasAnyRoles(userId, roles);
......@@ -436,7 +436,7 @@ public class PermissionServiceTest extends BaseDbUnitTest {
// mock 获得用户的角色
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.ALL.getScope())
.setStatus(CommonStatusEnum.ENABLE.getStatus()));
when(roleService.getRolesFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO));
when(roleService.getRoleListFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO));
when(roleService.getRoleFromCache(eq(2L))).thenReturn(roleDO);
// 调用
......@@ -456,7 +456,7 @@ public class PermissionServiceTest extends BaseDbUnitTest {
// mock 获得用户的角色
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.DEPT_CUSTOM.getScope())
.setStatus(CommonStatusEnum.ENABLE.getStatus()));
when(roleService.getRolesFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO));
when(roleService.getRoleListFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO));
when(roleService.getRoleFromCache(eq(2L))).thenReturn(roleDO);
// mock 部门的返回
when(userService.getUser(eq(1L))).thenReturn(new AdminUserDO().setDeptId(3L), null, null); // 最后返回 null 的目的,看看会不会重复调用
......@@ -480,7 +480,7 @@ public class PermissionServiceTest extends BaseDbUnitTest {
// mock 获得用户的角色
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.DEPT_ONLY.getScope())
.setStatus(CommonStatusEnum.ENABLE.getStatus()));
when(roleService.getRolesFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO));
when(roleService.getRoleListFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO));
when(roleService.getRoleFromCache(eq(2L))).thenReturn(roleDO);
// mock 部门的返回
when(userService.getUser(eq(1L))).thenReturn(new AdminUserDO().setDeptId(3L), null, null); // 最后返回 null 的目的,看看会不会重复调用
......@@ -503,7 +503,7 @@ public class PermissionServiceTest extends BaseDbUnitTest {
// mock 获得用户的角色
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.DEPT_AND_CHILD.getScope())
.setStatus(CommonStatusEnum.ENABLE.getStatus()));
when(roleService.getRolesFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO));
when(roleService.getRoleListFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO));
when(roleService.getRoleFromCache(eq(2L))).thenReturn(roleDO);
// mock 部门的返回
when(userService.getUser(eq(1L))).thenReturn(new AdminUserDO().setDeptId(3L), null, null); // 最后返回 null 的目的,看看会不会重复调用
......@@ -531,7 +531,7 @@ public class PermissionServiceTest extends BaseDbUnitTest {
// mock 获得用户的角色
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setDataScope(DataScopeEnum.SELF.getScope())
.setStatus(CommonStatusEnum.ENABLE.getStatus()));
when(roleService.getRolesFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO));
when(roleService.getRoleListFromCache(eq(singleton(2L)))).thenReturn(singletonList(roleDO));
when(roleService.getRoleFromCache(eq(2L))).thenReturn(roleDO);
// 调用
......
......@@ -196,7 +196,7 @@ public class TenantServiceImplTest extends BaseDbUnitTest {
role100.setTenantId(dbTenant.getId());
RoleDO role101 = randomPojo(RoleDO.class, o -> o.setId(101L));
role101.setTenantId(dbTenant.getId());
when(roleService.getRoles(isNull())).thenReturn(asList(role100, role101));
when(roleService.getRoleList(isNull())).thenReturn(asList(role100, role101));
// mock 每个角色的权限
when(permissionService.getRoleMenuIds(eq(101L))).thenReturn(asSet(201L, 202L));
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论