upgrade module naocs-plugin-impl from junit4 to junit5 (#12230)
This commit is contained in:
parent
833e6ca59a
commit
ab6591ac83
@ -23,13 +23,14 @@ import com.alibaba.nacos.plugin.auth.impl.roles.NacosRoleServiceImpl;
|
|||||||
import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetails;
|
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.users.NacosUserDetailsServiceImpl;
|
||||||
import org.apache.commons.lang.StringUtils;
|
import org.apache.commons.lang.StringUtils;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.invocation.InvocationOnMock;
|
import org.mockito.invocation.InvocationOnMock;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.mockito.junit.jupiter.MockitoSettings;
|
||||||
|
import org.mockito.quality.Strictness;
|
||||||
import org.mockito.stubbing.Answer;
|
import org.mockito.stubbing.Answer;
|
||||||
import org.springframework.ldap.core.LdapTemplate;
|
import org.springframework.ldap.core.LdapTemplate;
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
@ -40,10 +41,30 @@ import java.lang.reflect.Method;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class LdapAuthenticationProviderTest {
|
// todo remove this
|
||||||
|
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||||
|
class LdapAuthenticationProviderTest {
|
||||||
|
|
||||||
|
private static final String LDAP_PREFIX = "LDAP_";
|
||||||
|
|
||||||
|
private final String adminUserName = "nacos";
|
||||||
|
|
||||||
|
private final String normalUserName = "normal";
|
||||||
|
|
||||||
|
private final String filterPrefix = "uid";
|
||||||
|
|
||||||
|
private final boolean caseSensitive = true;
|
||||||
|
|
||||||
|
Method isAdmin;
|
||||||
|
|
||||||
|
Method ldapLogin;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private NacosUserDetailsServiceImpl userDetailsService;
|
private NacosUserDetailsServiceImpl userDetailsService;
|
||||||
@ -60,32 +81,18 @@ public class LdapAuthenticationProviderTest {
|
|||||||
|
|
||||||
private List<RoleInfo> roleInfos = new ArrayList<>();
|
private List<RoleInfo> roleInfos = new ArrayList<>();
|
||||||
|
|
||||||
private final String adminUserName = "nacos";
|
|
||||||
|
|
||||||
private final String normalUserName = "normal";
|
|
||||||
|
|
||||||
private final String filterPrefix = "uid";
|
|
||||||
|
|
||||||
private final boolean caseSensitive = true;
|
|
||||||
|
|
||||||
private static final String LDAP_PREFIX = "LDAP_";
|
|
||||||
|
|
||||||
Method isAdmin;
|
|
||||||
|
|
||||||
Method ldapLogin;
|
|
||||||
|
|
||||||
private String defaultPassWord = "nacos";
|
private String defaultPassWord = "nacos";
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() throws NoSuchMethodException {
|
void setUp() throws NoSuchMethodException {
|
||||||
RoleInfo adminRole = new RoleInfo();
|
RoleInfo adminRole = new RoleInfo();
|
||||||
adminRole.setRole(AuthConstants.GLOBAL_ADMIN_ROLE);
|
adminRole.setRole(AuthConstants.GLOBAL_ADMIN_ROLE);
|
||||||
adminRole.setUsername(adminUserName);
|
adminRole.setUsername(adminUserName);
|
||||||
roleInfos.add(adminRole);
|
roleInfos.add(adminRole);
|
||||||
when(nacosRoleService.getRoles(adminUserName)).thenReturn(roleInfos);
|
when(nacosRoleService.getRoles(adminUserName)).thenReturn(roleInfos);
|
||||||
when(nacosRoleService.getRoles(normalUserName)).thenReturn(new ArrayList<>());
|
when(nacosRoleService.getRoles(normalUserName)).thenReturn(new ArrayList<>());
|
||||||
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + adminUserName + ")", defaultPassWord))
|
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + adminUserName + ")", defaultPassWord)).thenAnswer(
|
||||||
.thenAnswer(new Answer<Boolean>() {
|
new Answer<Boolean>() {
|
||||||
@Override
|
@Override
|
||||||
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
||||||
Object[] args = invocation.getArguments();
|
Object[] args = invocation.getArguments();
|
||||||
@ -97,10 +104,10 @@ public class LdapAuthenticationProviderTest {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
this.ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapTemplate, userDetailsService,
|
this.ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapTemplate, userDetailsService, nacosRoleService, filterPrefix,
|
||||||
nacosRoleService, filterPrefix, caseSensitive);
|
caseSensitive);
|
||||||
this.ldapAuthenticationProviderForCloseCaseSensitive = new LdapAuthenticationProvider(ldapTemplate,
|
this.ldapAuthenticationProviderForCloseCaseSensitive = new LdapAuthenticationProvider(ldapTemplate, userDetailsService,
|
||||||
userDetailsService, nacosRoleService, filterPrefix, !caseSensitive);
|
nacosRoleService, filterPrefix, !caseSensitive);
|
||||||
isAdmin = LdapAuthenticationProvider.class.getDeclaredMethod("isAdmin", String.class);
|
isAdmin = LdapAuthenticationProvider.class.getDeclaredMethod("isAdmin", String.class);
|
||||||
isAdmin.setAccessible(true);
|
isAdmin.setAccessible(true);
|
||||||
ldapLogin = LdapAuthenticationProvider.class.getDeclaredMethod("ldapLogin", String.class, String.class);
|
ldapLogin = LdapAuthenticationProvider.class.getDeclaredMethod("ldapLogin", String.class, String.class);
|
||||||
@ -108,77 +115,75 @@ public class LdapAuthenticationProviderTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testIsAdmin() {
|
void testIsAdmin() {
|
||||||
try {
|
try {
|
||||||
Boolean result = (Boolean) isAdmin.invoke(ldapAuthenticationProvider, adminUserName);
|
Boolean result = (Boolean) isAdmin.invoke(ldapAuthenticationProvider, adminUserName);
|
||||||
Assert.assertTrue(result);
|
assertTrue(result);
|
||||||
} catch (IllegalAccessException e) {
|
} catch (IllegalAccessException e) {
|
||||||
Assert.fail();
|
fail();
|
||||||
} catch (InvocationTargetException e) {
|
} catch (InvocationTargetException e) {
|
||||||
Assert.fail();
|
fail();
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Boolean result = (Boolean) isAdmin.invoke(ldapAuthenticationProvider, normalUserName);
|
Boolean result = (Boolean) isAdmin.invoke(ldapAuthenticationProvider, normalUserName);
|
||||||
Assert.assertTrue(!result);
|
assertFalse(result);
|
||||||
} catch (IllegalAccessException e) {
|
} catch (IllegalAccessException e) {
|
||||||
Assert.fail();
|
fail();
|
||||||
} catch (InvocationTargetException e) {
|
} catch (InvocationTargetException e) {
|
||||||
Assert.fail();
|
fail();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testldapLogin() {
|
void testldapLogin() {
|
||||||
try {
|
try {
|
||||||
Boolean result = (Boolean) ldapLogin.invoke(ldapAuthenticationProvider, adminUserName, defaultPassWord);
|
Boolean result = (Boolean) ldapLogin.invoke(ldapAuthenticationProvider, adminUserName, defaultPassWord);
|
||||||
Assert.assertTrue(result);
|
assertTrue(result);
|
||||||
} catch (IllegalAccessException e) {
|
} catch (IllegalAccessException e) {
|
||||||
Assert.fail();
|
fail();
|
||||||
} catch (InvocationTargetException e) {
|
} catch (InvocationTargetException e) {
|
||||||
Assert.fail();
|
fail();
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Boolean result = (Boolean) ldapLogin.invoke(ldapAuthenticationProvider, adminUserName, "123");
|
Boolean result = (Boolean) ldapLogin.invoke(ldapAuthenticationProvider, adminUserName, "123");
|
||||||
Assert.assertTrue(!result);
|
assertFalse(result);
|
||||||
} catch (IllegalAccessException e) {
|
} catch (IllegalAccessException e) {
|
||||||
Assert.fail();
|
fail();
|
||||||
} catch (InvocationTargetException e) {
|
} catch (InvocationTargetException e) {
|
||||||
Assert.fail();
|
fail();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDefaultCaseSensitive() {
|
void testDefaultCaseSensitive() {
|
||||||
String userName = StringUtils.upperCase(normalUserName);
|
String userName = StringUtils.upperCase(normalUserName);
|
||||||
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + userName + ")", defaultPassWord))
|
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + userName + ")", defaultPassWord)).thenAnswer(new Answer<Boolean>() {
|
||||||
.thenAnswer(new Answer<Boolean>() {
|
@Override
|
||||||
@Override
|
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
||||||
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
Object[] args = invocation.getArguments();
|
||||||
Object[] args = invocation.getArguments();
|
String b = (String) args[1];
|
||||||
String b = (String) args[1];
|
String c = (String) args[2];
|
||||||
String c = (String) args[2];
|
if (defaultPassWord.equals(c)) {
|
||||||
if (defaultPassWord.equals(c)) {
|
return true;
|
||||||
return true;
|
}
|
||||||
}
|
return false;
|
||||||
return false;
|
}
|
||||||
}
|
});
|
||||||
});
|
|
||||||
User userUpperCase = new User();
|
User userUpperCase = new User();
|
||||||
userUpperCase.setUsername(LDAP_PREFIX + userName);
|
userUpperCase.setUsername(LDAP_PREFIX + userName);
|
||||||
userUpperCase.setPassword(defaultPassWord);
|
userUpperCase.setPassword(defaultPassWord);
|
||||||
when(userDetailsService.loadUserByUsername(LDAP_PREFIX + userName))
|
when(userDetailsService.loadUserByUsername(LDAP_PREFIX + userName)).thenReturn(new NacosUserDetails(userUpperCase));
|
||||||
.thenReturn(new NacosUserDetails(userUpperCase));
|
|
||||||
Authentication authentication = new UsernamePasswordAuthenticationToken(userName, defaultPassWord);
|
Authentication authentication = new UsernamePasswordAuthenticationToken(userName, defaultPassWord);
|
||||||
Authentication result = ldapAuthenticationProvider.authenticate(authentication);
|
Authentication result = ldapAuthenticationProvider.authenticate(authentication);
|
||||||
NacosUserDetails nacosUserDetails = (NacosUserDetails) result.getPrincipal();
|
NacosUserDetails nacosUserDetails = (NacosUserDetails) result.getPrincipal();
|
||||||
Assert.assertTrue(nacosUserDetails.getUsername().equals(LDAP_PREFIX + userName));
|
assertEquals(nacosUserDetails.getUsername(), LDAP_PREFIX + userName);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCloseCaseSensitive() {
|
void testCloseCaseSensitive() {
|
||||||
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + normalUserName + ")", defaultPassWord))
|
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + normalUserName + ")", defaultPassWord)).thenAnswer(
|
||||||
.thenAnswer(new Answer<Boolean>() {
|
new Answer<Boolean>() {
|
||||||
@Override
|
@Override
|
||||||
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
||||||
Object[] args = invocation.getArguments();
|
Object[] args = invocation.getArguments();
|
||||||
@ -193,12 +198,10 @@ public class LdapAuthenticationProviderTest {
|
|||||||
User user = new User();
|
User user = new User();
|
||||||
user.setUsername(LDAP_PREFIX + normalUserName);
|
user.setUsername(LDAP_PREFIX + normalUserName);
|
||||||
user.setPassword(defaultPassWord);
|
user.setPassword(defaultPassWord);
|
||||||
when(userDetailsService.loadUserByUsername(LDAP_PREFIX + normalUserName))
|
when(userDetailsService.loadUserByUsername(LDAP_PREFIX + normalUserName)).thenReturn(new NacosUserDetails(user));
|
||||||
.thenReturn(new NacosUserDetails(user));
|
Authentication authentication = new UsernamePasswordAuthenticationToken(StringUtils.upperCase(normalUserName), defaultPassWord);
|
||||||
Authentication authentication = new UsernamePasswordAuthenticationToken(StringUtils.upperCase(normalUserName),
|
|
||||||
defaultPassWord);
|
|
||||||
Authentication result = ldapAuthenticationProviderForCloseCaseSensitive.authenticate(authentication);
|
Authentication result = ldapAuthenticationProviderForCloseCaseSensitive.authenticate(authentication);
|
||||||
NacosUserDetails nacosUserDetails = (NacosUserDetails) result.getPrincipal();
|
NacosUserDetails nacosUserDetails = (NacosUserDetails) result.getPrincipal();
|
||||||
Assert.assertTrue(nacosUserDetails.getUsername().equals(LDAP_PREFIX + normalUserName));
|
assertEquals(nacosUserDetails.getUsername(), LDAP_PREFIX + normalUserName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -17,24 +17,29 @@
|
|||||||
package com.alibaba.nacos.plugin.auth.impl.configuration;
|
package com.alibaba.nacos.plugin.auth.impl.configuration;
|
||||||
|
|
||||||
import com.alibaba.nacos.sys.env.EnvUtil;
|
import com.alibaba.nacos.sys.env.EnvUtil;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
import org.springframework.context.annotation.ConditionContext;
|
import org.springframework.context.annotation.ConditionContext;
|
||||||
import org.springframework.core.env.ConfigurableEnvironment;
|
import org.springframework.core.env.ConfigurableEnvironment;
|
||||||
import org.springframework.core.type.AnnotatedTypeMetadata;
|
import org.springframework.core.type.AnnotatedTypeMetadata;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ConditionOnLdapAuth test.
|
* ConditionOnLdapAuth test.
|
||||||
|
*
|
||||||
* @ClassName: ConditionOnLdapAuthTest
|
* @ClassName: ConditionOnLdapAuthTest
|
||||||
* @Author: ChenHao26
|
* @Author: ChenHao26
|
||||||
* @Date: 2022/8/16 17:03
|
* @Date: 2022/8/16 17:03
|
||||||
*/
|
*/
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class ConditionOnLdapAuthTest {
|
class ConditionOnLdapAuthTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private static ConfigurableEnvironment environment;
|
||||||
|
|
||||||
private ConditionOnLdapAuth conditionOnLdapAuth;
|
private ConditionOnLdapAuth conditionOnLdapAuth;
|
||||||
|
|
||||||
@ -44,18 +49,15 @@ public class ConditionOnLdapAuthTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private AnnotatedTypeMetadata annotatedTypeMetadata;
|
private AnnotatedTypeMetadata annotatedTypeMetadata;
|
||||||
|
|
||||||
@Mock
|
@BeforeEach
|
||||||
private static ConfigurableEnvironment environment;
|
void setup() {
|
||||||
|
|
||||||
@Before
|
|
||||||
public void setup() {
|
|
||||||
conditionOnLdapAuth = new ConditionOnLdapAuth();
|
conditionOnLdapAuth = new ConditionOnLdapAuth();
|
||||||
EnvUtil.setEnvironment(environment);
|
EnvUtil.setEnvironment(environment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void matches() {
|
void matches() {
|
||||||
boolean matches = conditionOnLdapAuth.matches(conditionContext, annotatedTypeMetadata);
|
boolean matches = conditionOnLdapAuth.matches(conditionContext, annotatedTypeMetadata);
|
||||||
Assert.assertFalse(matches);
|
assertFalse(matches);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -25,11 +25,11 @@ 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.NacosUser;
|
||||||
import com.alibaba.nacos.sys.env.EnvUtil;
|
import com.alibaba.nacos.sys.env.EnvUtil;
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
import org.springframework.mock.env.MockEnvironment;
|
import org.springframework.mock.env.MockEnvironment;
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
@ -39,12 +39,12 @@ import java.lang.reflect.Field;
|
|||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class UserControllerTest {
|
class UserControllerTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private HttpServletRequest request;
|
private HttpServletRequest request;
|
||||||
@ -65,8 +65,8 @@ public class UserControllerTest {
|
|||||||
|
|
||||||
private NacosUser user;
|
private NacosUser user;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() throws Exception {
|
void setUp() throws Exception {
|
||||||
userController = new UserController();
|
userController = new UserController();
|
||||||
user = new NacosUser();
|
user = new NacosUser();
|
||||||
user.setUserName("nacos");
|
user.setUserName("nacos");
|
||||||
@ -76,18 +76,16 @@ public class UserControllerTest {
|
|||||||
injectObject("iAuthenticationManager", authenticationManager);
|
injectObject("iAuthenticationManager", authenticationManager);
|
||||||
|
|
||||||
MockEnvironment mockEnvironment = new MockEnvironment();
|
MockEnvironment mockEnvironment = new MockEnvironment();
|
||||||
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder().encodeToString(
|
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder()
|
||||||
"SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes(
|
.encodeToString("SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes(StandardCharsets.UTF_8)));
|
||||||
StandardCharsets.UTF_8)));
|
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
||||||
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS,
|
|
||||||
AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
|
||||||
|
|
||||||
EnvUtil.setEnvironment(mockEnvironment);
|
EnvUtil.setEnvironment(mockEnvironment);
|
||||||
injectObject("jwtTokenManager", tokenManagerDelegate);
|
injectObject("jwtTokenManager", tokenManagerDelegate);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testLoginWithAuthedUser() throws AccessException, IOException {
|
void testLoginWithAuthedUser() throws AccessException, IOException {
|
||||||
when(authenticationManager.authenticate(request)).thenReturn(user);
|
when(authenticationManager.authenticate(request)).thenReturn(user);
|
||||||
when(authenticationManager.hasGlobalAdminRole(user)).thenReturn(true);
|
when(authenticationManager.hasGlobalAdminRole(user)).thenReturn(true);
|
||||||
when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name());
|
when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name());
|
||||||
|
@ -17,16 +17,16 @@
|
|||||||
package com.alibaba.nacos.plugin.auth.impl.jwt;
|
package com.alibaba.nacos.plugin.auth.impl.jwt;
|
||||||
|
|
||||||
import com.alibaba.nacos.plugin.auth.exception.AccessException;
|
import com.alibaba.nacos.plugin.auth.exception.AccessException;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.Assert.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* NacosJwtParserTest.
|
* NacosJwtParserTest.
|
||||||
@ -34,16 +34,16 @@ import static org.junit.Assert.assertTrue;
|
|||||||
* @author Weizhan▪Yun
|
* @author Weizhan▪Yun
|
||||||
* @date 2023/2/1 16:32
|
* @date 2023/2/1 16:32
|
||||||
*/
|
*/
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class NacosJwtParserTest {
|
class NacosJwtParserTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testParseWithOriginKey() {
|
void testParseWithOriginKey() {
|
||||||
new NacosJwtParser("SecretKey012345678901234567890123456789012345678901234567890123456789");
|
new NacosJwtParser("SecretKey012345678901234567890123456789012345678901234567890123456789");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testParseWith16Key() {
|
void testParseWith16Key() {
|
||||||
Exception e = null;
|
Exception e = null;
|
||||||
try {
|
try {
|
||||||
new NacosJwtParser("SecretKey0123456");
|
new NacosJwtParser("SecretKey0123456");
|
||||||
@ -57,7 +57,7 @@ public class NacosJwtParserTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testParseWith32Key() {
|
void testParseWith32Key() {
|
||||||
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey01234567890123456789012"));
|
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey01234567890123456789012"));
|
||||||
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
|
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
|
||||||
|
|
||||||
@ -65,7 +65,7 @@ public class NacosJwtParserTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testParseWith48Key() {
|
void testParseWith48Key() {
|
||||||
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567890120124568aa9012345"));
|
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567890120124568aa9012345"));
|
||||||
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
|
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
|
||||||
|
|
||||||
@ -73,18 +73,16 @@ public class NacosJwtParserTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testParseWith64Key() {
|
void testParseWith64Key() {
|
||||||
NacosJwtParser parser = new NacosJwtParser(
|
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567SecretKey0123456789012345678901289012"));
|
||||||
encode("SecretKey012345678901234567SecretKey0123456789012345678901289012"));
|
|
||||||
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
|
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
|
||||||
|
|
||||||
assertTrue(token.startsWith(NacosSignatureAlgorithm.HS512.getHeader()));
|
assertTrue(token.startsWith(NacosSignatureAlgorithm.HS512.getHeader()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetExpireTimeInSeconds() throws AccessException {
|
void testGetExpireTimeInSeconds() throws AccessException {
|
||||||
NacosJwtParser parser = new NacosJwtParser(
|
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567SecretKey0123456789012345678901289012"));
|
||||||
encode("SecretKey012345678901234567SecretKey0123456789012345678901289012"));
|
|
||||||
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
|
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
|
||||||
long expiredTimeSeconds = parser.getExpireTimeInSeconds(token);
|
long expiredTimeSeconds = parser.getExpireTimeInSeconds(token);
|
||||||
assertTrue(expiredTimeSeconds * 1000 - System.currentTimeMillis() > 0);
|
assertTrue(expiredTimeSeconds * 1000 - System.currentTimeMillis() > 0);
|
||||||
|
@ -20,31 +20,35 @@ import com.alibaba.nacos.persistence.model.Page;
|
|||||||
import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder;
|
import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder;
|
||||||
import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate;
|
import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate;
|
||||||
import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest;
|
import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.mockito.junit.jupiter.MockitoSettings;
|
||||||
|
import org.mockito.quality.Strictness;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class EmbeddedPermissionPersistServiceImplTest {
|
// todo remove this
|
||||||
|
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||||
|
class EmbeddedPermissionPersistServiceImplTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private DatabaseOperate databaseOperate;
|
private DatabaseOperate databaseOperate;
|
||||||
|
|
||||||
private EmbeddedPermissionPersistServiceImpl embeddedPermissionPersistService;
|
private EmbeddedPermissionPersistServiceImpl embeddedPermissionPersistService;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() throws Exception {
|
void setUp() throws Exception {
|
||||||
when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0);
|
when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0);
|
||||||
embeddedPermissionPersistService = new EmbeddedPermissionPersistServiceImpl();
|
embeddedPermissionPersistService = new EmbeddedPermissionPersistServiceImpl();
|
||||||
Class<EmbeddedPermissionPersistServiceImpl> embeddedPermissionPersistServiceClass = EmbeddedPermissionPersistServiceImpl.class;
|
Class<EmbeddedPermissionPersistServiceImpl> embeddedPermissionPersistServiceClass = EmbeddedPermissionPersistServiceImpl.class;
|
||||||
@ -54,15 +58,15 @@ public class EmbeddedPermissionPersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetPermissions() {
|
void testGetPermissions() {
|
||||||
String role = "role";
|
String role = "role";
|
||||||
Page<PermissionInfo> permissions = embeddedPermissionPersistService.getPermissions(role, 1, 10);
|
Page<PermissionInfo> permissions = embeddedPermissionPersistService.getPermissions(role, 1, 10);
|
||||||
|
|
||||||
Assert.assertNotNull(permissions);
|
assertNotNull(permissions);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddPermission() {
|
void testAddPermission() {
|
||||||
embeddedPermissionPersistService.addPermission("role", "resource", "action");
|
embeddedPermissionPersistService.addPermission("role", "resource", "action");
|
||||||
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
|
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
|
||||||
|
|
||||||
@ -70,7 +74,7 @@ public class EmbeddedPermissionPersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDeletePermission() {
|
void testDeletePermission() {
|
||||||
embeddedPermissionPersistService.deletePermission("role", "resource", "action");
|
embeddedPermissionPersistService.deletePermission("role", "resource", "action");
|
||||||
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
|
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
|
||||||
|
|
||||||
|
@ -20,30 +20,35 @@ import com.alibaba.nacos.persistence.model.Page;
|
|||||||
import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder;
|
import com.alibaba.nacos.persistence.repository.embedded.EmbeddedStorageContextHolder;
|
||||||
import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate;
|
import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate;
|
||||||
import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest;
|
import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.mockito.junit.jupiter.MockitoSettings;
|
||||||
|
import org.mockito.quality.Strictness;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class EmbeddedRolePersistServiceImplTest {
|
// todo remove this
|
||||||
|
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||||
|
class EmbeddedRolePersistServiceImplTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private DatabaseOperate databaseOperate;
|
private DatabaseOperate databaseOperate;
|
||||||
|
|
||||||
private EmbeddedRolePersistServiceImpl embeddedRolePersistService;
|
private EmbeddedRolePersistServiceImpl embeddedRolePersistService;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() throws Exception {
|
void setUp() throws Exception {
|
||||||
when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0);
|
when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0);
|
||||||
embeddedRolePersistService = new EmbeddedRolePersistServiceImpl();
|
embeddedRolePersistService = new EmbeddedRolePersistServiceImpl();
|
||||||
Class<EmbeddedRolePersistServiceImpl> embeddedRolePersistServiceClass = EmbeddedRolePersistServiceImpl.class;
|
Class<EmbeddedRolePersistServiceImpl> embeddedRolePersistServiceClass = EmbeddedRolePersistServiceImpl.class;
|
||||||
@ -53,41 +58,41 @@ public class EmbeddedRolePersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetRoles() {
|
void testGetRoles() {
|
||||||
Page<RoleInfo> roles = embeddedRolePersistService.getRoles(1, 10);
|
Page<RoleInfo> roles = embeddedRolePersistService.getRoles(1, 10);
|
||||||
Assert.assertNotNull(roles);
|
assertNotNull(roles);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetRolesByUserName() {
|
void testGetRolesByUserName() {
|
||||||
Page<RoleInfo> page = embeddedRolePersistService.getRolesByUserNameAndRoleName("userName", "roleName", 1, 10);
|
Page<RoleInfo> page = embeddedRolePersistService.getRolesByUserNameAndRoleName("userName", "roleName", 1, 10);
|
||||||
|
|
||||||
Assert.assertNotNull(page);
|
assertNotNull(page);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddRole() {
|
void testAddRole() {
|
||||||
embeddedRolePersistService.addRole("role", "userName");
|
embeddedRolePersistService.addRole("role", "userName");
|
||||||
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
|
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
|
||||||
|
|
||||||
Assert.assertEquals(currentSqlContext.size(), 0);
|
assertEquals(0, currentSqlContext.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDeleteRole() {
|
void testDeleteRole() {
|
||||||
embeddedRolePersistService.deleteRole("role");
|
embeddedRolePersistService.deleteRole("role");
|
||||||
embeddedRolePersistService.deleteRole("role", "userName");
|
embeddedRolePersistService.deleteRole("role", "userName");
|
||||||
|
|
||||||
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
|
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
|
||||||
|
|
||||||
Assert.assertEquals(currentSqlContext.size(), 0);
|
assertEquals(0, currentSqlContext.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testFindRolesLikeRoleName() {
|
void testFindRolesLikeRoleName() {
|
||||||
|
|
||||||
List<String> role = embeddedRolePersistService.findRolesLikeRoleName("role");
|
List<String> role = embeddedRolePersistService.findRolesLikeRoleName("role");
|
||||||
|
|
||||||
Assert.assertEquals(role.size(), 0);
|
assertEquals(0, role.size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,31 +18,37 @@ package com.alibaba.nacos.plugin.auth.impl.persistence;
|
|||||||
|
|
||||||
import com.alibaba.nacos.persistence.model.Page;
|
import com.alibaba.nacos.persistence.model.Page;
|
||||||
import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate;
|
import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.mockito.junit.jupiter.MockitoSettings;
|
||||||
|
import org.mockito.quality.Strictness;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class EmbeddedUserPersistServiceImplTest {
|
// todo remove this
|
||||||
|
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||||
|
class EmbeddedUserPersistServiceImplTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private DatabaseOperate databaseOperate;
|
private DatabaseOperate databaseOperate;
|
||||||
|
|
||||||
private EmbeddedUserPersistServiceImpl embeddedUserPersistService;
|
private EmbeddedUserPersistServiceImpl embeddedUserPersistService;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() throws Exception {
|
void setUp() throws Exception {
|
||||||
when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0);
|
when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0);
|
||||||
embeddedUserPersistService = new EmbeddedUserPersistServiceImpl();
|
embeddedUserPersistService = new EmbeddedUserPersistServiceImpl();
|
||||||
Class<EmbeddedUserPersistServiceImpl> embeddedUserPersistServiceClass = EmbeddedUserPersistServiceImpl.class;
|
Class<EmbeddedUserPersistServiceImpl> embeddedUserPersistServiceClass = EmbeddedUserPersistServiceImpl.class;
|
||||||
@ -53,43 +59,43 @@ public class EmbeddedUserPersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateUser() {
|
void testCreateUser() {
|
||||||
embeddedUserPersistService.createUser("username", "password");
|
embeddedUserPersistService.createUser("username", "password");
|
||||||
|
|
||||||
Mockito.verify(databaseOperate).blockUpdate();
|
Mockito.verify(databaseOperate).blockUpdate();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDeleteUser() {
|
void testDeleteUser() {
|
||||||
embeddedUserPersistService.deleteUser("username");
|
embeddedUserPersistService.deleteUser("username");
|
||||||
|
|
||||||
Mockito.verify(databaseOperate).blockUpdate();
|
Mockito.verify(databaseOperate).blockUpdate();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testUpdateUserPassword() {
|
void testUpdateUserPassword() {
|
||||||
embeddedUserPersistService.updateUserPassword("username", "password");
|
embeddedUserPersistService.updateUserPassword("username", "password");
|
||||||
|
|
||||||
Mockito.verify(databaseOperate).blockUpdate();
|
Mockito.verify(databaseOperate).blockUpdate();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testFindUserByUsername() {
|
void testFindUserByUsername() {
|
||||||
User user = embeddedUserPersistService.findUserByUsername("username");
|
User user = embeddedUserPersistService.findUserByUsername("username");
|
||||||
|
|
||||||
Assert.assertNull(user);
|
assertNull(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetUsers() {
|
void testGetUsers() {
|
||||||
Page<User> users = embeddedUserPersistService.getUsers(1, 10, "nacos");
|
Page<User> users = embeddedUserPersistService.getUsers(1, 10, "nacos");
|
||||||
|
|
||||||
Assert.assertNotNull(users);
|
assertNotNull(users);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testFindUserLikeUsername() {
|
void testFindUserLikeUsername() {
|
||||||
List<String> username = embeddedUserPersistService.findUserLikeUsername("username");
|
List<String> username = embeddedUserPersistService.findUserLikeUsername("username");
|
||||||
Assert.assertEquals(username.size(), 0);
|
assertEquals(0, username.size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,24 +20,28 @@ import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration;
|
|||||||
import com.alibaba.nacos.persistence.datasource.DataSourceService;
|
import com.alibaba.nacos.persistence.datasource.DataSourceService;
|
||||||
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
|
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
|
||||||
import com.alibaba.nacos.persistence.model.Page;
|
import com.alibaba.nacos.persistence.model.Page;
|
||||||
import org.junit.After;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.mockito.junit.jupiter.MockitoSettings;
|
||||||
|
import org.mockito.quality.Strictness;
|
||||||
import org.springframework.jdbc.core.JdbcTemplate;
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class ExternalPermissionPersistServiceImplTest {
|
// todo remove this
|
||||||
|
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||||
|
class ExternalPermissionPersistServiceImplTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private JdbcTemplate jdbcTemplate;
|
private JdbcTemplate jdbcTemplate;
|
||||||
@ -51,8 +55,8 @@ public class ExternalPermissionPersistServiceImplTest {
|
|||||||
|
|
||||||
private ExternalPermissionPersistServiceImpl externalPermissionPersistService;
|
private ExternalPermissionPersistServiceImpl externalPermissionPersistService;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() throws Exception {
|
void setUp() throws Exception {
|
||||||
externalPermissionPersistService = new ExternalPermissionPersistServiceImpl();
|
externalPermissionPersistService = new ExternalPermissionPersistServiceImpl();
|
||||||
when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0);
|
when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0);
|
||||||
when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate);
|
when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate);
|
||||||
@ -65,8 +69,8 @@ public class ExternalPermissionPersistServiceImplTest {
|
|||||||
externalPermissionPersistService.init();
|
externalPermissionPersistService.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@AfterEach
|
||||||
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
|
void tearDown() throws NoSuchFieldException, IllegalAccessException {
|
||||||
DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache);
|
DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache);
|
||||||
Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService");
|
Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService");
|
||||||
datasourceField.setAccessible(true);
|
datasourceField.setAccessible(true);
|
||||||
@ -74,13 +78,13 @@ public class ExternalPermissionPersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetPermissions() {
|
void testGetPermissions() {
|
||||||
Page<PermissionInfo> role = externalPermissionPersistService.getPermissions("role", 1, 10);
|
Page<PermissionInfo> role = externalPermissionPersistService.getPermissions("role", 1, 10);
|
||||||
Assert.assertNotNull(role);
|
assertNotNull(role);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddPermission() {
|
void testAddPermission() {
|
||||||
String sql = "INSERT INTO permissions (role, resource, action) VALUES (?, ?, ?)";
|
String sql = "INSERT INTO permissions (role, resource, action) VALUES (?, ?, ?)";
|
||||||
externalPermissionPersistService.addPermission("role", "resource", "action");
|
externalPermissionPersistService.addPermission("role", "resource", "action");
|
||||||
|
|
||||||
@ -88,7 +92,7 @@ public class ExternalPermissionPersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDeletePermission() {
|
void testDeletePermission() {
|
||||||
String sql = "DELETE FROM permissions WHERE role=? AND resource=? AND action=?";
|
String sql = "DELETE FROM permissions WHERE role=? AND resource=? AND action=?";
|
||||||
externalPermissionPersistService.deletePermission("role", "resource", "action");
|
externalPermissionPersistService.deletePermission("role", "resource", "action");
|
||||||
|
|
||||||
|
@ -20,25 +20,30 @@ import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration;
|
|||||||
import com.alibaba.nacos.persistence.datasource.DataSourceService;
|
import com.alibaba.nacos.persistence.datasource.DataSourceService;
|
||||||
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
|
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
|
||||||
import com.alibaba.nacos.persistence.model.Page;
|
import com.alibaba.nacos.persistence.model.Page;
|
||||||
import org.junit.After;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.mockito.junit.jupiter.MockitoSettings;
|
||||||
|
import org.mockito.quality.Strictness;
|
||||||
import org.springframework.jdbc.core.JdbcTemplate;
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class ExternalRolePersistServiceImplTest {
|
// todo remove this
|
||||||
|
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||||
|
class ExternalRolePersistServiceImplTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private JdbcTemplate jdbcTemplate;
|
private JdbcTemplate jdbcTemplate;
|
||||||
@ -52,8 +57,8 @@ public class ExternalRolePersistServiceImplTest {
|
|||||||
|
|
||||||
private ExternalRolePersistServiceImpl externalRolePersistService;
|
private ExternalRolePersistServiceImpl externalRolePersistService;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() throws Exception {
|
void setUp() throws Exception {
|
||||||
externalRolePersistService = new ExternalRolePersistServiceImpl();
|
externalRolePersistService = new ExternalRolePersistServiceImpl();
|
||||||
when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0);
|
when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0);
|
||||||
when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate);
|
when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate);
|
||||||
@ -66,8 +71,8 @@ public class ExternalRolePersistServiceImplTest {
|
|||||||
externalRolePersistService.init();
|
externalRolePersistService.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@AfterEach
|
||||||
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
|
void tearDown() throws NoSuchFieldException, IllegalAccessException {
|
||||||
DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache);
|
DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache);
|
||||||
Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService");
|
Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService");
|
||||||
datasourceField.setAccessible(true);
|
datasourceField.setAccessible(true);
|
||||||
@ -75,21 +80,20 @@ public class ExternalRolePersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetRoles() {
|
void testGetRoles() {
|
||||||
Page<RoleInfo> roles = externalRolePersistService.getRoles(1, 10);
|
Page<RoleInfo> roles = externalRolePersistService.getRoles(1, 10);
|
||||||
|
|
||||||
Assert.assertNotNull(roles);
|
assertNotNull(roles);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetRolesByUserName() {
|
void testGetRolesByUserName() {
|
||||||
Page<RoleInfo> userName = externalRolePersistService
|
Page<RoleInfo> userName = externalRolePersistService.getRolesByUserNameAndRoleName("userName", "roleName", 1, 10);
|
||||||
.getRolesByUserNameAndRoleName("userName", "roleName", 1, 10);
|
assertNotNull(userName);
|
||||||
Assert.assertNotNull(userName);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAddRole() {
|
void testAddRole() {
|
||||||
externalRolePersistService.addRole("role", "userName");
|
externalRolePersistService.addRole("role", "userName");
|
||||||
|
|
||||||
String sql = "INSERT INTO roles (role, username) VALUES (?, ?)";
|
String sql = "INSERT INTO roles (role, username) VALUES (?, ?)";
|
||||||
@ -97,7 +101,7 @@ public class ExternalRolePersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDeleteRole() {
|
void testDeleteRole() {
|
||||||
|
|
||||||
externalRolePersistService.deleteRole("role");
|
externalRolePersistService.deleteRole("role");
|
||||||
String sql = "DELETE FROM roles WHERE role=?";
|
String sql = "DELETE FROM roles WHERE role=?";
|
||||||
@ -110,9 +114,9 @@ public class ExternalRolePersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testFindRolesLikeRoleName() {
|
void testFindRolesLikeRoleName() {
|
||||||
List<String> role = externalRolePersistService.findRolesLikeRoleName("role");
|
List<String> role = externalRolePersistService.findRolesLikeRoleName("role");
|
||||||
|
|
||||||
Assert.assertEquals(role.size(), 0);
|
assertEquals(0, role.size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,25 +20,31 @@ import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration;
|
|||||||
import com.alibaba.nacos.persistence.datasource.DataSourceService;
|
import com.alibaba.nacos.persistence.datasource.DataSourceService;
|
||||||
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
|
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
|
||||||
import com.alibaba.nacos.persistence.model.Page;
|
import com.alibaba.nacos.persistence.model.Page;
|
||||||
import org.junit.After;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.mockito.junit.jupiter.MockitoSettings;
|
||||||
|
import org.mockito.quality.Strictness;
|
||||||
import org.springframework.jdbc.core.JdbcTemplate;
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class ExternalUserPersistServiceImplTest {
|
// todo remove this
|
||||||
|
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||||
|
class ExternalUserPersistServiceImplTest {
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private JdbcTemplate jdbcTemplate;
|
private JdbcTemplate jdbcTemplate;
|
||||||
@ -52,8 +58,8 @@ public class ExternalUserPersistServiceImplTest {
|
|||||||
|
|
||||||
private ExternalUserPersistServiceImpl externalUserPersistService;
|
private ExternalUserPersistServiceImpl externalUserPersistService;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() throws Exception {
|
void setUp() throws Exception {
|
||||||
externalUserPersistService = new ExternalUserPersistServiceImpl();
|
externalUserPersistService = new ExternalUserPersistServiceImpl();
|
||||||
when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0);
|
when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0);
|
||||||
when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate);
|
when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate);
|
||||||
@ -66,8 +72,8 @@ public class ExternalUserPersistServiceImplTest {
|
|||||||
externalUserPersistService.init();
|
externalUserPersistService.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@AfterEach
|
||||||
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
|
void tearDown() throws NoSuchFieldException, IllegalAccessException {
|
||||||
DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache);
|
DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache);
|
||||||
Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService");
|
Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService");
|
||||||
datasourceField.setAccessible(true);
|
datasourceField.setAccessible(true);
|
||||||
@ -75,7 +81,7 @@ public class ExternalUserPersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateUser() {
|
void testCreateUser() {
|
||||||
externalUserPersistService.createUser("username", "password");
|
externalUserPersistService.createUser("username", "password");
|
||||||
|
|
||||||
String sql = "INSERT INTO users (username, password, enabled) VALUES (?, ?, ?)";
|
String sql = "INSERT INTO users (username, password, enabled) VALUES (?, ?, ?)";
|
||||||
@ -83,7 +89,7 @@ public class ExternalUserPersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testDeleteUser() {
|
void testDeleteUser() {
|
||||||
externalUserPersistService.deleteUser("username");
|
externalUserPersistService.deleteUser("username");
|
||||||
|
|
||||||
String sql = "DELETE FROM users WHERE username=?";
|
String sql = "DELETE FROM users WHERE username=?";
|
||||||
@ -91,7 +97,7 @@ public class ExternalUserPersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testUpdateUserPassword() {
|
void testUpdateUserPassword() {
|
||||||
externalUserPersistService.updateUserPassword("username", "password");
|
externalUserPersistService.updateUserPassword("username", "password");
|
||||||
|
|
||||||
String sql = "UPDATE users SET password = ? WHERE username=?";
|
String sql = "UPDATE users SET password = ? WHERE username=?";
|
||||||
@ -99,23 +105,23 @@ public class ExternalUserPersistServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testFindUserByUsername() {
|
void testFindUserByUsername() {
|
||||||
User username = externalUserPersistService.findUserByUsername("username");
|
User username = externalUserPersistService.findUserByUsername("username");
|
||||||
|
|
||||||
Assert.assertNull(username);
|
assertNull(username);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetUsers() {
|
void testGetUsers() {
|
||||||
Page<User> users = externalUserPersistService.getUsers(1, 10, "nacos");
|
Page<User> users = externalUserPersistService.getUsers(1, 10, "nacos");
|
||||||
|
|
||||||
Assert.assertNotNull(users);
|
assertNotNull(users);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testFindUserLikeUsername() {
|
void testFindUserLikeUsername() {
|
||||||
List<String> username = externalUserPersistService.findUserLikeUsername("username");
|
List<String> username = externalUserPersistService.findUserLikeUsername("username");
|
||||||
|
|
||||||
Assert.assertEquals(username.size(), 0);
|
assertEquals(0, username.size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -28,18 +28,23 @@ import com.alibaba.nacos.plugin.auth.impl.persistence.RolePersistService;
|
|||||||
import com.alibaba.nacos.plugin.auth.impl.persistence.User;
|
import com.alibaba.nacos.plugin.auth.impl.persistence.User;
|
||||||
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
|
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
|
||||||
import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl;
|
import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* NacosRoleServiceImpl Test.
|
* NacosRoleServiceImpl Test.
|
||||||
*
|
*
|
||||||
@ -48,8 +53,10 @@ import java.util.List;
|
|||||||
* @Date: 2022/8/16 17:31
|
* @Date: 2022/8/16 17:31
|
||||||
* @Description: TODO
|
* @Description: TODO
|
||||||
*/
|
*/
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class NacosRoleServiceImplTest {
|
class NacosRoleServiceImplTest {
|
||||||
|
|
||||||
|
Class<NacosRoleServiceImpl> nacosRoleServiceClass;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private AuthConfigs authConfigs;
|
private AuthConfigs authConfigs;
|
||||||
@ -66,10 +73,8 @@ public class NacosRoleServiceImplTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private NacosRoleServiceImpl nacosRoleService;
|
private NacosRoleServiceImpl nacosRoleService;
|
||||||
|
|
||||||
Class<NacosRoleServiceImpl> nacosRoleServiceClass;
|
@BeforeEach
|
||||||
|
void setup() throws Exception {
|
||||||
@Before
|
|
||||||
public void setup() throws Exception {
|
|
||||||
nacosRoleService = new NacosRoleServiceImpl();
|
nacosRoleService = new NacosRoleServiceImpl();
|
||||||
nacosRoleServiceClass = NacosRoleServiceImpl.class;
|
nacosRoleServiceClass = NacosRoleServiceImpl.class;
|
||||||
Field authConfigsFile = nacosRoleServiceClass.getDeclaredField("authConfigs");
|
Field authConfigsFile = nacosRoleServiceClass.getDeclaredField("authConfigs");
|
||||||
@ -90,107 +95,105 @@ public class NacosRoleServiceImplTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void reload() throws Exception {
|
void reload() throws Exception {
|
||||||
Method reload = nacosRoleServiceClass.getDeclaredMethod("reload");
|
Method reload = nacosRoleServiceClass.getDeclaredMethod("reload");
|
||||||
reload.setAccessible(true);
|
reload.setAccessible(true);
|
||||||
reload.invoke(nacosRoleService);
|
reload.invoke(nacosRoleService);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void hasPermission() {
|
void hasPermission() {
|
||||||
Permission permission = new Permission();
|
Permission permission = new Permission();
|
||||||
permission.setAction("rw");
|
permission.setAction("rw");
|
||||||
permission.setResource(Resource.EMPTY_RESOURCE);
|
permission.setResource(Resource.EMPTY_RESOURCE);
|
||||||
NacosUser nacosUser = new NacosUser();
|
NacosUser nacosUser = new NacosUser();
|
||||||
nacosUser.setUserName("nacos");
|
nacosUser.setUserName("nacos");
|
||||||
boolean res = nacosRoleService.hasPermission(nacosUser, permission);
|
boolean res = nacosRoleService.hasPermission(nacosUser, permission);
|
||||||
Assert.assertFalse(res);
|
assertFalse(res);
|
||||||
|
|
||||||
Permission permission2 = new Permission();
|
Permission permission2 = new Permission();
|
||||||
permission2.setAction("rw");
|
permission2.setAction("rw");
|
||||||
Resource resource = new Resource("public", "group", AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, "rw", null);
|
Resource resource = new Resource("public", "group", AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, "rw", null);
|
||||||
permission2.setResource(resource);
|
permission2.setResource(resource);
|
||||||
boolean res2 = nacosRoleService.hasPermission(nacosUser, permission2);
|
boolean res2 = nacosRoleService.hasPermission(nacosUser, permission2);
|
||||||
Assert.assertTrue(res2);
|
assertTrue(res2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getRoles() {
|
void getRoles() {
|
||||||
List<RoleInfo> nacos = nacosRoleService.getRoles("role-admin");
|
List<RoleInfo> nacos = nacosRoleService.getRoles("role-admin");
|
||||||
Assert.assertEquals(nacos, Collections.emptyList());
|
assertEquals(nacos, Collections.emptyList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getRolesFromDatabase() {
|
void getRolesFromDatabase() {
|
||||||
Page<RoleInfo> roleInfoPage = nacosRoleService.getRolesFromDatabase("nacos", "ROLE_ADMIN", 1,
|
Page<RoleInfo> roleInfoPage = nacosRoleService.getRolesFromDatabase("nacos", "ROLE_ADMIN", 1, Integer.MAX_VALUE);
|
||||||
Integer.MAX_VALUE);
|
assertEquals(0, roleInfoPage.getTotalCount());
|
||||||
Assert.assertEquals(roleInfoPage.getTotalCount(), 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getPermissions() {
|
void getPermissions() {
|
||||||
boolean cachingEnabled = authConfigs.isCachingEnabled();
|
boolean cachingEnabled = authConfigs.isCachingEnabled();
|
||||||
Assert.assertFalse(cachingEnabled);
|
assertFalse(cachingEnabled);
|
||||||
List<PermissionInfo> permissions = nacosRoleService.getPermissions("role-admin");
|
List<PermissionInfo> permissions = nacosRoleService.getPermissions("role-admin");
|
||||||
Assert.assertEquals(permissions, Collections.emptyList());
|
assertEquals(permissions, Collections.emptyList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getPermissionsByRoleFromDatabase() {
|
void getPermissionsByRoleFromDatabase() {
|
||||||
Page<PermissionInfo> permissionsByRoleFromDatabase = nacosRoleService.getPermissionsByRoleFromDatabase(
|
Page<PermissionInfo> permissionsByRoleFromDatabase = nacosRoleService.getPermissionsByRoleFromDatabase("role-admin", 1,
|
||||||
"role-admin", 1, Integer.MAX_VALUE);
|
Integer.MAX_VALUE);
|
||||||
Assert.assertNull(permissionsByRoleFromDatabase);
|
assertNull(permissionsByRoleFromDatabase);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void addRole() {
|
void addRole() {
|
||||||
String username = "nacos";
|
String username = "nacos";
|
||||||
User userFromDatabase = userDetailsService.getUserFromDatabase(username);
|
User userFromDatabase = userDetailsService.getUserFromDatabase(username);
|
||||||
Assert.assertNull(userFromDatabase);
|
assertNull(userFromDatabase);
|
||||||
try {
|
try {
|
||||||
nacosRoleService.addRole("role-admin", "nacos");
|
nacosRoleService.addRole("role-admin", "nacos");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Assert.assertTrue(e.getMessage().contains("user 'nacos' not found!"));
|
assertTrue(e.getMessage().contains("user 'nacos' not found!"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void deleteRole() {
|
void deleteRole() {
|
||||||
try {
|
try {
|
||||||
nacosRoleService.deleteRole("role-admin");
|
nacosRoleService.deleteRole("role-admin");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Assert.assertNull(e);
|
assertNull(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getPermissionsFromDatabase() {
|
void getPermissionsFromDatabase() {
|
||||||
Page<PermissionInfo> permissionsFromDatabase = nacosRoleService.getPermissionsFromDatabase("role-admin", 1,
|
Page<PermissionInfo> permissionsFromDatabase = nacosRoleService.getPermissionsFromDatabase("role-admin", 1, Integer.MAX_VALUE);
|
||||||
Integer.MAX_VALUE);
|
assertEquals(0, permissionsFromDatabase.getTotalCount());
|
||||||
Assert.assertEquals(permissionsFromDatabase.getTotalCount(), 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void addPermission() {
|
void addPermission() {
|
||||||
try {
|
try {
|
||||||
nacosRoleService.addPermission("role-admin", "", "rw");
|
nacosRoleService.addPermission("role-admin", "", "rw");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
Assert.assertTrue(e.getMessage().contains("role role-admin not found!"));
|
assertTrue(e.getMessage().contains("role role-admin not found!"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void findRolesLikeRoleName() {
|
void findRolesLikeRoleName() {
|
||||||
List<String> rolesLikeRoleName = rolePersistService.findRolesLikeRoleName("role-admin");
|
List<String> rolesLikeRoleName = rolePersistService.findRolesLikeRoleName("role-admin");
|
||||||
Assert.assertEquals(rolesLikeRoleName, Collections.emptyList());
|
assertEquals(rolesLikeRoleName, Collections.emptyList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void joinResource() throws Exception {
|
void joinResource() throws Exception {
|
||||||
Method method = nacosRoleServiceClass.getDeclaredMethod("joinResource", Resource.class);
|
Method method = nacosRoleServiceClass.getDeclaredMethod("joinResource", Resource.class);
|
||||||
method.setAccessible(true);
|
method.setAccessible(true);
|
||||||
Resource resource = new Resource("public", "group", AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, "rw", null);
|
Resource resource = new Resource("public", "group", AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, "rw", null);
|
||||||
Object invoke = method.invoke(nacosRoleService, new Resource[] {resource});
|
Object invoke = method.invoke(nacosRoleService, new Resource[] {resource});
|
||||||
Assert.assertNotNull(invoke);
|
assertNotNull(invoke);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,16 +20,20 @@ import com.alibaba.nacos.plugin.auth.exception.AccessException;
|
|||||||
import com.alibaba.nacos.plugin.auth.impl.token.impl.CachedJwtTokenManager;
|
import com.alibaba.nacos.plugin.auth.impl.token.impl.CachedJwtTokenManager;
|
||||||
import com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager;
|
import com.alibaba.nacos.plugin.auth.impl.token.impl.JwtTokenManager;
|
||||||
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
|
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.mockito.junit.jupiter.MockitoSettings;
|
||||||
|
import org.mockito.quality.Strictness;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@ -38,8 +42,10 @@ import static org.mockito.Mockito.when;
|
|||||||
*
|
*
|
||||||
* @author majorhe
|
* @author majorhe
|
||||||
*/
|
*/
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class TokenManagerDelegateTest {
|
// todo remove this
|
||||||
|
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||||
|
class TokenManagerDelegateTest {
|
||||||
|
|
||||||
private TokenManagerDelegate tokenManagerDelegate;
|
private TokenManagerDelegate tokenManagerDelegate;
|
||||||
|
|
||||||
@ -55,8 +61,8 @@ public class TokenManagerDelegateTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private NacosUser user;
|
private NacosUser user;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() throws Exception {
|
void setUp() throws Exception {
|
||||||
tokenManagerDelegate = new TokenManagerDelegate();
|
tokenManagerDelegate = new TokenManagerDelegate();
|
||||||
injectObject("jwtTokenManager", jwtTokenManager);
|
injectObject("jwtTokenManager", jwtTokenManager);
|
||||||
injectObject("cachedJwtTokenManager", cachedJwtTokenManager);
|
injectObject("cachedJwtTokenManager", cachedJwtTokenManager);
|
||||||
@ -70,38 +76,38 @@ public class TokenManagerDelegateTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateToken1() throws AccessException {
|
void testCreateToken1() throws AccessException {
|
||||||
Assert.assertEquals("token", tokenManagerDelegate.createToken(authentication));
|
assertEquals("token", tokenManagerDelegate.createToken(authentication));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateToken2() throws AccessException {
|
void testCreateToken2() throws AccessException {
|
||||||
Assert.assertEquals("token", tokenManagerDelegate.createToken("nacos"));
|
assertEquals("token", tokenManagerDelegate.createToken("nacos"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetAuthentication() throws AccessException {
|
void testGetAuthentication() throws AccessException {
|
||||||
Assert.assertNotNull(tokenManagerDelegate.getAuthentication("token"));
|
assertNotNull(tokenManagerDelegate.getAuthentication("token"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testValidateToken() throws AccessException {
|
void testValidateToken() throws AccessException {
|
||||||
tokenManagerDelegate.validateToken("token");
|
tokenManagerDelegate.validateToken("token");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testParseToken() throws AccessException {
|
void testParseToken() throws AccessException {
|
||||||
Assert.assertNotNull(tokenManagerDelegate.parseToken("token"));
|
assertNotNull(tokenManagerDelegate.parseToken("token"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetTokenTtlInSeconds() throws AccessException {
|
void testGetTokenTtlInSeconds() throws AccessException {
|
||||||
Assert.assertTrue(tokenManagerDelegate.getTokenTtlInSeconds("token") > 0);
|
assertTrue(tokenManagerDelegate.getTokenTtlInSeconds("token") > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetTokenValidityInSeconds() throws AccessException {
|
void testGetTokenValidityInSeconds() throws AccessException {
|
||||||
Assert.assertTrue(tokenManagerDelegate.getTokenValidityInSeconds() > 0);
|
assertTrue(tokenManagerDelegate.getTokenValidityInSeconds() > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
|
private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
@ -18,16 +18,20 @@ package com.alibaba.nacos.plugin.auth.impl.token.impl;
|
|||||||
|
|
||||||
import com.alibaba.nacos.plugin.auth.exception.AccessException;
|
import com.alibaba.nacos.plugin.auth.exception.AccessException;
|
||||||
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
|
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.mockito.junit.jupiter.MockitoSettings;
|
||||||
|
import org.mockito.quality.Strictness;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
|
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.anyString;
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@ -36,8 +40,10 @@ import static org.mockito.Mockito.when;
|
|||||||
*
|
*
|
||||||
* @author Majorhe
|
* @author Majorhe
|
||||||
*/
|
*/
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class CachedJwtTokenManagerTest {
|
// todo remove this
|
||||||
|
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||||
|
class CachedJwtTokenManagerTest {
|
||||||
|
|
||||||
private CachedJwtTokenManager cachedJwtTokenManager;
|
private CachedJwtTokenManager cachedJwtTokenManager;
|
||||||
|
|
||||||
@ -50,8 +56,8 @@ public class CachedJwtTokenManagerTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private NacosUser user;
|
private NacosUser user;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() throws Exception {
|
void setUp() throws Exception {
|
||||||
cachedJwtTokenManager = new CachedJwtTokenManager();
|
cachedJwtTokenManager = new CachedJwtTokenManager();
|
||||||
injectObject("jwtTokenManager", jwtTokenManager);
|
injectObject("jwtTokenManager", jwtTokenManager);
|
||||||
when(jwtTokenManager.getTokenValidityInSeconds()).thenReturn(100L);
|
when(jwtTokenManager.getTokenValidityInSeconds()).thenReturn(100L);
|
||||||
@ -64,38 +70,38 @@ public class CachedJwtTokenManagerTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateToken1() throws AccessException {
|
void testCreateToken1() throws AccessException {
|
||||||
Assert.assertEquals("token", cachedJwtTokenManager.createToken(authentication));
|
assertEquals("token", cachedJwtTokenManager.createToken(authentication));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateToken2() throws AccessException {
|
void testCreateToken2() throws AccessException {
|
||||||
Assert.assertEquals("token", cachedJwtTokenManager.createToken("nacos"));
|
assertEquals("token", cachedJwtTokenManager.createToken("nacos"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetAuthentication() throws AccessException {
|
void testGetAuthentication() throws AccessException {
|
||||||
Assert.assertNotNull(cachedJwtTokenManager.getAuthentication("token"));
|
assertNotNull(cachedJwtTokenManager.getAuthentication("token"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testValidateToken() throws AccessException {
|
void testValidateToken() throws AccessException {
|
||||||
cachedJwtTokenManager.validateToken("token");
|
cachedJwtTokenManager.validateToken("token");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testParseToken() throws AccessException {
|
void testParseToken() throws AccessException {
|
||||||
Assert.assertNotNull(cachedJwtTokenManager.parseToken("token"));
|
assertNotNull(cachedJwtTokenManager.parseToken("token"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetTokenTtlInSeconds() throws AccessException {
|
void testGetTokenTtlInSeconds() throws AccessException {
|
||||||
Assert.assertTrue(cachedJwtTokenManager.getTokenTtlInSeconds("token") > 0);
|
assertTrue(cachedJwtTokenManager.getTokenTtlInSeconds("token") > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetTokenValidityInSeconds() {
|
void testGetTokenValidityInSeconds() {
|
||||||
Assert.assertTrue(cachedJwtTokenManager.getTokenValidityInSeconds() > 0);
|
assertTrue(cachedJwtTokenManager.getTokenValidityInSeconds() > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
|
private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
@ -21,12 +21,11 @@ import com.alibaba.nacos.plugin.auth.exception.AccessException;
|
|||||||
import com.alibaba.nacos.plugin.auth.impl.constant.AuthConstants;
|
import com.alibaba.nacos.plugin.auth.impl.constant.AuthConstants;
|
||||||
import com.alibaba.nacos.plugin.auth.impl.jwt.NacosJwtParser;
|
import com.alibaba.nacos.plugin.auth.impl.jwt.NacosJwtParser;
|
||||||
import com.alibaba.nacos.sys.env.EnvUtil;
|
import com.alibaba.nacos.sys.env.EnvUtil;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
import org.springframework.mock.env.MockEnvironment;
|
import org.springframework.mock.env.MockEnvironment;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
|
|
||||||
@ -34,39 +33,40 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.Assert.assertNotEquals;
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class JwtTokenManagerTest {
|
class JwtTokenManagerTest {
|
||||||
|
|
||||||
private JwtTokenManager jwtTokenManager;
|
private JwtTokenManager jwtTokenManager;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
private AuthConfigs authConfigs;
|
private AuthConfigs authConfigs;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public void setUp() {
|
void setUp() {
|
||||||
when(authConfigs.isAuthEnabled()).thenReturn(true);
|
when(authConfigs.isAuthEnabled()).thenReturn(true);
|
||||||
MockEnvironment mockEnvironment = new MockEnvironment();
|
MockEnvironment mockEnvironment = new MockEnvironment();
|
||||||
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder().encodeToString(
|
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder()
|
||||||
"SecretKey0123$567890$234567890123456789012345678901234567890123456789"
|
.encodeToString("SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes(StandardCharsets.UTF_8)));
|
||||||
.getBytes(StandardCharsets.UTF_8)));
|
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
||||||
mockEnvironment
|
|
||||||
.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
|
||||||
|
|
||||||
EnvUtil.setEnvironment(mockEnvironment);
|
EnvUtil.setEnvironment(mockEnvironment);
|
||||||
jwtTokenManager = new JwtTokenManager(authConfigs);
|
jwtTokenManager = new JwtTokenManager(authConfigs);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateTokenAndSecretKeyWithoutSpecialSymbol() throws AccessException {
|
void testCreateTokenAndSecretKeyWithoutSpecialSymbol() throws AccessException {
|
||||||
createToken("SecretKey0123567890234567890123456789012345678901234567890123456789");
|
createToken("SecretKey0123567890234567890123456789012345678901234567890123456789");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateTokenAndSecretKeyWithSpecialSymbol() throws AccessException {
|
void testCreateTokenAndSecretKeyWithSpecialSymbol() throws AccessException {
|
||||||
createToken("SecretKey01234@#!5678901234567890123456789012345678901234567890123456789");
|
createToken("SecretKey01234@#!5678901234567890123456789012345678901234567890123456789");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,75 +74,72 @@ public class JwtTokenManagerTest {
|
|||||||
MockEnvironment mockEnvironment = new MockEnvironment();
|
MockEnvironment mockEnvironment = new MockEnvironment();
|
||||||
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY,
|
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY,
|
||||||
Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8)));
|
Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8)));
|
||||||
mockEnvironment
|
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
||||||
.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
|
||||||
|
|
||||||
EnvUtil.setEnvironment(mockEnvironment);
|
EnvUtil.setEnvironment(mockEnvironment);
|
||||||
|
|
||||||
JwtTokenManager jwtTokenManager = new JwtTokenManager(authConfigs);
|
JwtTokenManager jwtTokenManager = new JwtTokenManager(authConfigs);
|
||||||
String nacosToken = jwtTokenManager.createToken("nacos");
|
String nacosToken = jwtTokenManager.createToken("nacos");
|
||||||
Assert.assertNotNull(nacosToken);
|
assertNotNull(nacosToken);
|
||||||
jwtTokenManager.validateToken(nacosToken);
|
jwtTokenManager.validateToken(nacosToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void getAuthentication() throws AccessException {
|
void getAuthentication() throws AccessException {
|
||||||
String nacosToken = jwtTokenManager.createToken("nacos");
|
String nacosToken = jwtTokenManager.createToken("nacos");
|
||||||
Authentication authentication = jwtTokenManager.getAuthentication(nacosToken);
|
Authentication authentication = jwtTokenManager.getAuthentication(nacosToken);
|
||||||
Assert.assertNotNull(authentication);
|
assertNotNull(authentication);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testInvalidSecretKey() {
|
void testInvalidSecretKey() {
|
||||||
Assert.assertThrows(IllegalArgumentException.class, () -> createToken("0123456789ABCDEF0123456789ABCDE"));
|
assertThrows(IllegalArgumentException.class, () -> createToken("0123456789ABCDEF0123456789ABCDE"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetTokenTtlInSeconds() throws AccessException {
|
void testGetTokenTtlInSeconds() throws AccessException {
|
||||||
Assert.assertTrue(jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")) > 0);
|
assertTrue(jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")) > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetExpiredTimeInSeconds() throws AccessException {
|
void testGetExpiredTimeInSeconds() throws AccessException {
|
||||||
Assert.assertTrue(jwtTokenManager.getExpiredTimeInSeconds(jwtTokenManager.createToken("nacos")) > 0);
|
assertTrue(jwtTokenManager.getExpiredTimeInSeconds(jwtTokenManager.createToken("nacos")) > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetTokenTtlInSecondsWhenAuthDisabled() throws AccessException {
|
void testGetTokenTtlInSecondsWhenAuthDisabled() throws AccessException {
|
||||||
when(authConfigs.isAuthEnabled()).thenReturn(false);
|
when(authConfigs.isAuthEnabled()).thenReturn(false);
|
||||||
// valid secret key
|
// valid secret key
|
||||||
String ttl = EnvUtil.getProperty(AuthConstants.TOKEN_EXPIRE_SECONDS);
|
String ttl = EnvUtil.getProperty(AuthConstants.TOKEN_EXPIRE_SECONDS);
|
||||||
Assert.assertEquals(Integer.parseInt(ttl), jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")));
|
assertEquals(Integer.parseInt(ttl), jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")));
|
||||||
// invalid secret key
|
// invalid secret key
|
||||||
MockEnvironment mockEnvironment = new MockEnvironment();
|
MockEnvironment mockEnvironment = new MockEnvironment();
|
||||||
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, "");
|
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, "");
|
||||||
EnvUtil.setEnvironment(mockEnvironment);
|
EnvUtil.setEnvironment(mockEnvironment);
|
||||||
jwtTokenManager = new JwtTokenManager(authConfigs);
|
jwtTokenManager = new JwtTokenManager(authConfigs);
|
||||||
Assert.assertEquals(Integer.parseInt(ttl), jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")));
|
assertEquals(Integer.parseInt(ttl), jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateTokenWhenDisableAuthAndSecretKeyIsBlank() {
|
void testCreateTokenWhenDisableAuthAndSecretKeyIsBlank() {
|
||||||
when(authConfigs.isAuthEnabled()).thenReturn(false);
|
when(authConfigs.isAuthEnabled()).thenReturn(false);
|
||||||
MockEnvironment mockEnvironment = new MockEnvironment();
|
MockEnvironment mockEnvironment = new MockEnvironment();
|
||||||
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, "");
|
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, "");
|
||||||
mockEnvironment
|
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
||||||
.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
|
||||||
|
|
||||||
EnvUtil.setEnvironment(mockEnvironment);
|
EnvUtil.setEnvironment(mockEnvironment);
|
||||||
jwtTokenManager = new JwtTokenManager(authConfigs);
|
jwtTokenManager = new JwtTokenManager(authConfigs);
|
||||||
assertEquals("AUTH_DISABLED", jwtTokenManager.createToken("nacos"));
|
assertEquals("AUTH_DISABLED", jwtTokenManager.createToken("nacos"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreateTokenWhenDisableAuthAndSecretKeyIsNotBlank() throws AccessException {
|
void testCreateTokenWhenDisableAuthAndSecretKeyIsNotBlank() throws AccessException {
|
||||||
when(authConfigs.isAuthEnabled()).thenReturn(false);
|
when(authConfigs.isAuthEnabled()).thenReturn(false);
|
||||||
MockEnvironment mockEnvironment = new MockEnvironment();
|
MockEnvironment mockEnvironment = new MockEnvironment();
|
||||||
String tmpKey = "SecretKey0123567890234567890123456789012345678901234567890123456789";
|
String tmpKey = "SecretKey0123567890234567890123456789012345678901234567890123456789";
|
||||||
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY,
|
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY,
|
||||||
Base64.getEncoder().encodeToString(tmpKey.getBytes(StandardCharsets.UTF_8)));
|
Base64.getEncoder().encodeToString(tmpKey.getBytes(StandardCharsets.UTF_8)));
|
||||||
mockEnvironment
|
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
||||||
.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
|
||||||
EnvUtil.setEnvironment(mockEnvironment);
|
EnvUtil.setEnvironment(mockEnvironment);
|
||||||
jwtTokenManager = new JwtTokenManager(authConfigs);
|
jwtTokenManager = new JwtTokenManager(authConfigs);
|
||||||
String token = jwtTokenManager.createToken("nacos");
|
String token = jwtTokenManager.createToken("nacos");
|
||||||
@ -151,31 +148,28 @@ public class JwtTokenManagerTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testNacosJwtParser() throws AccessException {
|
void testNacosJwtParser() throws AccessException {
|
||||||
String secretKey = "SecretKey0123$567890$234567890123456789012345678901234567890123456789";
|
String secretKey = "SecretKey0123$567890$234567890123456789012345678901234567890123456789";
|
||||||
MockEnvironment mockEnvironment = new MockEnvironment();
|
MockEnvironment mockEnvironment = new MockEnvironment();
|
||||||
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY,
|
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY,
|
||||||
Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8)));
|
Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8)));
|
||||||
mockEnvironment
|
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
||||||
.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
|
|
||||||
|
|
||||||
EnvUtil.setEnvironment(mockEnvironment);
|
EnvUtil.setEnvironment(mockEnvironment);
|
||||||
|
|
||||||
JwtTokenManager jwtTokenManager = new JwtTokenManager(authConfigs);
|
JwtTokenManager jwtTokenManager = new JwtTokenManager(authConfigs);
|
||||||
String nacosToken = jwtTokenManager.createToken("nacos");
|
String nacosToken = jwtTokenManager.createToken("nacos");
|
||||||
Assert.assertNotNull(nacosToken);
|
assertNotNull(nacosToken);
|
||||||
System.out.println("oldToken: " + nacosToken);
|
System.out.println("oldToken: " + nacosToken);
|
||||||
|
|
||||||
jwtTokenManager.validateToken(nacosToken);
|
jwtTokenManager.validateToken(nacosToken);
|
||||||
NacosJwtParser nacosJwtParser = new NacosJwtParser(
|
NacosJwtParser nacosJwtParser = new NacosJwtParser(Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8)));
|
||||||
Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8)));
|
|
||||||
|
|
||||||
//check old token
|
//check old token
|
||||||
nacosJwtParser.parse(nacosToken);
|
nacosJwtParser.parse(nacosToken);
|
||||||
|
|
||||||
//create new token
|
//create new token
|
||||||
String newToken = nacosJwtParser.jwtBuilder().setUserName("nacos").setExpiredTime(TimeUnit.DAYS.toSeconds(10L))
|
String newToken = nacosJwtParser.jwtBuilder().setUserName("nacos").setExpiredTime(TimeUnit.DAYS.toSeconds(10L)).compact();
|
||||||
.compact();
|
|
||||||
System.out.println("newToken: " + newToken);
|
System.out.println("newToken: " + newToken);
|
||||||
jwtTokenManager.validateToken(newToken);
|
jwtTokenManager.validateToken(newToken);
|
||||||
}
|
}
|
||||||
|
@ -16,8 +16,9 @@
|
|||||||
|
|
||||||
package com.alibaba.nacos.plugin.auth.impl.utils;
|
package com.alibaba.nacos.plugin.auth.impl.utils;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base64Decoder test.
|
* Base64Decoder test.
|
||||||
@ -25,22 +26,22 @@ import org.junit.Test;
|
|||||||
* @author xYohn
|
* @author xYohn
|
||||||
* @date 2023/8/8
|
* @date 2023/8/8
|
||||||
*/
|
*/
|
||||||
public class Base64DecodeTest {
|
class Base64DecodeTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testStandardDecode() {
|
void testStandardDecode() {
|
||||||
String origin = "aGVsbG8sbmFjb3MhdGVzdEJhc2U2NGVuY29kZQ==";
|
String origin = "aGVsbG8sbmFjb3MhdGVzdEJhc2U2NGVuY29kZQ==";
|
||||||
String expectDecodeOrigin = "hello,nacos!testBase64encode";
|
String expectDecodeOrigin = "hello,nacos!testBase64encode";
|
||||||
byte[] decodeOrigin = Base64Decode.decode(origin);
|
byte[] decodeOrigin = Base64Decode.decode(origin);
|
||||||
Assert.assertArrayEquals(decodeOrigin, expectDecodeOrigin.getBytes());
|
assertArrayEquals(decodeOrigin, expectDecodeOrigin.getBytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testNotStandardDecode() {
|
void testNotStandardDecode() {
|
||||||
String notStandardOrigin = "SecretKey012345678901234567890123456789012345678901234567890123456789";
|
String notStandardOrigin = "SecretKey012345678901234567890123456789012345678901234567890123456789";
|
||||||
byte[] decodeNotStandardOrigin = Base64Decode.decode(notStandardOrigin);
|
byte[] decodeNotStandardOrigin = Base64Decode.decode(notStandardOrigin);
|
||||||
String truncationOrigin = "SecretKey01234567890123456789012345678901234567890123456789012345678";
|
String truncationOrigin = "SecretKey01234567890123456789012345678901234567890123456789012345678";
|
||||||
byte[] decodeTruncationOrigin = Base64Decode.decode(truncationOrigin);
|
byte[] decodeTruncationOrigin = Base64Decode.decode(truncationOrigin);
|
||||||
Assert.assertArrayEquals(decodeNotStandardOrigin, decodeTruncationOrigin);
|
assertArrayEquals(decodeNotStandardOrigin, decodeTruncationOrigin);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -16,36 +16,38 @@
|
|||||||
|
|
||||||
package com.alibaba.nacos.plugin.auth.impl.utils;
|
package com.alibaba.nacos.plugin.auth.impl.utils;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* PasswordEncoderUtil test.
|
* PasswordEncoderUtil test.
|
||||||
|
*
|
||||||
* @ClassName: PasswordEncoderUtilTest
|
* @ClassName: PasswordEncoderUtilTest
|
||||||
* @Author: ChenHao26
|
* @Author: ChenHao26
|
||||||
* @Date: 2022/8/17 01:25
|
* @Date: 2022/8/17 01:25
|
||||||
*/
|
*/
|
||||||
public class PasswordEncoderUtilTest {
|
class PasswordEncoderUtilTest {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* encode test.
|
* encode test.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void encode() {
|
void encode() {
|
||||||
String str = PasswordEncoderUtil.encode("nacos");
|
String str = PasswordEncoderUtil.encode("nacos");
|
||||||
String str2 = PasswordEncoderUtil.encode("nacos");
|
String str2 = PasswordEncoderUtil.encode("nacos");
|
||||||
Assert.assertNotEquals(str2, str);
|
assertNotEquals(str2, str);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void matches() {
|
void matches() {
|
||||||
Boolean result1 = PasswordEncoderUtil.matches("nacos",
|
Boolean result1 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXYxhzTmjWGJ21T.WX8thVsw0K2mO");
|
||||||
"$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXYxhzTmjWGJ21T.WX8thVsw0K2mO");
|
assertTrue(result1);
|
||||||
Assert.assertTrue(result1);
|
Boolean result2 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXcxhzTmjWGJ21T.WX8thVsw0K2mO");
|
||||||
Boolean result2 = PasswordEncoderUtil.matches("nacos",
|
assertFalse(result2);
|
||||||
"$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXcxhzTmjWGJ21T.WX8thVsw0K2mO");
|
|
||||||
Assert.assertFalse(result2);
|
|
||||||
Boolean matches = PasswordEncoderUtil.matches("nacos", PasswordEncoderUtil.encode("nacos"));
|
Boolean matches = PasswordEncoderUtil.matches("nacos", PasswordEncoderUtil.encode("nacos"));
|
||||||
Assert.assertTrue(matches);
|
assertTrue(matches);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -16,18 +16,19 @@
|
|||||||
|
|
||||||
package com.alibaba.nacos.plugin.auth.impl.utils;
|
package com.alibaba.nacos.plugin.auth.impl.utils;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class PasswordGeneratorUtilTest {
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
class PasswordGeneratorUtilTest {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* generatePwd test.
|
* generatePwd test.
|
||||||
*/
|
*/
|
||||||
@Test
|
@Test
|
||||||
public void generatePwd() {
|
void generatePwd() {
|
||||||
String pwd = PasswordGeneratorUtil.generateRandomPassword();
|
String pwd = PasswordGeneratorUtil.generateRandomPassword();
|
||||||
Assert.assertEquals(8, pwd.length());
|
assertEquals(8, pwd.length());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -19,51 +19,54 @@ package com.alibaba.nacos.plugin.control.impl;
|
|||||||
import com.alibaba.nacos.plugin.control.connection.request.ConnectionCheckRequest;
|
import com.alibaba.nacos.plugin.control.connection.request.ConnectionCheckRequest;
|
||||||
import com.alibaba.nacos.plugin.control.connection.response.ConnectionCheckResponse;
|
import com.alibaba.nacos.plugin.control.connection.response.ConnectionCheckResponse;
|
||||||
import com.alibaba.nacos.plugin.control.connection.rule.ConnectionControlRule;
|
import com.alibaba.nacos.plugin.control.connection.rule.ConnectionControlRule;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class NacosConnectionControlManagerTest {
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class NacosConnectionControlManagerTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testApplyConnectionLimitRule() {
|
void testApplyConnectionLimitRule() {
|
||||||
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
|
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
|
||||||
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
|
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
|
||||||
connectionControlRule.setCountLimit(10);
|
connectionControlRule.setCountLimit(10);
|
||||||
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
|
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
|
||||||
ConnectionControlRule connectionLimitRule = nacosConnectionControlManager.getConnectionLimitRule();
|
ConnectionControlRule connectionLimitRule = nacosConnectionControlManager.getConnectionLimitRule();
|
||||||
Assert.assertEquals(connectionControlRule, connectionLimitRule);
|
assertEquals(connectionControlRule, connectionLimitRule);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCheckLimit() {
|
void testCheckLimit() {
|
||||||
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
|
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
|
||||||
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
|
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
|
||||||
connectionControlRule.setCountLimit(10);
|
connectionControlRule.setCountLimit(10);
|
||||||
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
|
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
|
||||||
ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test");
|
ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test");
|
||||||
ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest);
|
ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest);
|
||||||
Assert.assertFalse(connectionCheckResponse.isSuccess());
|
assertFalse(connectionCheckResponse.isSuccess());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCheckUnLimit() {
|
void testCheckUnLimit() {
|
||||||
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
|
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
|
||||||
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
|
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
|
||||||
connectionControlRule.setCountLimit(30);
|
connectionControlRule.setCountLimit(30);
|
||||||
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
|
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
|
||||||
ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test");
|
ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test");
|
||||||
ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest);
|
ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest);
|
||||||
Assert.assertTrue(connectionCheckResponse.isSuccess());
|
assertTrue(connectionCheckResponse.isSuccess());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCheckLimitCountLessThanZero() {
|
void testCheckLimitCountLessThanZero() {
|
||||||
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
|
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
|
||||||
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
|
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
|
||||||
connectionControlRule.setCountLimit(-1);
|
connectionControlRule.setCountLimit(-1);
|
||||||
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
|
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
|
||||||
ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test");
|
ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test");
|
||||||
ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest);
|
ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest);
|
||||||
Assert.assertTrue(connectionCheckResponse.isSuccess());
|
assertTrue(connectionCheckResponse.isSuccess());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,20 +18,21 @@ package com.alibaba.nacos.plugin.control.impl;
|
|||||||
|
|
||||||
import com.alibaba.nacos.plugin.control.connection.ConnectionControlManager;
|
import com.alibaba.nacos.plugin.control.connection.ConnectionControlManager;
|
||||||
import com.alibaba.nacos.plugin.control.tps.TpsControlManager;
|
import com.alibaba.nacos.plugin.control.tps.TpsControlManager;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class NacosControlManagerBuilderTest {
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
class NacosControlManagerBuilderTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void test() {
|
void test() {
|
||||||
NacosControlManagerBuilder nacosControlManagerBuilder = new NacosControlManagerBuilder();
|
NacosControlManagerBuilder nacosControlManagerBuilder = new NacosControlManagerBuilder();
|
||||||
ConnectionControlManager connectionControlManager = nacosControlManagerBuilder.buildConnectionControlManager();
|
ConnectionControlManager connectionControlManager = nacosControlManagerBuilder.buildConnectionControlManager();
|
||||||
TpsControlManager tpsControlManager = nacosControlManagerBuilder.buildTpsControlManager();
|
TpsControlManager tpsControlManager = nacosControlManagerBuilder.buildTpsControlManager();
|
||||||
|
|
||||||
Assert.assertEquals("nacos", tpsControlManager.getName());
|
assertEquals("nacos", tpsControlManager.getName());
|
||||||
Assert.assertEquals("nacos", connectionControlManager.getName());
|
assertEquals("nacos", connectionControlManager.getName());
|
||||||
Assert.assertEquals("nacos", nacosControlManagerBuilder.getName());
|
assertEquals("nacos", nacosControlManagerBuilder.getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -21,51 +21,53 @@ import com.alibaba.nacos.plugin.control.tps.request.TpsCheckRequest;
|
|||||||
import com.alibaba.nacos.plugin.control.tps.response.TpsCheckResponse;
|
import com.alibaba.nacos.plugin.control.tps.response.TpsCheckResponse;
|
||||||
import com.alibaba.nacos.plugin.control.tps.rule.RuleDetail;
|
import com.alibaba.nacos.plugin.control.tps.rule.RuleDetail;
|
||||||
import com.alibaba.nacos.plugin.control.tps.rule.TpsControlRule;
|
import com.alibaba.nacos.plugin.control.tps.rule.TpsControlRule;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class NacosTpsControlManagerTest {
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class NacosTpsControlManagerTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testRegisterTpsPoint1() {
|
void testRegisterTpsPoint1() {
|
||||||
|
|
||||||
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
|
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
|
||||||
nacosTpsControlManager.registerTpsPoint("test");
|
nacosTpsControlManager.registerTpsPoint("test");
|
||||||
|
|
||||||
Assert.assertTrue(nacosTpsControlManager.getPoints().containsKey("test"));
|
assertTrue(nacosTpsControlManager.getPoints().containsKey("test"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testRegisterTpsPoint2() {
|
void testRegisterTpsPoint2() {
|
||||||
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
|
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
|
||||||
TpsControlRule tpsLimitRule = new TpsControlRule();
|
TpsControlRule tpsLimitRule = new TpsControlRule();
|
||||||
nacosTpsControlManager.applyTpsRule("test", tpsLimitRule);
|
nacosTpsControlManager.applyTpsRule("test", tpsLimitRule);
|
||||||
nacosTpsControlManager.registerTpsPoint("test");
|
nacosTpsControlManager.registerTpsPoint("test");
|
||||||
|
|
||||||
Assert.assertTrue(nacosTpsControlManager.getPoints().containsKey("test"));
|
assertTrue(nacosTpsControlManager.getPoints().containsKey("test"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testApplyTpsRule1() {
|
void testApplyTpsRule1() {
|
||||||
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
|
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
|
||||||
TpsControlRule tpsLimitRule = new TpsControlRule();
|
TpsControlRule tpsLimitRule = new TpsControlRule();
|
||||||
nacosTpsControlManager.applyTpsRule("test", tpsLimitRule);
|
nacosTpsControlManager.applyTpsRule("test", tpsLimitRule);
|
||||||
|
|
||||||
Assert.assertTrue(nacosTpsControlManager.getRules().containsKey("test"));
|
assertTrue(nacosTpsControlManager.getRules().containsKey("test"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testApplyTpsRule2() {
|
void testApplyTpsRule2() {
|
||||||
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
|
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
|
||||||
nacosTpsControlManager.applyTpsRule("test", null);
|
nacosTpsControlManager.applyTpsRule("test", null);
|
||||||
|
|
||||||
Assert.assertFalse(nacosTpsControlManager.getRules().containsKey("test"));
|
assertFalse(nacosTpsControlManager.getRules().containsKey("test"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCheck() {
|
void testCheck() {
|
||||||
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
|
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
|
||||||
nacosTpsControlManager.registerTpsPoint("test");
|
nacosTpsControlManager.registerTpsPoint("test");
|
||||||
final TpsControlRule tpsLimitRule = new TpsControlRule();
|
final TpsControlRule tpsLimitRule = new TpsControlRule();
|
||||||
@ -82,6 +84,6 @@ public class NacosTpsControlManagerTest {
|
|||||||
tpsCheckRequest.setPointName("test");
|
tpsCheckRequest.setPointName("test");
|
||||||
tpsCheckRequest.setTimestamp(timeMillis);
|
tpsCheckRequest.setTimestamp(timeMillis);
|
||||||
TpsCheckResponse check = nacosTpsControlManager.check(tpsCheckRequest);
|
TpsCheckResponse check = nacosTpsControlManager.check(tpsCheckRequest);
|
||||||
Assert.assertTrue(check.isSuccess());
|
assertTrue(check.isSuccess());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user