upgrade module naocs-plugin-impl from junit4 to junit5 (#12230)

This commit is contained in:
shalk(xiao kun) 2024-06-17 14:07:37 +08:00 committed by GitHub
parent 833e6ca59a
commit ab6591ac83
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 466 additions and 417 deletions

View File

@ -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.NacosUserDetailsServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.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.springframework.ldap.core.LdapTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -40,10 +41,30 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
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;
@RunWith(MockitoJUnitRunner.class)
public class LdapAuthenticationProviderTest {
@ExtendWith(MockitoExtension.class)
// 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
private NacosUserDetailsServiceImpl userDetailsService;
@ -60,32 +81,18 @@ public class LdapAuthenticationProviderTest {
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";
@Before
public void setUp() throws NoSuchMethodException {
@BeforeEach
void setUp() throws NoSuchMethodException {
RoleInfo adminRole = new RoleInfo();
adminRole.setRole(AuthConstants.GLOBAL_ADMIN_ROLE);
adminRole.setUsername(adminUserName);
roleInfos.add(adminRole);
when(nacosRoleService.getRoles(adminUserName)).thenReturn(roleInfos);
when(nacosRoleService.getRoles(normalUserName)).thenReturn(new ArrayList<>());
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + adminUserName + ")", defaultPassWord))
.thenAnswer(new Answer<Boolean>() {
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + adminUserName + ")", defaultPassWord)).thenAnswer(
new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
@ -97,10 +104,10 @@ public class LdapAuthenticationProviderTest {
return false;
}
});
this.ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapTemplate, userDetailsService,
nacosRoleService, filterPrefix, caseSensitive);
this.ldapAuthenticationProviderForCloseCaseSensitive = new LdapAuthenticationProvider(ldapTemplate,
userDetailsService, nacosRoleService, filterPrefix, !caseSensitive);
this.ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapTemplate, userDetailsService, nacosRoleService, filterPrefix,
caseSensitive);
this.ldapAuthenticationProviderForCloseCaseSensitive = new LdapAuthenticationProvider(ldapTemplate, userDetailsService,
nacosRoleService, filterPrefix, !caseSensitive);
isAdmin = LdapAuthenticationProvider.class.getDeclaredMethod("isAdmin", String.class);
isAdmin.setAccessible(true);
ldapLogin = LdapAuthenticationProvider.class.getDeclaredMethod("ldapLogin", String.class, String.class);
@ -108,77 +115,75 @@ public class LdapAuthenticationProviderTest {
}
@Test
public void testIsAdmin() {
void testIsAdmin() {
try {
Boolean result = (Boolean) isAdmin.invoke(ldapAuthenticationProvider, adminUserName);
Assert.assertTrue(result);
assertTrue(result);
} catch (IllegalAccessException e) {
Assert.fail();
fail();
} catch (InvocationTargetException e) {
Assert.fail();
fail();
}
try {
Boolean result = (Boolean) isAdmin.invoke(ldapAuthenticationProvider, normalUserName);
Assert.assertTrue(!result);
assertFalse(result);
} catch (IllegalAccessException e) {
Assert.fail();
fail();
} catch (InvocationTargetException e) {
Assert.fail();
fail();
}
}
@Test
public void testldapLogin() {
void testldapLogin() {
try {
Boolean result = (Boolean) ldapLogin.invoke(ldapAuthenticationProvider, adminUserName, defaultPassWord);
Assert.assertTrue(result);
assertTrue(result);
} catch (IllegalAccessException e) {
Assert.fail();
fail();
} catch (InvocationTargetException e) {
Assert.fail();
fail();
}
try {
Boolean result = (Boolean) ldapLogin.invoke(ldapAuthenticationProvider, adminUserName, "123");
Assert.assertTrue(!result);
assertFalse(result);
} catch (IllegalAccessException e) {
Assert.fail();
fail();
} catch (InvocationTargetException e) {
Assert.fail();
fail();
}
}
@Test
public void testDefaultCaseSensitive() {
void testDefaultCaseSensitive() {
String userName = StringUtils.upperCase(normalUserName);
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + userName + ")", defaultPassWord))
.thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
String b = (String) args[1];
String c = (String) args[2];
if (defaultPassWord.equals(c)) {
return true;
}
return false;
}
});
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + userName + ")", defaultPassWord)).thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
String b = (String) args[1];
String c = (String) args[2];
if (defaultPassWord.equals(c)) {
return true;
}
return false;
}
});
User userUpperCase = new User();
userUpperCase.setUsername(LDAP_PREFIX + userName);
userUpperCase.setPassword(defaultPassWord);
when(userDetailsService.loadUserByUsername(LDAP_PREFIX + userName))
.thenReturn(new NacosUserDetails(userUpperCase));
when(userDetailsService.loadUserByUsername(LDAP_PREFIX + userName)).thenReturn(new NacosUserDetails(userUpperCase));
Authentication authentication = new UsernamePasswordAuthenticationToken(userName, defaultPassWord);
Authentication result = ldapAuthenticationProvider.authenticate(authentication);
NacosUserDetails nacosUserDetails = (NacosUserDetails) result.getPrincipal();
Assert.assertTrue(nacosUserDetails.getUsername().equals(LDAP_PREFIX + userName));
assertEquals(nacosUserDetails.getUsername(), LDAP_PREFIX + userName);
}
@Test
public void testCloseCaseSensitive() {
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + normalUserName + ")", defaultPassWord))
.thenAnswer(new Answer<Boolean>() {
void testCloseCaseSensitive() {
when(ldapTemplate.authenticate("", "(" + filterPrefix + "=" + normalUserName + ")", defaultPassWord)).thenAnswer(
new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
@ -193,12 +198,10 @@ public class LdapAuthenticationProviderTest {
User user = new User();
user.setUsername(LDAP_PREFIX + normalUserName);
user.setPassword(defaultPassWord);
when(userDetailsService.loadUserByUsername(LDAP_PREFIX + normalUserName))
.thenReturn(new NacosUserDetails(user));
Authentication authentication = new UsernamePasswordAuthenticationToken(StringUtils.upperCase(normalUserName),
defaultPassWord);
when(userDetailsService.loadUserByUsername(LDAP_PREFIX + normalUserName)).thenReturn(new NacosUserDetails(user));
Authentication authentication = new UsernamePasswordAuthenticationToken(StringUtils.upperCase(normalUserName), defaultPassWord);
Authentication result = ldapAuthenticationProviderForCloseCaseSensitive.authenticate(authentication);
NacosUserDetails nacosUserDetails = (NacosUserDetails) result.getPrincipal();
Assert.assertTrue(nacosUserDetails.getUsername().equals(LDAP_PREFIX + normalUserName));
assertEquals(nacosUserDetails.getUsername(), LDAP_PREFIX + normalUserName);
}
}

View File

@ -17,24 +17,29 @@
package com.alibaba.nacos.plugin.auth.impl.configuration;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* ConditionOnLdapAuth test.
*
* @ClassName: ConditionOnLdapAuthTest
* @Author: ChenHao26
* @Date: 2022/8/16 17:03
*/
@RunWith(MockitoJUnitRunner.class)
public class ConditionOnLdapAuthTest {
@ExtendWith(MockitoExtension.class)
class ConditionOnLdapAuthTest {
@Mock
private static ConfigurableEnvironment environment;
private ConditionOnLdapAuth conditionOnLdapAuth;
@ -44,18 +49,15 @@ public class ConditionOnLdapAuthTest {
@Mock
private AnnotatedTypeMetadata annotatedTypeMetadata;
@Mock
private static ConfigurableEnvironment environment;
@Before
public void setup() {
@BeforeEach
void setup() {
conditionOnLdapAuth = new ConditionOnLdapAuth();
EnvUtil.setEnvironment(environment);
}
@Test
public void matches() {
void matches() {
boolean matches = conditionOnLdapAuth.matches(conditionContext, annotatedTypeMetadata);
Assert.assertFalse(matches);
assertFalse(matches);
}
}

View File

@ -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.sys.env.EnvUtil;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.env.MockEnvironment;
import javax.servlet.http.HttpServletRequest;
@ -39,12 +39,12 @@ import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
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.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class UserControllerTest {
@ExtendWith(MockitoExtension.class)
class UserControllerTest {
@Mock
private HttpServletRequest request;
@ -65,8 +65,8 @@ public class UserControllerTest {
private NacosUser user;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
userController = new UserController();
user = new NacosUser();
user.setUserName("nacos");
@ -76,18 +76,16 @@ public class UserControllerTest {
injectObject("iAuthenticationManager", authenticationManager);
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder().encodeToString(
"SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes(
StandardCharsets.UTF_8)));
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS,
AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder()
.encodeToString("SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes(StandardCharsets.UTF_8)));
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
EnvUtil.setEnvironment(mockEnvironment);
injectObject("jwtTokenManager", tokenManagerDelegate);
}
@Test
public void testLoginWithAuthedUser() throws AccessException, IOException {
void testLoginWithAuthedUser() throws AccessException, IOException {
when(authenticationManager.authenticate(request)).thenReturn(user);
when(authenticationManager.hasGlobalAdminRole(user)).thenReturn(true);
when(authConfigs.getNacosAuthSystemType()).thenReturn(AuthSystemTypes.NACOS.name());

View File

@ -17,16 +17,16 @@
package com.alibaba.nacos.plugin.auth.impl.jwt;
import com.alibaba.nacos.plugin.auth.exception.AccessException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* NacosJwtParserTest.
@ -34,16 +34,16 @@ import static org.junit.Assert.assertTrue;
* @author WeizhanYun
* @date 2023/2/1 16:32
*/
@RunWith(MockitoJUnitRunner.class)
public class NacosJwtParserTest {
@ExtendWith(MockitoExtension.class)
class NacosJwtParserTest {
@Test
public void testParseWithOriginKey() {
void testParseWithOriginKey() {
new NacosJwtParser("SecretKey012345678901234567890123456789012345678901234567890123456789");
}
@Test
public void testParseWith16Key() {
void testParseWith16Key() {
Exception e = null;
try {
new NacosJwtParser("SecretKey0123456");
@ -57,7 +57,7 @@ public class NacosJwtParserTest {
}
@Test
public void testParseWith32Key() {
void testParseWith32Key() {
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey01234567890123456789012"));
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
@ -65,7 +65,7 @@ public class NacosJwtParserTest {
}
@Test
public void testParseWith48Key() {
void testParseWith48Key() {
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567890120124568aa9012345"));
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
@ -73,18 +73,16 @@ public class NacosJwtParserTest {
}
@Test
public void testParseWith64Key() {
NacosJwtParser parser = new NacosJwtParser(
encode("SecretKey012345678901234567SecretKey0123456789012345678901289012"));
void testParseWith64Key() {
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567SecretKey0123456789012345678901289012"));
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
assertTrue(token.startsWith(NacosSignatureAlgorithm.HS512.getHeader()));
}
@Test
public void testGetExpireTimeInSeconds() throws AccessException {
NacosJwtParser parser = new NacosJwtParser(
encode("SecretKey012345678901234567SecretKey0123456789012345678901289012"));
void testGetExpireTimeInSeconds() throws AccessException {
NacosJwtParser parser = new NacosJwtParser(encode("SecretKey012345678901234567SecretKey0123456789012345678901289012"));
String token = parser.jwtBuilder().setUserName("nacos").setExpiredTime(100L).compact();
long expiredTimeSeconds = parser.getExpireTimeInSeconds(token);
assertTrue(expiredTimeSeconds * 1000 - System.currentTimeMillis() > 0);

View File

@ -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.operate.DatabaseOperate;
import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.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.util.List;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class EmbeddedPermissionPersistServiceImplTest {
@ExtendWith(MockitoExtension.class)
// todo remove this
@MockitoSettings(strictness = Strictness.LENIENT)
class EmbeddedPermissionPersistServiceImplTest {
@Mock
private DatabaseOperate databaseOperate;
private EmbeddedPermissionPersistServiceImpl embeddedPermissionPersistService;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0);
embeddedPermissionPersistService = new EmbeddedPermissionPersistServiceImpl();
Class<EmbeddedPermissionPersistServiceImpl> embeddedPermissionPersistServiceClass = EmbeddedPermissionPersistServiceImpl.class;
@ -54,15 +58,15 @@ public class EmbeddedPermissionPersistServiceImplTest {
}
@Test
public void testGetPermissions() {
void testGetPermissions() {
String role = "role";
Page<PermissionInfo> permissions = embeddedPermissionPersistService.getPermissions(role, 1, 10);
Assert.assertNotNull(permissions);
assertNotNull(permissions);
}
@Test
public void testAddPermission() {
void testAddPermission() {
embeddedPermissionPersistService.addPermission("role", "resource", "action");
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
@ -70,7 +74,7 @@ public class EmbeddedPermissionPersistServiceImplTest {
}
@Test
public void testDeletePermission() {
void testDeletePermission() {
embeddedPermissionPersistService.deletePermission("role", "resource", "action");
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();

View File

@ -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.operate.DatabaseOperate;
import com.alibaba.nacos.persistence.repository.embedded.sql.ModifyRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.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.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.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class EmbeddedRolePersistServiceImplTest {
@ExtendWith(MockitoExtension.class)
// todo remove this
@MockitoSettings(strictness = Strictness.LENIENT)
class EmbeddedRolePersistServiceImplTest {
@Mock
private DatabaseOperate databaseOperate;
private EmbeddedRolePersistServiceImpl embeddedRolePersistService;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0);
embeddedRolePersistService = new EmbeddedRolePersistServiceImpl();
Class<EmbeddedRolePersistServiceImpl> embeddedRolePersistServiceClass = EmbeddedRolePersistServiceImpl.class;
@ -53,41 +58,41 @@ public class EmbeddedRolePersistServiceImplTest {
}
@Test
public void testGetRoles() {
void testGetRoles() {
Page<RoleInfo> roles = embeddedRolePersistService.getRoles(1, 10);
Assert.assertNotNull(roles);
assertNotNull(roles);
}
@Test
public void testGetRolesByUserName() {
void testGetRolesByUserName() {
Page<RoleInfo> page = embeddedRolePersistService.getRolesByUserNameAndRoleName("userName", "roleName", 1, 10);
Assert.assertNotNull(page);
assertNotNull(page);
}
@Test
public void testAddRole() {
void testAddRole() {
embeddedRolePersistService.addRole("role", "userName");
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
Assert.assertEquals(currentSqlContext.size(), 0);
assertEquals(0, currentSqlContext.size());
}
@Test
public void testDeleteRole() {
void testDeleteRole() {
embeddedRolePersistService.deleteRole("role");
embeddedRolePersistService.deleteRole("role", "userName");
List<ModifyRequest> currentSqlContext = EmbeddedStorageContextHolder.getCurrentSqlContext();
Assert.assertEquals(currentSqlContext.size(), 0);
assertEquals(0, currentSqlContext.size());
}
@Test
public void testFindRolesLikeRoleName() {
void testFindRolesLikeRoleName() {
List<String> role = embeddedRolePersistService.findRolesLikeRoleName("role");
Assert.assertEquals(role.size(), 0);
assertEquals(0, role.size());
}
}

View File

@ -18,31 +18,37 @@ package com.alibaba.nacos.plugin.auth.impl.persistence;
import com.alibaba.nacos.persistence.model.Page;
import com.alibaba.nacos.persistence.repository.embedded.operate.DatabaseOperate;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.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.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.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class EmbeddedUserPersistServiceImplTest {
@ExtendWith(MockitoExtension.class)
// todo remove this
@MockitoSettings(strictness = Strictness.LENIENT)
class EmbeddedUserPersistServiceImplTest {
@Mock
private DatabaseOperate databaseOperate;
private EmbeddedUserPersistServiceImpl embeddedUserPersistService;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
when(databaseOperate.queryOne(any(String.class), any(Object[].class), eq(Integer.class))).thenReturn(0);
embeddedUserPersistService = new EmbeddedUserPersistServiceImpl();
Class<EmbeddedUserPersistServiceImpl> embeddedUserPersistServiceClass = EmbeddedUserPersistServiceImpl.class;
@ -53,43 +59,43 @@ public class EmbeddedUserPersistServiceImplTest {
}
@Test
public void testCreateUser() {
void testCreateUser() {
embeddedUserPersistService.createUser("username", "password");
Mockito.verify(databaseOperate).blockUpdate();
}
@Test
public void testDeleteUser() {
void testDeleteUser() {
embeddedUserPersistService.deleteUser("username");
Mockito.verify(databaseOperate).blockUpdate();
}
@Test
public void testUpdateUserPassword() {
void testUpdateUserPassword() {
embeddedUserPersistService.updateUserPassword("username", "password");
Mockito.verify(databaseOperate).blockUpdate();
}
@Test
public void testFindUserByUsername() {
void testFindUserByUsername() {
User user = embeddedUserPersistService.findUserByUsername("username");
Assert.assertNull(user);
assertNull(user);
}
@Test
public void testGetUsers() {
void testGetUsers() {
Page<User> users = embeddedUserPersistService.getUsers(1, 10, "nacos");
Assert.assertNotNull(users);
assertNotNull(users);
}
@Test
public void testFindUserLikeUsername() {
void testFindUserLikeUsername() {
List<String> username = embeddedUserPersistService.findUserLikeUsername("username");
Assert.assertEquals(username.size(), 0);
assertEquals(0, username.size());
}
}

View File

@ -20,24 +20,28 @@ import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration;
import com.alibaba.nacos.persistence.datasource.DataSourceService;
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
import com.alibaba.nacos.persistence.model.Page;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.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 java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ExternalPermissionPersistServiceImplTest {
@ExtendWith(MockitoExtension.class)
// todo remove this
@MockitoSettings(strictness = Strictness.LENIENT)
class ExternalPermissionPersistServiceImplTest {
@Mock
private JdbcTemplate jdbcTemplate;
@ -51,8 +55,8 @@ public class ExternalPermissionPersistServiceImplTest {
private ExternalPermissionPersistServiceImpl externalPermissionPersistService;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
externalPermissionPersistService = new ExternalPermissionPersistServiceImpl();
when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0);
when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate);
@ -65,8 +69,8 @@ public class ExternalPermissionPersistServiceImplTest {
externalPermissionPersistService.init();
}
@After
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
@AfterEach
void tearDown() throws NoSuchFieldException, IllegalAccessException {
DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache);
Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService");
datasourceField.setAccessible(true);
@ -74,13 +78,13 @@ public class ExternalPermissionPersistServiceImplTest {
}
@Test
public void testGetPermissions() {
void testGetPermissions() {
Page<PermissionInfo> role = externalPermissionPersistService.getPermissions("role", 1, 10);
Assert.assertNotNull(role);
assertNotNull(role);
}
@Test
public void testAddPermission() {
void testAddPermission() {
String sql = "INSERT INTO permissions (role, resource, action) VALUES (?, ?, ?)";
externalPermissionPersistService.addPermission("role", "resource", "action");
@ -88,7 +92,7 @@ public class ExternalPermissionPersistServiceImplTest {
}
@Test
public void testDeletePermission() {
void testDeletePermission() {
String sql = "DELETE FROM permissions WHERE role=? AND resource=? AND action=?";
externalPermissionPersistService.deletePermission("role", "resource", "action");

View File

@ -20,25 +20,30 @@ import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration;
import com.alibaba.nacos.persistence.datasource.DataSourceService;
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
import com.alibaba.nacos.persistence.model.Page;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.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 java.lang.reflect.Field;
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.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ExternalRolePersistServiceImplTest {
@ExtendWith(MockitoExtension.class)
// todo remove this
@MockitoSettings(strictness = Strictness.LENIENT)
class ExternalRolePersistServiceImplTest {
@Mock
private JdbcTemplate jdbcTemplate;
@ -52,8 +57,8 @@ public class ExternalRolePersistServiceImplTest {
private ExternalRolePersistServiceImpl externalRolePersistService;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
externalRolePersistService = new ExternalRolePersistServiceImpl();
when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0);
when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate);
@ -66,8 +71,8 @@ public class ExternalRolePersistServiceImplTest {
externalRolePersistService.init();
}
@After
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
@AfterEach
void tearDown() throws NoSuchFieldException, IllegalAccessException {
DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache);
Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService");
datasourceField.setAccessible(true);
@ -75,21 +80,20 @@ public class ExternalRolePersistServiceImplTest {
}
@Test
public void testGetRoles() {
void testGetRoles() {
Page<RoleInfo> roles = externalRolePersistService.getRoles(1, 10);
Assert.assertNotNull(roles);
assertNotNull(roles);
}
@Test
public void testGetRolesByUserName() {
Page<RoleInfo> userName = externalRolePersistService
.getRolesByUserNameAndRoleName("userName", "roleName", 1, 10);
Assert.assertNotNull(userName);
void testGetRolesByUserName() {
Page<RoleInfo> userName = externalRolePersistService.getRolesByUserNameAndRoleName("userName", "roleName", 1, 10);
assertNotNull(userName);
}
@Test
public void testAddRole() {
void testAddRole() {
externalRolePersistService.addRole("role", "userName");
String sql = "INSERT INTO roles (role, username) VALUES (?, ?)";
@ -97,7 +101,7 @@ public class ExternalRolePersistServiceImplTest {
}
@Test
public void testDeleteRole() {
void testDeleteRole() {
externalRolePersistService.deleteRole("role");
String sql = "DELETE FROM roles WHERE role=?";
@ -110,9 +114,9 @@ public class ExternalRolePersistServiceImplTest {
}
@Test
public void testFindRolesLikeRoleName() {
void testFindRolesLikeRoleName() {
List<String> role = externalRolePersistService.findRolesLikeRoleName("role");
Assert.assertEquals(role.size(), 0);
assertEquals(0, role.size());
}
}

View File

@ -20,25 +20,31 @@ import com.alibaba.nacos.persistence.configuration.DatasourceConfiguration;
import com.alibaba.nacos.persistence.datasource.DataSourceService;
import com.alibaba.nacos.persistence.datasource.DynamicDataSource;
import com.alibaba.nacos.persistence.model.Page;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.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 java.lang.reflect.Field;
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.eq;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ExternalUserPersistServiceImplTest {
@ExtendWith(MockitoExtension.class)
// todo remove this
@MockitoSettings(strictness = Strictness.LENIENT)
class ExternalUserPersistServiceImplTest {
@Mock
private JdbcTemplate jdbcTemplate;
@ -52,8 +58,8 @@ public class ExternalUserPersistServiceImplTest {
private ExternalUserPersistServiceImpl externalUserPersistService;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
externalUserPersistService = new ExternalUserPersistServiceImpl();
when(jdbcTemplate.queryForObject(any(), any(), eq(Integer.class))).thenReturn(0);
when(dataSourceService.getJdbcTemplate()).thenReturn(jdbcTemplate);
@ -66,8 +72,8 @@ public class ExternalUserPersistServiceImplTest {
externalUserPersistService.init();
}
@After
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
@AfterEach
void tearDown() throws NoSuchFieldException, IllegalAccessException {
DatasourceConfiguration.setEmbeddedStorage(embeddedStorageCache);
Field datasourceField = DynamicDataSource.class.getDeclaredField("basicDataSourceService");
datasourceField.setAccessible(true);
@ -75,7 +81,7 @@ public class ExternalUserPersistServiceImplTest {
}
@Test
public void testCreateUser() {
void testCreateUser() {
externalUserPersistService.createUser("username", "password");
String sql = "INSERT INTO users (username, password, enabled) VALUES (?, ?, ?)";
@ -83,7 +89,7 @@ public class ExternalUserPersistServiceImplTest {
}
@Test
public void testDeleteUser() {
void testDeleteUser() {
externalUserPersistService.deleteUser("username");
String sql = "DELETE FROM users WHERE username=?";
@ -91,7 +97,7 @@ public class ExternalUserPersistServiceImplTest {
}
@Test
public void testUpdateUserPassword() {
void testUpdateUserPassword() {
externalUserPersistService.updateUserPassword("username", "password");
String sql = "UPDATE users SET password = ? WHERE username=?";
@ -99,23 +105,23 @@ public class ExternalUserPersistServiceImplTest {
}
@Test
public void testFindUserByUsername() {
void testFindUserByUsername() {
User username = externalUserPersistService.findUserByUsername("username");
Assert.assertNull(username);
assertNull(username);
}
@Test
public void testGetUsers() {
void testGetUsers() {
Page<User> users = externalUserPersistService.getUsers(1, 10, "nacos");
Assert.assertNotNull(users);
assertNotNull(users);
}
@Test
public void testFindUserLikeUsername() {
void testFindUserLikeUsername() {
List<String> username = externalUserPersistService.findUserLikeUsername("username");
Assert.assertEquals(username.size(), 0);
assertEquals(0, username.size());
}
}

View File

@ -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.users.NacosUser;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUserDetailsServiceImpl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
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.
*
@ -48,8 +53,10 @@ import java.util.List;
* @Date: 2022/8/16 17:31
* @Description: TODO
*/
@RunWith(MockitoJUnitRunner.class)
public class NacosRoleServiceImplTest {
@ExtendWith(MockitoExtension.class)
class NacosRoleServiceImplTest {
Class<NacosRoleServiceImpl> nacosRoleServiceClass;
@Mock
private AuthConfigs authConfigs;
@ -66,10 +73,8 @@ public class NacosRoleServiceImplTest {
@Mock
private NacosRoleServiceImpl nacosRoleService;
Class<NacosRoleServiceImpl> nacosRoleServiceClass;
@Before
public void setup() throws Exception {
@BeforeEach
void setup() throws Exception {
nacosRoleService = new NacosRoleServiceImpl();
nacosRoleServiceClass = NacosRoleServiceImpl.class;
Field authConfigsFile = nacosRoleServiceClass.getDeclaredField("authConfigs");
@ -90,107 +95,105 @@ public class NacosRoleServiceImplTest {
}
@Test
public void reload() throws Exception {
void reload() throws Exception {
Method reload = nacosRoleServiceClass.getDeclaredMethod("reload");
reload.setAccessible(true);
reload.invoke(nacosRoleService);
}
@Test
public void hasPermission() {
void hasPermission() {
Permission permission = new Permission();
permission.setAction("rw");
permission.setResource(Resource.EMPTY_RESOURCE);
NacosUser nacosUser = new NacosUser();
nacosUser.setUserName("nacos");
boolean res = nacosRoleService.hasPermission(nacosUser, permission);
Assert.assertFalse(res);
assertFalse(res);
Permission permission2 = new Permission();
permission2.setAction("rw");
Resource resource = new Resource("public", "group", AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, "rw", null);
permission2.setResource(resource);
boolean res2 = nacosRoleService.hasPermission(nacosUser, permission2);
Assert.assertTrue(res2);
assertTrue(res2);
}
@Test
public void getRoles() {
void getRoles() {
List<RoleInfo> nacos = nacosRoleService.getRoles("role-admin");
Assert.assertEquals(nacos, Collections.emptyList());
assertEquals(nacos, Collections.emptyList());
}
@Test
public void getRolesFromDatabase() {
Page<RoleInfo> roleInfoPage = nacosRoleService.getRolesFromDatabase("nacos", "ROLE_ADMIN", 1,
Integer.MAX_VALUE);
Assert.assertEquals(roleInfoPage.getTotalCount(), 0);
void getRolesFromDatabase() {
Page<RoleInfo> roleInfoPage = nacosRoleService.getRolesFromDatabase("nacos", "ROLE_ADMIN", 1, Integer.MAX_VALUE);
assertEquals(0, roleInfoPage.getTotalCount());
}
@Test
public void getPermissions() {
void getPermissions() {
boolean cachingEnabled = authConfigs.isCachingEnabled();
Assert.assertFalse(cachingEnabled);
assertFalse(cachingEnabled);
List<PermissionInfo> permissions = nacosRoleService.getPermissions("role-admin");
Assert.assertEquals(permissions, Collections.emptyList());
assertEquals(permissions, Collections.emptyList());
}
@Test
public void getPermissionsByRoleFromDatabase() {
Page<PermissionInfo> permissionsByRoleFromDatabase = nacosRoleService.getPermissionsByRoleFromDatabase(
"role-admin", 1, Integer.MAX_VALUE);
Assert.assertNull(permissionsByRoleFromDatabase);
void getPermissionsByRoleFromDatabase() {
Page<PermissionInfo> permissionsByRoleFromDatabase = nacosRoleService.getPermissionsByRoleFromDatabase("role-admin", 1,
Integer.MAX_VALUE);
assertNull(permissionsByRoleFromDatabase);
}
@Test
public void addRole() {
void addRole() {
String username = "nacos";
User userFromDatabase = userDetailsService.getUserFromDatabase(username);
Assert.assertNull(userFromDatabase);
assertNull(userFromDatabase);
try {
nacosRoleService.addRole("role-admin", "nacos");
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("user 'nacos' not found!"));
assertTrue(e.getMessage().contains("user 'nacos' not found!"));
}
}
@Test
public void deleteRole() {
void deleteRole() {
try {
nacosRoleService.deleteRole("role-admin");
} catch (Exception e) {
Assert.assertNull(e);
assertNull(e);
}
}
@Test
public void getPermissionsFromDatabase() {
Page<PermissionInfo> permissionsFromDatabase = nacosRoleService.getPermissionsFromDatabase("role-admin", 1,
Integer.MAX_VALUE);
Assert.assertEquals(permissionsFromDatabase.getTotalCount(), 0);
void getPermissionsFromDatabase() {
Page<PermissionInfo> permissionsFromDatabase = nacosRoleService.getPermissionsFromDatabase("role-admin", 1, Integer.MAX_VALUE);
assertEquals(0, permissionsFromDatabase.getTotalCount());
}
@Test
public void addPermission() {
void addPermission() {
try {
nacosRoleService.addPermission("role-admin", "", "rw");
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("role role-admin not found!"));
assertTrue(e.getMessage().contains("role role-admin not found!"));
}
}
@Test
public void findRolesLikeRoleName() {
void findRolesLikeRoleName() {
List<String> rolesLikeRoleName = rolePersistService.findRolesLikeRoleName("role-admin");
Assert.assertEquals(rolesLikeRoleName, Collections.emptyList());
assertEquals(rolesLikeRoleName, Collections.emptyList());
}
@Test
public void joinResource() throws Exception {
void joinResource() throws Exception {
Method method = nacosRoleServiceClass.getDeclaredMethod("joinResource", Resource.class);
method.setAccessible(true);
Resource resource = new Resource("public", "group", AuthConstants.UPDATE_PASSWORD_ENTRY_POINT, "rw", null);
Object invoke = method.invoke(nacosRoleService, new Resource[] {resource});
Assert.assertNotNull(invoke);
assertNotNull(invoke);
}
}

View File

@ -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.JwtTokenManager;
import com.alibaba.nacos.plugin.auth.impl.users.NacosUser;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.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 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.Mockito.when;
@ -38,8 +42,10 @@ import static org.mockito.Mockito.when;
*
* @author majorhe
*/
@RunWith(MockitoJUnitRunner.class)
public class TokenManagerDelegateTest {
@ExtendWith(MockitoExtension.class)
// todo remove this
@MockitoSettings(strictness = Strictness.LENIENT)
class TokenManagerDelegateTest {
private TokenManagerDelegate tokenManagerDelegate;
@ -55,8 +61,8 @@ public class TokenManagerDelegateTest {
@Mock
private NacosUser user;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
tokenManagerDelegate = new TokenManagerDelegate();
injectObject("jwtTokenManager", jwtTokenManager);
injectObject("cachedJwtTokenManager", cachedJwtTokenManager);
@ -70,38 +76,38 @@ public class TokenManagerDelegateTest {
}
@Test
public void testCreateToken1() throws AccessException {
Assert.assertEquals("token", tokenManagerDelegate.createToken(authentication));
void testCreateToken1() throws AccessException {
assertEquals("token", tokenManagerDelegate.createToken(authentication));
}
@Test
public void testCreateToken2() throws AccessException {
Assert.assertEquals("token", tokenManagerDelegate.createToken("nacos"));
void testCreateToken2() throws AccessException {
assertEquals("token", tokenManagerDelegate.createToken("nacos"));
}
@Test
public void testGetAuthentication() throws AccessException {
Assert.assertNotNull(tokenManagerDelegate.getAuthentication("token"));
void testGetAuthentication() throws AccessException {
assertNotNull(tokenManagerDelegate.getAuthentication("token"));
}
@Test
public void testValidateToken() throws AccessException {
void testValidateToken() throws AccessException {
tokenManagerDelegate.validateToken("token");
}
@Test
public void testParseToken() throws AccessException {
Assert.assertNotNull(tokenManagerDelegate.parseToken("token"));
void testParseToken() throws AccessException {
assertNotNull(tokenManagerDelegate.parseToken("token"));
}
@Test
public void testGetTokenTtlInSeconds() throws AccessException {
Assert.assertTrue(tokenManagerDelegate.getTokenTtlInSeconds("token") > 0);
void testGetTokenTtlInSeconds() throws AccessException {
assertTrue(tokenManagerDelegate.getTokenTtlInSeconds("token") > 0);
}
@Test
public void testGetTokenValidityInSeconds() throws AccessException {
Assert.assertTrue(tokenManagerDelegate.getTokenValidityInSeconds() > 0);
void testGetTokenValidityInSeconds() throws AccessException {
assertTrue(tokenManagerDelegate.getTokenValidityInSeconds() > 0);
}
private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {

View File

@ -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.impl.users.NacosUser;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.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 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.Mockito.when;
@ -36,8 +40,10 @@ import static org.mockito.Mockito.when;
*
* @author Majorhe
*/
@RunWith(MockitoJUnitRunner.class)
public class CachedJwtTokenManagerTest {
@ExtendWith(MockitoExtension.class)
// todo remove this
@MockitoSettings(strictness = Strictness.LENIENT)
class CachedJwtTokenManagerTest {
private CachedJwtTokenManager cachedJwtTokenManager;
@ -50,8 +56,8 @@ public class CachedJwtTokenManagerTest {
@Mock
private NacosUser user;
@Before
public void setUp() throws Exception {
@BeforeEach
void setUp() throws Exception {
cachedJwtTokenManager = new CachedJwtTokenManager();
injectObject("jwtTokenManager", jwtTokenManager);
when(jwtTokenManager.getTokenValidityInSeconds()).thenReturn(100L);
@ -64,38 +70,38 @@ public class CachedJwtTokenManagerTest {
}
@Test
public void testCreateToken1() throws AccessException {
Assert.assertEquals("token", cachedJwtTokenManager.createToken(authentication));
void testCreateToken1() throws AccessException {
assertEquals("token", cachedJwtTokenManager.createToken(authentication));
}
@Test
public void testCreateToken2() throws AccessException {
Assert.assertEquals("token", cachedJwtTokenManager.createToken("nacos"));
void testCreateToken2() throws AccessException {
assertEquals("token", cachedJwtTokenManager.createToken("nacos"));
}
@Test
public void testGetAuthentication() throws AccessException {
Assert.assertNotNull(cachedJwtTokenManager.getAuthentication("token"));
void testGetAuthentication() throws AccessException {
assertNotNull(cachedJwtTokenManager.getAuthentication("token"));
}
@Test
public void testValidateToken() throws AccessException {
void testValidateToken() throws AccessException {
cachedJwtTokenManager.validateToken("token");
}
@Test
public void testParseToken() throws AccessException {
Assert.assertNotNull(cachedJwtTokenManager.parseToken("token"));
void testParseToken() throws AccessException {
assertNotNull(cachedJwtTokenManager.parseToken("token"));
}
@Test
public void testGetTokenTtlInSeconds() throws AccessException {
Assert.assertTrue(cachedJwtTokenManager.getTokenTtlInSeconds("token") > 0);
void testGetTokenTtlInSeconds() throws AccessException {
assertTrue(cachedJwtTokenManager.getTokenTtlInSeconds("token") > 0);
}
@Test
public void testGetTokenValidityInSeconds() {
Assert.assertTrue(cachedJwtTokenManager.getTokenValidityInSeconds() > 0);
void testGetTokenValidityInSeconds() {
assertTrue(cachedJwtTokenManager.getTokenValidityInSeconds() > 0);
}
private void injectObject(String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {

View File

@ -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.jwt.NacosJwtParser;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.security.core.Authentication;
@ -34,39 +33,40 @@ import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
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;
@RunWith(MockitoJUnitRunner.class)
public class JwtTokenManagerTest {
@ExtendWith(MockitoExtension.class)
class JwtTokenManagerTest {
private JwtTokenManager jwtTokenManager;
@Mock
private AuthConfigs authConfigs;
@Before
public void setUp() {
@BeforeEach
void setUp() {
when(authConfigs.isAuthEnabled()).thenReturn(true);
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder().encodeToString(
"SecretKey0123$567890$234567890123456789012345678901234567890123456789"
.getBytes(StandardCharsets.UTF_8)));
mockEnvironment
.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, Base64.getEncoder()
.encodeToString("SecretKey0123$567890$234567890123456789012345678901234567890123456789".getBytes(StandardCharsets.UTF_8)));
mockEnvironment.setProperty(AuthConstants.TOKEN_EXPIRE_SECONDS, AuthConstants.DEFAULT_TOKEN_EXPIRE_SECONDS.toString());
EnvUtil.setEnvironment(mockEnvironment);
jwtTokenManager = new JwtTokenManager(authConfigs);
}
@Test
public void testCreateTokenAndSecretKeyWithoutSpecialSymbol() throws AccessException {
void testCreateTokenAndSecretKeyWithoutSpecialSymbol() throws AccessException {
createToken("SecretKey0123567890234567890123456789012345678901234567890123456789");
}
@Test
public void testCreateTokenAndSecretKeyWithSpecialSymbol() throws AccessException {
void testCreateTokenAndSecretKeyWithSpecialSymbol() throws AccessException {
createToken("SecretKey01234@#!5678901234567890123456789012345678901234567890123456789");
}
@ -74,75 +74,72 @@ public class JwtTokenManagerTest {
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY,
Base64.getEncoder().encodeToString(secretKey.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);
JwtTokenManager jwtTokenManager = new JwtTokenManager(authConfigs);
String nacosToken = jwtTokenManager.createToken("nacos");
Assert.assertNotNull(nacosToken);
assertNotNull(nacosToken);
jwtTokenManager.validateToken(nacosToken);
}
@Test
public void getAuthentication() throws AccessException {
void getAuthentication() throws AccessException {
String nacosToken = jwtTokenManager.createToken("nacos");
Authentication authentication = jwtTokenManager.getAuthentication(nacosToken);
Assert.assertNotNull(authentication);
assertNotNull(authentication);
}
@Test
public void testInvalidSecretKey() {
Assert.assertThrows(IllegalArgumentException.class, () -> createToken("0123456789ABCDEF0123456789ABCDE"));
void testInvalidSecretKey() {
assertThrows(IllegalArgumentException.class, () -> createToken("0123456789ABCDEF0123456789ABCDE"));
}
@Test
public void testGetTokenTtlInSeconds() throws AccessException {
Assert.assertTrue(jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")) > 0);
void testGetTokenTtlInSeconds() throws AccessException {
assertTrue(jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")) > 0);
}
@Test
public void testGetExpiredTimeInSeconds() throws AccessException {
Assert.assertTrue(jwtTokenManager.getExpiredTimeInSeconds(jwtTokenManager.createToken("nacos")) > 0);
void testGetExpiredTimeInSeconds() throws AccessException {
assertTrue(jwtTokenManager.getExpiredTimeInSeconds(jwtTokenManager.createToken("nacos")) > 0);
}
@Test
public void testGetTokenTtlInSecondsWhenAuthDisabled() throws AccessException {
void testGetTokenTtlInSecondsWhenAuthDisabled() throws AccessException {
when(authConfigs.isAuthEnabled()).thenReturn(false);
// valid secret key
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
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, "");
EnvUtil.setEnvironment(mockEnvironment);
jwtTokenManager = new JwtTokenManager(authConfigs);
Assert.assertEquals(Integer.parseInt(ttl), jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")));
assertEquals(Integer.parseInt(ttl), jwtTokenManager.getTokenTtlInSeconds(jwtTokenManager.createToken("nacos")));
}
@Test
public void testCreateTokenWhenDisableAuthAndSecretKeyIsBlank() {
void testCreateTokenWhenDisableAuthAndSecretKeyIsBlank() {
when(authConfigs.isAuthEnabled()).thenReturn(false);
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY, "");
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);
jwtTokenManager = new JwtTokenManager(authConfigs);
assertEquals("AUTH_DISABLED", jwtTokenManager.createToken("nacos"));
}
@Test
public void testCreateTokenWhenDisableAuthAndSecretKeyIsNotBlank() throws AccessException {
void testCreateTokenWhenDisableAuthAndSecretKeyIsNotBlank() throws AccessException {
when(authConfigs.isAuthEnabled()).thenReturn(false);
MockEnvironment mockEnvironment = new MockEnvironment();
String tmpKey = "SecretKey0123567890234567890123456789012345678901234567890123456789";
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY,
Base64.getEncoder().encodeToString(tmpKey.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);
jwtTokenManager = new JwtTokenManager(authConfigs);
String token = jwtTokenManager.createToken("nacos");
@ -151,31 +148,28 @@ public class JwtTokenManagerTest {
}
@Test
public void testNacosJwtParser() throws AccessException {
void testNacosJwtParser() throws AccessException {
String secretKey = "SecretKey0123$567890$234567890123456789012345678901234567890123456789";
MockEnvironment mockEnvironment = new MockEnvironment();
mockEnvironment.setProperty(AuthConstants.TOKEN_SECRET_KEY,
Base64.getEncoder().encodeToString(secretKey.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);
JwtTokenManager jwtTokenManager = new JwtTokenManager(authConfigs);
String nacosToken = jwtTokenManager.createToken("nacos");
Assert.assertNotNull(nacosToken);
assertNotNull(nacosToken);
System.out.println("oldToken: " + nacosToken);
jwtTokenManager.validateToken(nacosToken);
NacosJwtParser nacosJwtParser = new NacosJwtParser(
Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8)));
NacosJwtParser nacosJwtParser = new NacosJwtParser(Base64.getEncoder().encodeToString(secretKey.getBytes(StandardCharsets.UTF_8)));
//check old token
nacosJwtParser.parse(nacosToken);
//create new token
String newToken = nacosJwtParser.jwtBuilder().setUserName("nacos").setExpiredTime(TimeUnit.DAYS.toSeconds(10L))
.compact();
String newToken = nacosJwtParser.jwtBuilder().setUserName("nacos").setExpiredTime(TimeUnit.DAYS.toSeconds(10L)).compact();
System.out.println("newToken: " + newToken);
jwtTokenManager.validateToken(newToken);
}

View File

@ -16,8 +16,9 @@
package com.alibaba.nacos.plugin.auth.impl.utils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/**
* Base64Decoder test.
@ -25,22 +26,22 @@ import org.junit.Test;
* @author xYohn
* @date 2023/8/8
*/
public class Base64DecodeTest {
class Base64DecodeTest {
@Test
public void testStandardDecode() {
void testStandardDecode() {
String origin = "aGVsbG8sbmFjb3MhdGVzdEJhc2U2NGVuY29kZQ==";
String expectDecodeOrigin = "hello,nacos!testBase64encode";
byte[] decodeOrigin = Base64Decode.decode(origin);
Assert.assertArrayEquals(decodeOrigin, expectDecodeOrigin.getBytes());
assertArrayEquals(decodeOrigin, expectDecodeOrigin.getBytes());
}
@Test
public void testNotStandardDecode() {
void testNotStandardDecode() {
String notStandardOrigin = "SecretKey012345678901234567890123456789012345678901234567890123456789";
byte[] decodeNotStandardOrigin = Base64Decode.decode(notStandardOrigin);
String truncationOrigin = "SecretKey01234567890123456789012345678901234567890123456789012345678";
byte[] decodeTruncationOrigin = Base64Decode.decode(truncationOrigin);
Assert.assertArrayEquals(decodeNotStandardOrigin, decodeTruncationOrigin);
assertArrayEquals(decodeNotStandardOrigin, decodeTruncationOrigin);
}
}

View File

@ -16,36 +16,38 @@
package com.alibaba.nacos.plugin.auth.impl.utils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.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.
*
* @ClassName: PasswordEncoderUtilTest
* @Author: ChenHao26
* @Date: 2022/8/17 01:25
*/
public class PasswordEncoderUtilTest {
class PasswordEncoderUtilTest {
/**
* encode test.
*/
@Test
public void encode() {
void encode() {
String str = PasswordEncoderUtil.encode("nacos");
String str2 = PasswordEncoderUtil.encode("nacos");
Assert.assertNotEquals(str2, str);
assertNotEquals(str2, str);
}
@Test
public void matches() {
Boolean result1 = PasswordEncoderUtil.matches("nacos",
"$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXYxhzTmjWGJ21T.WX8thVsw0K2mO");
Assert.assertTrue(result1);
Boolean result2 = PasswordEncoderUtil.matches("nacos",
"$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXcxhzTmjWGJ21T.WX8thVsw0K2mO");
Assert.assertFalse(result2);
void matches() {
Boolean result1 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXYxhzTmjWGJ21T.WX8thVsw0K2mO");
assertTrue(result1);
Boolean result2 = PasswordEncoderUtil.matches("nacos", "$2a$10$MK2dspqy7MKcCU63x8PoI.vTGXcxhzTmjWGJ21T.WX8thVsw0K2mO");
assertFalse(result2);
Boolean matches = PasswordEncoderUtil.matches("nacos", PasswordEncoderUtil.encode("nacos"));
Assert.assertTrue(matches);
assertTrue(matches);
}
}

View File

@ -16,18 +16,19 @@
package com.alibaba.nacos.plugin.auth.impl.utils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class PasswordGeneratorUtilTest {
import static org.junit.jupiter.api.Assertions.assertEquals;
class PasswordGeneratorUtilTest {
/**
* generatePwd test.
*/
@Test
public void generatePwd() {
void generatePwd() {
String pwd = PasswordGeneratorUtil.generateRandomPassword();
Assert.assertEquals(8, pwd.length());
assertEquals(8, pwd.length());
}
}

View File

@ -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.response.ConnectionCheckResponse;
import com.alibaba.nacos.plugin.control.connection.rule.ConnectionControlRule;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.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
public void testApplyConnectionLimitRule() {
void testApplyConnectionLimitRule() {
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
connectionControlRule.setCountLimit(10);
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
ConnectionControlRule connectionLimitRule = nacosConnectionControlManager.getConnectionLimitRule();
Assert.assertEquals(connectionControlRule, connectionLimitRule);
assertEquals(connectionControlRule, connectionLimitRule);
}
@Test
public void testCheckLimit() {
void testCheckLimit() {
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
connectionControlRule.setCountLimit(10);
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test");
ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest);
Assert.assertFalse(connectionCheckResponse.isSuccess());
assertFalse(connectionCheckResponse.isSuccess());
}
@Test
public void testCheckUnLimit() {
void testCheckUnLimit() {
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
connectionControlRule.setCountLimit(30);
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test");
ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest);
Assert.assertTrue(connectionCheckResponse.isSuccess());
assertTrue(connectionCheckResponse.isSuccess());
}
@Test
public void testCheckLimitCountLessThanZero() {
void testCheckLimitCountLessThanZero() {
NacosConnectionControlManager nacosConnectionControlManager = new NacosConnectionControlManager();
ConnectionControlRule connectionControlRule = new ConnectionControlRule();
connectionControlRule.setCountLimit(-1);
nacosConnectionControlManager.applyConnectionLimitRule(connectionControlRule);
ConnectionCheckRequest connectionCheckRequest = new ConnectionCheckRequest("127.0.0.1", "test", "test");
ConnectionCheckResponse connectionCheckResponse = nacosConnectionControlManager.check(connectionCheckRequest);
Assert.assertTrue(connectionCheckResponse.isSuccess());
assertTrue(connectionCheckResponse.isSuccess());
}
}

View File

@ -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.tps.TpsControlManager;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class NacosControlManagerBuilderTest {
import static org.junit.jupiter.api.Assertions.assertEquals;
class NacosControlManagerBuilderTest {
@Test
public void test() {
void test() {
NacosControlManagerBuilder nacosControlManagerBuilder = new NacosControlManagerBuilder();
ConnectionControlManager connectionControlManager = nacosControlManagerBuilder.buildConnectionControlManager();
TpsControlManager tpsControlManager = nacosControlManagerBuilder.buildTpsControlManager();
Assert.assertEquals("nacos", tpsControlManager.getName());
Assert.assertEquals("nacos", connectionControlManager.getName());
Assert.assertEquals("nacos", nacosControlManagerBuilder.getName());
assertEquals("nacos", tpsControlManager.getName());
assertEquals("nacos", connectionControlManager.getName());
assertEquals("nacos", nacosControlManagerBuilder.getName());
}
}

View File

@ -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.rule.RuleDetail;
import com.alibaba.nacos.plugin.control.tps.rule.TpsControlRule;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
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
public void testRegisterTpsPoint1() {
void testRegisterTpsPoint1() {
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
nacosTpsControlManager.registerTpsPoint("test");
Assert.assertTrue(nacosTpsControlManager.getPoints().containsKey("test"));
assertTrue(nacosTpsControlManager.getPoints().containsKey("test"));
}
@Test
public void testRegisterTpsPoint2() {
void testRegisterTpsPoint2() {
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
TpsControlRule tpsLimitRule = new TpsControlRule();
nacosTpsControlManager.applyTpsRule("test", tpsLimitRule);
nacosTpsControlManager.registerTpsPoint("test");
Assert.assertTrue(nacosTpsControlManager.getPoints().containsKey("test"));
assertTrue(nacosTpsControlManager.getPoints().containsKey("test"));
}
@Test
public void testApplyTpsRule1() {
void testApplyTpsRule1() {
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
TpsControlRule tpsLimitRule = new TpsControlRule();
nacosTpsControlManager.applyTpsRule("test", tpsLimitRule);
Assert.assertTrue(nacosTpsControlManager.getRules().containsKey("test"));
assertTrue(nacosTpsControlManager.getRules().containsKey("test"));
}
@Test
public void testApplyTpsRule2() {
void testApplyTpsRule2() {
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
nacosTpsControlManager.applyTpsRule("test", null);
Assert.assertFalse(nacosTpsControlManager.getRules().containsKey("test"));
assertFalse(nacosTpsControlManager.getRules().containsKey("test"));
}
@Test
public void testCheck() {
void testCheck() {
NacosTpsControlManager nacosTpsControlManager = new NacosTpsControlManager();
nacosTpsControlManager.registerTpsPoint("test");
final TpsControlRule tpsLimitRule = new TpsControlRule();
@ -82,6 +84,6 @@ public class NacosTpsControlManagerTest {
tpsCheckRequest.setPointName("test");
tpsCheckRequest.setTimestamp(timeMillis);
TpsCheckResponse check = nacosTpsControlManager.check(tpsCheckRequest);
Assert.assertTrue(check.isSuccess());
assertTrue(check.isSuccess());
}
}