add some UT for default auth plugin (#12318)

This commit is contained in:
hth 2024-07-08 10:48:51 +08:00 committed by GitHub
parent 97162438f7
commit e8e8cd29c0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 829 additions and 13 deletions

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.auth.config;
import com.alibaba.nacos.auth.mock.MockAuthPluginServiceB;
import com.alibaba.nacos.sys.module.ModuleState;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.junit.jupiter.api.AfterEach;
@ -45,7 +46,6 @@ class AuthModuleStateBuilderTest {
void setUp() throws Exception {
when(context.getBean(AuthConfigs.class)).thenReturn(authConfigs);
ApplicationUtils.injectContext(context);
when(authConfigs.getNacosAuthSystemType()).thenReturn("nacos");
}
@AfterEach
@ -54,10 +54,32 @@ class AuthModuleStateBuilderTest {
@Test
void testBuild() {
when(authConfigs.getNacosAuthSystemType()).thenReturn("nacos");
ModuleState actual = new AuthModuleStateBuilder().build();
assertFalse((Boolean) actual.getStates().get(AUTH_ENABLED));
assertFalse((Boolean) actual.getStates().get("login_page_enabled"));
assertEquals("nacos", actual.getStates().get("auth_system_type"));
assertTrue((Boolean) actual.getStates().get("auth_admin_request"));
when(authConfigs.getNacosAuthSystemType()).thenReturn(MockAuthPluginServiceB.TEST_PLUGIN);
ModuleState actual2 = new AuthModuleStateBuilder().build();
assertTrue((Boolean) actual2.getStates().get("login_page_enabled"));
assertEquals(MockAuthPluginServiceB.TEST_PLUGIN, actual2.getStates().get("auth_system_type"));
assertFalse((Boolean) actual2.getStates().get("auth_admin_request"));
}
@Test
void testCacheable() {
AuthModuleStateBuilder authModuleStateBuilder = new AuthModuleStateBuilder();
authModuleStateBuilder.build();
boolean cacheable = authModuleStateBuilder.isCacheable();
assertFalse(cacheable);
when(authConfigs.getNacosAuthSystemType()).thenReturn(MockAuthPluginServiceB.TEST_PLUGIN);
AuthModuleStateBuilder authModuleStateBuilder2 = new AuthModuleStateBuilder();
authModuleStateBuilder2.build();
boolean cacheable2 = authModuleStateBuilder2.isCacheable();
assertTrue(cacheable2);
}
}

View File

@ -0,0 +1,68 @@
/*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.auth.mock;
import com.alibaba.nacos.plugin.auth.api.IdentityContext;
import com.alibaba.nacos.plugin.auth.api.Permission;
import com.alibaba.nacos.plugin.auth.api.Resource;
import com.alibaba.nacos.plugin.auth.constant.ActionTypes;
import com.alibaba.nacos.plugin.auth.spi.server.AuthPluginService;
import java.util.Collection;
import java.util.Collections;
public class MockAuthPluginServiceB implements AuthPluginService {
public static final String TEST_PLUGIN = "testB";
public static final String IDENTITY_TEST_KEY = "identity-test-key";
@Override
public Collection<String> identityNames() {
return Collections.singletonList(IDENTITY_TEST_KEY);
}
@Override
public boolean enableAuth(ActionTypes action, String type) {
return true;
}
@Override
public boolean validateIdentity(IdentityContext identityContext, Resource resource) {
return false;
}
@Override
public Boolean validateAuthority(IdentityContext identityContext, Permission permission) {
return false;
}
@Override
public String getAuthServiceName() {
return TEST_PLUGIN;
}
@Override
public boolean isLoginEnabled() {
return true;
}
@Override
public boolean isAdminRequest() {
return false;
}
}

View File

@ -15,3 +15,4 @@
#
com.alibaba.nacos.auth.mock.MockAuthPluginService
com.alibaba.nacos.auth.mock.MockAuthPluginServiceB

View File

@ -0,0 +1,211 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.plugin.auth.impl.authenticate;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.plugin.auth.api.Permission;
import com.alibaba.nacos.plugin.auth.exception.AccessException;
import com.alibaba.nacos.plugin.auth.impl.constant.AuthConstants;
import com.alibaba.nacos.plugin.auth.impl.persistence.User;
import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl;
import com.alibaba.nacos.plugin.auth.impl.token.TokenManagerDelegate;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl;
import com.alibaba.nacos.plugin.auth.impl.utils.PasswordEncoderUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class AbstractAuthenticationManagerTest {
@InjectMocks
private AbstractAuthenticationManager abstractAuthenticationManager;
@Mock
private NacosUserDetailsServiceImpl userDetailsService;
@Mock
private TokenManagerDelegate jwtTokenManager;
@Mock
private NacosRoleServiceImpl roleService;
private User user;
@BeforeEach
void setUp() throws Exception {
user = new User();
user.setUsername("nacos");
user.setPassword(PasswordEncoderUtil.encode("test"));
}
@Test
void testAuthenticate1() {
assertThrows(AccessException.class, () -> {
abstractAuthenticationManager.authenticate(null, "pwd");
});
}
@Test
void testAuthenticate2() {
assertThrows(AccessException.class, () -> {
abstractAuthenticationManager.authenticate("nacos", null);
});
}
@Test
void testAuthenticate3() throws AccessException {
NacosUserDetails nacosUserDetails = new NacosUserDetails(user);
when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails);
when(jwtTokenManager.createToken(anyString())).thenReturn("token");
NacosUser nacosUser = abstractAuthenticationManager.authenticate("nacos", "test");
assertEquals("token", nacosUser.getToken());
assertEquals(user.getUsername(), nacosUser.getUserName());
}
@Test
void testAuthenticate4() {
when(userDetailsService.loadUserByUsername(anyString())).thenReturn(null);
assertThrows(AccessException.class, () -> {
abstractAuthenticationManager.authenticate("nacos", "test");
});
}
@Test
void testAuthenticate5() {
assertThrows(AccessException.class, () -> {
abstractAuthenticationManager.authenticate("");
});
}
@Test
void testAuthenticate6() throws AccessException {
NacosUser nacosUser = new NacosUser();
when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser);
NacosUser authenticate = abstractAuthenticationManager.authenticate("token");
assertEquals(nacosUser, authenticate);
}
@Test
void testAuthenticate7() throws AccessException {
NacosUser nacosUser = new NacosUser();
when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser);
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
mockHttpServletRequest.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.TOKEN_PREFIX + "-token");
NacosUser authenticate = abstractAuthenticationManager.authenticate(mockHttpServletRequest);
assertEquals(nacosUser, authenticate);
}
@Test
void testAuthenticate8() throws AccessException {
NacosUser nacosUser = new NacosUser();
when(jwtTokenManager.parseToken(anyString())).thenReturn(nacosUser);
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
mockHttpServletRequest.addHeader(AuthConstants.AUTHORIZATION_HEADER, "token");
mockHttpServletRequest.addParameter(Constants.ACCESS_TOKEN, "token");
NacosUser authenticate = abstractAuthenticationManager.authenticate(mockHttpServletRequest);
assertEquals(nacosUser, authenticate);
}
@Test
void testAuthenticate9() throws AccessException {
NacosUserDetails nacosUserDetails = new NacosUserDetails(user);
when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails);
when(jwtTokenManager.createToken(anyString())).thenReturn("token");
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
mockHttpServletRequest.addHeader(AuthConstants.AUTHORIZATION_HEADER, "token");
mockHttpServletRequest.addParameter(AuthConstants.PARAM_USERNAME, "nacos");
mockHttpServletRequest.addParameter(AuthConstants.PARAM_PASSWORD, "test");
NacosUser authenticate = abstractAuthenticationManager.authenticate(mockHttpServletRequest);
assertEquals("token", authenticate.getToken());
assertEquals(user.getUsername(), authenticate.getUserName());
}
@Test
void testAuthorize() {
Permission permission = new Permission();
NacosUser nacosUser = new NacosUser();
when(roleService.hasPermission(nacosUser, permission)).thenReturn(false);
assertThrows(AccessException.class, () -> {
abstractAuthenticationManager.authorize(permission, nacosUser);
});
}
@Test
void testHasGlobalAdminRole() {
when(roleService.hasGlobalAdminRole(anyString())).thenReturn(true);
boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole("nacos");
assertTrue(hasGlobalAdminRole);
}
@Test
void testHasGlobalAdminRole2() {
when(roleService.hasGlobalAdminRole()).thenReturn(true);
boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole();
assertTrue(hasGlobalAdminRole);
}
@Test
void testHasGlobalAdminRole3() {
NacosUser nacosUser = new NacosUser("nacos");
nacosUser.setGlobalAdmin(true);
boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole(nacosUser);
assertTrue(hasGlobalAdminRole);
}
@Test
void testHasGlobalAdminRole4() {
NacosUser nacosUser = new NacosUser("nacos");
nacosUser.setGlobalAdmin(false);
when(roleService.hasGlobalAdminRole(anyString())).thenReturn(true);
boolean hasGlobalAdminRole = abstractAuthenticationManager.hasGlobalAdminRole(nacosUser);
assertTrue(hasGlobalAdminRole);
}
}

View File

@ -0,0 +1,73 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.plugin.auth.impl.authenticate;
import com.alibaba.nacos.plugin.auth.exception.AccessException;
import com.alibaba.nacos.plugin.auth.impl.persistence.User;
import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl;
import com.alibaba.nacos.plugin.auth.impl.token.TokenManagerDelegate;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl;
import com.alibaba.nacos.plugin.auth.impl.utils.PasswordEncoderUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.ldap.core.LdapTemplate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class LdapAuthenticationManagerTest {
@Mock
private NacosUserDetailsServiceImpl userDetailsService;
@Mock
private TokenManagerDelegate jwtTokenManager;
@Mock
private NacosRoleServiceImpl roleService;
@Mock
private LdapTemplate ldapTemplate;
private LdapAuthenticationManager ldapAuthenticationManager;
private User user;
@BeforeEach
void setUp() throws Exception {
user = new User();
user.setUsername("nacos");
user.setPassword(PasswordEncoderUtil.encode("test"));
ldapAuthenticationManager = new LdapAuthenticationManager(ldapTemplate, userDetailsService, jwtTokenManager,
roleService, "", true);
}
@Test
void testLdapAuthenticate() throws AccessException {
NacosUserDetails nacosUserDetails = new NacosUserDetails(user);
when(userDetailsService.loadUserByUsername(anyString())).thenReturn(nacosUserDetails);
NacosUser authenticate = ldapAuthenticationManager.authenticate("nacos", "test");
assertEquals(user.getUsername(), authenticate.getUserName());
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.plugin.auth.impl.controller;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.plugin.auth.impl.persistence.PermissionInfo;
import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class PermissionControllerTest {
@InjectMocks
private PermissionController permissionController;
@Mock
private NacosRoleServiceImpl nacosRoleService;
@BeforeEach
void setUp() throws Exception {
}
@Test
void testGetPermissions() {
Page<PermissionInfo> permissionInfoPage = new Page<PermissionInfo>();
when(nacosRoleService.getPermissionsFromDatabase(anyString(), anyInt(), anyInt())).thenReturn(
permissionInfoPage);
Object permissions = permissionController.getPermissions(1, 10, "admin");
assertEquals(permissionInfoPage, permissions);
}
@Test
void testFuzzySearchPermission() {
Page<PermissionInfo> permissionInfoPage = new Page<PermissionInfo>();
when(nacosRoleService.findPermissionsLike4Page(anyString(), anyInt(), anyInt())).thenReturn(permissionInfoPage);
Page<PermissionInfo> permissions = permissionController.fuzzySearchPermission(1, 10, "admin");
assertEquals(permissionInfoPage, permissions);
}
@Test
void testAddPermission() {
RestResult<String> result = (RestResult<String>) permissionController.addPermission("admin", "test", "test");
verify(nacosRoleService, times(1)).addPermission(anyString(), anyString(), anyString());
assertEquals(200, result.getCode());
}
@Test
void testDeletePermission() {
RestResult<String> result = (RestResult<String>) permissionController.deletePermission("admin", "test", "test");
verify(nacosRoleService, times(1)).deletePermission(anyString(), anyString(), anyString());
assertEquals(200, result.getCode());
}
}

View File

@ -0,0 +1,114 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.plugin.auth.impl.controller;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo;
import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class RoleControllerTest {
@Mock
private NacosRoleServiceImpl roleService;
@InjectMocks
private RoleController roleController;
@BeforeEach
void setUp() throws Exception {
}
@Test
void testGetRoles() {
Page<RoleInfo> rolesTest = new Page<RoleInfo>();
when(roleService.getRolesFromDatabase(anyString(), anyString(), anyInt(), anyInt())).thenReturn(rolesTest);
Object roles = roleController.getRoles(1, 10, "nacos", "test");
assertEquals(rolesTest, roles);
}
@Test
void testFuzzySearchRole() {
Page<RoleInfo> rolesTest = new Page<RoleInfo>();
when(roleService.findRolesLike4Page(anyString(), anyString(), anyInt(), anyInt())).thenReturn(rolesTest);
Page<RoleInfo> roleInfoPage = roleController.fuzzySearchRole(1, 10, "nacos", "test");
assertEquals(rolesTest, roleInfoPage);
}
@Test
void testSearchRoles() {
List<String> test = new ArrayList<>();
when(roleService.findRolesLikeRoleName(anyString())).thenReturn(test);
List<String> list = roleController.searchRoles("test");
assertEquals(test, list);
}
@Test
void testAddRole() {
RestResult<String> result = (RestResult<String>) roleController.addRole("test", "nacos");
verify(roleService, times(1)).addRole(anyString(), anyString());
assertEquals(200, result.getCode());
}
@Test
void testDeleteRole1() {
RestResult<String> result = (RestResult<String>) roleController.deleteRole("test", null);
verify(roleService, times(1)).deleteRole(anyString());
assertEquals(200, result.getCode());
}
@Test
void testDeleteRole2() {
RestResult<String> result = (RestResult<String>) roleController.deleteRole("test", "nacos");
verify(roleService, times(1)).deleteRole(anyString(), anyString());
assertEquals(200, result.getCode());
}
}

View File

@ -17,29 +17,47 @@
package com.alibaba.nacos.plugin.auth.impl.controller;
import com.alibaba.nacos.auth.config.AuthConfigs;
import com.alibaba.nacos.common.model.RestResult;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.plugin.auth.api.IdentityContext;
import com.alibaba.nacos.plugin.auth.exception.AccessException;
import com.alibaba.nacos.plugin.auth.impl.authenticate.IAuthenticationManager;
import com.alibaba.nacos.plugin.auth.impl.constant.AuthConstants;
import com.alibaba.nacos.plugin.auth.impl.constant.AuthSystemTypes;
import com.alibaba.nacos.plugin.auth.impl.persistence.RoleInfo;
import com.alibaba.nacos.plugin.auth.impl.persistence.User;
import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl;
import com.alibaba.nacos.plugin.auth.impl.token.TokenManagerDelegate;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl;
import com.alibaba.nacos.sys.env.EnvUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@ -61,27 +79,32 @@ class UserControllerTest {
@Mock
private TokenManagerDelegate tokenManagerDelegate;
@Mock
private NacosUserDetailsServiceImpl userDetailsService;
@Mock
private NacosRoleServiceImpl roleService;
@InjectMocks
private UserController userController;
private NacosUser user;
@BeforeEach
void setUp() throws Exception {
userController = new UserController();
user = new NacosUser();
user.setUserName("nacos");
user.setGlobalAdmin(true);
user.setToken("1234567890");
injectObject("authConfigs", authConfigs);
injectObject("iAuthenticationManager", authenticationManager);
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder()
.encodeToString("SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes(StandardCharsets.UTF_8)));
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder().encodeToString(
"SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes(
StandardCharsets.UTF_8)));
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS,
AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
EnvUtil.setEnvironment(mockEnvironment);
injectObject("jwtTokenManager", tokenManagerDelegate);
}
@Test
@ -98,9 +121,224 @@ class UserControllerTest {
assertTrue(actualString.contains("\"globalAdmin\":true"));
}
private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
Field field = UserController.class.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(userController, value);
@Test
void testCreateUser1() {
when(userDetailsService.getUserFromDatabase("nacos")).thenReturn(null);
RestResult<String> result = (RestResult<String>) userController.createUser("nacos", "test");
assertEquals(200, result.getCode());
}
@Test
void testCreateUser2() {
when(userDetailsService.getUserFromDatabase("nacos")).thenReturn(new User());
assertThrows(IllegalArgumentException.class, () -> {
userController.createUser("nacos", "test");
});
}
@Test
void testCreateAdminUser1() {
when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name());
when(authenticationManager.hasGlobalAdminRole()).thenReturn(true);
RestResult<String> result = (RestResult<String>) userController.createAdminUser("test");
assertEquals(HttpStatus.CONFLICT.value(), result.getCode());
}
@Test
void testCreateAdminUser2() {
RestResult<String> result = (RestResult<String>) userController.createAdminUser("test");
assertEquals(HttpStatus.NOT_IMPLEMENTED.value(), result.getCode());
}
@Test
void testCreateAdminUser3() {
when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name());
when(authenticationManager.hasGlobalAdminRole()).thenReturn(false);
ObjectNode result = (ObjectNode) userController.createAdminUser("test");
assertEquals("test", result.get(AuthConstants.PARAM_PASSWORD).asText());
}
@Test
void testDeleteUser1() {
List<RoleInfo> roleInfoList = new ArrayList<>(1);
RoleInfo testRole = new RoleInfo();
testRole.setUsername("nacos");
testRole.setRole(AuthConstants.GLOBAL_ADMIN_ROLE);
roleInfoList.add(testRole);
when(roleService.getRoles(anyString())).thenReturn(roleInfoList);
assertThrows(IllegalArgumentException.class, () -> {
userController.deleteUser("nacos");
});
}
@Test
void testDeleteUser2() {
List<RoleInfo> roleInfoList = new ArrayList<>(1);
RoleInfo testRole = new RoleInfo();
testRole.setUsername("nacos");
testRole.setRole("testRole");
roleInfoList.add(testRole);
when(roleService.getRoles(anyString())).thenReturn(roleInfoList);
RestResult<String> result = (RestResult<String>) userController.deleteUser("nacos");
assertEquals(200, result.getCode());
}
@Test
void testUpdateUser1() throws IOException {
when(authConfigs.isAuthEnabled()).thenReturn(false);
when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(new User());
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
RestResult<String> result = (RestResult<String>) userController.updateUser("nacos", "test",
mockHttpServletResponse, mockHttpServletRequest);
assertEquals(200, result.getCode());
}
@Test
void testUpdateUser2() {
when(authConfigs.isAuthEnabled()).thenReturn(false);
when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(null);
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
assertThrows(IllegalArgumentException.class, () -> {
userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest);
});
}
@Test
void testUpdateUser3() throws IOException {
when(authConfigs.isAuthEnabled()).thenReturn(true);
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
Object result = userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest);
assertNull(result);
assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus());
}
@Test
void testUpdateUser4() throws IOException {
when(authConfigs.isAuthEnabled()).thenReturn(true);
when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(new User());
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
IdentityContext identityContext = new IdentityContext();
identityContext.setParameter(AuthConstants.NACOS_USER_KEY, user);
mockHttpServletRequest.getSession()
.setAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_CONTEXT,
identityContext);
MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
RestResult<String> result = (RestResult<String>) userController.updateUser("nacos", "test",
mockHttpServletResponse, mockHttpServletRequest);
assertEquals(200, result.getCode());
}
@Test
void testUpdateUser5() throws IOException, AccessException {
when(authConfigs.isAuthEnabled()).thenReturn(true);
when(userDetailsService.getUserFromDatabase(anyString())).thenReturn(new User());
when(authenticationManager.authenticate(any(MockHttpServletRequest.class))).thenReturn(user);
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
IdentityContext identityContext = new IdentityContext();
identityContext.setParameter(AuthConstants.NACOS_USER_KEY, null);
mockHttpServletRequest.getSession()
.setAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_CONTEXT,
identityContext);
MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
RestResult<String> result = (RestResult<String>) userController.updateUser("nacos", "test",
mockHttpServletResponse, mockHttpServletRequest);
assertEquals(200, result.getCode());
}
@Test
void testUpdateUser6() throws IOException, AccessException {
when(authConfigs.isAuthEnabled()).thenReturn(true);
when(authenticationManager.authenticate(any(MockHttpServletRequest.class))).thenReturn(null);
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
IdentityContext identityContext = new IdentityContext();
identityContext.setParameter(AuthConstants.NACOS_USER_KEY, null);
mockHttpServletRequest.getSession()
.setAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_CONTEXT,
identityContext);
MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
Object result = userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest);
assertNull(result);
assertEquals(HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus());
}
@Test
void testUpdateUser7() throws IOException, AccessException {
when(authConfigs.isAuthEnabled()).thenReturn(true);
when(authenticationManager.authenticate(any(MockHttpServletRequest.class))).thenThrow(
new AccessException("test"));
MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
IdentityContext identityContext = new IdentityContext();
identityContext.setParameter(AuthConstants.NACOS_USER_KEY, null);
mockHttpServletRequest.getSession()
.setAttribute(com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_CONTEXT,
identityContext);
MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
Object result = userController.updateUser("nacos", "test", mockHttpServletResponse, mockHttpServletRequest);
assertNull(result);
assertEquals(HttpServletResponse.SC_FORBIDDEN, mockHttpServletResponse.getStatus());
}
@Test
void testGetUsers() {
Page<User> userPage = new Page<>();
when(userDetailsService.getUsersFromDatabase(anyInt(), anyInt(), anyString())).thenReturn(userPage);
Page<User> nacos = userController.getUsers(1, 10, "nacos");
assertEquals(userPage, nacos);
}
@Test
void testFuzzySearchUser() {
Page<User> userPage = new Page<>();
when(userDetailsService.findUsersLike4Page(anyString(), anyInt(), anyInt())).thenReturn(userPage);
Page<User> nacos = userController.fuzzySearchUser(1, 10, "nacos");
assertEquals(userPage, nacos);
}
@Test
void testSearchUsersLikeUsername() {
List<String> test = new ArrayList<>(1);
when(userDetailsService.findUserLikeUsername(anyString())).thenReturn(test);
List<String> list = userController.searchUsersLikeUsername("nacos");
assertEquals(test, list);
}
}