From 084c2a6ad9cff484cbcc72e6a69547c4be523aba Mon Sep 17 00:00:00 2001 From: "shalk(xiao kun)" Date: Fri, 10 May 2024 20:35:34 +0800 Subject: [PATCH 1/5] refact(client): remove junit4 to junit5 --- .../nacos/client/ability/AbilityTest.java | 33 +- .../ClientAbilityControlManagerTest.java | 24 +- .../impl/NacosClientAuthServiceImplTest.java | 69 ++-- .../ram/RamClientAuthServiceImplTest.java | 52 +-- .../ram/identify/CredentialServiceTest.java | 78 ++-- .../ram/identify/CredentialWatcherTest.java | 62 +-- .../auth/ram/identify/CredentialsTest.java | 40 +- .../auth/ram/identify/StsConfigTest.java | 82 ++-- .../ram/identify/StsCredentialHolderTest.java | 73 ++-- .../AbstractResourceInjectorTest.java | 16 +- .../injector/ConfigResourceInjectorTest.java | 86 ++-- .../injector/NamingResourceInjectorTest.java | 88 ++-- .../client/auth/ram/utils/SignUtilTest.java | 34 +- .../auth/ram/utils/SpasAdapterTest.java | 70 ++-- .../client/config/NacosConfigServiceTest.java | 118 +++--- .../client/config/common/GroupKeyTest.java | 94 +++-- .../config/filter/impl/ConfigContextTest.java | 13 +- .../impl/ConfigEncryptionFilterTest.java | 39 +- .../impl/ConfigEncryptionFilterTest1.java | 51 +-- .../impl/ConfigFilterChainManagerTest.java | 25 +- .../filter/impl/ConfigFilterChainTest.java | 15 +- .../config/filter/impl/ConfigRequestTest.java | 40 +- .../filter/impl/ConfigResponseTest.java | 42 +- .../config/http/MetricsHttpAgentTest.java | 38 +- .../config/http/ServerHttpAgentTest.java | 246 ++++++----- .../client/config/impl/CacheDataTest.java | 125 +++--- .../client/config/impl/ClientWorkerTest.java | 194 ++++----- .../config/impl/ConfigChangeHandlerTest.java | 19 +- .../impl/ConfigHttpClientManagerTest.java | 30 +- .../nacos/client/config/impl/LimiterTest.java | 18 +- .../impl/PropertiesChangeParserTest.java | 39 +- .../config/impl/ServerListManagerTest.java | 133 +++--- .../config/impl/YmlChangeParserTest.java | 62 +-- .../AbstractConfigChangeListenerTest.java | 13 +- .../listener/impl/PropertiesListenerTest.java | 36 +- .../client/config/utils/ContentUtilsTest.java | 123 +++--- .../client/config/utils/JvmUtilTest.java | 36 +- .../client/config/utils/ParamUtilsTest.java | 224 +++++----- .../config/utils/SnapShotSwitchTest.java | 18 +- .../client/env/NacosClientPropertiesTest.java | 211 +++++----- .../client/env/SearchablePropertiesTest.java | 56 +-- .../env/SystemEnvPropertySourceTest.java | 46 +-- .../env/convert/CompositeConverterTest.java | 97 +++-- .../client/logging/NacosLoggingTest.java | 34 +- .../NacosNamingMaintainServiceTest.java | 88 ++-- .../client/naming/NacosNamingServiceTest.java | 317 +++++++------- .../naming/backups/FailoverReactorTest.java | 64 +-- .../DiskFailoverDataSourceTest.java | 39 +- .../client/naming/cache/DiskCacheTest.java | 76 ++-- .../naming/cache/ServiceInfoHolderTest.java | 105 ++--- .../client/naming/core/BalancerTest.java | 50 +-- .../client/naming/core/ProtectModeTest.java | 19 +- .../naming/core/ServerListManagerTest.java | 179 ++++---- .../core/ServiceInfoUpdateServiceTest.java | 72 ++-- .../event/InstancesChangeEventTest.java | 23 +- .../event/InstancesChangeNotifierTest.java | 58 +-- .../remote/AbstractNamingClientProxyTest.java | 37 +- .../remote/NamingClientProxyDelegateTest.java | 142 ++++--- .../gprc/NamingGrpcClientProxyTest.java | 330 +++++++-------- .../gprc/NamingPushRequestHandlerTest.java | 19 +- .../gprc/redo/NamingGrpcRedoServiceTest.java | 96 ++--- .../gprc/redo/RedoScheduledTaskTest.java | 82 ++-- .../redo/data/BatchInstanceRedoDataTest.java | 30 +- .../gprc/redo/data/InstanceRedoDataTest.java | 26 +- .../http/NamingHttpClientManagerTest.java | 32 +- .../http/NamingHttpClientProxyTest.java | 387 +++++++++--------- .../client/naming/utils/CacheDirUtilTest.java | 30 +- .../client/naming/utils/ChooserTest.java | 97 ++--- .../naming/utils/CollectionUtilsTest.java | 51 +-- .../naming/utils/ConcurrentDiskUtilTest.java | 94 +++-- .../naming/utils/GenericPollerTest.java | 23 +- .../client/naming/utils/InitUtilsTest.java | 137 ++++--- .../naming/utils/NamingHttpUtilTest.java | 26 +- .../nacos/client/naming/utils/PairTest.java | 15 +- .../client/security/SecurityProxyTest.java | 41 +- .../nacos/client/utils/AppNameUtilsTest.java | 42 +- .../client/utils/ContextPathUtilTest.java | 10 +- .../nacos/client/utils/EnvUtilTest.java | 40 +- .../nacos/client/utils/LogUtilsTest.java | 13 +- .../nacos/client/utils/ParamUtilTest.java | 128 +++--- .../nacos/client/utils/PreInitUtilsTest.java | 8 +- .../nacos/client/utils/StringUtilsTest.java | 36 +- .../nacos/client/utils/TemplateUtilsTest.java | 52 +-- .../nacos/client/utils/TenantUtilTest.java | 27 +- .../client/utils/ValidatorUtilsTest.java | 71 ++-- 85 files changed, 3237 insertions(+), 3017 deletions(-) diff --git a/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java b/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java index e4b53de1097..dbfe68b2db2 100644 --- a/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java @@ -30,21 +30,24 @@ import com.alibaba.nacos.common.remote.client.RpcClientConfig; import com.alibaba.nacos.common.remote.client.ServerListFactory; import com.alibaba.nacos.common.remote.client.ServerRequestHandler; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + import java.util.HashMap; import java.util.List; import java.util.Map; -public class AbilityTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class AbilityTest { private RpcClient rpcClient; private Connection connection; - + @Test - public void testReceive() throws Exception { + void testReceive() throws Exception { rpcClient = new RpcClient(new RpcClientConfig() { @Override public String name() { @@ -127,7 +130,7 @@ public void close() { }; rpcClient.start(); // test not ready - Assert.assertNull(rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1)); + assertNull(rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1)); // test ready rpcClient.serverListFactory(new ServerListFactory() { @@ -149,23 +152,23 @@ public List getServerList() { }); rpcClient.start(); // if connect successfully - Assert.assertEquals(rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - Assert.assertEquals(rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_2), AbilityStatus.NOT_SUPPORTED); + assertEquals(AbilityStatus.SUPPORTED, rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1)); + assertEquals(AbilityStatus.NOT_SUPPORTED, rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_2)); } - - @After - public void testServerRequestAbility() { + + @AfterEach + void testServerRequestAbility() { //test support ServerRequestHandler serverRequestHandler = (request, connection) -> { - Assert.assertEquals(connection.getConnectionAbility(AbilityKey.SERVER_TEST_1), AbilityStatus.SUPPORTED); - Assert.assertEquals(connection.getConnectionAbility(AbilityKey.SERVER_TEST_2), AbilityStatus.NOT_SUPPORTED); + assertEquals(AbilityStatus.SUPPORTED, connection.getConnectionAbility(AbilityKey.SERVER_TEST_1)); + assertEquals(AbilityStatus.NOT_SUPPORTED, connection.getConnectionAbility(AbilityKey.SERVER_TEST_2)); return new Response() { }; }; serverRequestHandler.requestReply(null, connection); // test no ability table serverRequestHandler = (request, connection) -> { - Assert.assertEquals(connection.getConnectionAbility(AbilityKey.SERVER_TEST_1), AbilityStatus.UNKNOWN); + assertEquals(AbilityStatus.UNKNOWN, connection.getConnectionAbility(AbilityKey.SERVER_TEST_1)); return new Response() { }; }; serverRequestHandler.requestReply(null, new TestConnection(new RpcClient.ServerInfo())); diff --git a/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java index c31378f0d75..e82426bdd1f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java @@ -18,34 +18,34 @@ import com.alibaba.nacos.api.ability.constant.AbilityKey; import com.alibaba.nacos.api.ability.constant.AbilityMode; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ClientAbilityControlManagerTest { +class ClientAbilityControlManagerTest { ClientAbilityControlManager clientAbilityControlManager; - - @Before - public void setUp() { + + @BeforeEach + void setUp() { clientAbilityControlManager = new ClientAbilityControlManager(); } - + @Test - public void testInitCurrentNodeAbilities() { + void testInitCurrentNodeAbilities() { Map> actual = clientAbilityControlManager.initCurrentNodeAbilities(); assertEquals(1, actual.size()); assertTrue(actual.containsKey(AbilityMode.SDK_CLIENT)); // Current not define sdk ability. assertEquals(0, actual.get(AbilityMode.SDK_CLIENT).size()); } - + @Test - public void testGetPriority() { + void testGetPriority() { assertEquals(0, clientAbilityControlManager.getPriority()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java index 11fe0ce83c1..17f05311078 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java @@ -20,21 +20,24 @@ import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.param.Header; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class NacosClientAuthServiceImplTest { - +class NacosClientAuthServiceImplTest { + @Test - public void testLoginSuccess() throws Exception { + void testLoginSuccess() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); @@ -53,11 +56,11 @@ public void testLoginSuccess() throws Exception { //when boolean ret = nacosClientAuthService.login(properties); //then - Assert.assertTrue(ret); + assertTrue(ret); } - + @Test - public void testTestLoginFailCode() throws Exception { + void testTestLoginFailCode() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); result.setCode(400); @@ -72,11 +75,11 @@ public void testTestLoginFailCode() throws Exception { nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); boolean ret = nacosClientAuthService.login(properties); - Assert.assertFalse(ret); + assertFalse(ret); } - + @Test - public void testTestLoginFailHttp() throws Exception { + void testTestLoginFailHttp() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); when(nacosRestTemplate.postForm(any(), (Header) any(), any(), any(), any())).thenThrow(new Exception()); Properties properties = new Properties(); @@ -89,12 +92,12 @@ public void testTestLoginFailHttp() throws Exception { nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); boolean ret = nacosClientAuthService.login(properties); - Assert.assertFalse(ret); + assertFalse(ret); } - + @Test - public void testTestLoginServerListSuccess() throws Exception { + void testTestLoginServerListSuccess() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); @@ -112,11 +115,11 @@ public void testTestLoginServerListSuccess() throws Exception { nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); boolean ret = nacosClientAuthService.login(properties); - Assert.assertTrue(ret); + assertTrue(ret); } - + @Test - public void testTestLoginServerListLoginInWindow() throws Exception { + void testTestLoginServerListLoginInWindow() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); @@ -136,12 +139,12 @@ public void testTestLoginServerListLoginInWindow() throws Exception { nacosClientAuthService.login(properties); //then boolean ret = nacosClientAuthService.login(properties); - Assert.assertTrue(ret); + assertTrue(ret); } - + @Test - public void testGetAccessToken() throws Exception { + void testGetAccessToken() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); result.setData("{\"accessToken\":\"abc\",\"tokenTtl\":1000}"); @@ -158,13 +161,13 @@ public void testGetAccessToken() throws Exception { nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); //when - Assert.assertTrue(nacosClientAuthService.login(properties)); + assertTrue(nacosClientAuthService.login(properties)); //then - Assert.assertEquals("abc", nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); + assertEquals("abc", nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); } - + @Test - public void testGetAccessEmptyToken() throws Exception { + void testGetAccessEmptyToken() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); result.setData("{\"accessToken\":\"\",\"tokenTtl\":1000}"); @@ -181,13 +184,13 @@ public void testGetAccessEmptyToken() throws Exception { nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); //when - Assert.assertTrue(nacosClientAuthService.login(properties)); + assertTrue(nacosClientAuthService.login(properties)); //then - Assert.assertEquals("", nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); + assertEquals("", nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); } - + @Test - public void testGetAccessTokenWithoutToken() throws Exception { + void testGetAccessTokenWithoutToken() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); result.setData("{\"tokenTtl\":1000}"); @@ -204,13 +207,13 @@ public void testGetAccessTokenWithoutToken() throws Exception { nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); //when - Assert.assertTrue(nacosClientAuthService.login(properties)); + assertTrue(nacosClientAuthService.login(properties)); //then - Assert.assertNull(nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); + assertNull(nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); } - + @Test - public void testGetAccessTokenWithInvalidTtl() throws Exception { + void testGetAccessTokenWithInvalidTtl() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult result = new HttpRestResult<>(); result.setData("{\"accessToken\":\"abc\",\"tokenTtl\":\"abc\"}"); @@ -227,6 +230,6 @@ public void testGetAccessTokenWithInvalidTtl() throws Exception { nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); //when - Assert.assertFalse(nacosClientAuthService.login(properties)); + assertFalse(nacosClientAuthService.login(properties)); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java index 6613a62ef6d..9cf1c7dda6d 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java @@ -21,23 +21,23 @@ import com.alibaba.nacos.client.auth.ram.injector.AbstractResourceInjector; import com.alibaba.nacos.plugin.auth.api.RequestResource; import com.alibaba.nacos.common.utils.ReflectUtils; -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.util.Map; import java.util.Properties; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -@RunWith(MockitoJUnitRunner.class) -public class RamClientAuthServiceImplTest { +@ExtendWith(MockitoExtension.class) +class RamClientAuthServiceImplTest { private static final String MOCK = "mock"; @@ -53,9 +53,9 @@ public class RamClientAuthServiceImplTest { private RamContext ramContext; private RequestResource resource; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { ramClientAuthService = new RamClientAuthServiceImpl(); Map resourceInjectors = (Map) ReflectUtils .getFieldValue(ramClientAuthService, "resourceInjectors"); @@ -69,9 +69,9 @@ public void setUp() throws Exception { roleProperties.setProperty(PropertyKeyConst.RAM_ROLE_NAME, PropertyKeyConst.RAM_ROLE_NAME); resource = new RequestResource(); } - + @Test - public void testLoginWithAkSk() { + void testLoginWithAkSk() { assertTrue(ramClientAuthService.login(akSkProperties)); assertEquals(PropertyKeyConst.ACCESS_KEY, ramContext.getAccessKey()); assertEquals(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey()); @@ -81,36 +81,36 @@ public void testLoginWithAkSk() { assertEquals(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey()); assertNull(ramContext.getRamRoleName()); } - + @Test - public void testLoginWithRoleName() { + void testLoginWithRoleName() { assertTrue(ramClientAuthService.login(roleProperties)); - assertNull(PropertyKeyConst.ACCESS_KEY, ramContext.getAccessKey()); - assertNull(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey()); + assertNull(ramContext.getAccessKey(), PropertyKeyConst.ACCESS_KEY); + assertNull(ramContext.getSecretKey(), PropertyKeyConst.SECRET_KEY); assertEquals(PropertyKeyConst.RAM_ROLE_NAME, ramContext.getRamRoleName()); assertTrue(ramClientAuthService.login(akSkProperties)); - assertNull(PropertyKeyConst.ACCESS_KEY, ramContext.getAccessKey()); - assertNull(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey()); + assertNull(ramContext.getAccessKey(), PropertyKeyConst.ACCESS_KEY); + assertNull(ramContext.getSecretKey(), PropertyKeyConst.SECRET_KEY); assertEquals(PropertyKeyConst.RAM_ROLE_NAME, ramContext.getRamRoleName()); } - + @Test - public void testGetLoginIdentityContextWithoutLogin() { + void testGetLoginIdentityContextWithoutLogin() { LoginIdentityContext actual = ramClientAuthService.getLoginIdentityContext(resource); assertTrue(actual.getAllKey().isEmpty()); verify(mockResourceInjector, never()).doInject(resource, ramContext, actual); } - + @Test - public void testGetLoginIdentityContextWithoutInjector() { + void testGetLoginIdentityContextWithoutInjector() { ramClientAuthService.login(akSkProperties); LoginIdentityContext actual = ramClientAuthService.getLoginIdentityContext(resource); assertTrue(actual.getAllKey().isEmpty()); verify(mockResourceInjector, never()).doInject(resource, ramContext, actual); } - + @Test - public void testGetLoginIdentityContextWithInjector() { + void testGetLoginIdentityContextWithInjector() { ramClientAuthService.login(akSkProperties); resource.setType(MOCK); LoginIdentityContext actual = ramClientAuthService.getLoginIdentityContext(resource); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java index 0e371c64749..0eb3b1a3965 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java @@ -18,49 +18,49 @@ package com.alibaba.nacos.client.auth.ram.identify; -import junit.framework.TestCase; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class CredentialServiceTest extends TestCase { +class CredentialServiceTest { private static final String APP_NAME = "app"; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { System.clearProperty(IdentifyConstants.PROJECT_NAME_PROPERTY); CredentialService.freeInstance(); CredentialService.freeInstance(APP_NAME); } - + @Test - public void testGetInstance() { + void testGetInstance() { CredentialService credentialService1 = CredentialService.getInstance(); CredentialService credentialService2 = CredentialService.getInstance(); - Assert.assertEquals(credentialService1, credentialService2); + assertEquals(credentialService1, credentialService2); } - + @Test - public void testGetInstance2() { + void testGetInstance2() { CredentialService credentialService1 = CredentialService.getInstance(APP_NAME); CredentialService credentialService2 = CredentialService.getInstance(APP_NAME); - Assert.assertEquals(credentialService1, credentialService2); + assertEquals(credentialService1, credentialService2); } - + @Test - public void testGetInstance3() throws NoSuchFieldException, IllegalAccessException { + void testGetInstance3() throws NoSuchFieldException, IllegalAccessException { System.setProperty(IdentifyConstants.PROJECT_NAME_PROPERTY, APP_NAME); CredentialService credentialService1 = CredentialService.getInstance(); Field appNameField = credentialService1.getClass().getDeclaredField("appName"); @@ -68,23 +68,23 @@ public void testGetInstance3() throws NoSuchFieldException, IllegalAccessExcepti String appName = (String) appNameField.get(credentialService1); assertEquals(APP_NAME, appName); } - + @Test - public void testFreeInstance() { + void testFreeInstance() { CredentialService credentialService1 = CredentialService.getInstance(); CredentialService credentialService2 = CredentialService.freeInstance(); - Assert.assertEquals(credentialService1, credentialService2); + assertEquals(credentialService1, credentialService2); } - + @Test - public void testFreeInstance2() { + void testFreeInstance2() { CredentialService credentialService1 = CredentialService.getInstance(); CredentialService credentialService2 = CredentialService.freeInstance(); - Assert.assertEquals(credentialService1, credentialService2); + assertEquals(credentialService1, credentialService2); } - + @Test - public void testFree() throws NoSuchFieldException, IllegalAccessException { + void testFree() throws NoSuchFieldException, IllegalAccessException { CredentialService credentialService1 = CredentialService.getInstance(); CredentialWatcher mockWatcher = mock(CredentialWatcher.class); Field watcherField = CredentialService.class.getDeclaredField("watcher"); @@ -95,26 +95,26 @@ public void testFree() throws NoSuchFieldException, IllegalAccessException { //then verify(mockWatcher, times(1)).stop(); } - + @Test - public void testGetCredential() { + void testGetCredential() { CredentialService credentialService1 = CredentialService.getInstance(); Credentials credential = credentialService1.getCredential(); - Assert.assertNotNull(credential); + assertNotNull(credential); } - + @Test - public void testSetCredential() { + void testSetCredential() { CredentialService credentialService1 = CredentialService.getInstance(); Credentials credential = new Credentials(); //when credentialService1.setCredential(credential); //then - Assert.assertEquals(credential, credentialService1.getCredential()); + assertEquals(credential, credentialService1.getCredential()); } - + @Test - public void testSetStaticCredential() throws NoSuchFieldException, IllegalAccessException { + void testSetStaticCredential() throws NoSuchFieldException, IllegalAccessException { CredentialService credentialService1 = CredentialService.getInstance(); CredentialWatcher mockWatcher = mock(CredentialWatcher.class); Field watcherField = CredentialService.class.getDeclaredField("watcher"); @@ -124,12 +124,12 @@ public void testSetStaticCredential() throws NoSuchFieldException, IllegalAccess //when credentialService1.setStaticCredential(credential); //then - Assert.assertEquals(credential, credentialService1.getCredential()); + assertEquals(credential, credentialService1.getCredential()); verify(mockWatcher, times(1)).stop(); } - + @Test - public void testRegisterCredentialListener() { + void testRegisterCredentialListener() { CredentialListener expect = mock(CredentialListener.class); CredentialService credentialService1 = CredentialService.getInstance(); credentialService1.registerCredentialListener(expect); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java index c99077b05af..6e3a11d559b 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java @@ -16,13 +16,12 @@ package com.alibaba.nacos.client.auth.ram.identify; -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.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.BufferedWriter; import java.io.File; @@ -39,16 +38,17 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class CredentialWatcherTest { +@ExtendWith(MockitoExtension.class) +class CredentialWatcherTest { @Mock private CredentialService credentialService; @@ -58,9 +58,9 @@ public class CredentialWatcherTest { private Method loadCredentialMethod; private Method loadCredentialFromPropertiesMethod; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { credentialWatcher = new CredentialWatcher("testApp", credentialService); loadCredentialMethod = CredentialWatcher.class.getDeclaredMethod("loadCredential", boolean.class); loadCredentialMethod.setAccessible(true); @@ -68,27 +68,27 @@ public void setUp() throws Exception { .getDeclaredMethod("loadCredentialFromProperties", InputStream.class, boolean.class, Credentials.class); loadCredentialFromPropertiesMethod.setAccessible(true); } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { credentialWatcher.stop(); System.clearProperty("spas.identity"); System.clearProperty(IdentifyConstants.ENV_ACCESS_KEY); System.clearProperty(IdentifyConstants.ENV_SECRET_KEY); CredentialService.freeInstance(); } - + @Test - public void testStop() throws NoSuchFieldException, IllegalAccessException { + void testStop() throws NoSuchFieldException, IllegalAccessException { credentialWatcher.stop(); Field executorField = CredentialWatcher.class.getDeclaredField("executor"); executorField.setAccessible(true); ScheduledExecutorService executor = (ScheduledExecutorService) executorField.get(credentialWatcher); - Assert.assertTrue(executor.isShutdown()); + assertTrue(executor.isShutdown()); } - + @Test - public void testLoadCredentialByEnv() throws InvocationTargetException, IllegalAccessException { + void testLoadCredentialByEnv() throws InvocationTargetException, IllegalAccessException { System.setProperty(IdentifyConstants.ENV_ACCESS_KEY, "testAk"); System.setProperty(IdentifyConstants.ENV_SECRET_KEY, "testSk"); final AtomicReference readAk = new AtomicReference<>(""); @@ -106,9 +106,9 @@ public void testLoadCredentialByEnv() throws InvocationTargetException, IllegalA assertEquals("testSk", readSK.get()); assertNull(readTenantId.get()); } - + @Test - public void testLoadCredentialByIdentityFile() throws InvocationTargetException, IllegalAccessException { + void testLoadCredentialByIdentityFile() throws InvocationTargetException, IllegalAccessException { URL url = CredentialWatcherTest.class.getResource("/spas.identity"); System.setProperty("spas.identity", url.getPath()); final AtomicReference readAk = new AtomicReference<>(""); @@ -126,9 +126,9 @@ public void testLoadCredentialByIdentityFile() throws InvocationTargetException, assertEquals("testSk", readSK.get()); assertEquals("testTenantId", readTenantId.get()); } - + @Test - public void testLoadCredentialByInvalidIdentityFile() throws InvocationTargetException, IllegalAccessException { + void testLoadCredentialByInvalidIdentityFile() throws InvocationTargetException, IllegalAccessException { URL url = CredentialWatcherTest.class.getResource("/spas_invalid.identity"); System.setProperty("spas.identity", url.getPath()); final AtomicReference readAk = new AtomicReference<>(""); @@ -146,12 +146,12 @@ public void testLoadCredentialByInvalidIdentityFile() throws InvocationTargetExc assertEquals("testSk", readSK.get()); assertEquals("testTenantId", readTenantId.get()); } - + /** * The docker file is need /etc permission, which depend environment. So use mock InputStream to test. */ @Test - public void testLoadCredentialByDockerFile() + void testLoadCredentialByDockerFile() throws FileNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { URL url = CredentialWatcherTest.class.getResource("/spas_docker.identity"); InputStream propertiesIS = new FileInputStream(url.getPath()); @@ -164,9 +164,9 @@ public void testLoadCredentialByDockerFile() assertEquals("testSk", actual.getSecretKey()); assertEquals("testTenantId", actual.getTenantId()); } - + @Test - public void testLoadCredentialByFileWithIoException() + void testLoadCredentialByFileWithIoException() throws IOException, InvocationTargetException, IllegalAccessException { InputStream propertiesIS = mock(InputStream.class); when(propertiesIS.read(any())).thenThrow(new IOException("test")); @@ -177,9 +177,9 @@ public void testLoadCredentialByFileWithIoException() assertNull(actual.getSecretKey()); assertNull(actual.getTenantId()); } - + @Test - public void testReLoadCredential() + void testReLoadCredential() throws InvocationTargetException, IllegalAccessException, InterruptedException { URL url = CredentialWatcherTest.class.getResource("/spas_modified.identity"); modifiedFile(url, true); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java index 919aacf0582..bf236ee0422 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java @@ -18,26 +18,28 @@ package com.alibaba.nacos.client.auth.ram.identify; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CredentialsTest { -public class CredentialsTest { - @Test - public void testGetter() { + void testGetter() { // given String ak = "ak"; String sk = "sk"; String tenantId = "100"; Credentials credentials = new Credentials(ak, sk, tenantId); // when then - Assert.assertEquals(ak, credentials.getAccessKey()); - Assert.assertEquals(sk, credentials.getSecretKey()); - Assert.assertEquals(tenantId, credentials.getTenantId()); + assertEquals(ak, credentials.getAccessKey()); + assertEquals(sk, credentials.getSecretKey()); + assertEquals(tenantId, credentials.getTenantId()); } - + @Test - public void testSetter() { + void testSetter() { //given String ak = "ak"; String sk = "sk"; @@ -48,13 +50,13 @@ public void testSetter() { credentials.setSecretKey(sk); credentials.setTenantId(tenantId); //then - Assert.assertEquals(ak, credentials.getAccessKey()); - Assert.assertEquals(sk, credentials.getSecretKey()); - Assert.assertEquals(tenantId, credentials.getTenantId()); + assertEquals(ak, credentials.getAccessKey()); + assertEquals(sk, credentials.getSecretKey()); + assertEquals(tenantId, credentials.getTenantId()); } - + @Test - public void testValid() { + void testValid() { //given String ak = "ak"; String sk = "sk"; @@ -63,11 +65,11 @@ public void testValid() { //when boolean actual = credentials.valid(); //then - Assert.assertTrue(actual); + assertTrue(actual); } - + @Test - public void testIdentical() { + void testIdentical() { //given String ak = "ak"; String sk = "sk"; @@ -77,6 +79,6 @@ public void testIdentical() { //then boolean actual = credentials1.identical(credentials2); //then - Assert.assertTrue(actual); + assertTrue(actual); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsConfigTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsConfigTest.java index fdfa26070da..c735f04aca1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsConfigTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsConfigTest.java @@ -16,17 +16,21 @@ package com.alibaba.nacos.client.auth.ram.identify; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -public class StsConfigTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class StsConfigTest { - @After - public void after() { + private static void resetStsConfig() { StsConfig.getInstance().setRamRoleName(null); StsConfig.getInstance().setTimeToRefreshInMillisecond(3 * 60 * 1000); StsConfig.getInstance().setCacheSecurityCredentials(true); @@ -39,73 +43,83 @@ public void after() { System.clearProperty(IdentifyConstants.SECURITY_CACHE_PROPERTY); } + @BeforeEach + void before() { + resetStsConfig(); + } + + @AfterEach + void after() { + resetStsConfig(); + } + @Test - public void testGetInstance() { + void testGetInstance() { StsConfig instance1 = StsConfig.getInstance(); StsConfig instance2 = StsConfig.getInstance(); - Assert.assertEquals(instance1, instance2); + assertEquals(instance1, instance2); } @Test - public void testGetRamRoleName() { + void testGetRamRoleName() { StsConfig.getInstance().setRamRoleName("test"); - Assert.assertEquals("test", StsConfig.getInstance().getRamRoleName()); + assertEquals("test", StsConfig.getInstance().getRamRoleName()); } @Test - public void testGetTimeToRefreshInMillisecond() { - Assert.assertEquals(3 * 60 * 1000, StsConfig.getInstance().getTimeToRefreshInMillisecond()); + void testGetTimeToRefreshInMillisecond() { + assertEquals(3 * 60 * 1000, StsConfig.getInstance().getTimeToRefreshInMillisecond()); StsConfig.getInstance().setTimeToRefreshInMillisecond(3000); - Assert.assertEquals(3000, StsConfig.getInstance().getTimeToRefreshInMillisecond()); + assertEquals(3000, StsConfig.getInstance().getTimeToRefreshInMillisecond()); } @Test - public void testGetSecurityCredentialsUrl() { - Assert.assertNull(StsConfig.getInstance().getSecurityCredentialsUrl()); + void testGetSecurityCredentialsUrl() { + assertNull(StsConfig.getInstance().getSecurityCredentialsUrl()); String expect = "localhost"; StsConfig.getInstance().setSecurityCredentialsUrl(expect); - Assert.assertEquals(expect, StsConfig.getInstance().getSecurityCredentialsUrl()); + assertEquals(expect, StsConfig.getInstance().getSecurityCredentialsUrl()); } @Test - public void testGetSecurityCredentialsUrlDefault() { + void testGetSecurityCredentialsUrlDefault() { StsConfig.getInstance().setRamRoleName("test"); - Assert.assertEquals("http://100.100.100.200/latest/meta-data/ram/security-credentials/test", + assertEquals("http://100.100.100.200/latest/meta-data/ram/security-credentials/test", StsConfig.getInstance().getSecurityCredentialsUrl()); } @Test - public void testGetSecurityCredentials() { - Assert.assertNull(StsConfig.getInstance().getSecurityCredentials()); + void testGetSecurityCredentials() { + assertNull(StsConfig.getInstance().getSecurityCredentials()); String expect = "abc"; StsConfig.getInstance().setSecurityCredentials(expect); - Assert.assertEquals(expect, StsConfig.getInstance().getSecurityCredentials()); + assertEquals(expect, StsConfig.getInstance().getSecurityCredentials()); } @Test - public void testIsCacheSecurityCredentials() { - Assert.assertTrue(StsConfig.getInstance().isCacheSecurityCredentials()); + void testIsCacheSecurityCredentials() { + assertTrue(StsConfig.getInstance().isCacheSecurityCredentials()); StsConfig.getInstance().setCacheSecurityCredentials(false); - Assert.assertFalse(StsConfig.getInstance().isCacheSecurityCredentials()); + assertFalse(StsConfig.getInstance().isCacheSecurityCredentials()); } @Test - public void testIsOnFalse() { + void testIsOnFalse() { boolean stsOn = StsConfig.getInstance().isStsOn(); - Assert.assertFalse(stsOn); + assertFalse(stsOn); } @Test - public void testIsOnTrue() { + void testIsOnTrue() { StsConfig.getInstance().setSecurityCredentials("abc"); boolean stsOn = StsConfig.getInstance().isStsOn(); - Assert.assertTrue(stsOn); + assertTrue(stsOn); } @Test - public void testFromEnv() + void testFromEnv() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor constructor = StsConfig.class.getDeclaredConstructor(); constructor.setAccessible(true); @@ -115,11 +129,11 @@ public void testFromEnv() System.setProperty(IdentifyConstants.SECURITY_URL_PROPERTY, "localhost"); System.setProperty(IdentifyConstants.SECURITY_CACHE_PROPERTY, "false"); StsConfig stsConfig = constructor.newInstance(); - Assert.assertEquals("test", stsConfig.getRamRoleName()); - Assert.assertEquals(3000, stsConfig.getTimeToRefreshInMillisecond()); - Assert.assertEquals("abc", stsConfig.getSecurityCredentials()); - Assert.assertEquals("localhost", stsConfig.getSecurityCredentialsUrl()); - Assert.assertFalse(stsConfig.isCacheSecurityCredentials()); + assertEquals("test", stsConfig.getRamRoleName()); + assertEquals(3000, stsConfig.getTimeToRefreshInMillisecond()); + assertEquals("abc", stsConfig.getSecurityCredentials()); + assertEquals("localhost", stsConfig.getSecurityCredentialsUrl()); + assertFalse(stsConfig.isCacheSecurityCredentials()); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java index 6cbd2744ceb..ef3641baf16 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java @@ -23,24 +23,25 @@ import com.alibaba.nacos.common.http.client.response.HttpClientResponse; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.utils.JacksonUtils; -import org.junit.After; -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.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.ByteArrayInputStream; import java.lang.reflect.Field; import java.util.Date; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class StsCredentialHolderTest { +@ExtendWith(MockitoExtension.class) +class StsCredentialHolderTest { private String securityCredentialsUrl; @@ -48,9 +49,9 @@ public class StsCredentialHolderTest { @Mock private HttpClientRequest mockRest; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { securityCredentialsUrl = StsConfig.getInstance().getSecurityCredentialsUrl(); StsConfig.getInstance().setSecurityCredentialsUrl("url"); Field field = NacosRestTemplate.class.getDeclaredField("requestClient"); @@ -58,9 +59,9 @@ public void setUp() throws Exception { httpClient = (HttpClientRequest) field.get(ConfigHttpClientManager.getInstance().getNacosRestTemplate()); field.set(ConfigHttpClientManager.getInstance().getNacosRestTemplate(), mockRest); } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { StsConfig.getInstance().setSecurityCredentials(null); StsConfig.getInstance().setSecurityCredentialsUrl(securityCredentialsUrl); Field field = NacosRestTemplate.class.getDeclaredField("requestClient"); @@ -75,9 +76,9 @@ private void clearForSts() throws NoSuchFieldException, IllegalAccessException { field.setAccessible(true); field.set(StsCredentialHolder.getInstance(), null); } - + @Test - public void testGetStsCredentialFromCache() throws NoSuchFieldException, IllegalAccessException { + void testGetStsCredentialFromCache() throws NoSuchFieldException, IllegalAccessException { StsCredential stsCredential = buildMockStsCredential(); setStsCredential(stsCredential); assertEquals(stsCredential, StsCredentialHolder.getInstance().getStsCredential()); @@ -88,16 +89,16 @@ private void setStsCredential(StsCredential stsCredential) throws NoSuchFieldExc field.setAccessible(true); field.set(StsCredentialHolder.getInstance(), stsCredential); } - + @Test - public void testGetStsCredentialFromStringCache() throws NoSuchFieldException, IllegalAccessException { + void testGetStsCredentialFromStringCache() throws NoSuchFieldException, IllegalAccessException { StsCredential stsCredential = buildMockStsCredential(); StsConfig.getInstance().setSecurityCredentials(JacksonUtils.toJson(stsCredential)); assertEquals(stsCredential.toString(), StsCredentialHolder.getInstance().getStsCredential().toString()); } - + @Test - public void testGetStsCredentialFromRequest() throws Exception { + void testGetStsCredentialFromRequest() throws Exception { StsCredential stsCredential = buildMockStsCredential(); HttpClientResponse response = mock(HttpClientResponse.class); when(response.getStatusCode()).thenReturn(200); @@ -106,21 +107,25 @@ public void testGetStsCredentialFromRequest() throws Exception { when(mockRest.execute(any(), any(), any())).thenReturn(response); assertEquals(stsCredential.toString(), StsCredentialHolder.getInstance().getStsCredential().toString()); } - - @Test(expected = NacosRuntimeException.class) - public void testGetStsCredentialFromRequestFailure() throws Exception { - HttpClientResponse response = mock(HttpClientResponse.class); - when(response.getStatusCode()).thenReturn(500); - when(response.getHeaders()).thenReturn(Header.newInstance()); - when(response.getBody()).thenReturn(new ByteArrayInputStream(new byte[0])); - when(mockRest.execute(any(), any(), any())).thenReturn(response); - StsCredentialHolder.getInstance().getStsCredential(); + + @Test + void testGetStsCredentialFromRequestFailure() throws Exception { + assertThrows(NacosRuntimeException.class, () -> { + HttpClientResponse response = mock(HttpClientResponse.class); + when(response.getStatusCode()).thenReturn(500); + when(response.getHeaders()).thenReturn(Header.newInstance()); + when(response.getBody()).thenReturn(new ByteArrayInputStream(new byte[0])); + when(mockRest.execute(any(), any(), any())).thenReturn(response); + StsCredentialHolder.getInstance().getStsCredential(); + }); } - - @Test(expected = NacosRuntimeException.class) - public void testGetStsCredentialFromRequestException() throws Exception { - when(mockRest.execute(any(), any(), any())).thenThrow(new RuntimeException("test")); - StsCredentialHolder.getInstance().getStsCredential(); + + @Test + void testGetStsCredentialFromRequestException() throws Exception { + assertThrows(NacosRuntimeException.class, () -> { + when(mockRest.execute(any(), any(), any())).thenThrow(new RuntimeException("test")); + StsCredentialHolder.getInstance().getStsCredential(); + }); } private StsCredential buildMockStsCredential() { diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java index ac11121e8c4..94d6721023a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java @@ -16,23 +16,23 @@ package com.alibaba.nacos.client.auth.ram.injector; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class AbstractResourceInjectorTest { +class AbstractResourceInjectorTest { AbstractResourceInjector injector; - - @Before - public void setUp() { + + @BeforeEach + void setUp() { injector = new AbstractResourceInjector() { }; } - + /** * TODO, fill test case after AbstractResourceInjector include default logic. */ @Test - public void testDoInject() { + void testDoInject() { injector.doInject(null, null, null); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java index 13a1c742143..41402273f80 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java @@ -25,15 +25,17 @@ import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; import com.alibaba.nacos.plugin.auth.api.RequestResource; import com.alibaba.nacos.plugin.auth.constant.SignType; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Date; -public class ConfigResourceInjectorTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ConfigResourceInjectorTest { private ConfigResourceInjector configResourceInjector; @@ -46,9 +48,9 @@ public class ConfigResourceInjectorTest { private String cachedSecurityCredentials; private StsCredential stsCredential; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { configResourceInjector = new ConfigResourceInjector(); ramContext = new RamContext(); ramContext.setAccessKey(PropertyKeyConst.ACCESS_KEY); @@ -63,67 +65,67 @@ public void setUp() throws Exception { StsConfig.getInstance().setSecurityCredentials(""); stsCredential = new StsCredential(); } - - @After - public void tearDown() throws NoSuchFieldException, IllegalAccessException { + + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { StsConfig.getInstance().setSecurityCredentialsUrl(cachedSecurityCredentialsUrl); StsConfig.getInstance().setSecurityCredentials(cachedSecurityCredentials); clearForSts(); } - + @Test - public void testDoInjectWithFullResource() throws Exception { + void testDoInjectWithFullResource() throws Exception { LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); - Assert.assertTrue(actual.getAllKey().contains("Timestamp")); - Assert.assertTrue(actual.getAllKey().contains("Spas-Signature")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); } - + @Test - public void testDoInjectWithTenant() throws Exception { + void testDoInjectWithTenant() throws Exception { resource.setGroup(""); LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); - Assert.assertTrue(actual.getAllKey().contains("Timestamp")); - Assert.assertTrue(actual.getAllKey().contains("Spas-Signature")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); } - + @Test - public void testDoInjectWithGroup() throws Exception { + void testDoInjectWithGroup() throws Exception { resource.setNamespace(""); LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); - Assert.assertTrue(actual.getAllKey().contains("Timestamp")); - Assert.assertTrue(actual.getAllKey().contains("Spas-Signature")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); } - + @Test - public void testDoInjectWithoutResource() throws Exception { + void testDoInjectWithoutResource() throws Exception { resource = new RequestResource(); LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); - Assert.assertTrue(actual.getAllKey().contains("Timestamp")); - Assert.assertTrue(actual.getAllKey().contains("Spas-Signature")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("Spas-AccessKey")); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); } - + @Test - public void testDoInjectForSts() throws NoSuchFieldException, IllegalAccessException { + void testDoInjectForSts() throws NoSuchFieldException, IllegalAccessException { prepareForSts(); LoginIdentityContext actual = new LoginIdentityContext(); configResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(4, actual.getAllKey().size()); - Assert.assertEquals("test-sts-ak", actual.getParameter("Spas-AccessKey")); - Assert.assertTrue(actual.getAllKey().contains("Timestamp")); - Assert.assertTrue(actual.getAllKey().contains("Spas-Signature")); - Assert.assertTrue(actual.getAllKey().contains(IdentifyConstants.SECURITY_TOKEN_HEADER)); + assertEquals(4, actual.getAllKey().size()); + assertEquals("test-sts-ak", actual.getParameter("Spas-AccessKey")); + assertTrue(actual.getAllKey().contains("Timestamp")); + assertTrue(actual.getAllKey().contains("Spas-Signature")); + assertTrue(actual.getAllKey().contains(IdentifyConstants.SECURITY_TOKEN_HEADER)); } private void prepareForSts() throws NoSuchFieldException, IllegalAccessException { diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java index 9c51266e8ce..ad721cd4436 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java @@ -24,15 +24,17 @@ import com.alibaba.nacos.client.auth.ram.utils.SignUtil; import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; import com.alibaba.nacos.plugin.auth.api.RequestResource; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Date; -public class NamingResourceInjectorTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class NamingResourceInjectorTest { private NamingResourceInjector namingResourceInjector; @@ -41,9 +43,9 @@ public class NamingResourceInjectorTest { private RequestResource resource; private StsCredential stsCredential; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { namingResourceInjector = new NamingResourceInjector(); ramContext = new RamContext(); ramContext.setAccessKey(PropertyKeyConst.ACCESS_KEY); @@ -51,82 +53,82 @@ public void setUp() throws Exception { stsCredential = new StsCredential(); StsConfig.getInstance().setRamRoleName(null); } - - @After - public void tearDown() throws NoSuchFieldException, IllegalAccessException { + + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { clearForSts(); } - + @Test - public void testDoInjectWithEmpty() throws Exception { + void testDoInjectWithEmpty() throws Exception { resource = RequestResource.namingBuilder().setResource("").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); - Assert.assertTrue(Long.parseLong(actual.getParameter("data")) - System.currentTimeMillis() < 100); - Assert.assertEquals(expectSign, actual.getParameter("signature")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); + assertTrue(Long.parseLong(actual.getParameter("data")) - System.currentTimeMillis() < 100); + assertEquals(expectSign, actual.getParameter("signature")); } @Test - public void testDoInjectWithGroup() throws Exception { + void testDoInjectWithGroup() throws Exception { resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); - Assert.assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); - Assert.assertEquals(expectSign, actual.getParameter("signature")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); + assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); + assertEquals(expectSign, actual.getParameter("signature")); } - + @Test - public void testDoInjectWithoutGroup() throws Exception { + void testDoInjectWithoutGroup() throws Exception { resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); - Assert.assertTrue(actual.getParameter("data").endsWith("@@group@@aaa")); - Assert.assertEquals(3, actual.getAllKey().size()); - Assert.assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); + assertTrue(actual.getParameter("data").endsWith("@@group@@aaa")); + assertEquals(3, actual.getAllKey().size()); + assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); - Assert.assertEquals(expectSign, actual.getParameter("signature")); + assertEquals(expectSign, actual.getParameter("signature")); } - + @Test - public void testDoInjectWithGroupForSts() throws Exception { + void testDoInjectWithGroupForSts() throws Exception { prepareForSts(); resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); String expectSign = SignUtil.sign(actual.getParameter("data"), "test-sts-sk"); - Assert.assertEquals(4, actual.getAllKey().size()); - Assert.assertEquals("test-sts-ak", actual.getParameter("ak")); - Assert.assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); - Assert.assertEquals(expectSign, actual.getParameter("signature")); + assertEquals(4, actual.getAllKey().size()); + assertEquals("test-sts-ak", actual.getParameter("ak")); + assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); + assertEquals(expectSign, actual.getParameter("signature")); } - + @Test - public void testDoInjectWithoutGroupForSts() throws Exception { + void testDoInjectWithoutGroupForSts() throws Exception { prepareForSts(); resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); String expectSign = SignUtil.sign(actual.getParameter("data"), "test-sts-sk"); - Assert.assertEquals(4, actual.getAllKey().size()); - Assert.assertEquals("test-sts-ak", actual.getParameter("ak")); - Assert.assertTrue(actual.getParameter("data").endsWith("@@group@@aaa")); - Assert.assertEquals(expectSign, actual.getParameter("signature")); + assertEquals(4, actual.getAllKey().size()); + assertEquals("test-sts-ak", actual.getParameter("ak")); + assertTrue(actual.getParameter("data").endsWith("@@group@@aaa")); + assertEquals(expectSign, actual.getParameter("signature")); } - + @Test - public void testDoInjectForStsWithException() throws Exception { + void testDoInjectForStsWithException() throws Exception { prepareForSts(); stsCredential.setExpiration(new Date()); resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); - Assert.assertEquals(0, actual.getAllKey().size()); + assertEquals(0, actual.getAllKey().size()); } private void prepareForSts() throws NoSuchFieldException, IllegalAccessException { diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java index 01141a40d2e..dc130aeacdf 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java @@ -16,26 +16,32 @@ package com.alibaba.nacos.client.auth.ram.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; -public class SignUtilTest { - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SignUtilTest { + @Test - public void testSign() throws Exception { + void testSign() throws Exception { String actual = SignUtil.sign("aaa", "b"); - Assert.assertEquals("DxyaKScrqL26yXYOuHXE3OwfQ0Y=", actual); + assertEquals("DxyaKScrqL26yXYOuHXE3OwfQ0Y=", actual); } - - @Test(expected = Exception.class) - public void testSignWithException() throws Exception { - SignUtil.sign(null, "b"); + + @Test + void testSignWithException() throws Exception { + assertThrows(Exception.class, () -> { + SignUtil.sign(null, "b"); + }); } - - @Test(expected = Exception.class) - public void testSignWithException2() throws Exception { - SignUtil.sign("aaa".getBytes(StandardCharsets.UTF_8), "b".getBytes(StandardCharsets.UTF_8), null); + + @Test + void testSignWithException2() throws Exception { + assertThrows(Exception.class, () -> { + SignUtil.sign("aaa".getBytes(StandardCharsets.UTF_8), "b".getBytes(StandardCharsets.UTF_8), null); + }); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java index 097bebf3e71..b60abfb46e9 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java @@ -16,73 +16,77 @@ package com.alibaba.nacos.client.auth.ram.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -public class SpasAdapterTest { - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SpasAdapterTest { + @Test - public void test() { - Assert.assertNull(SpasAdapter.getAk()); - Assert.assertNull(SpasAdapter.getSk()); - try { + void test() { + assertNull(SpasAdapter.getAk()); + assertNull(SpasAdapter.getSk()); + Assertions.assertDoesNotThrow(() -> { SpasAdapter.freeCredentialInstance(); - } catch (Exception e) { - Assert.fail(); - } + }); } - + @Test - public void testSign() { + void testSign() { - Assert.assertNull(SpasAdapter.getSignHeaders("", "", "123")); + assertNull(SpasAdapter.getSignHeaders("", "", "123")); final Map map1 = SpasAdapter.getSignHeaders("aa", "bb", "123"); - Assert.assertEquals(2, map1.size()); - Assert.assertEquals(SpasAdapter.signWithHmacSha1Encrypt("bb+aa+" + map1.get("Timestamp"), "123"), + assertEquals(2, map1.size()); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt("bb+aa+" + map1.get("Timestamp"), "123"), map1.get("Spas-Signature")); final Map map2 = SpasAdapter.getSignHeaders("aa", "", "123"); - Assert.assertEquals(2, map2.size()); - Assert.assertEquals(SpasAdapter.signWithHmacSha1Encrypt("aa" + "+" + map2.get("Timestamp"), "123"), + assertEquals(2, map2.size()); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt("aa" + "+" + map2.get("Timestamp"), "123"), map2.get("Spas-Signature")); final Map map3 = SpasAdapter.getSignHeaders("", "bb", "123"); - Assert.assertEquals(2, map3.size()); - Assert.assertEquals(SpasAdapter.signWithHmacSha1Encrypt(map3.get("Timestamp"), "123"), + assertEquals(2, map3.size()); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt(map3.get("Timestamp"), "123"), map3.get("Spas-Signature")); } - + @Test - public void testSign2() { + void testSign2() { - Assert.assertNull(SpasAdapter.getSignHeaders((Map) null, "123")); + assertNull(SpasAdapter.getSignHeaders((Map) null, "123")); Map param1 = new HashMap<>(); param1.put("tenant", "bb"); param1.put("group", "aa"); final Map map1 = SpasAdapter.getSignHeaders(param1, "123"); - Assert.assertEquals(2, map1.size()); - Assert.assertEquals(SpasAdapter.signWithHmacSha1Encrypt("bb+aa+" + map1.get("Timestamp"), "123"), + assertEquals(2, map1.size()); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt("bb+aa+" + map1.get("Timestamp"), "123"), map1.get("Spas-Signature")); } - + @Test - public void testGetSignHeadersWithoutTenant() { + void testGetSignHeadersWithoutTenant() { Map param1 = new HashMap<>(); param1.put("group", "aa"); final Map map1 = SpasAdapter.getSignHeaders(param1, "123"); - Assert.assertEquals(2, map1.size()); - Assert.assertEquals(SpasAdapter.signWithHmacSha1Encrypt("aa+" + map1.get("Timestamp"), "123"), + assertEquals(2, map1.size()); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt("aa+" + map1.get("Timestamp"), "123"), map1.get("Spas-Signature")); } - - @Test(expected = Exception.class) - public void testSignWithHmacSha1EncryptWithException() { - SpasAdapter.signWithHmacSha1Encrypt(null, "123"); + + @Test + void testSignWithHmacSha1EncryptWithException() { + assertThrows(Exception.class, () -> { + SpasAdapter.signWithHmacSha1Encrypt(null, "123"); + }); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java index 134cd986860..fe55ce53b4c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java @@ -25,25 +25,27 @@ import com.alibaba.nacos.client.config.impl.LocalConfigInfoProcessor; import com.alibaba.nacos.client.config.impl.ServerListManager; import com.alibaba.nacos.client.env.NacosClientProperties; -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.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Properties; import java.util.concurrent.Executor; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -@RunWith(MockitoJUnitRunner.class) -public class NacosConfigServiceTest { +@ExtendWith(MockitoExtension.class) +class NacosConfigServiceTest { private NacosConfigService nacosConfigService; @@ -55,23 +57,23 @@ private void setFinal(Field field, Object ins, Object newValue) throws Exception field.setAccessible(false); } - - @Before - public void mock() throws Exception { + + @BeforeEach + void mock() throws Exception { final Properties properties = new Properties(); properties.put("serverAddr", "1.1.1.1"); nacosConfigService = new NacosConfigService(properties); mockWoker = Mockito.mock(ClientWorker.class); setFinal(NacosConfigService.class.getDeclaredField("worker"), nacosConfigService, mockWoker); } - - @After - public void clean() { + + @AfterEach + void clean() { LocalConfigInfoProcessor.cleanAllSnapshot(); } - + @Test - public void testGetConfigFromServer() throws NacosException { + void testGetConfigFromServer() throws NacosException { final String dataId = "1"; final String group = "2"; final String tenant = ""; @@ -81,13 +83,13 @@ public void testGetConfigFromServer() throws NacosException { response.setConfigType("bb"); Mockito.when(mockWoker.getServerConfig(dataId, group, "", timeout, false)).thenReturn(response); final String config = nacosConfigService.getConfig(dataId, group, timeout); - Assert.assertEquals("aa", config); + assertEquals("aa", config); Mockito.verify(mockWoker, Mockito.times(1)).getServerConfig(dataId, group, tenant, timeout, false); } - + @Test - public void testGetConfigFromFailOver() throws NacosException { + void testGetConfigFromFailOver() throws NacosException { final String dataId = "1failover"; final String group = "2"; final String tenant = ""; @@ -102,14 +104,14 @@ public void testGetConfigFromFailOver() throws NacosException { final int timeout = 3000; final String config = nacosConfigService.getConfig(dataId, group, timeout); - Assert.assertEquals(contentFailOver, config); + assertEquals(contentFailOver, config); } finally { localConfigInfoProcessorMockedStatic.close(); } } - + @Test - public void testGetConfigFromLocalCache() throws NacosException { + void testGetConfigFromLocalCache() throws NacosException { final String dataId = "1localcache"; final String group = "2"; final String tenant = ""; @@ -131,15 +133,15 @@ public void testGetConfigFromLocalCache() throws NacosException { Mockito.when(mockWoker.getServerConfig(dataId, group, "", timeout, false)).thenThrow(new NacosException()); final String config = nacosConfigService.getConfig(dataId, group, timeout); - Assert.assertEquals(contentFailOver, config); + assertEquals(contentFailOver, config); } finally { localConfigInfoProcessorMockedStatic.close(); } } - + @Test - public void testGetConfig403() throws NacosException { + void testGetConfig403() throws NacosException { final String dataId = "1localcache403"; final String group = "2"; final String tenant = ""; @@ -158,17 +160,17 @@ public void testGetConfig403() throws NacosException { .thenThrow(new NacosException(NacosException.NO_RIGHT, "no right")); try { nacosConfigService.getConfig(dataId, group, timeout); - Assert.assertTrue(false); + assertTrue(false); } catch (NacosException e) { - Assert.assertEquals(NacosException.NO_RIGHT, e.getErrCode()); + assertEquals(NacosException.NO_RIGHT, e.getErrCode()); } } finally { localConfigInfoProcessorMockedStatic.close(); } } - + @Test - public void testGetConfigAndSignListener() throws NacosException { + void testGetConfigAndSignListener() throws NacosException { final String dataId = "1"; final String group = "2"; final String tenant = ""; @@ -238,14 +240,14 @@ public boolean removeConfig(String dataId, String group, String tenant, String t }); final String config = nacosConfigService.getConfigAndSignListener(dataId, group, timeout, listener); - Assert.assertEquals(content, config); + assertEquals(content, config); Mockito.verify(mockWoker, Mockito.times(1)) .addTenantListenersWithContent(dataId, group, content, null, Arrays.asList(listener)); } - + @Test - public void testAddListener() throws NacosException { + void testAddListener() throws NacosException { String dataId = "1"; String group = "2"; Listener listener = new Listener() { @@ -263,9 +265,9 @@ public void receiveConfigInfo(String configInfo) { nacosConfigService.addListener(dataId, group, listener); Mockito.verify(mockWoker, Mockito.times(1)).addTenantListeners(dataId, group, Arrays.asList(listener)); } - + @Test - public void testPublishConfig() throws NacosException { + void testPublishConfig() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; @@ -275,14 +277,14 @@ public void testPublishConfig() throws NacosException { .thenReturn(true); final boolean b = nacosConfigService.publishConfig(dataId, group, content); - Assert.assertTrue(b); + assertTrue(b); Mockito.verify(mockWoker, Mockito.times(1)) .publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); } - + @Test - public void testPublishConfig2() throws NacosException { + void testPublishConfig2() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; @@ -293,14 +295,14 @@ public void testPublishConfig2() throws NacosException { .thenReturn(true); final boolean b = nacosConfigService.publishConfig(dataId, group, content, type); - Assert.assertTrue(b); + assertTrue(b); Mockito.verify(mockWoker, Mockito.times(1)) .publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); } - + @Test - public void testPublishConfigCas() throws NacosException { + void testPublishConfigCas() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; @@ -312,14 +314,14 @@ public void testPublishConfigCas() throws NacosException { .thenReturn(true); final boolean b = nacosConfigService.publishConfigCas(dataId, group, content, casMd5); - Assert.assertTrue(b); + assertTrue(b); Mockito.verify(mockWoker, Mockito.times(1)) .publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); } - + @Test - public void testPublishConfigCas2() throws NacosException { + void testPublishConfigCas2() throws NacosException { String dataId = "1"; String group = "2"; String content = "123"; @@ -331,14 +333,14 @@ public void testPublishConfigCas2() throws NacosException { .thenReturn(true); final boolean b = nacosConfigService.publishConfigCas(dataId, group, content, casMd5, type); - Assert.assertTrue(b); + assertTrue(b); Mockito.verify(mockWoker, Mockito.times(1)) .publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); } - + @Test - public void testRemoveConfig() throws NacosException { + void testRemoveConfig() throws NacosException { String dataId = "1"; String group = "2"; String tenant = ""; @@ -346,13 +348,13 @@ public void testRemoveConfig() throws NacosException { Mockito.when(mockWoker.removeConfig(dataId, group, tenant, null)).thenReturn(true); final boolean b = nacosConfigService.removeConfig(dataId, group); - Assert.assertTrue(b); + assertTrue(b); Mockito.verify(mockWoker, Mockito.times(1)).removeConfig(dataId, group, tenant, null); } - + @Test - public void testRemoveListener() { + void testRemoveListener() { String dataId = "1"; String group = "2"; Listener listener = new Listener() { @@ -370,25 +372,23 @@ public void receiveConfigInfo(String configInfo) { nacosConfigService.removeListener(dataId, group, listener); Mockito.verify(mockWoker, Mockito.times(1)).removeTenantListener(dataId, group, listener); } - + @Test - public void testGetServerStatus() { + void testGetServerStatus() { Mockito.when(mockWoker.isHealthServer()).thenReturn(true); - Assert.assertEquals("UP", nacosConfigService.getServerStatus()); + assertEquals("UP", nacosConfigService.getServerStatus()); Mockito.verify(mockWoker, Mockito.times(1)).isHealthServer(); Mockito.when(mockWoker.isHealthServer()).thenReturn(false); - Assert.assertEquals("DOWN", nacosConfigService.getServerStatus()); + assertEquals("DOWN", nacosConfigService.getServerStatus()); Mockito.verify(mockWoker, Mockito.times(2)).isHealthServer(); } - + @Test - public void testShutDown() { - try { + void testShutDown() { + Assertions.assertDoesNotThrow(() -> { nacosConfigService.shutDown(); - } catch (Exception e) { - Assert.fail(); - } + }); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java b/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java index d35167b38c3..276cf09c883 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java @@ -16,68 +16,72 @@ package com.alibaba.nacos.client.config.common; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class GroupKeyTest { -public class GroupKeyTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test - public void testGetKey() { - Assert.assertEquals("1+foo", GroupKey.getKey("1", "foo")); - Assert.assertEquals("1+foo+bar", GroupKey.getKey("1", "foo", "bar")); - Assert.assertEquals("1+f%2Boo+b%25ar", GroupKey.getKey("1", "f+oo", "b%ar")); + void testGetKey() { + assertEquals("1+foo", GroupKey.getKey("1", "foo")); + assertEquals("1+foo+bar", GroupKey.getKey("1", "foo", "bar")); + assertEquals("1+f%2Boo+b%25ar", GroupKey.getKey("1", "f+oo", "b%ar")); } - + @Test - public void testGetKeyTenant() { - Assert.assertEquals("1+foo+bar", GroupKey.getKeyTenant("1", "foo", "bar")); + void testGetKeyTenant() { + assertEquals("1+foo+bar", GroupKey.getKeyTenant("1", "foo", "bar")); } - + @Test - public void testParseKey() { - Assert.assertArrayEquals(new String[] {"a", "f+oo", null}, GroupKey.parseKey("a+f%2Boo")); - Assert.assertArrayEquals(new String[] {"b", "f%oo", null}, GroupKey.parseKey("b+f%25oo")); - Assert.assertArrayEquals(new String[] {"a", "b", "c"}, GroupKey.parseKey("a+b+c")); + void testParseKey() { + assertArrayEquals(new String[] {"a", "f+oo", null}, GroupKey.parseKey("a+f%2Boo")); + assertArrayEquals(new String[] {"b", "f%oo", null}, GroupKey.parseKey("b+f%25oo")); + assertArrayEquals(new String[] {"a", "b", "c"}, GroupKey.parseKey("a+b+c")); } - + @Test - public void testParseKeyIllegalArgumentException1() { - thrown.expect(IllegalArgumentException.class); - GroupKey.parseKey(""); + void testParseKeyIllegalArgumentException1() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.parseKey(""); + }); } - + @Test - public void testParseKeyIllegalArgumentException2() { - thrown.expect(IllegalArgumentException.class); - GroupKey.parseKey("f%oo"); + void testParseKeyIllegalArgumentException2() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.parseKey("f%oo"); + }); } - + @Test - public void testParseKeyIllegalArgumentException3() { - thrown.expect(IllegalArgumentException.class); - GroupKey.parseKey("f+o+o+bar"); + void testParseKeyIllegalArgumentException3() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.parseKey("f+o+o+bar"); + }); } - + @Test - public void testParseKeyIllegalArgumentException4() { - thrown.expect(IllegalArgumentException.class); - GroupKey.parseKey("f++bar"); + void testParseKeyIllegalArgumentException4() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.parseKey("f++bar"); + }); } - + @Test - public void testGetKeyDatIdParam() { - thrown.expect(IllegalArgumentException.class); - GroupKey.getKey("", "a"); + void testGetKeyDatIdParam() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.getKey("", "a"); + }); } - + @Test - public void testGetKeyGroupParam() { - thrown.expect(IllegalArgumentException.class); - GroupKey.getKey("a", ""); + void testGetKeyGroupParam() { + assertThrows(IllegalArgumentException.class, () -> { + GroupKey.getKey("a", ""); + }); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java index 47acff2c38d..8ec8c4fd9bd 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java @@ -16,13 +16,14 @@ package com.alibaba.nacos.client.config.filter.impl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigContextTest { -public class ConfigContextTest { - @Test - public void testParameter() { + void testParameter() { ConfigContext context = new ConfigContext(); String key = "key"; String v = "v"; @@ -30,7 +31,7 @@ public void testParameter() { String actual = (String) context.getParameter(key); - Assert.assertEquals(v, actual); + assertEquals(v, actual); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest.java index fa6c5463252..98f84a21a1b 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest.java @@ -18,21 +18,22 @@ import com.alibaba.nacos.api.config.filter.IConfigFilterChain; import com.alibaba.nacos.api.exception.NacosException; -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 static org.junit.jupiter.api.Assertions.assertEquals; /** * ConfigCryptoFilterTest. * * @author lixiaoshuang */ -@RunWith(MockitoJUnitRunner.class) -public class ConfigEncryptionFilterTest { +@ExtendWith(MockitoExtension.class) +class ConfigEncryptionFilterTest { private ConfigEncryptionFilter configEncryptionFilter; @@ -45,25 +46,25 @@ public class ConfigEncryptionFilterTest { @Mock private IConfigFilterChain iConfigFilterChain; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { configEncryptionFilter = new ConfigEncryptionFilter(); - - Mockito.when(configRequest.getDataId()).thenReturn("cipher-aes-test"); - Mockito.when(configRequest.getContent()).thenReturn("nacos"); - - Mockito.when(configResponse.getDataId()).thenReturn("test-dataid"); - Mockito.when(configResponse.getContent()).thenReturn("nacos"); - Mockito.when(configResponse.getEncryptedDataKey()).thenReturn("1234567890"); } @Test - public void testDoFilter() throws NacosException { + void doFilter() throws NacosException { + Mockito.when(configRequest.getDataId()).thenReturn("cipher-aes-test"); + Mockito.when(configRequest.getContent()).thenReturn("nacos"); + configEncryptionFilter.doFilter(configRequest, null, iConfigFilterChain); Mockito.verify(configRequest, Mockito.atLeast(1)).getDataId(); Mockito.verify(configRequest, Mockito.atLeast(1)).getContent(); + Mockito.when(configResponse.getDataId()).thenReturn("test-dataid"); + Mockito.when(configResponse.getContent()).thenReturn("nacos"); + Mockito.when(configResponse.getEncryptedDataKey()).thenReturn("1234567890"); + configEncryptionFilter.doFilter(null, configResponse, iConfigFilterChain); Mockito.verify(configResponse, Mockito.atLeast(1)).getDataId(); @@ -72,8 +73,8 @@ public void testDoFilter() throws NacosException { } @Test - public void testGetOrder() { + void testGetOrder() { int order = configEncryptionFilter.getOrder(); - Assert.assertEquals(order, 0); + assertEquals(0, order); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java index 34566ebf640..a3d906940c7 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java @@ -26,17 +26,18 @@ import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.Cipher; + +import static org.junit.jupiter.api.Assertions.assertEquals; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; -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; /** * AES encryption algorithm testing dataId with prefix cipher. @@ -45,8 +46,8 @@ * @Date 2023/12/23 9:45 PM * @Version 1.0 */ -@RunWith(MockitoJUnitRunner.class) -public class ConfigEncryptionFilterTest1 { +@ExtendWith(MockitoExtension.class) +class ConfigEncryptionFilterTest1 { private ConfigEncryptionFilter configEncryptionFilter; @@ -54,9 +55,9 @@ public class ConfigEncryptionFilterTest1 { @Mock private IConfigFilterChain iConfigFilterChain; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { mockEncryptionPluginService = new EncryptionPluginService() { private static final String ALGORITHM = "AES"; @@ -148,9 +149,9 @@ private String aesDecrypt(String content, String key) { configEncryptionFilter = new ConfigEncryptionFilter(); } - + @Test - public void testDoFilterEncryptedData() throws NacosException { + void testDoFilterEncryptedData() throws NacosException { String dataId = "cipher-aes-test"; String content = "nacos"; final String encryptionContent = mockEncryptionPluginService.encrypt(mockEncryptionPluginService.generateSecretKey(), content); @@ -160,20 +161,20 @@ public void testDoFilterEncryptedData() throws NacosException { configRequest.setDataId(dataId); configRequest.setContent(content); configEncryptionFilter.doFilter(configRequest, null, iConfigFilterChain); - Assert.assertEquals(configRequest.getContent(), encryptionContent); - Assert.assertEquals(configRequest.getEncryptedDataKey(), theKeyOfContentKey); + assertEquals(configRequest.getContent(), encryptionContent); + assertEquals(configRequest.getEncryptedDataKey(), theKeyOfContentKey); ConfigResponse configResponse = new ConfigResponse(); configResponse.setDataId(dataId); configResponse.setContent(encryptionContent); configResponse.setEncryptedDataKey(theKeyOfContentKey); configEncryptionFilter.doFilter(null, configResponse, iConfigFilterChain); - Assert.assertEquals(configResponse.getContent(), content); - Assert.assertEquals(configResponse.getEncryptedDataKey(), mockEncryptionPluginService.generateSecretKey()); + assertEquals(configResponse.getContent(), content); + assertEquals(configResponse.getEncryptedDataKey(), mockEncryptionPluginService.generateSecretKey()); } - + @Test - public void testDoFilter() throws NacosException { + void testDoFilter() throws NacosException { String dataId = "test"; String content = "nacos"; @@ -181,21 +182,21 @@ public void testDoFilter() throws NacosException { configRequest.setDataId(dataId); configRequest.setContent(content); configEncryptionFilter.doFilter(configRequest, null, iConfigFilterChain); - Assert.assertEquals(configRequest.getContent(), content); - Assert.assertEquals(configRequest.getEncryptedDataKey(), ""); + assertEquals(configRequest.getContent(), content); + assertEquals("", configRequest.getEncryptedDataKey()); ConfigResponse configResponse = new ConfigResponse(); configResponse.setDataId(dataId); configResponse.setContent(content); configResponse.setEncryptedDataKey(""); configEncryptionFilter.doFilter(null, configResponse, iConfigFilterChain); - Assert.assertEquals(configResponse.getContent(), content); - Assert.assertEquals(configResponse.getEncryptedDataKey(), ""); + assertEquals(configResponse.getContent(), content); + assertEquals("", configResponse.getEncryptedDataKey()); } - + @Test - public void testGetOrder() { + void testGetOrder() { int order = configEncryptionFilter.getOrder(); - Assert.assertEquals(order, 0); + assertEquals(0, order); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java index ef74f305b8e..46cfda2d8fb 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java @@ -22,15 +22,16 @@ import com.alibaba.nacos.api.config.filter.IConfigRequest; import com.alibaba.nacos.api.config.filter.IConfigResponse; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; -public class ConfigFilterChainManagerTest { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigFilterChainManagerTest { private static class MyIConfigFilter implements IConfigFilter { @@ -83,9 +84,9 @@ public String getFilterName() { return name; } } - + @Test - public void testAddFilterOrder() throws NacosException { + void testAddFilterOrder() throws NacosException { final ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(new Properties()); MyIConfigFilter filter1 = new MyIConfigFilter("filter1", 1); MyIConfigFilter filter2 = new MyIConfigFilter("filter2", 2); @@ -103,17 +104,17 @@ public void testAddFilterOrder() throws NacosException { IConfigContext configContext = configRequest.getConfigContext(); // doFilter works - Assert.assertEquals(1, configContext.getParameter("filter1")); - Assert.assertEquals(2, configContext.getParameter("filter2")); - Assert.assertEquals(3, configContext.getParameter("filter3")); + assertEquals(1, configContext.getParameter("filter1")); + assertEquals(2, configContext.getParameter("filter2")); + assertEquals(3, configContext.getParameter("filter3")); //order List orders = (List) configContext.getParameter("orders"); - Assert.assertEquals(Arrays.asList(1, 2, 3), orders); + assertEquals(Arrays.asList(1, 2, 3), orders); } - + @Test - public void testAddFilterNotRepeat() throws NacosException { + void testAddFilterNotRepeat() throws NacosException { final ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(new Properties()); MyIConfigFilter filter1 = new MyIConfigFilter("filter1", 1); MyIConfigFilter filter2 = new MyIConfigFilter("filter2", 2); @@ -128,6 +129,6 @@ public void testAddFilterNotRepeat() throws NacosException { IConfigContext configContext = configRequest.getConfigContext(); - Assert.assertEquals(2, configContext.getParameter("filterCount")); + assertEquals(2, configContext.getParameter("filterCount")); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java index 379bd1af051..c177e81ab92 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java @@ -17,13 +17,14 @@ package com.alibaba.nacos.client.config.filter.impl; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigFilterChainTest { -public class ConfigFilterChainTest { - @Test - public void testConfigFilterChain() { + void testConfigFilterChain() { ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(null); configFilterChainManager.addFilter(new DemoFilter1()); configFilterChainManager.addFilter(new DemoFilter2()); @@ -31,8 +32,8 @@ public void testConfigFilterChain() { ConfigResponse configResponse = new ConfigResponse(); try { configFilterChainManager.doFilter(configRequest, configResponse); - Assert.assertEquals(DemoFilter1.class.getName(), configRequest.getParameter("filter1")); - Assert.assertEquals(DemoFilter2.class.getName(), configRequest.getParameter("filter2")); + assertEquals(DemoFilter1.class.getName(), configRequest.getParameter("filter1")); + assertEquals(DemoFilter2.class.getName(), configRequest.getParameter("filter2")); } catch (NacosException e) { e.printStackTrace(); } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java index 35c9c0bf718..76f17db7edf 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java @@ -17,13 +17,15 @@ package com.alibaba.nacos.client.config.filter.impl; import com.alibaba.nacos.api.config.filter.IConfigContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ConfigRequestTest { -public class ConfigRequestTest { - @Test - public void testGetterAndSetter() { + void testGetterAndSetter() { ConfigRequest configRequest = new ConfigRequest(); String dataId = "id"; String group = "group"; @@ -37,16 +39,16 @@ public void testGetterAndSetter() { configRequest.setTenant(tenant); configRequest.setType(type); - Assert.assertEquals(dataId, configRequest.getDataId()); - Assert.assertEquals(group, configRequest.getGroup()); - Assert.assertEquals(tenant, configRequest.getTenant()); - Assert.assertEquals(content, configRequest.getContent()); - Assert.assertEquals(type, configRequest.getType()); + assertEquals(dataId, configRequest.getDataId()); + assertEquals(group, configRequest.getGroup()); + assertEquals(tenant, configRequest.getTenant()); + assertEquals(content, configRequest.getContent()); + assertEquals(type, configRequest.getType()); } - + @Test - public void testGetParameter() { + void testGetParameter() { ConfigRequest configRequest = new ConfigRequest(); String dataId = "id"; String group = "group"; @@ -58,16 +60,16 @@ public void testGetParameter() { configRequest.setGroup(group); configRequest.setTenant(tenant); - Assert.assertEquals(dataId, configRequest.getParameter("dataId")); - Assert.assertEquals(group, configRequest.getParameter("group")); - Assert.assertEquals(tenant, configRequest.getParameter("tenant")); - Assert.assertEquals(content, configRequest.getParameter("content")); + assertEquals(dataId, configRequest.getParameter("dataId")); + assertEquals(group, configRequest.getParameter("group")); + assertEquals(tenant, configRequest.getParameter("tenant")); + assertEquals(content, configRequest.getParameter("content")); } - + @Test - public void testGetConfigContext() { + void testGetConfigContext() { ConfigRequest configRequest = new ConfigRequest(); IConfigContext configContext = configRequest.getConfigContext(); - Assert.assertNotNull(configContext); + assertNotNull(configContext); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java index 12b01064c72..0450e0d41c2 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java @@ -17,13 +17,15 @@ package com.alibaba.nacos.client.config.filter.impl; import com.alibaba.nacos.api.config.filter.IConfigContext; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ConfigResponseTest { -public class ConfigResponseTest { - @Test - public void testGetterAndSetter() { + void testGetterAndSetter() { ConfigResponse configResponse = new ConfigResponse(); String dataId = "id"; String group = "group"; @@ -37,15 +39,15 @@ public void testGetterAndSetter() { configResponse.setTenant(tenant); configResponse.setConfigType(type); - Assert.assertEquals(dataId, configResponse.getDataId()); - Assert.assertEquals(group, configResponse.getGroup()); - Assert.assertEquals(tenant, configResponse.getTenant()); - Assert.assertEquals(content, configResponse.getContent()); - Assert.assertEquals(type, configResponse.getConfigType()); + assertEquals(dataId, configResponse.getDataId()); + assertEquals(group, configResponse.getGroup()); + assertEquals(tenant, configResponse.getTenant()); + assertEquals(content, configResponse.getContent()); + assertEquals(type, configResponse.getConfigType()); } - + @Test - public void getParameter() { + void getParameter() { ConfigResponse configResponse = new ConfigResponse(); String dataId = "id"; String group = "group"; @@ -59,17 +61,17 @@ public void getParameter() { configResponse.setTenant(tenant); configResponse.putParameter(custom, custom); - Assert.assertEquals(dataId, configResponse.getParameter("dataId")); - Assert.assertEquals(group, configResponse.getParameter("group")); - Assert.assertEquals(tenant, configResponse.getParameter("tenant")); - Assert.assertEquals(content, configResponse.getParameter("content")); - Assert.assertEquals(custom, configResponse.getParameter("custom")); + assertEquals(dataId, configResponse.getParameter("dataId")); + assertEquals(group, configResponse.getParameter("group")); + assertEquals(tenant, configResponse.getParameter("tenant")); + assertEquals(content, configResponse.getParameter("content")); + assertEquals(custom, configResponse.getParameter("custom")); } - + @Test - public void getConfigContext() { + void getConfigContext() { ConfigResponse configResponse = new ConfigResponse(); IConfigContext configContext = configResponse.getConfigContext(); - Assert.assertNotNull(configContext); + assertNotNull(configContext); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java b/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java index ef56426aebf..548f50716ef 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java @@ -19,13 +19,15 @@ import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.param.Header; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -public class MetricsHttpAgentTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class MetricsHttpAgentTest { private static class MockHttpAgent implements HttpAgent { @@ -104,9 +106,9 @@ public boolean isShutdown() { return shutdown; } } - + @Test - public void testGetter() { + void testGetter() { String name = "name"; String encode = "UTF-8"; String tenant = "aaa"; @@ -114,14 +116,14 @@ public void testGetter() { final HttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); - Assert.assertEquals(name, metricsHttpAgent.getName()); - Assert.assertEquals(encode, metricsHttpAgent.getEncode()); - Assert.assertEquals(tenant, metricsHttpAgent.getTenant()); - Assert.assertEquals(namespace, metricsHttpAgent.getNamespace()); + assertEquals(name, metricsHttpAgent.getName()); + assertEquals(encode, metricsHttpAgent.getEncode()); + assertEquals(tenant, metricsHttpAgent.getTenant()); + assertEquals(namespace, metricsHttpAgent.getNamespace()); } - + @Test - public void testLifeCycle() throws NacosException { + void testLifeCycle() throws NacosException { String name = "name"; String encode = "UTF-8"; String tenant = "aaa"; @@ -130,14 +132,14 @@ public void testLifeCycle() throws NacosException { final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); metricsHttpAgent.start(); - Assert.assertTrue(mockHttpAgent.isStart()); + assertTrue(mockHttpAgent.isStart()); metricsHttpAgent.shutdown(); - Assert.assertTrue(mockHttpAgent.isShutdown()); + assertTrue(mockHttpAgent.isShutdown()); } - + @Test - public void testHttpMethod() throws Exception { + void testHttpMethod() throws Exception { String name = "name"; String encode = "UTF-8"; String tenant = "aaa"; @@ -147,13 +149,13 @@ public void testHttpMethod() throws Exception { final HttpRestResult result1 = metricsHttpAgent .httpGet("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - Assert.assertEquals("get /aa", result1.getMessage()); + assertEquals("get /aa", result1.getMessage()); final HttpRestResult result2 = metricsHttpAgent .httpPost("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - Assert.assertEquals("post /aa", result2.getMessage()); + assertEquals("post /aa", result2.getMessage()); final HttpRestResult result3 = metricsHttpAgent .httpDelete("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - Assert.assertEquals("delete /aa", result3.getMessage()); + assertEquals("delete /aa", result3.getMessage()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java b/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java index c394e2485dc..51594fa98b9 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java @@ -24,14 +24,16 @@ import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.Query; -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.Assertions; +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.net.ConnectException; @@ -41,13 +43,19 @@ import java.util.Iterator; import java.util.Properties; +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.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ServerHttpAgentTest { +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class ServerHttpAgentTest { private static final String SERVER_ADDRESS_1 = "http://1.1.1.1:8848"; @@ -66,9 +74,9 @@ public class ServerHttpAgentTest { NacosRestTemplate nacosRestTemplate; ServerHttpAgent serverHttpAgent; - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { serverHttpAgent = new ServerHttpAgent(serverListManager, new Properties()); injectRestTemplate(); when(serverListManager.getCurrentServerAddr()).thenReturn(SERVER_ADDRESS_1); @@ -81,50 +89,50 @@ private void injectRestTemplate() throws NoSuchFieldException, IllegalAccessExce restTemplateField.setAccessible(true); restTemplateField.set(serverHttpAgent, nacosRestTemplate); } - - @After - public void tearDown() throws NacosException { + + @AfterEach + void tearDown() throws NacosException { serverHttpAgent.shutdown(); } - + @Test - public void testConstruct() throws NacosException { + void testConstruct() throws NacosException { ServerListManager server = new ServerListManager(); final ServerHttpAgent serverHttpAgent1 = new ServerHttpAgent(server); - Assert.assertNotNull(serverHttpAgent1); + assertNotNull(serverHttpAgent1); final ServerHttpAgent serverHttpAgent2 = new ServerHttpAgent(server, new Properties()); - Assert.assertNotNull(serverHttpAgent2); + assertNotNull(serverHttpAgent2); final Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1"); final ServerHttpAgent serverHttpAgent3 = new ServerHttpAgent(properties); - Assert.assertNotNull(serverHttpAgent3); + assertNotNull(serverHttpAgent3); } - + @Test - public void testGetterAndSetter() throws NacosException { + void testGetterAndSetter() throws NacosException { ServerListManager server = new ServerListManager("aaa", "namespace1"); final ServerHttpAgent serverHttpAgent = new ServerHttpAgent(server, new Properties()); final String appname = ServerHttpAgent.getAppname(); //set by AppNameUtils, init in ParamUtils static block - Assert.assertEquals("unknown", appname); + assertEquals("unknown", appname); final String encode = serverHttpAgent.getEncode(); final String namespace = serverHttpAgent.getNamespace(); final String tenant = serverHttpAgent.getTenant(); final String name = serverHttpAgent.getName(); - Assert.assertNull(encode); - Assert.assertEquals("namespace1", namespace); - Assert.assertEquals("namespace1", tenant); - Assert.assertEquals("custom-aaa_8080_nacos_serverlist_namespace1", name); + assertNull(encode); + assertEquals("namespace1", namespace); + assertEquals("namespace1", tenant); + assertEquals("custom-aaa_8080_nacos_serverlist_namespace1", name); } - + @Test - public void testLifCycle() throws NacosException { + void testLifCycle() throws NacosException { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "aaa"); ServerListManager server = Mockito.mock(ServerListManager.class); @@ -132,42 +140,44 @@ public void testLifCycle() throws NacosException { serverHttpAgent.start(); Mockito.verify(server).start(); - - try { + + Assertions.assertDoesNotThrow(() -> { serverHttpAgent.shutdown(); - } catch (NullPointerException e) { - Assert.fail(); - } + }); } - + @Test - public void testHttpGetSuccess() throws Exception { + void testHttpGetSuccess() throws Exception { when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); HttpRestResult actual = serverHttpAgent .httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + assertEquals(mockResult, actual); } - - @Test(expected = ConnectException.class) - public void testHttpGetFailed() throws Exception { - when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); - when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); - serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + + @Test + void testHttpGetFailed() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); + when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); + serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } - - @Test(expected = NacosException.class) - public void testHttpWithRequestException() throws Exception { - when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))) - .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); - serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + + @Test + void testHttpWithRequestException() throws Exception { + assertThrows(NacosException.class, () -> { + when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))) + .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); + serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } - + @Test - public void testRetryWithNewServer() throws Exception { + void testRetryWithNewServer() throws Exception { when(mockIterator.hasNext()).thenReturn(true); when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException()); @@ -176,44 +186,50 @@ public void testRetryWithNewServer() throws Exception { when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); HttpRestResult actual = serverHttpAgent .httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + assertEquals(mockResult, actual); } - - @Test(expected = ConnectException.class) - public void testRetryTimeout() throws Exception { - when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))).thenThrow(new SocketTimeoutException()); - serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + + @Test + void testRetryTimeout() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))).thenThrow(new SocketTimeoutException()); + serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + }); } - + @Test - public void testHttpPostSuccess() throws Exception { + void testHttpPostSuccess() throws Exception { when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); HttpRestResult actual = serverHttpAgent .httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + assertEquals(mockResult, actual); } - - @Test(expected = ConnectException.class) - public void testHttpPostFailed() throws Exception { - when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); - when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); - serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + + @Test + void testHttpPostFailed() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); + when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); + serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } - - @Test(expected = NacosException.class) - public void testHttpPostWithRequestException() throws Exception { - when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), anyMap(), eq(String.class))) - .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); - serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + + @Test + void testHttpPostWithRequestException() throws Exception { + assertThrows(NacosException.class, () -> { + when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), anyMap(), eq(String.class))) + .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); + serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } - + @Test - public void testRetryPostWithNewServer() throws Exception { + void testRetryPostWithNewServer() throws Exception { when(mockIterator.hasNext()).thenReturn(true); when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), anyMap(), eq(String.class))).thenThrow(new ConnectException()); @@ -222,44 +238,50 @@ public void testRetryPostWithNewServer() throws Exception { when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); HttpRestResult actual = serverHttpAgent .httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + assertEquals(mockResult, actual); } - - @Test(expected = ConnectException.class) - public void testRetryPostTimeout() throws Exception { - when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), anyMap(), eq(String.class))).thenThrow(new SocketTimeoutException()); - serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + + @Test + void testRetryPostTimeout() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), anyMap(), eq(String.class))).thenThrow(new SocketTimeoutException()); + serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + }); } - + @Test - public void testHttpDeleteSuccess() throws Exception { + void testHttpDeleteSuccess() throws Exception { when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); HttpRestResult actual = serverHttpAgent .httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + assertEquals(mockResult, actual); } - - @Test(expected = ConnectException.class) - public void testHttpDeleteFailed() throws Exception { - when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); - when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); - serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + + @Test + void testHttpDeleteFailed() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); + when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_NOT_FOUND); + serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } - - @Test(expected = NacosException.class) - public void testHttpDeleteWithRequestException() throws Exception { - when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))) - .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); - serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + + @Test + void testHttpDeleteWithRequestException() throws Exception { + assertThrows(NacosException.class, () -> { + when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))) + .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); + serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + }); } - + @Test - public void testRetryDeleteWithNewServer() throws Exception { + void testRetryDeleteWithNewServer() throws Exception { when(mockIterator.hasNext()).thenReturn(true); when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException()); @@ -268,13 +290,15 @@ public void testRetryDeleteWithNewServer() throws Exception { when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); HttpRestResult actual = serverHttpAgent .httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); - Assert.assertEquals(mockResult, actual); + assertEquals(mockResult, actual); } - - @Test(expected = ConnectException.class) - public void testRetryDeleteTimeout() throws Exception { - when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))).thenThrow(new SocketTimeoutException()); - serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + + @Test + void testRetryDeleteTimeout() throws Exception { + assertThrows(ConnectException.class, () -> { + when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), + any(Header.class), any(Query.class), eq(String.class))).thenThrow(new SocketTimeoutException()); + serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); + }); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java index 7ff7116345b..632b319441f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java @@ -27,8 +27,7 @@ import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.listener.Subscriber; import com.alibaba.nacos.common.utils.MD5Utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Date; @@ -37,34 +36,40 @@ import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; -public class CacheDataTest { - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CacheDataTest { + @Test - public void testConstructorAndEquals() { + void testConstructorAndEquals() { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData cacheData1 = new CacheData(filter, "name1", "key", "group", "tenant"); - Assert.assertEquals("CacheData [key, group]", cacheData1.toString()); + assertEquals("CacheData [key, group]", cacheData1.toString()); final CacheData cacheData2 = new CacheData(filter, "name2", "key", "group"); - Assert.assertEquals(cacheData1, cacheData2); - Assert.assertEquals(cacheData1.hashCode(), cacheData2.hashCode()); + assertEquals(cacheData1, cacheData2); + assertEquals(cacheData1.hashCode(), cacheData2.hashCode()); final CacheData cacheData3 = new CacheData(filter, "name2", "key3", "group", "tenant"); - Assert.assertNotEquals(cacheData1, cacheData3); + assertNotEquals(cacheData1, cacheData3); } - + @Test - public void testGetter() { + void testGetter() { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData cacheData1 = new CacheData(filter, "name1", "key", "group", "tenant"); - Assert.assertTrue(cacheData1.isInitializing()); - Assert.assertNull(cacheData1.getContent()); - Assert.assertEquals(0, cacheData1.getTaskId()); - Assert.assertFalse(cacheData1.isConsistentWithServer()); - Assert.assertFalse(cacheData1.isUseLocalConfigInfo()); - Assert.assertEquals(0, cacheData1.getLastModifiedTs().intValue()); - Assert.assertEquals(0, cacheData1.getLocalConfigInfoVersion()); + assertTrue(cacheData1.isInitializing()); + assertNull(cacheData1.getContent()); + assertEquals(0, cacheData1.getTaskId()); + assertFalse(cacheData1.isConsistentWithServer()); + assertFalse(cacheData1.isUseLocalConfigInfo()); + assertEquals(0, cacheData1.getLastModifiedTs().intValue()); + assertEquals(0, cacheData1.getLocalConfigInfoVersion()); cacheData1.setInitializing(false); cacheData1.setContent("123"); @@ -76,30 +81,30 @@ public void testGetter() { cacheData1.setUseLocalConfigInfo(true); cacheData1.setLocalConfigInfoVersion(timeStamp); - Assert.assertFalse(cacheData1.isInitializing()); - Assert.assertEquals("123", cacheData1.getContent()); - Assert.assertEquals(MD5Utils.md5Hex("123", "UTF-8"), cacheData1.getMd5()); + assertFalse(cacheData1.isInitializing()); + assertEquals("123", cacheData1.getContent()); + assertEquals(MD5Utils.md5Hex("123", "UTF-8"), cacheData1.getMd5()); - Assert.assertEquals(123, cacheData1.getTaskId()); - Assert.assertTrue(cacheData1.isConsistentWithServer()); - Assert.assertEquals("123", cacheData1.getType()); - Assert.assertTrue(cacheData1.isUseLocalConfigInfo()); - Assert.assertEquals(timeStamp, cacheData1.getLastModifiedTs().longValue()); - Assert.assertEquals(timeStamp, cacheData1.getLocalConfigInfoVersion()); + assertEquals(123, cacheData1.getTaskId()); + assertTrue(cacheData1.isConsistentWithServer()); + assertEquals("123", cacheData1.getType()); + assertTrue(cacheData1.isUseLocalConfigInfo()); + assertEquals(timeStamp, cacheData1.getLastModifiedTs().longValue()); + assertEquals(timeStamp, cacheData1.getLocalConfigInfoVersion()); } - + @Test - public void testNotifyWarnTimeout() { + void testNotifyWarnTimeout() { System.setProperty("nacos.listener.notify.warn.timeout", "5000"); long notifyWarnTimeout = CacheData.initNotifyWarnTimeout(); - Assert.assertEquals(5000, notifyWarnTimeout); + assertEquals(5000, notifyWarnTimeout); System.setProperty("nacos.listener.notify.warn.timeout", "1bf000abc"); long notifyWarnTimeout2 = CacheData.initNotifyWarnTimeout(); - Assert.assertEquals(60000, notifyWarnTimeout2); + assertEquals(60000, notifyWarnTimeout2); } - + @Test - public void testListener() throws NacosException { + void testListener() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData cacheData1 = new CacheData(filter, "name1", "key", "group", "tenant"); @@ -114,16 +119,16 @@ public void receiveConfigInfo(String configInfo) { } }; cacheData1.addListener(listener); - Assert.assertEquals(1, cacheData1.getListeners().size()); - Assert.assertEquals(listener, cacheData1.getListeners().get(0)); + assertEquals(1, cacheData1.getListeners().size()); + assertEquals(listener, cacheData1.getListeners().get(0)); cacheData1.removeListener(listener); - Assert.assertEquals(0, cacheData1.getListeners().size()); + assertEquals(0, cacheData1.getListeners().size()); } - + @Test - public void testCheckListenerMd5() throws NacosException { + void testCheckListenerMd5() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData data = new CacheData(filter, "name1", "key", "group", "tenant"); final List list = new ArrayList<>(); @@ -140,22 +145,22 @@ public void receiveConfigInfo(String configInfo) { }; data.addListener(listener); data.checkListenerMd5(); - Assert.assertTrue(data.checkListenersMd5Consistent()); - Assert.assertEquals(0, list.size()); + assertTrue(data.checkListenersMd5Consistent()); + assertEquals(0, list.size()); data.setContent("new"); - Assert.assertFalse(data.checkListenersMd5Consistent()); + assertFalse(data.checkListenersMd5Consistent()); data.checkListenerMd5(); - Assert.assertEquals(1, list.size()); - Assert.assertEquals("new", list.get(0)); + assertEquals(1, list.size()); + assertEquals("new", list.get(0)); } - + @Test - public void testCheckListenerMd5NotifyTimeouts() throws NacosException { + void testCheckListenerMd5NotifyTimeouts() throws NacosException { System.setProperty("nacos.listener.notify.warn.timeout", "1000"); long notifyWarnTimeout = CacheData.initNotifyWarnTimeout(); - Assert.assertEquals(1000, notifyWarnTimeout); + assertEquals(1000, notifyWarnTimeout); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData data = new CacheData(filter, "name1", "keytimeouts", "group", "tenant"); Listener listener = new Listener() { @@ -192,12 +197,12 @@ public Class subscribeType() { data.addListener(listener); data.setContent("new"); data.checkListenerMd5(); - Assert.assertTrue(data.checkListenersMd5Consistent()); - Assert.assertEquals("keytimeouts", dataIdNotifyTimeouts.get()); + assertTrue(data.checkListenersMd5Consistent()); + assertEquals("keytimeouts", dataIdNotifyTimeouts.get()); } - + @Test - public void testAbstractSharedListener() throws NacosException { + void testAbstractSharedListener() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData data = new CacheData(filter, "name1", "keyshare", "group", "tenant"); @@ -223,14 +228,14 @@ public void innerReceive(String dataId, String group, String configInfo) { String content = "content" + System.currentTimeMillis(); data.setContent(content); data.checkListenerMd5(); - Assert.assertTrue(data.checkListenersMd5Consistent()); - Assert.assertEquals(dataIdReceive[0], "keyshare"); - Assert.assertEquals(groupReceive[0], "group"); - Assert.assertEquals(contentReceive[0], content); + assertTrue(data.checkListenersMd5Consistent()); + assertEquals("keyshare", dataIdReceive[0]); + assertEquals("group", groupReceive[0]); + assertEquals(contentReceive[0], content); } - + @Test - public void testAbstractConfigChangeListener() throws NacosException { + void testAbstractConfigChangeListener() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); final CacheData data = new CacheData(filter, "name1", "keyshare", "group", "tenant"); data.setType("properties"); @@ -253,10 +258,10 @@ public Executor getExecutor() { String content = "b=b\nc=abc\nd=d"; data.setContent(content); data.checkListenerMd5(); - Assert.assertTrue(data.checkListenersMd5Consistent()); - Assert.assertEquals(PropertyChangeType.DELETED, changeItemReceived.get().getChangeItem("a").getType()); - Assert.assertEquals(PropertyChangeType.MODIFIED, changeItemReceived.get().getChangeItem("c").getType()); - Assert.assertEquals(PropertyChangeType.ADDED, changeItemReceived.get().getChangeItem("d").getType()); + assertTrue(data.checkListenersMd5Consistent()); + assertEquals(PropertyChangeType.DELETED, changeItemReceived.get().getChangeItem("a").getType()); + assertEquals(PropertyChangeType.MODIFIED, changeItemReceived.get().getChangeItem("c").getType()); + assertEquals(PropertyChangeType.ADDED, changeItemReceived.get().getChangeItem("d").getType()); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java index 5c780ebbc9d..6c811e6d48e 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java @@ -42,15 +42,14 @@ import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.MD5Utils; import com.fasterxml.jackson.databind.JsonNode; -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.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import java.lang.reflect.Field; @@ -66,9 +65,12 @@ import java.util.concurrent.atomic.AtomicReference; import static com.alibaba.nacos.api.annotation.NacosProperties.NAMESPACE; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +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; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; @@ -76,8 +78,8 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; -@RunWith(MockitoJUnitRunner.class) -public class ClientWorkerTest { +@ExtendWith(MockitoExtension.class) +class ClientWorkerTest { MockedStatic rpcClientFactoryMockedStatic; @@ -91,9 +93,9 @@ public class ClientWorkerTest { @Mock RpcClient rpcClient; - - @Before - public void before() { + + @BeforeEach + void before() { rpcClientFactoryMockedStatic = Mockito.mockStatic(RpcClientFactory.class); rpcClientFactoryMockedStatic.when( @@ -115,26 +117,26 @@ public void before() { } clientWorkerSpy = Mockito.spy(clientWorker); } - - @After - public void after() { + + @AfterEach + void after() { rpcClientFactoryMockedStatic.close(); localConfigInfoProcessorMockedStatic.close(); } - + @Test - public void testConstruct() throws NacosException { + void testConstruct() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties); - Assert.assertNotNull(clientWorker); + assertNotNull(clientWorker); } - + @Test - public void testAddListenerWithoutTenant() throws NacosException { + void testAddListenerWithoutTenant() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -152,19 +154,19 @@ public void receiveConfigInfo(String configInfo) { clientWorker.addListeners(dataId, group, Collections.singletonList(listener)); List listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(1, listeners.size()); - Assert.assertEquals(listener, listeners.get(0)); + assertEquals(1, listeners.size()); + assertEquals(listener, listeners.get(0)); clientWorker.removeListener(dataId, group, listener); listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(0, listeners.size()); + assertEquals(0, listeners.size()); CacheData cacheData = clientWorker.addCacheDataIfAbsent(dataId, group); - Assert.assertEquals(cacheData, clientWorker.getCache(dataId, group)); + assertEquals(cacheData, clientWorker.getCache(dataId, group)); } - + @Test - public void testListenerWithTenant() throws NacosException { + void testListenerWithTenant() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -183,34 +185,34 @@ public void receiveConfigInfo(String configInfo) { clientWorker.addTenantListeners(dataId, group, Collections.singletonList(listener)); List listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(1, listeners.size()); - Assert.assertEquals(listener, listeners.get(0)); + assertEquals(1, listeners.size()); + assertEquals(listener, listeners.get(0)); clientWorker.removeTenantListener(dataId, group, listener); listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(0, listeners.size()); + assertEquals(0, listeners.size()); String content = "d"; clientWorker.addTenantListenersWithContent(dataId, group, content, null, Collections.singletonList(listener)); listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(1, listeners.size()); - Assert.assertEquals(listener, listeners.get(0)); + assertEquals(1, listeners.size()); + assertEquals(listener, listeners.get(0)); clientWorker.removeTenantListener(dataId, group, listener); listeners = clientWorker.getCache(dataId, group).getListeners(); - Assert.assertEquals(0, listeners.size()); + assertEquals(0, listeners.size()); String tenant = "c"; CacheData cacheData = clientWorker.addCacheDataIfAbsent(dataId, group, tenant); - Assert.assertEquals(cacheData, clientWorker.getCache(dataId, group, tenant)); + assertEquals(cacheData, clientWorker.getCache(dataId, group, tenant)); clientWorker.removeCache(dataId, group, tenant); - Assert.assertNull(clientWorker.getCache(dataId, group, tenant)); + assertNull(clientWorker.getCache(dataId, group, tenant)); } - + @Test - public void testPublishConfigSuccess() throws NacosException { + void testPublishConfigSuccess() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -234,12 +236,12 @@ public void testPublishConfigSuccess() throws NacosException { .thenReturn(new ConfigPublishResponse()); boolean b = clientWorker.publishConfig(dataId, group, tenant, appName, tag, betaIps, content, null, casMd5, type); - Assert.assertTrue(b); + assertTrue(b); } - + @Test - public void testPublishConfigFail() throws NacosException { + void testPublishConfigFail() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -263,12 +265,12 @@ public void testPublishConfigFail() throws NacosException { .thenReturn(ConfigPublishResponse.buildFailResponse(503, "over limit")); boolean b = clientWorker.publishConfig(dataId, group, tenant, appName, tag, betaIps, content, null, casMd5, type); - Assert.assertFalse(b); + assertFalse(b); } - + @Test - public void testPublishConfigException() throws NacosException { + void testPublishConfigException() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -291,12 +293,12 @@ public void testPublishConfigException() throws NacosException { Mockito.when(rpcClient.request(any(ConfigPublishRequest.class), anyLong())).thenThrow(new NacosException()); boolean b = clientWorker.publishConfig(dataId, group, tenant, appName, tag, betaIps, content, null, casMd5, type); - Assert.assertFalse(b); + assertFalse(b); } - + @Test - public void testRemoveConfig() throws NacosException { + void testRemoveConfig() throws NacosException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); @@ -315,16 +317,16 @@ public void testRemoveConfig() throws NacosException { .thenThrow(new NacosException(503, "overlimit")); clientWorker.removeConfig(dataId, group, tenant, tag); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("overlimit", e.getErrMsg()); - Assert.assertEquals(503, e.getErrCode()); + assertEquals("overlimit", e.getErrMsg()); + assertEquals(503, e.getErrCode()); } } - + @Test - public void testGeConfigConfigSuccess() throws NacosException { + void testGeConfigConfigSuccess() throws NacosException { Properties prop = new Properties(); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -340,14 +342,14 @@ public void testGeConfigConfigSuccess() throws NacosException { .thenReturn(ConfigQueryResponse.buildSuccessResponse(content)); ConfigResponse configResponse = clientWorker.getServerConfig(dataId, group, tenant, 100, true); - Assert.assertEquals(content, configResponse.getContent()); + assertEquals(content, configResponse.getContent()); localConfigInfoProcessorMockedStatic.verify( () -> LocalConfigInfoProcessor.saveSnapshot(eq(clientWorker.getAgentName()), eq(dataId), eq(group), eq(tenant), eq(content)), times(1)); } - + @Test - public void testHandleConfigChangeReqeust() throws Exception { + void testHandleConfigChangeReqeust() throws Exception { Properties prop = new Properties(); String tenant = "c"; @@ -375,9 +377,9 @@ public void testHandleConfigChangeReqeust() throws Exception { Mockito.verify(cacheDataMocked, times(1)).setConsistentWithServer(false); Mockito.verify(atomicBoolean, times(1)).set(true); } - + @Test - public void testHandleClientMetricsReqeust() throws Exception { + void testHandleClientMetricsReqeust() throws Exception { Properties prop = new Properties(); String tenant = "c"; @@ -418,15 +420,15 @@ public void testHandleClientMetricsReqeust() throws Exception { String metricValues = jsonNode.get("metricValues") .get(ClientConfigMetricRequest.MetricsKey.build(ClientConfigMetricRequest.MetricsKey.CACHE_DATA, GroupKey.getKeyTenant(dataId, group, tenant)).toString()).textValue(); - + int colonIndex = metricValues.lastIndexOf(":"); - Assert.assertEquals(content, metricValues.substring(0, colonIndex)); - Assert.assertEquals(md5, metricValues.substring(colonIndex + 1, metricValues.length())); + assertEquals(content, metricValues.substring(0, colonIndex)); + assertEquals(md5, metricValues.substring(colonIndex + 1, metricValues.length())); } - + @Test - public void testGeConfigConfigNotFound() throws NacosException { + void testGeConfigConfigNotFound() throws NacosException { Properties prop = new Properties(); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -441,15 +443,15 @@ public void testGeConfigConfigNotFound() throws NacosException { Mockito.when(rpcClient.request(any(ConfigQueryRequest.class), anyLong())).thenReturn(configQueryResponse); ConfigResponse configResponse = clientWorker.getServerConfig(dataId, group, tenant, 100, true); - Assert.assertNull(configResponse.getContent()); + assertNull(configResponse.getContent()); localConfigInfoProcessorMockedStatic.verify( () -> LocalConfigInfoProcessor.saveSnapshot(eq(clientWorker.getAgentName()), eq(dataId), eq(group), eq(tenant), eq(null)), times(1)); } - + @Test - public void testGeConfigConfigConflict() throws NacosException { + void testGeConfigConfigConflict() throws NacosException { Properties prop = new Properties(); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -465,32 +467,32 @@ public void testGeConfigConfigConflict() throws NacosException { try { clientWorker.getServerConfig(dataId, group, tenant, 100, true); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals(NacosException.CONFLICT, e.getErrCode()); + assertEquals(NacosException.CONFLICT, e.getErrCode()); } } - + @Test - public void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties); clientWorker.shutdown(); Field agent1 = ClientWorker.class.getDeclaredField("agent"); agent1.setAccessible(true); ConfigTransportClient o = (ConfigTransportClient) agent1.get(clientWorker); - Assert.assertTrue(o.executor.isShutdown()); + assertTrue(o.executor.isShutdown()); agent1.setAccessible(false); - - Assert.assertNull(clientWorker.getAgentName()); + + assertNull(clientWorker.getAgentName()); } - + @Test - public void testExecuteConfigListen() throws Exception { + void testExecuteConfigListen() throws Exception { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); @@ -511,7 +513,7 @@ public void testExecuteConfigListen() throws Exception { String dataIdUseLocalCache = "dataIdUseLocalCache" + System.currentTimeMillis(); CacheData cacheUseLocalCache = useLocalCache(filter, agent.getName(), dataIdUseLocalCache, group, tenant, "content" + System.currentTimeMillis()); - Assert.assertFalse(cacheUseLocalCache.isUseLocalConfigInfo()); + assertFalse(cacheUseLocalCache.isUseLocalConfigInfo()); cacheDatas.add(cacheUseLocalCache); @@ -570,11 +572,11 @@ public void receiveConfigInfo(String configInfo) { (clientWorker.getAgent()).executeConfigListen(); //assert //use local cache. - Assert.assertTrue(cacheUseLocalCache.isUseLocalConfigInfo()); + assertTrue(cacheUseLocalCache.isUseLocalConfigInfo()); //discard cache to be deleted. - Assert.assertFalse(cacheMapMocked.get().containsKey(GroupKey.getKeyTenant(dataIdDiscard, group, tenant))); + assertFalse(cacheMapMocked.get().containsKey(GroupKey.getKeyTenant(dataIdDiscard, group, tenant))); //normal cache listener be notified. - Assert.assertEquals(configQueryResponse.getContent(), normalContent.get()); + assertEquals(configQueryResponse.getContent(), normalContent.get()); } @@ -614,30 +616,30 @@ private CacheData useLocalCache(ConfigFilterChainManager filter, String envName, () -> LocalConfigInfoProcessor.getFailover(envName, dataId, group, tenant)).thenReturn(failOverContent); return cacheData; } - + @Test - public void testIsHealthServer() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testIsHealthServer() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties prop = new Properties(); ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); ServerListManager agent = Mockito.mock(ServerListManager.class); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties); ClientWorker.ConfigRpcTransportClient client = Mockito.mock(ClientWorker.ConfigRpcTransportClient.class); Mockito.when(client.isHealthServer()).thenReturn(Boolean.TRUE); - + Field declaredField = ClientWorker.class.getDeclaredField("agent"); declaredField.setAccessible(true); declaredField.set(clientWorker, client); - - Assert.assertTrue(clientWorker.isHealthServer()); - + + assertTrue(clientWorker.isHealthServer()); + Mockito.when(client.isHealthServer()).thenReturn(Boolean.FALSE); assertFalse(clientWorker.isHealthServer()); } - + @Test - public void testPutCache() throws Exception { + void testPutCache() throws Exception { // 反射调用私有方法putCacheIfAbsent Method putCacheMethod = ClientWorker.class.getDeclaredMethod("putCache", String.class, CacheData.class); putCacheMethod.setAccessible(true); @@ -655,16 +657,16 @@ public void testPutCache() throws Exception { clientWorker); // 检查cacheMap是否包含特定的key assertNotNull(cacheMapRef.get().get(key)); - Assert.assertEquals(cacheData, cacheMapRef.get().get(key)); + assertEquals(cacheData, cacheMapRef.get().get(key)); // 测试再次插入相同的key将覆盖原始的值 CacheData newCacheData = new CacheData(filter, "newEnv", "newDataId", "newGroup"); putCacheMethod.invoke(clientWorker, key, newCacheData); // 检查key对应的value是否改变为newCacheData - Assert.assertEquals(newCacheData, cacheMapRef.get().get(key)); + assertEquals(newCacheData, cacheMapRef.get().get(key)); } - + @Test - public void testAddListenersEnsureCacheDataSafe() + void testAddListenersEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { String dataId = "testDataId"; String group = "testGroup"; @@ -694,9 +696,9 @@ public void testAddListenersEnsureCacheDataSafe() assertFalse(cacheDataFromCache2.isDiscard()); assertFalse(cacheDataFromCache2.isConsistentWithServer()); } - + @Test - public void testAddTenantListenersEnsureCacheDataSafe() + void testAddTenantListenersEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { String dataId = "testDataId"; String group = "testGroup"; @@ -727,9 +729,9 @@ public void testAddTenantListenersEnsureCacheDataSafe() assertFalse(cacheDataFromCache2.isDiscard()); assertFalse(cacheDataFromCache2.isConsistentWithServer()); } - + @Test - public void testAddTenantListenersWithContentEnsureCacheDataSafe() + void testAddTenantListenersWithContentEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { String dataId = "testDataId"; String group = "testGroup"; diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java index f83713720e5..6b08e9a83c9 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java @@ -17,23 +17,24 @@ package com.alibaba.nacos.client.config.impl; import com.alibaba.nacos.api.config.ConfigChangeItem; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; -public class ConfigChangeHandlerTest { - +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigChangeHandlerTest { + @Test - public void testParseProperties() throws IOException { + void testParseProperties() throws IOException { Map properties = ConfigChangeHandler.getInstance().parseChangeData("", "app.name = nacos", "properties"); - Assert.assertEquals("nacos", ((ConfigChangeItem) properties.get("app.name")).getNewValue()); + assertEquals("nacos", ((ConfigChangeItem) properties.get("app.name")).getNewValue()); } - + @Test - public void testParseYaml() throws IOException { + void testParseYaml() throws IOException { Map properties = ConfigChangeHandler.getInstance().parseChangeData("", "app:\n name: nacos", "yaml"); - Assert.assertEquals("nacos", ((ConfigChangeItem) properties.get("app.name")).getNewValue()); + assertEquals("nacos", ((ConfigChangeItem) properties.get("app.name")).getNewValue()); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java index 71355f74975..a4dc38223cc 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java @@ -16,33 +16,33 @@ package com.alibaba.nacos.client.config.impl; -import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.http.client.NacosRestTemplate; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class ConfigHttpClientManagerTest { -public class ConfigHttpClientManagerTest { - @Test - public void test() { + void test() { final ConfigHttpClientManager instance1 = ConfigHttpClientManager.getInstance(); final ConfigHttpClientManager instance2 = ConfigHttpClientManager.getInstance(); - Assert.assertEquals(instance1, instance2); + assertEquals(instance1, instance2); final NacosRestTemplate nacosRestTemplate = instance1.getNacosRestTemplate(); - Assert.assertNotNull(nacosRestTemplate); + assertNotNull(nacosRestTemplate); final int time1 = instance1.getConnectTimeoutOrDefault(10); - Assert.assertEquals(1000, time1); + assertEquals(1000, time1); final int time2 = instance1.getConnectTimeoutOrDefault(2000); - Assert.assertEquals(2000, time2); - - try { + assertEquals(2000, time2); + + Assertions.assertDoesNotThrow(() -> { instance1.shutdown(); - } catch (NacosException e) { - Assert.fail(); - } + }); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java index f481066306f..c933e17a660 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java @@ -16,22 +16,24 @@ package com.alibaba.nacos.client.config.impl; -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.assertTrue; + +class LimiterTest { -public class LimiterTest { - @Test - public void testIsLimit() { + void testIsLimit() { String keyId = "a"; //For initiating. - Assert.assertFalse(Limiter.isLimit(keyId)); + assertFalse(Limiter.isLimit(keyId)); long start = System.currentTimeMillis(); for (int j = 0; j < 5; j++) { - Assert.assertFalse(Limiter.isLimit(keyId)); + assertFalse(Limiter.isLimit(keyId)); } long elapse = System.currentTimeMillis() - start; // assert < limit 5qps - Assert.assertTrue(elapse > 980); + assertTrue(elapse > 980); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java index 9f06717c525..48c299667b1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java @@ -17,42 +17,45 @@ package com.alibaba.nacos.client.config.impl; import com.alibaba.nacos.api.config.ConfigChangeItem; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; -public class PropertiesChangeParserTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PropertiesChangeParserTest { private final PropertiesChangeParser parser = new PropertiesChangeParser(); private final String type = "properties"; - + @Test - public void testType() { - Assert.assertTrue(parser.isResponsibleFor(type)); + void testType() { + assertTrue(parser.isResponsibleFor(type)); } - + @Test - public void testAddKey() throws IOException { + void testAddKey() throws IOException { Map map = parser.doParse("", "app.name = nacos", type); - Assert.assertNull(map.get("app.name").getOldValue()); - Assert.assertEquals("nacos", map.get("app.name").getNewValue()); + assertNull(map.get("app.name").getOldValue()); + assertEquals("nacos", map.get("app.name").getNewValue()); } - + @Test - public void testRemoveKey() throws IOException { + void testRemoveKey() throws IOException { Map map = parser.doParse("app.name = nacos", "", type); - Assert.assertEquals("nacos", map.get("app.name").getOldValue()); - Assert.assertNull(map.get("app.name").getNewValue()); + assertEquals("nacos", map.get("app.name").getOldValue()); + assertNull(map.get("app.name").getNewValue()); } - + @Test - public void testModifyKey() throws IOException { + void testModifyKey() throws IOException { Map map = parser.doParse("app.name = rocketMQ", "app.name = nacos", type); - Assert.assertEquals("rocketMQ", map.get("app.name").getOldValue()); - Assert.assertEquals("nacos", map.get("app.name").getNewValue()); + assertEquals("rocketMQ", map.get("app.name").getOldValue()); + assertEquals("nacos", map.get("app.name").getNewValue()); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java index c0496b80f92..db2cc367025 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java @@ -19,8 +19,7 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.client.env.NacosClientProperties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.ArrayList; @@ -29,32 +28,38 @@ import java.util.Properties; import static com.alibaba.nacos.common.constant.RequestUrlConstants.HTTP_PREFIX; +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; +import static org.junit.jupiter.api.Assertions.fail; + +class ServerListManagerTest { -public class ServerListManagerTest { - @Test - public void testStart() throws NacosException { + void testStart() throws NacosException { final ServerListManager mgr = new ServerListManager("localhost", 0); try { mgr.start(); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals( + assertEquals( "fail to get NACOS-server serverlist! env:custom-localhost_0_nacos_serverlist, not connnect url:http://localhost:0/nacos/serverlist", e.getErrMsg()); } mgr.shutdown(); } - + @Test - public void testGetter() throws NacosException { + void testGetter() throws NacosException { { final ServerListManager mgr = new ServerListManager(); - Assert.assertEquals("nacos", mgr.getContentPath()); - Assert.assertEquals("default", mgr.getName()); - Assert.assertEquals("", mgr.getTenant()); - Assert.assertEquals("", mgr.getNamespace()); - Assert.assertEquals("1.1.1.1-2.2.2.2_8848", mgr.getFixedNameSuffix("http://1.1.1.1", "2.2.2.2:8848")); + assertEquals("nacos", mgr.getContentPath()); + assertEquals("default", mgr.getName()); + assertEquals("", mgr.getTenant()); + assertEquals("", mgr.getNamespace()); + assertEquals("1.1.1.1-2.2.2.2_8848", mgr.getFixedNameSuffix("http://1.1.1.1", "2.2.2.2:8848")); } { @@ -64,7 +69,7 @@ public void testGetter() throws NacosException { final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties); final ServerListManager mgr2 = new ServerListManager(nacosClientProperties); - Assert.assertEquals("aaa", mgr2.getContentPath()); + assertEquals("aaa", mgr2.getContentPath()); } // Test https @@ -74,8 +79,8 @@ public void testGetter() throws NacosException { properties.put(PropertyKeyConst.SERVER_ADDR, "https://1.1.1.1:8848"); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties); final ServerListManager mgr2 = new ServerListManager(nacosClientProperties); - Assert.assertEquals("aaa", mgr2.getContentPath()); - Assert.assertEquals("[https://1.1.1.1:8848]", mgr2.getServerUrls().toString()); + assertEquals("aaa", mgr2.getContentPath()); + assertEquals("[https://1.1.1.1:8848]", mgr2.getServerUrls().toString()); } { @@ -85,11 +90,11 @@ public void testGetter() throws NacosException { final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties2); final ServerListManager mgr3 = new ServerListManager(nacosClientProperties); - Assert.assertEquals(1, mgr3.getServerUrls().size()); - Assert.assertEquals("http://1.1.1.1:8848", mgr3.getServerUrls().get(0)); - Assert.assertEquals("[http://1.1.1.1:8848]", mgr3.getUrlString()); - Assert.assertTrue(mgr3.contain("http://1.1.1.1:8848")); - Assert.assertEquals("ServerManager-fixed-1.1.1.1_8848-[http://1.1.1.1:8848]", mgr3.toString()); + assertEquals(1, mgr3.getServerUrls().size()); + assertEquals("http://1.1.1.1:8848", mgr3.getServerUrls().get(0)); + assertEquals("[http://1.1.1.1:8848]", mgr3.getUrlString()); + assertTrue(mgr3.contain("http://1.1.1.1:8848")); + assertEquals("ServerManager-fixed-1.1.1.1_8848-[http://1.1.1.1:8848]", mgr3.toString()); } { @@ -99,11 +104,11 @@ public void testGetter() throws NacosException { final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties3); final ServerListManager mgr4 = new ServerListManager(nacosClientProperties); - Assert.assertEquals(2, mgr4.getServerUrls().size()); - Assert.assertEquals("http://1.1.1.1:8848", mgr4.getServerUrls().get(0)); - Assert.assertEquals("http://2.2.2.2:8848", mgr4.getServerUrls().get(1)); - Assert.assertTrue(mgr4.contain("http://1.1.1.1:8848")); - Assert.assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", mgr4.toString()); + assertEquals(2, mgr4.getServerUrls().size()); + assertEquals("http://1.1.1.1:8848", mgr4.getServerUrls().get(0)); + assertEquals("http://2.2.2.2:8848", mgr4.getServerUrls().get(1)); + assertTrue(mgr4.contain("http://1.1.1.1:8848")); + assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", mgr4.toString()); } { @@ -113,17 +118,17 @@ public void testGetter() throws NacosException { final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties4); final ServerListManager mgr5 = new ServerListManager(nacosClientProperties); - Assert.assertEquals(2, mgr5.getServerUrls().size()); - Assert.assertEquals("http://1.1.1.1:8848", mgr5.getServerUrls().get(0)); - Assert.assertEquals("http://2.2.2.2:8848", mgr5.getServerUrls().get(1)); - Assert.assertTrue(mgr5.contain("http://1.1.1.1:8848")); - Assert.assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", mgr5.toString()); + assertEquals(2, mgr5.getServerUrls().size()); + assertEquals("http://1.1.1.1:8848", mgr5.getServerUrls().get(0)); + assertEquals("http://2.2.2.2:8848", mgr5.getServerUrls().get(1)); + assertTrue(mgr5.contain("http://1.1.1.1:8848")); + assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", mgr5.toString()); } } - + @Test - public void testIterator() { + void testIterator() { List addrs = new ArrayList<>(); String addr = "1.1.1.1:8848"; addrs.add(addr); @@ -131,26 +136,26 @@ public void testIterator() { // new iterator final Iterator it = mgr.iterator(); - Assert.assertTrue(it.hasNext()); - Assert.assertEquals(addr, it.next()); + assertTrue(it.hasNext()); + assertEquals(addr, it.next()); - Assert.assertNull(mgr.getIterator()); + assertNull(mgr.getIterator()); mgr.refreshCurrentServerAddr(); - Assert.assertNotNull(mgr.getIterator()); + assertNotNull(mgr.getIterator()); final String currentServerAddr = mgr.getCurrentServerAddr(); - Assert.assertEquals(addr, currentServerAddr); + assertEquals(addr, currentServerAddr); final String nextServerAddr = mgr.getNextServerAddr(); - Assert.assertEquals(addr, nextServerAddr); + assertEquals(addr, nextServerAddr); final Iterator iterator1 = mgr.iterator(); - Assert.assertTrue(iterator1.hasNext()); + assertTrue(iterator1.hasNext()); } - + @Test - public void testAddressServerBaseServerAddrsStr() throws NacosException { + void testAddressServerBaseServerAddrsStr() throws NacosException { Properties properties = new Properties(); String serverAddrStr = "nacos.test.com:8080"; properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddrStr); @@ -158,12 +163,12 @@ public void testAddressServerBaseServerAddrsStr() throws NacosException { properties.setProperty(PropertyKeyConst.CONTEXT_PATH, endpointContextPath); final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); ServerListManager serverListManager = new ServerListManager(clientProperties); - Assert.assertEquals(1, serverListManager.serverUrls.size()); - Assert.assertTrue(serverListManager.serverUrls.contains(HTTP_PREFIX + serverAddrStr)); + assertEquals(1, serverListManager.serverUrls.size()); + assertTrue(serverListManager.serverUrls.contains(HTTP_PREFIX + serverAddrStr)); } - + @Test - public void testAddressServerBaseEndpoint() throws NacosException { + void testAddressServerBaseEndpoint() throws NacosException { Properties properties = new Properties(); String endpoint = "127.0.0.1"; properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); @@ -173,12 +178,12 @@ public void testAddressServerBaseEndpoint() throws NacosException { properties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, endpointContextPath); final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); ServerListManager serverListManager = new ServerListManager(clientProperties); - Assert.assertTrue(serverListManager.addressServerUrl.startsWith( + assertTrue(serverListManager.addressServerUrl.startsWith( HTTP_PREFIX + endpoint + ":" + endpointPort + endpointContextPath)); } - + @Test - public void testInitParam() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testInitParam() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties properties = new Properties(); String endpoint = "127.0.0.1"; properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); @@ -193,26 +198,26 @@ public void testInitParam() throws NacosException, NoSuchFieldException, Illegal Field endpointField = ServerListManager.class.getDeclaredField("endpoint"); endpointField.setAccessible(true); String fieldEndpoint = (String) endpointField.get(serverListManager); - Assert.assertEquals(endpoint, fieldEndpoint); + assertEquals(endpoint, fieldEndpoint); Field endpointPortField = ServerListManager.class.getDeclaredField("endpointPort"); endpointPortField.setAccessible(true); String fieldEndpointPort = String.valueOf(endpointPortField.get(serverListManager)); - Assert.assertEquals(endpointPort, fieldEndpointPort); + assertEquals(endpointPort, fieldEndpointPort); Field endpointContextPathField = ServerListManager.class.getDeclaredField("endpointContextPath"); endpointContextPathField.setAccessible(true); String fieldEndpointContextPath = String.valueOf(endpointContextPathField.get(serverListManager)); - Assert.assertEquals(endpointContextPath, fieldEndpointContextPath); + assertEquals(endpointContextPath, fieldEndpointContextPath); Field contentPathField = ServerListManager.class.getDeclaredField("contentPath"); contentPathField.setAccessible(true); String fieldContentPath = String.valueOf(contentPathField.get(serverListManager)); - Assert.assertEquals(fieldContentPath, contextPath); + assertEquals(fieldContentPath, contextPath); } - + @Test - public void testWithEndpointContextPath() throws NacosException { + void testWithEndpointContextPath() throws NacosException { Properties properties = new Properties(); String endpoint = "127.0.0.1"; properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); @@ -224,12 +229,12 @@ public void testWithEndpointContextPath() throws NacosException { properties.setProperty(PropertyKeyConst.CONTEXT_PATH, contextPath); final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); ServerListManager serverListManager = new ServerListManager(clientProperties); - Assert.assertTrue(serverListManager.addressServerUrl.contains(endpointContextPath)); - Assert.assertTrue(serverListManager.getName().contains("endpointContextPath")); + assertTrue(serverListManager.addressServerUrl.contains(endpointContextPath)); + assertTrue(serverListManager.getName().contains("endpointContextPath")); } - + @Test - public void testWithoutEndpointContextPath() throws NacosException { + void testWithoutEndpointContextPath() throws NacosException { Properties properties = new Properties(); String endpoint = "127.0.0.1"; properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); @@ -240,9 +245,9 @@ public void testWithoutEndpointContextPath() throws NacosException { final NacosClientProperties clientProperties = NacosClientProperties.PROTOTYPE.derive(properties); ServerListManager serverListManager = new ServerListManager(clientProperties); String endpointContextPath = "/endpointContextPath"; - Assert.assertFalse(serverListManager.addressServerUrl.contains(endpointContextPath)); - Assert.assertTrue(serverListManager.addressServerUrl.contains(contextPath)); - Assert.assertFalse(serverListManager.getName().contains("endpointContextPath")); - Assert.assertTrue(serverListManager.getName().contains("contextPath")); + assertFalse(serverListManager.addressServerUrl.contains(endpointContextPath)); + assertTrue(serverListManager.addressServerUrl.contains(contextPath)); + assertFalse(serverListManager.getName().contains("endpointContextPath")); + assertTrue(serverListManager.getName().contains("contextPath")); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java index 10d1b765029..4504a060805 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java @@ -18,46 +18,50 @@ import com.alibaba.nacos.api.config.ConfigChangeItem; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; -public class YmlChangeParserTest { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class YmlChangeParserTest { private final YmlChangeParser parser = new YmlChangeParser(); private final String type = "yaml"; - + @Test - public void testType() { - Assert.assertTrue(parser.isResponsibleFor(type)); + void testType() { + assertTrue(parser.isResponsibleFor(type)); } - + @Test - public void testAddKey() throws IOException { + void testAddKey() throws IOException { Map map = parser.doParse("", "app:\n name: nacos", type); - Assert.assertNull(map.get("app.name").getOldValue()); - Assert.assertEquals("nacos", map.get("app.name").getNewValue()); + assertNull(map.get("app.name").getOldValue()); + assertEquals("nacos", map.get("app.name").getNewValue()); } - + @Test - public void testRemoveKey() throws IOException { + void testRemoveKey() throws IOException { Map map = parser.doParse("app:\n name: nacos", "", type); - Assert.assertEquals("nacos", map.get("app.name").getOldValue()); - Assert.assertNull(map.get("app.name").getNewValue()); + assertEquals("nacos", map.get("app.name").getOldValue()); + assertNull(map.get("app.name").getNewValue()); } - + @Test - public void testModifyKey() throws IOException { + void testModifyKey() throws IOException { Map map = parser.doParse("app:\n name: rocketMQ", "app:\n name: nacos", type); - Assert.assertEquals("rocketMQ", map.get("app.name").getOldValue()); - Assert.assertEquals("nacos", map.get("app.name").getNewValue()); + assertEquals("rocketMQ", map.get("app.name").getOldValue()); + assertEquals("nacos", map.get("app.name").getNewValue()); } - + @Test - public void testComplexYaml() throws IOException { + void testComplexYaml() throws IOException { /* * map: * key1: "string" @@ -70,15 +74,17 @@ public void testComplexYaml() throws IOException { String s = "map:\n" + " key1: \"string\"\n" + " key2:\n" + " - item1\n" + " - item2\n" + " - item3\n" + " key3: 123 \n"; Map map = parser.doParse(s, s, type); - Assert.assertEquals(0, map.size()); + assertEquals(0, map.size()); } - - @Test(expected = NacosRuntimeException.class) - public void testChangeInvalidKey() { - parser.doParse("anykey:\n a", - "anykey: !!javax.script.ScriptEngineManager [\n" + " !!java.net.URLClassLoader [[\n" - + " !!java.net.URL [\"http://[yourhost]:[port]/yaml-payload.jar\"]\n" + " ]]\n" + "]", - type); + + @Test + void testChangeInvalidKey() { + assertThrows(NacosRuntimeException.class, () -> { + parser.doParse("anykey:\n a", + "anykey: !!javax.script.ScriptEngineManager [\n" + " !!java.net.URLClassLoader [[\n" + + " !!java.net.URL [\"http://[yourhost]:[port]/yaml-payload.jar\"]\n" + " ]]\n" + "]", + type); + }); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java index 12f2898c6fe..742c9a9e884 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java @@ -17,16 +17,17 @@ package com.alibaba.nacos.client.config.listener.impl; import com.alibaba.nacos.api.config.ConfigChangeEvent; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayDeque; import java.util.Deque; -public class AbstractConfigChangeListenerTest { - +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AbstractConfigChangeListenerTest { + @Test - public void receiveConfigInfo() { + void receiveConfigInfo() { final Deque data = new ArrayDeque(); AbstractConfigChangeListener a = new AbstractConfigChangeListener() { @Override @@ -41,6 +42,6 @@ public void receiveConfigInfo(String configInfo) { }; a.receiveConfigInfo("foo"); final String actual = data.poll(); - Assert.assertEquals("foo", actual); + assertEquals("foo", actual); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java index 9f7f4e63236..6c93762fc03 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java @@ -16,17 +16,19 @@ package com.alibaba.nacos.client.config.listener.impl; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayDeque; import java.util.Deque; import java.util.Properties; -public class PropertiesListenerTest { - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class PropertiesListenerTest { + @Test - public void testReceiveConfigInfo() { + void testReceiveConfigInfo() { final Deque q2 = new ArrayDeque(); PropertiesListener a = new PropertiesListener() { @Override @@ -36,13 +38,13 @@ public void innerReceive(Properties properties) { }; a.receiveConfigInfo("foo=bar"); final Properties actual = q2.poll(); - Assert.assertEquals(1, actual.size()); - Assert.assertEquals("bar", actual.getProperty("foo")); + assertEquals(1, actual.size()); + assertEquals("bar", actual.getProperty("foo")); } - + @Test - public void testReceiveConfigInfoEmpty() { + void testReceiveConfigInfoEmpty() { final Deque q2 = new ArrayDeque(); PropertiesListener a = new PropertiesListener() { @Override @@ -52,11 +54,11 @@ public void innerReceive(Properties properties) { }; a.receiveConfigInfo(""); final Properties actual = q2.poll(); - Assert.assertNull(actual); + assertNull(actual); } - + @Test - public void testReceiveConfigInfoIsNotProperties() { + void testReceiveConfigInfoIsNotProperties() { final Deque q2 = new ArrayDeque(); PropertiesListener a = new PropertiesListener() { @Override @@ -66,11 +68,11 @@ public void innerReceive(Properties properties) { }; a.receiveConfigInfo(null); final Properties actual = q2.poll(); - Assert.assertNull(actual); + assertNull(actual); } - + @Test - public void testInnerReceive() { + void testInnerReceive() { final Deque q2 = new ArrayDeque(); PropertiesListener a = new PropertiesListener() { @Override @@ -82,8 +84,8 @@ public void innerReceive(Properties properties) { input.put("foo", "bar"); a.innerReceive(input); final Properties actual = q2.poll(); - Assert.assertEquals(1, actual.size()); - Assert.assertEquals("bar", actual.getProperty("foo")); + assertEquals(1, actual.size()); + assertEquals("bar", actual.getProperty("foo")); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java index ba2e0b33041..66b2d4f18c2 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java @@ -18,103 +18,108 @@ package com.alibaba.nacos.client.config.utils; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.Arrays; import static com.alibaba.nacos.api.common.Constants.WORD_SEPARATOR; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ContentUtilsTest { -public class ContentUtilsTest { - - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); - @Test - public void testVerifyIncrementPubContent() { + void testVerifyIncrementPubContent() { String content = "aabbb"; ContentUtils.verifyIncrementPubContent(content); } - + @Test - public void testVerifyIncrementPubContentFail1() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("publish/delete content can not be null"); - String content = null; - ContentUtils.verifyIncrementPubContent(content); + void testVerifyIncrementPubContentFail1() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String content = null; + ContentUtils.verifyIncrementPubContent(content); + }); + assertTrue(exception.getMessage().contains("publish/delete content can not be null")); } - + @Test - public void testVerifyIncrementPubContentFail2() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("publish/delete content can not contain return and linefeed"); - String content = "aa\rbbb"; - ContentUtils.verifyIncrementPubContent(content); + void testVerifyIncrementPubContentFail2() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String content = "aa\rbbb"; + ContentUtils.verifyIncrementPubContent(content); + }); + assertTrue(exception.getMessage().contains("publish/delete content can not contain return and linefeed")); } - + @Test - public void testVerifyIncrementPubContentFail3() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("publish/delete content can not be null"); - String content = ""; - ContentUtils.verifyIncrementPubContent(content); + void testVerifyIncrementPubContentFail3() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String content = ""; + ContentUtils.verifyIncrementPubContent(content); + }); + assertTrue(exception.getMessage().contains("publish/delete content can not be null")); } - + @Test - public void testVerifyIncrementPubContentFail4() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("publish/delete content can not contain(char)2"); - String content = "aa" + WORD_SEPARATOR + "bbb"; - ContentUtils.verifyIncrementPubContent(content); + void testVerifyIncrementPubContentFail4() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String content = "aa" + WORD_SEPARATOR + "bbb"; + ContentUtils.verifyIncrementPubContent(content); + }); + assertTrue(exception.getMessage().contains("publish/delete content can not contain(char)2")); } - + @Test - public void testGetContentIdentity() { + void testGetContentIdentity() { String content = "aa" + WORD_SEPARATOR + "bbb"; String content1 = ContentUtils.getContentIdentity(content); - Assert.assertEquals("aa", content1); + assertEquals("aa", content1); } - - @Test(expected = IllegalArgumentException.class) - public void testGetContentIdentityFail() { - String content = "aabbb"; - ContentUtils.getContentIdentity(content); + + @Test + void testGetContentIdentityFail() { + assertThrows(IllegalArgumentException.class, () -> { + String content = "aabbb"; + ContentUtils.getContentIdentity(content); + }); } - + @Test - public void testGetContent() { + void testGetContent() { String content = "aa" + WORD_SEPARATOR + "bbb"; String content1 = ContentUtils.getContent(content); - Assert.assertEquals("bbb", content1); + assertEquals("bbb", content1); } - - @Test(expected = IllegalArgumentException.class) - public void testGetContentFail() { - String content = "aabbb"; - ContentUtils.getContent(content); + + @Test + void testGetContentFail() { + assertThrows(IllegalArgumentException.class, () -> { + String content = "aabbb"; + ContentUtils.getContent(content); + }); } - + @Test - public void testTruncateContent() { + void testTruncateContent() { String content = "aa"; String actual = ContentUtils.truncateContent(content); - Assert.assertEquals(content, actual); + assertEquals(content, actual); } - + @Test - public void testTruncateLongContent() { + void testTruncateLongContent() { char[] arr = new char[101]; Arrays.fill(arr, 'a'); String content = new String(arr); String actual = ContentUtils.truncateContent(content); - Assert.assertEquals(content.substring(0, 100) + "...", actual); + assertEquals(content.substring(0, 100) + "...", actual); } - + @Test - public void testTruncateContentNull() { + void testTruncateContentNull() { String actual = ContentUtils.truncateContent(null); - Assert.assertEquals("", actual); + assertEquals("", actual); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java index fcb39767a3f..2ffa632ee05 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java @@ -18,45 +18,47 @@ package com.alibaba.nacos.client.config.utils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -public class JvmUtilTest { +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class JvmUtilTest { Method initMethod; - - @Before - public void setUp() throws NoSuchMethodException { + + @BeforeEach + void setUp() throws NoSuchMethodException { initMethod = JvmUtil.class.getDeclaredMethod("init"); initMethod.setAccessible(true); } - - @After - public void tearDown() throws NoSuchFieldException, IllegalAccessException { + + @AfterEach + void tearDown() throws NoSuchFieldException, IllegalAccessException { System.clearProperty("isMultiInstance"); Field field = JvmUtil.class.getDeclaredField("isMultiInstance"); field.setAccessible(true); field.set(JvmUtil.class, false); } - + @Test - public void testIsMultiInstance() throws InvocationTargetException, IllegalAccessException { + void testIsMultiInstance() throws InvocationTargetException, IllegalAccessException { initMethod.invoke(JvmUtil.class); Boolean multiInstance = JvmUtil.isMultiInstance(); - Assert.assertFalse(multiInstance); + assertFalse(multiInstance); } - + @Test - public void testIsMultiInstance2() throws InvocationTargetException, IllegalAccessException { + void testIsMultiInstance2() throws InvocationTargetException, IllegalAccessException { System.setProperty("isMultiInstance", "true"); initMethod.invoke(JvmUtil.class); Boolean multiInstance = JvmUtil.isMultiInstance(); - Assert.assertTrue(multiInstance); + assertTrue(multiInstance); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java index ac9142edb3e..0b41c9ee49e 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java @@ -19,69 +19,71 @@ package com.alibaba.nacos.client.config.utils; import com.alibaba.nacos.api.exception.NacosException; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; -public class ParamUtilsTest { - - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class ParamUtilsTest { + @Test - public void testIsValid() { + void testIsValid() { String content = "abcABC09.:_-"; - Assert.assertTrue(ParamUtils.isValid(content)); + assertTrue(ParamUtils.isValid(content)); content = null; - Assert.assertFalse(ParamUtils.isValid(content)); + assertFalse(ParamUtils.isValid(content)); content = "@"; - Assert.assertFalse(ParamUtils.isValid(content)); + assertFalse(ParamUtils.isValid(content)); content = "+"; - Assert.assertFalse(ParamUtils.isValid(content)); + assertFalse(ParamUtils.isValid(content)); content = "/"; - Assert.assertFalse(ParamUtils.isValid(content)); + assertFalse(ParamUtils.isValid(content)); } - + @Test - public void testCheckTdg() throws NacosException { + void testCheckTdg() throws NacosException { String tenant = "a"; String dataId = "b"; String group = "c"; ParamUtils.checkTdg(tenant, dataId, group); } - + @Test - public void testCheckTdgFail1() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("dataId invalid"); - - String tenant = "a"; - String dataId = ""; - String group = "c"; - ParamUtils.checkTdg(tenant, dataId, group); + void testCheckTdgFail1() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + String tenant = "a"; + String dataId = ""; + String group = "c"; + ParamUtils.checkTdg(tenant, dataId, group); + }); + assertTrue(exception.getMessage().contains("dataId invalid")); } - + @Test - public void testCheckTdgFail2() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("group invalid"); - - String tenant = "a"; - String dataId = "b"; - String group = ""; - ParamUtils.checkTdg(tenant, dataId, group); + void testCheckTdgFail2() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + String tenant = "a"; + String dataId = "b"; + String group = ""; + ParamUtils.checkTdg(tenant, dataId, group); + }); + assertTrue(exception.getMessage().contains("group invalid")); } - + @Test - public void testCheckKeyParam1() throws NacosException { + void testCheckKeyParam1() throws NacosException { String dataId = "b"; String group = "c"; ParamUtils.checkKeyParam(dataId, group); @@ -90,23 +92,23 @@ public void testCheckKeyParam1() throws NacosException { dataId = ""; group = "c"; ParamUtils.checkKeyParam(dataId, group); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("dataId invalid", e.getMessage()); + assertEquals("dataId invalid", e.getMessage()); } try { dataId = "b"; group = ""; ParamUtils.checkKeyParam(dataId, group); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("group invalid", e.getMessage()); + assertEquals("group invalid", e.getMessage()); } } - + @Test - public void testCheckKeyParam2() throws NacosException { + void testCheckKeyParam2() throws NacosException { String dataId = "b"; String group = "c"; String datumId = "a"; @@ -117,9 +119,9 @@ public void testCheckKeyParam2() throws NacosException { group = "c"; ParamUtils.checkKeyParam(dataId, group, datumId); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("dataId invalid", e.getMessage()); + assertEquals("dataId invalid", e.getMessage()); } try { @@ -127,9 +129,9 @@ public void testCheckKeyParam2() throws NacosException { group = ""; ParamUtils.checkKeyParam(dataId, group, datumId); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("group invalid", e.getMessage()); + assertEquals("group invalid", e.getMessage()); } try { @@ -138,14 +140,14 @@ public void testCheckKeyParam2() throws NacosException { datumId = ""; ParamUtils.checkKeyParam(dataId, group, datumId); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("datumId invalid", e.getMessage()); + assertEquals("datumId invalid", e.getMessage()); } } - + @Test - public void testCheckKeyParam3() throws NacosException { + void testCheckKeyParam3() throws NacosException { String dataId = "b"; String group = "c"; ParamUtils.checkKeyParam(Arrays.asList(dataId), group); @@ -154,9 +156,9 @@ public void testCheckKeyParam3() throws NacosException { group = "c"; ParamUtils.checkKeyParam(new ArrayList(), group); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("dataIds invalid", e.getMessage()); + assertEquals("dataIds invalid", e.getMessage()); } try { @@ -164,9 +166,9 @@ public void testCheckKeyParam3() throws NacosException { group = "c"; ParamUtils.checkKeyParam(Arrays.asList(dataId), group); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("dataId invalid", e.getMessage()); + assertEquals("dataId invalid", e.getMessage()); } try { @@ -174,95 +176,101 @@ public void testCheckKeyParam3() throws NacosException { group = ""; ParamUtils.checkKeyParam(Arrays.asList(dataId), group); - Assert.fail(); + fail(); } catch (NacosException e) { - Assert.assertEquals("group invalid", e.getMessage()); + assertEquals("group invalid", e.getMessage()); } } - + @Test - public void testCheckParam() throws NacosException { + void testCheckParam() throws NacosException { String dataId = "b"; String group = "c"; String content = "a"; ParamUtils.checkParam(dataId, group, content); } - + @Test - public void testCheckParamFail() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("content invalid"); - - String dataId = "b"; - String group = "c"; - String content = ""; - ParamUtils.checkParam(dataId, group, content); + void testCheckParamFail() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + String dataId = "b"; + String group = "c"; + String content = ""; + ParamUtils.checkParam(dataId, group, content); + }); + assertTrue(exception.getMessage().contains("content invalid")); } - + @Test - public void testCheckParam2() throws NacosException { + void testCheckParam2() throws NacosException { String dataId = "b"; String group = "c"; String datumId = "d"; String content = "a"; ParamUtils.checkParam(dataId, group, datumId, content); } - + @Test - public void testCheckParam2Fail() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("content invalid"); - - String dataId = "b"; - String group = "c"; - String datumId = "d"; - String content = ""; - ParamUtils.checkParam(dataId, group, datumId, content); + void testCheckParam2Fail() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + String dataId = "b"; + String group = "c"; + String datumId = "d"; + String content = ""; + ParamUtils.checkParam(dataId, group, datumId, content); + }); + assertTrue(exception.getMessage().contains("content invalid")); } - + @Test - public void testCheckTenant() throws NacosException { + void testCheckTenant() throws NacosException { String tenant = "a"; ParamUtils.checkTenant(tenant); } - + @Test - public void testCheckTenantFail() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("tenant invalid"); - String tenant = ""; - ParamUtils.checkTenant(tenant); + void testCheckTenantFail() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + String tenant = ""; + ParamUtils.checkTenant(tenant); + }); + assertTrue(exception.getMessage().contains("tenant invalid")); } - + @Test - public void testCheckBetaIps() throws NacosException { + void testCheckBetaIps() throws NacosException { ParamUtils.checkBetaIps("127.0.0.1"); } - + @Test - public void testCheckBetaIpsFail1() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("betaIps invalid"); - - ParamUtils.checkBetaIps(""); + void testCheckBetaIpsFail1() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + ParamUtils.checkBetaIps(""); + }); + assertTrue(exception.getMessage().contains("betaIps invalid")); } - + @Test - public void testCheckBetaIpsFail2() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("betaIps invalid"); - ParamUtils.checkBetaIps("aaa"); + void testCheckBetaIpsFail2() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + ParamUtils.checkBetaIps("aaa"); + }); + assertTrue(exception.getMessage().contains("betaIps invalid")); } - + @Test - public void testCheckContent() throws NacosException { + void testCheckContent() throws NacosException { ParamUtils.checkContent("aaa"); } - + @Test - public void testCheckContentFail() throws NacosException { - exceptionRule.expect(NacosException.class); - exceptionRule.expectMessage("content invalid"); - ParamUtils.checkContent(""); + void testCheckContentFail() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + ParamUtils.checkContent(""); + }); + assertTrue(exception.getMessage().contains("content invalid")); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java index 13ad8f4364e..ae2d583cf4a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java @@ -18,21 +18,23 @@ package com.alibaba.nacos.client.config.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.assertTrue; + +class SnapShotSwitchTest { -public class SnapShotSwitchTest { - @Test - public void testGetIsSnapShot() { + void testGetIsSnapShot() { Boolean isSnapShot = SnapShotSwitch.getIsSnapShot(); - Assert.assertTrue(isSnapShot); + assertTrue(isSnapShot); SnapShotSwitch.setIsSnapShot(false); - Assert.assertFalse(SnapShotSwitch.getIsSnapShot()); + assertFalse(SnapShotSwitch.getIsSnapShot()); SnapShotSwitch.setIsSnapShot(true); - Assert.assertTrue(SnapShotSwitch.getIsSnapShot()); + assertTrue(SnapShotSwitch.getIsSnapShot()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java b/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java index ce696d99b3c..8d6a4c352c7 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java @@ -16,34 +16,39 @@ package com.alibaba.nacos.client.env; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.Properties; -public class NacosClientPropertiesTest { - - @BeforeClass - public static void init() { +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; + +class NacosClientPropertiesTest { + + @BeforeAll + static void init() { System.setProperty("nacos.env.first", "jvm"); } - - @AfterClass - public static void teardown() { + + @AfterAll + static void teardown() { System.clearProperty("nacos.env.first"); } - + @Test - public void testGetProperty() { + void testGetProperty() { NacosClientProperties.PROTOTYPE.setProperty("nacos.home", "/home/nacos"); final String value = NacosClientProperties.PROTOTYPE.getProperty("nacos.home"); - Assert.assertEquals("/home/nacos", value); + assertEquals("/home/nacos", value); } - + @Test - public void testGetPropertyMultiLayer() { + void testGetPropertyMultiLayer() { NacosClientProperties.PROTOTYPE.setProperty("top.layer", "top"); @@ -57,85 +62,85 @@ public void testGetPropertyMultiLayer() { layerCEnv.setProperty("c.layer", "c"); String value = layerCEnv.getProperty("c.layer"); - Assert.assertEquals("c", value); + assertEquals("c", value); value = layerCEnv.getProperty("b.layer"); - Assert.assertEquals("b", value); + assertEquals("b", value); value = layerCEnv.getProperty("a.layer"); - Assert.assertEquals("a", value); + assertEquals("a", value); value = layerCEnv.getProperty("top.layer"); - Assert.assertEquals("top", value); + assertEquals("top", value); } - + @Test - public void testGetPropertyDefaultValue() { + void testGetPropertyDefaultValue() { final String value = NacosClientProperties.PROTOTYPE.getProperty("nacos.home.default", "/home/default_value"); - Assert.assertEquals("/home/default_value", value); + assertEquals("/home/default_value", value); } - + @Test - public void testGetBoolean() { + void testGetBoolean() { NacosClientProperties.PROTOTYPE.setProperty("use.cluster", "true"); final Boolean value = NacosClientProperties.PROTOTYPE.getBoolean("use.cluster"); - Assert.assertTrue(value); + assertTrue(value); } - + @Test - public void testGetBooleanDefaultValue() { + void testGetBooleanDefaultValue() { final Boolean value = NacosClientProperties.PROTOTYPE.getBoolean("use.cluster.default", false); - Assert.assertFalse(value); + assertFalse(value); } - + @Test - public void testGetInteger() { + void testGetInteger() { NacosClientProperties.PROTOTYPE.setProperty("max.timeout", "200"); final Integer value = NacosClientProperties.PROTOTYPE.getInteger("max.timeout"); - Assert.assertEquals(200, value.intValue()); + assertEquals(200, value.intValue()); } - + @Test - public void testGetIntegerDefaultValue() { + void testGetIntegerDefaultValue() { final Integer value = NacosClientProperties.PROTOTYPE.getInteger("max.timeout.default", 400); - Assert.assertEquals(400, value.intValue()); + assertEquals(400, value.intValue()); } - + @Test - public void testGetLong() { + void testGetLong() { NacosClientProperties.PROTOTYPE.setProperty("connection.timeout", "200"); final Long value = NacosClientProperties.PROTOTYPE.getLong("connection.timeout"); - Assert.assertEquals(200L, value.longValue()); + assertEquals(200L, value.longValue()); } - + @Test - public void testGetLongDefault() { + void testGetLongDefault() { final Long value = NacosClientProperties.PROTOTYPE.getLong("connection.timeout.default", 400L); - Assert.assertEquals(400L, value.longValue()); + assertEquals(400L, value.longValue()); } - + @Test - public void setProperty() { + void setProperty() { NacosClientProperties.PROTOTYPE.setProperty("nacos.set.property", "true"); final String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.set.property"); - Assert.assertEquals("true", ret); + assertEquals("true", ret); } - + @Test - public void setPropertyWithScope() { + void setPropertyWithScope() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty("nacos.set.property.scope", "config"); String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.set.property.scope"); - Assert.assertNull(ret); + assertNull(ret); ret = properties.getProperty("nacos.set.property.scope"); - Assert.assertEquals("config", ret); + assertEquals("config", ret); } - + @Test - public void testAddProperties() { + void testAddProperties() { Properties properties = new Properties(); properties.setProperty("nacos.add.properties", "true"); @@ -143,11 +148,11 @@ public void testAddProperties() { final String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.add.properties"); - Assert.assertEquals("true", ret); + assertEquals("true", ret); } - + @Test - public void testAddPropertiesWithScope() { + void testAddPropertiesWithScope() { Properties properties = new Properties(); properties.setProperty("nacos.add.properties.scope", "config"); @@ -156,15 +161,15 @@ public void testAddPropertiesWithScope() { nacosClientProperties.addProperties(properties); String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.add.properties.scope"); - Assert.assertNull(ret); + assertNull(ret); ret = nacosClientProperties.getProperty("nacos.add.properties.scope"); - Assert.assertEquals("config", ret); + assertEquals("config", ret); } - + @Test - public void testTestDerive() { + void testTestDerive() { Properties properties = new Properties(); properties.setProperty("nacos.derive.properties.scope", "derive"); @@ -172,23 +177,23 @@ public void testTestDerive() { final String value = nacosClientProperties.getProperty("nacos.derive.properties.scope"); - Assert.assertEquals("derive", value); + assertEquals("derive", value); } - + @Test - public void testContainsKey() { + void testContainsKey() { NacosClientProperties.PROTOTYPE.setProperty("nacos.contains.key", "true"); boolean ret = NacosClientProperties.PROTOTYPE.containsKey("nacos.contains.key"); - Assert.assertTrue(ret); + assertTrue(ret); ret = NacosClientProperties.PROTOTYPE.containsKey("nacos.contains.key.in.sys"); - Assert.assertFalse(ret); + assertFalse(ret); } - + @Test - public void testContainsKeyMultiLayers() { + void testContainsKeyMultiLayers() { NacosClientProperties.PROTOTYPE.setProperty("top.layer", "top"); @@ -202,49 +207,49 @@ public void testContainsKeyMultiLayers() { layerCEnv.setProperty("c.layer", "c"); boolean exist = layerCEnv.containsKey("c.layer"); - Assert.assertTrue(exist); + assertTrue(exist); exist = layerCEnv.containsKey("b.layer"); - Assert.assertTrue(exist); + assertTrue(exist); exist = layerCEnv.containsKey("a.layer"); - Assert.assertTrue(exist); + assertTrue(exist); exist = layerCEnv.containsKey("top.layer"); - Assert.assertTrue(exist); + assertTrue(exist); } - + @Test - public void testContainsKeyWithScope() { + void testContainsKeyWithScope() { NacosClientProperties.PROTOTYPE.setProperty("nacos.contains.global.scope", "global"); final NacosClientProperties namingProperties = NacosClientProperties.PROTOTYPE.derive(); namingProperties.setProperty("nacos.contains.naming.scope", "naming"); boolean ret = NacosClientProperties.PROTOTYPE.containsKey("nacos.contains.global.scope"); - Assert.assertTrue(ret); + assertTrue(ret); ret = NacosClientProperties.PROTOTYPE.containsKey("nacos.contains.naming.scope"); - Assert.assertFalse(ret); + assertFalse(ret); ret = namingProperties.containsKey("nacos.contains.naming.scope"); - Assert.assertTrue(ret); + assertTrue(ret); ret = namingProperties.containsKey("nacos.contains.global.scope"); - Assert.assertTrue(ret); + assertTrue(ret); } - + @Test - public void testAsProperties() { + void testAsProperties() { NacosClientProperties.PROTOTYPE.setProperty("nacos.as.properties", "true"); final Properties properties = NacosClientProperties.PROTOTYPE.asProperties(); - Assert.assertNotNull(properties); - Assert.assertEquals("true", properties.getProperty("nacos.as.properties")); + assertNotNull(properties); + assertEquals("true", properties.getProperty("nacos.as.properties")); } - + @Test - public void testAsPropertiesWithScope() { + void testAsPropertiesWithScope() { NacosClientProperties.PROTOTYPE.setProperty("nacos.as.properties.global.scope", "global"); NacosClientProperties.PROTOTYPE.setProperty("nacos.server.addr.scope", "global"); @@ -253,17 +258,17 @@ public void testAsPropertiesWithScope() { configProperties.setProperty("nacos.server.addr.scope", "config"); final Properties properties = configProperties.asProperties(); - Assert.assertNotNull(properties); + assertNotNull(properties); String ret = properties.getProperty("nacos.as.properties.global.scope"); - Assert.assertEquals("global", ret); + assertEquals("global", ret); ret = properties.getProperty("nacos.server.addr.scope"); - Assert.assertEquals("config", ret); + assertEquals("config", ret); } - + @Test - public void testGetPropertyWithScope() { + void testGetPropertyWithScope() { NacosClientProperties.PROTOTYPE.setProperty("nacos.global.scope", "global"); @@ -274,41 +279,41 @@ public void testGetPropertyWithScope() { namingProperties.setProperty("nacos.naming.scope", "naming"); String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.global.scope"); - Assert.assertEquals("global", ret); + assertEquals("global", ret); ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.config.scope"); - Assert.assertNull(ret); + assertNull(ret); ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.naming.scope"); - Assert.assertNull(ret); + assertNull(ret); ret = configProperties.getProperty("nacos.config.scope"); - Assert.assertEquals("config", ret); + assertEquals("config", ret); ret = configProperties.getProperty("nacos.global.scope"); - Assert.assertEquals("global", ret); + assertEquals("global", ret); ret = configProperties.getProperty("nacos.naming.scope"); - Assert.assertNull(ret); + assertNull(ret); ret = namingProperties.getProperty("nacos.naming.scope"); - Assert.assertEquals("naming", ret); + assertEquals("naming", ret); ret = namingProperties.getProperty("nacos.global.scope"); - Assert.assertEquals("global", ret); + assertEquals("global", ret); ret = namingProperties.getProperty("nacos.config.scope"); - Assert.assertNull(ret); + assertNull(ret); } - + @Test - public void testGetPropertyFrom() { + void testGetPropertyFrom() { System.setProperty("nacos.home.default.test", "/home/jvm_args"); NacosClientProperties.PROTOTYPE.setProperty("nacos.home.default.test", "/home/properties_args"); - - Assert.assertEquals(NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.JVM, "nacos.home.default.test"), - "/home/jvm_args"); - Assert.assertEquals( - NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.PROPERTIES, "nacos.home.default.test"), - "/home/properties_args"); - Assert.assertEquals(NacosClientProperties.PROTOTYPE.getPropertyFrom(null, "nacos.home.default.test"), + + assertEquals( + "/home/jvm_args", NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.JVM, "nacos.home.default.test")); + assertEquals( + "/home/properties_args", + NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.PROPERTIES, "nacos.home.default.test")); + assertEquals(NacosClientProperties.PROTOTYPE.getPropertyFrom(null, "nacos.home.default.test"), NacosClientProperties.PROTOTYPE.getProperty("nacos.home.default.test")); } diff --git a/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java b/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java index 5518884b21a..e7fb2f3eb3e 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java @@ -17,59 +17,59 @@ package com.alibaba.nacos.client.env; import com.alibaba.nacos.client.constant.Constants; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Additional test cases for SearchableProperties. * *

Common cases see {@link NacosClientPropertiesTest}.

*/ -public class SearchablePropertiesTest { +class SearchablePropertiesTest { Method initMethod; - - @BeforeClass - public static void init() { + + @BeforeAll + static void init() { System.setProperty(Constants.SysEnv.NACOS_ENV_FIRST, "jvm"); } - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { initMethod = SearchableProperties.class.getDeclaredMethod("init"); initMethod.setAccessible(true); } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { init(); initMethod.invoke(null); } - - @AfterClass - public static void teardown() { + + @AfterAll + static void teardown() { System.clearProperty(Constants.SysEnv.NACOS_ENV_FIRST); } - + @Test - public void testInitWithInvalidOrder() throws IllegalAccessException, InvocationTargetException { + void testInitWithInvalidOrder() throws IllegalAccessException, InvocationTargetException { System.setProperty(Constants.SysEnv.NACOS_ENV_FIRST, "invalid"); List order = (List) initMethod.invoke(null); assertOrder(order, SourceType.PROPERTIES, SourceType.JVM, SourceType.ENV); } - + @Test - public void testInitWithoutSpecifiedOrder() throws IllegalAccessException, InvocationTargetException { + void testInitWithoutSpecifiedOrder() throws IllegalAccessException, InvocationTargetException { System.clearProperty(Constants.SysEnv.NACOS_ENV_FIRST); List order = (List) initMethod.invoke(null); assertOrder(order, SourceType.PROPERTIES, SourceType.JVM, SourceType.ENV); @@ -81,17 +81,17 @@ private void assertOrder(List order, SourceType... sourceTypes) { assertEquals(sourceTypes[i], order.get(i)); } } - + @Test - public void testGetPropertyFromEnv() { + void testGetPropertyFromEnv() { System.setProperty("testFromSource", "jvm"); NacosClientProperties properties = SearchableProperties.INSTANCE.derive(); properties.setProperty("testFromSource", "properties"); assertNull(properties.getPropertyFrom(SourceType.ENV, "testFromSource")); } - + @Test - public void testGetPropertyFromUnknown() { + void testGetPropertyFromUnknown() { System.setProperty("testFromSource", "jvm"); NacosClientProperties properties = SearchableProperties.INSTANCE.derive(); properties.setProperty("testFromSource", "properties"); diff --git a/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java b/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java index 89361fc68a2..669363c63b6 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java @@ -16,28 +16,28 @@ package com.alibaba.nacos.client.env; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Additional test cases for SystemEnvPropertySource. * *

Common cases see {@link NacosClientPropertiesTest}.

*/ -public class SystemEnvPropertySourceTest { +class SystemEnvPropertySourceTest { SystemEnvPropertySource systemEnvPropertySource; private Map mockEnvMap; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { systemEnvPropertySource = new SystemEnvPropertySource(); mockEnvMap = new HashMap<>(); Field envField = SystemEnvPropertySource.class.getDeclaredField("env"); @@ -48,44 +48,44 @@ public void setUp() throws Exception { mockEnvMap.put("TESTCASE3", "value3"); mockEnvMap.put("TEST_CASE_4", "value4"); } - + @Test - public void testGetEnvForLowerCaseKey() { + void testGetEnvForLowerCaseKey() { assertEquals("value1", systemEnvPropertySource.getProperty("testcase1")); } - + @Test - public void testGetEnvForLowerCaseKeyWithDot() { + void testGetEnvForLowerCaseKeyWithDot() { assertEquals("value2", systemEnvPropertySource.getProperty("test.case.2")); } - + @Test - public void testGetEnvForLowerCaseKeyWithHyphen() { + void testGetEnvForLowerCaseKeyWithHyphen() { assertEquals("value2", systemEnvPropertySource.getProperty("test-case-2")); } - + @Test - public void testGetEnvForLowerCaseKeyWithHyphenAndDot() { + void testGetEnvForLowerCaseKeyWithHyphenAndDot() { assertEquals("value2", systemEnvPropertySource.getProperty("test.case-2")); } - + @Test - public void testGetEnvForUpperCaseKey() { + void testGetEnvForUpperCaseKey() { assertEquals("value3", systemEnvPropertySource.getProperty("TESTCASE3")); } - + @Test - public void testGetEnvForUpperCaseKeyWithDot() { + void testGetEnvForUpperCaseKeyWithDot() { assertEquals("value4", systemEnvPropertySource.getProperty("TEST.CASE.4")); } - + @Test - public void testGetEnvForUpperCaseKeyWithHyphen() { + void testGetEnvForUpperCaseKeyWithHyphen() { assertEquals("value4", systemEnvPropertySource.getProperty("TEST-CASE-4")); } - + @Test - public void testGetEnvForUpperCaseKeyWithHyphenAndDot() { + void testGetEnvForUpperCaseKeyWithHyphenAndDot() { assertEquals("value4", systemEnvPropertySource.getProperty("TEST_CASE.4")); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java b/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java index a248a42eed6..4358018482c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java @@ -16,92 +16,101 @@ package com.alibaba.nacos.client.env.convert; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.MissingFormatArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class CompositeConverterTest { +class CompositeConverterTest { CompositeConverter compositeConverter; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { compositeConverter = new CompositeConverter(); } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { } - - @Test(expected = MissingFormatArgumentException.class) - public void testConvertNotSupportType() { - compositeConverter.convert("test", CompositeConverter.class); + + @Test + void testConvertNotSupportType() { + assertThrows(MissingFormatArgumentException.class, () -> { + compositeConverter.convert("test", CompositeConverter.class); + }); } - + @Test - public void testConvertBooleanForEmptyProperty() { + void testConvertBooleanForEmptyProperty() { assertNull(compositeConverter.convert(null, Boolean.class)); } - + @Test - public void testConvertBooleanTrue() { + void testConvertBooleanTrue() { assertTrue(compositeConverter.convert("true", Boolean.class)); assertTrue(compositeConverter.convert("on", Boolean.class)); assertTrue(compositeConverter.convert("yes", Boolean.class)); assertTrue(compositeConverter.convert("1", Boolean.class)); } - + @Test - public void testConvertBooleanFalse() { + void testConvertBooleanFalse() { assertFalse(compositeConverter.convert("false", Boolean.class)); assertFalse(compositeConverter.convert("off", Boolean.class)); assertFalse(compositeConverter.convert("no", Boolean.class)); assertFalse(compositeConverter.convert("0", Boolean.class)); } - - @Test(expected = IllegalArgumentException.class) - public void testConvertBooleanIllegal() { - compositeConverter.convert("aaa", Boolean.class); + + @Test + void testConvertBooleanIllegal() { + assertThrows(IllegalArgumentException.class, () -> { + compositeConverter.convert("aaa", Boolean.class); + }); } - + @Test - public void testConvertIntegerForEmptyProperty() { + void testConvertIntegerForEmptyProperty() { assertNull(compositeConverter.convert(null, Integer.class)); } - + @Test - public void testConvertInteger() { + void testConvertInteger() { assertEquals(100, (int) compositeConverter.convert("100", Integer.class)); assertEquals(Integer.MAX_VALUE, (int) compositeConverter.convert(String.valueOf(Integer.MAX_VALUE), Integer.class)); assertEquals(Integer.MIN_VALUE, (int) compositeConverter.convert(String.valueOf(Integer.MIN_VALUE), Integer.class)); } - - @Test(expected = IllegalArgumentException.class) - public void testConvertIntegerIllegal() { - compositeConverter.convert("aaa", Integer.class); + + @Test + void testConvertIntegerIllegal() { + assertThrows(IllegalArgumentException.class, () -> { + compositeConverter.convert("aaa", Integer.class); + }); } - + @Test - public void testConvertLongForEmptyProperty() { + void testConvertLongForEmptyProperty() { assertNull(compositeConverter.convert(null, Long.class)); } - + @Test - public void testConvertLong() { + void testConvertLong() { assertEquals(100L, (long) compositeConverter.convert("100", Long.class)); assertEquals(Long.MAX_VALUE, (long) compositeConverter.convert(String.valueOf(Long.MAX_VALUE), Long.class)); assertEquals(Long.MIN_VALUE, (long) compositeConverter.convert(String.valueOf(Long.MIN_VALUE), Long.class)); } - - @Test(expected = IllegalArgumentException.class) - public void testConvertLongIllegal() { - compositeConverter.convert("aaa", Long.class); + + @Test + void testConvertLongIllegal() { + assertThrows(IllegalArgumentException.class, () -> { + compositeConverter.convert("aaa", Long.class); + }); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java b/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java index b2d94d42404..38d857e8796 100644 --- a/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java @@ -20,21 +20,21 @@ import com.alibaba.nacos.common.logging.NacosLoggingAdapter; import com.alibaba.nacos.common.logging.NacosLoggingProperties; -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 java.lang.reflect.Field; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.doThrow; -@RunWith(MockitoJUnitRunner.class) -public class NacosLoggingTest { +@ExtendWith(MockitoExtension.class) +class NacosLoggingTest { @Mock NacosLoggingAdapter loggingAdapter; @@ -42,24 +42,24 @@ public class NacosLoggingTest { NacosLoggingProperties loggingProperties; NacosLogging instance; - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { loggingProperties = new NacosLoggingProperties("", new Properties()); instance = NacosLogging.getInstance(); Field loggingPropertiesField = NacosLogging.class.getDeclaredField("loggingProperties"); loggingPropertiesField.setAccessible(true); loggingPropertiesField.set(instance, loggingProperties); } - + @Test - public void testGetInstance() { + void testGetInstance() { NacosLogging instance = NacosLogging.getInstance(); - Assert.assertNotNull(instance); + assertNotNull(instance); } - + @Test - public void testLoadConfiguration() throws NoSuchFieldException, IllegalAccessException { + void testLoadConfiguration() throws NoSuchFieldException, IllegalAccessException { instance = NacosLogging.getInstance(); Field nacosLogging = NacosLogging.class.getDeclaredField("loggingAdapter"); nacosLogging.setAccessible(true); @@ -67,9 +67,9 @@ public void testLoadConfiguration() throws NoSuchFieldException, IllegalAccessEx instance.loadConfiguration(); Mockito.verify(loggingAdapter, Mockito.times(1)).loadConfiguration(loggingProperties); } - + @Test - public void testLoadConfigurationWithException() throws NoSuchFieldException, IllegalAccessException { + void testLoadConfigurationWithException() throws NoSuchFieldException, IllegalAccessException { instance = NacosLogging.getInstance(); Field nacosLoggingField = NacosLogging.class.getDeclaredField("loggingAdapter"); nacosLoggingField.setAccessible(true); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java index e5a84b6e022..020d80e316f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java @@ -29,10 +29,9 @@ import com.alibaba.nacos.client.naming.core.ServerListManager; import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy; import com.alibaba.nacos.client.security.SecurityProxy; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatcher; import java.lang.reflect.Field; @@ -41,12 +40,13 @@ import java.util.Properties; import java.util.concurrent.ScheduledExecutorService; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class NacosNamingMaintainServiceTest { +class NacosNamingMaintainServiceTest { private NacosNamingMaintainService nacosNamingMaintainService; @@ -57,9 +57,9 @@ public class NacosNamingMaintainServiceTest { private SecurityProxy securityProxy; private ScheduledExecutorService executorService; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { Properties prop = new Properties(); prop.setProperty(PropertyKeyConst.NAMESPACE, "public"); prop.setProperty("serverAddr", "localhost"); @@ -83,19 +83,19 @@ public void setUp() throws Exception { executorServiceField.setAccessible(true); executorServiceField.set(nacosNamingMaintainService, executorService); } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { } - + @Test - public void testConstructor() throws NacosException { + void testConstructor() throws NacosException { NacosNamingMaintainService client = new NacosNamingMaintainService("localhost"); - Assert.assertNotNull(client); + assertNotNull(client); } - + @Test - public void testUpdateInstance1() throws NacosException { + void testUpdateInstance1() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -105,9 +105,9 @@ public void testUpdateInstance1() throws NacosException { //then verify(serverProxy, times(1)).updateInstance(serviceName, groupName, instance); } - + @Test - public void testUpdateInstance2() throws NacosException { + void testUpdateInstance2() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -116,9 +116,9 @@ public void testUpdateInstance2() throws NacosException { //then verify(serverProxy, times(1)).updateInstance(serviceName, Constants.DEFAULT_GROUP, instance); } - + @Test - public void testQueryService1() throws NacosException { + void testQueryService1() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -127,9 +127,9 @@ public void testQueryService1() throws NacosException { //then verify(serverProxy, times(1)).queryService(serviceName, groupName); } - + @Test - public void testQueryService2() throws NacosException { + void testQueryService2() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -138,9 +138,9 @@ public void testQueryService2() throws NacosException { //then verify(serverProxy, times(1)).queryService(serviceName, Constants.DEFAULT_GROUP); } - + @Test - public void testCreateService1() throws NacosException { + void testCreateService1() throws NacosException { //given String serviceName = "service1"; //when @@ -155,9 +155,9 @@ public boolean matches(Service service) { } }), argThat(o -> o instanceof NoneSelector)); } - + @Test - public void testCreateService2() throws NacosException { + void testCreateService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -173,9 +173,9 @@ public boolean matches(Service service) { } }), argThat(o -> o instanceof NoneSelector)); } - + @Test - public void testCreateService3() throws NacosException { + void testCreateService3() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -192,9 +192,9 @@ public boolean matches(Service service) { } }), argThat(o -> o instanceof NoneSelector)); } - + @Test - public void testCreateService5() throws NacosException { + void testCreateService5() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -212,9 +212,9 @@ public boolean matches(Service service) { } }), argThat(o -> ((ExpressionSelector) o).getExpression().equals(expression))); } - + @Test - public void testCreateService4() throws NacosException { + void testCreateService4() throws NacosException { //given Service service = new Service(); AbstractSelector selector = new NoneSelector(); @@ -223,9 +223,9 @@ public void testCreateService4() throws NacosException { //then verify(serverProxy, times(1)).createService(service, selector); } - + @Test - public void testDeleteService1() throws NacosException { + void testDeleteService1() throws NacosException { //given String serviceName = "service1"; //when @@ -233,9 +233,9 @@ public void testDeleteService1() throws NacosException { //then verify(serverProxy, times(1)).deleteService(serviceName, Constants.DEFAULT_GROUP); } - + @Test - public void testDeleteService2() throws NacosException { + void testDeleteService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -244,9 +244,9 @@ public void testDeleteService2() throws NacosException { //then verify(serverProxy, times(1)).deleteService(serviceName, groupName); } - + @Test - public void testUpdateService1() throws NacosException { + void testUpdateService1() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -263,9 +263,9 @@ public boolean matches(Service service) { } }), argThat(o -> o instanceof NoneSelector)); } - + @Test - public void testUpdateService2() throws NacosException { + void testUpdateService2() throws NacosException { //given String serviceName = "service1"; String groupName = "groupName"; @@ -285,9 +285,9 @@ public boolean matches(Service service) { } }), argThat(o -> o instanceof NoneSelector)); } - + @Test - public void testUpdateService3() throws NacosException { + void testUpdateService3() throws NacosException { //given Service service = new Service(); AbstractSelector selector = new NoneSelector(); @@ -296,9 +296,9 @@ public void testUpdateService3() throws NacosException { //then verify(serverProxy, times(1)).updateService(service, selector); } - + @Test - public void testShutDown() throws NacosException { + void testShutDown() throws NacosException { //when nacosNamingMaintainService.shutDown(); //then diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java index 8a6e5a95e32..d02e1c2233d 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java @@ -32,15 +32,12 @@ import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy; import com.alibaba.nacos.client.naming.utils.CollectionUtils; import com.alibaba.nacos.client.naming.utils.UtilAndComs; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -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.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.util.ArrayList; @@ -49,7 +46,10 @@ import java.util.List; import java.util.Properties; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; @@ -60,11 +60,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NacosNamingServiceTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); +@ExtendWith(MockitoExtension.class) +class NacosNamingServiceTest { @Mock private NamingClientProxy proxy; @@ -76,18 +73,18 @@ public class NacosNamingServiceTest { private ServiceInfoHolder serviceInfoHolder; private NacosNamingService client; - - @Before - public void before() throws NoSuchFieldException, NacosException, IllegalAccessException { + + @BeforeEach + void before() throws NoSuchFieldException, NacosException, IllegalAccessException { Properties prop = new Properties(); prop.setProperty("serverAddr", "localhost"); prop.put(PropertyKeyConst.NAMESPACE, "test"); client = new NacosNamingService(prop); injectMocks(client); } - - @After - public void tearDown() throws NacosException { + + @AfterEach + void tearDown() throws NacosException { client.shutDown(); } @@ -116,9 +113,9 @@ private void injectMocks(NacosNamingService client) throws NoSuchFieldException, } serviceInfoHolderField.set(client, serviceInfoHolder); } - + @Test - public void testRegisterInstance1() throws NacosException { + void testRegisterInstance1() throws NacosException { //given String serviceName = "service1"; String ip = "1.1.1.1"; @@ -131,9 +128,9 @@ public void testRegisterInstance1() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(Constants.DEFAULT_CLUSTER_NAME))); } - + @Test - public void testBatchRegisterInstance() throws NacosException { + void testBatchRegisterInstance() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; @@ -150,9 +147,9 @@ public void testBatchRegisterInstance() throws NacosException { verify(proxy, times(1)).batchRegisterService(eq(serviceName), eq(Constants.DEFAULT_GROUP), argThat(instances -> CollectionUtils.isEqualCollection(instanceList, instances))); } - + @Test - public void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException { + void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; @@ -169,9 +166,9 @@ public void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException verify(proxy, times(1)).batchRegisterService(eq(serviceName), eq(Constants.DEFAULT_GROUP), argThat(instances -> CollectionUtils.isEqualCollection(instanceList, instances))); } - + @Test - public void testBatchRegisterInstanceWithWrongGroupNamePrefix() throws NacosException { + void testBatchRegisterInstanceWithWrongGroupNamePrefix() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; @@ -186,13 +183,13 @@ public void testBatchRegisterInstanceWithWrongGroupNamePrefix() throws NacosExce try { client.batchRegisterInstance(serviceName, Constants.DEFAULT_GROUP, instanceList); } catch (Exception e) { - Assert.assertTrue(e instanceof NacosException); - Assert.assertTrue(e.getMessage().contains("wrong group name prefix of instance service name")); + assertTrue(e instanceof NacosException); + assertTrue(e.getMessage().contains("wrong group name prefix of instance service name")); } } - + @Test - public void testBatchDeRegisterInstance() throws NacosException { + void testBatchDeRegisterInstance() throws NacosException { Instance instance = new Instance(); String serviceName = "service1"; String ip = "1.1.1.1"; @@ -207,13 +204,13 @@ public void testBatchDeRegisterInstance() throws NacosException { try { client.batchDeregisterInstance(serviceName, Constants.DEFAULT_GROUP, instanceList); } catch (Exception e) { - Assert.assertTrue(e instanceof NacosException); - Assert.assertTrue(e.getMessage().contains("not found")); + assertTrue(e instanceof NacosException); + assertTrue(e.getMessage().contains("not found")); } } - + @Test - public void testRegisterInstance2() throws NacosException { + void testRegisterInstance2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -227,9 +224,9 @@ public void testRegisterInstance2() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(Constants.DEFAULT_CLUSTER_NAME))); } - + @Test - public void testRegisterInstance3() throws NacosException { + void testRegisterInstance3() throws NacosException { //given String serviceName = "service1"; String clusterName = "cluster1"; @@ -243,9 +240,9 @@ public void testRegisterInstance3() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(clusterName))); } - + @Test - public void testRegisterInstance4() throws NacosException { + void testRegisterInstance4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -260,9 +257,9 @@ public void testRegisterInstance4() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(clusterName))); } - + @Test - public void testRegisterInstance5() throws NacosException { + void testRegisterInstance5() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -271,9 +268,9 @@ public void testRegisterInstance5() throws NacosException { //then verify(proxy, times(1)).registerService(serviceName, Constants.DEFAULT_GROUP, instance); } - + @Test - public void testRegisterInstance6() throws NacosException { + void testRegisterInstance6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -283,24 +280,24 @@ public void testRegisterInstance6() throws NacosException { //then verify(proxy, times(1)).registerService(serviceName, groupName, instance); } - + @Test - public void testRegisterInstance7() throws NacosException { - expectedException.expect(NacosException.class); - expectedException.expectMessage( - "Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)"); - - //given - String serviceName = "service1"; - String groupName = "group1"; - Instance instance = new Instance(); - instance.setClusterName("cluster1,cluster2"); - //when - client.registerInstance(serviceName, groupName, instance); + void testRegisterInstance7() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + //given + String serviceName = "service1"; + String groupName = "group1"; + Instance instance = new Instance(); + instance.setClusterName("cluster1,cluster2"); + //when + client.registerInstance(serviceName, groupName, instance); + }); + assertTrue(exception.getMessage().contains("Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)")); } - + @Test - public void testDeregisterInstance1() throws NacosException { + void testDeregisterInstance1() throws NacosException { //given String serviceName = "service1"; String ip = "1.1.1.1"; @@ -313,9 +310,9 @@ public void testDeregisterInstance1() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(Constants.DEFAULT_CLUSTER_NAME))); } - + @Test - public void testDeregisterInstance2() throws NacosException { + void testDeregisterInstance2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -329,9 +326,9 @@ public void testDeregisterInstance2() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(Constants.DEFAULT_CLUSTER_NAME))); } - + @Test - public void testDeregisterInstance3() throws NacosException { + void testDeregisterInstance3() throws NacosException { //given String serviceName = "service1"; String clusterName = "cluster1"; @@ -345,9 +342,9 @@ public void testDeregisterInstance3() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(clusterName))); } - + @Test - public void testDeregisterInstance4() throws NacosException { + void testDeregisterInstance4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -362,9 +359,9 @@ public void testDeregisterInstance4() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(clusterName))); } - + @Test - public void testDeregisterInstance5() throws NacosException { + void testDeregisterInstance5() throws NacosException { //given String serviceName = "service1"; Instance instance = new Instance(); @@ -373,9 +370,9 @@ public void testDeregisterInstance5() throws NacosException { //then verify(proxy, times(1)).deregisterService(serviceName, Constants.DEFAULT_GROUP, instance); } - + @Test - public void testDeregisterInstance6() throws NacosException { + void testDeregisterInstance6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -385,9 +382,9 @@ public void testDeregisterInstance6() throws NacosException { //then verify(proxy, times(1)).deregisterService(serviceName, groupName, instance); } - + @Test - public void testGetAllInstances1() throws NacosException { + void testGetAllInstances1() throws NacosException { //given String serviceName = "service1"; //when @@ -395,9 +392,9 @@ public void testGetAllInstances1() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, ""); } - + @Test - public void testGetAllInstances2() throws NacosException { + void testGetAllInstances2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -406,9 +403,9 @@ public void testGetAllInstances2() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, groupName, ""); } - + @Test - public void testGetAllInstances3() throws NacosException { + void testGetAllInstances3() throws NacosException { //given String serviceName = "service1"; //when @@ -416,9 +413,9 @@ public void testGetAllInstances3() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "", false); } - + @Test - public void testGetAllInstances4() throws NacosException { + void testGetAllInstances4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -428,9 +425,9 @@ public void testGetAllInstances4() throws NacosException { verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "", false); } - + @Test - public void testGetAllInstances5() throws NacosException { + void testGetAllInstances5() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -439,9 +436,9 @@ public void testGetAllInstances5() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } - + @Test - public void testGetAllInstances6() throws NacosException { + void testGetAllInstances6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -452,9 +449,9 @@ public void testGetAllInstances6() throws NacosException { verify(proxy, times(1)).subscribe(serviceName, groupName, "cluster1,cluster2"); } - + @Test - public void testGetAllInstances7() throws NacosException { + void testGetAllInstances7() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -464,9 +461,9 @@ public void testGetAllInstances7() throws NacosException { verify(proxy, times(1)) .queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false); } - + @Test - public void testGetAllInstances8() throws NacosException { + void testGetAllInstances8() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -476,9 +473,9 @@ public void testGetAllInstances8() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "cluster1,cluster2", false); } - + @Test - public void testGetAllInstanceFromFailover() throws NacosException { + void testGetAllInstanceFromFailover() throws NacosException { when(serviceInfoHolder.isFailoverSwitch()).thenReturn(true); ServiceInfo serviceInfo = new ServiceInfo("group1@@service1"); serviceInfo.setHosts(Collections.singletonList(new Instance())); @@ -488,9 +485,9 @@ public void testGetAllInstanceFromFailover() throws NacosException { assertEquals(1, actual.size()); assertEquals(new Instance(), actual.get(0)); } - + @Test - public void testGetAllInstanceFromFailoverEmpty() throws NacosException { + void testGetAllInstanceFromFailoverEmpty() throws NacosException { when(serviceInfoHolder.isFailoverSwitch()).thenReturn(true); ServiceInfo serviceInfo = new ServiceInfo("group1@@service1"); when(serviceInfoHolder.getFailoverServiceInfo(anyString(), anyString(), anyString())).thenReturn(serviceInfo); @@ -498,9 +495,9 @@ public void testGetAllInstanceFromFailoverEmpty() throws NacosException { verify(proxy).queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean()); assertEquals(0, actual.size()); } - + @Test - public void testSelectInstances1() throws NacosException { + void testSelectInstances1() throws NacosException { //given String serviceName = "service1"; //when @@ -508,9 +505,9 @@ public void testSelectInstances1() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, ""); } - + @Test - public void testSelectInstances2() throws NacosException { + void testSelectInstances2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -519,9 +516,9 @@ public void testSelectInstances2() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, groupName, ""); } - + @Test - public void testSelectInstances3() throws NacosException { + void testSelectInstances3() throws NacosException { //given String serviceName = "service1"; //when @@ -529,9 +526,9 @@ public void testSelectInstances3() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "", false); } - + @Test - public void testSelectInstances4() throws NacosException { + void testSelectInstances4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -541,9 +538,9 @@ public void testSelectInstances4() throws NacosException { verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "", false); } - + @Test - public void testSelectInstances5() throws NacosException { + void testSelectInstances5() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -552,9 +549,9 @@ public void testSelectInstances5() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } - + @Test - public void testSelectInstances6() throws NacosException { + void testSelectInstances6() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -565,9 +562,9 @@ public void testSelectInstances6() throws NacosException { verify(proxy, times(1)).subscribe(serviceName, groupName, "cluster1,cluster2"); } - + @Test - public void testSelectInstances7() throws NacosException { + void testSelectInstances7() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -577,9 +574,9 @@ public void testSelectInstances7() throws NacosException { verify(proxy, times(1)) .queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false); } - + @Test - public void testSelectInstances8() throws NacosException { + void testSelectInstances8() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -589,9 +586,9 @@ public void testSelectInstances8() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "cluster1,cluster2", false); } - + @Test - public void testSelectInstancesWithHealthyFlag() throws NacosException { + void testSelectInstancesWithHealthyFlag() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setHealthy(true); @@ -623,11 +620,11 @@ public void testSelectInstancesWithHealthyFlag() throws NacosException { List instances = client.selectInstances(serviceName, groupName, clusterList, true, false); //then assertEquals(1, instances.size()); - Assert.assertSame(healthyInstance, instances.get(0)); + assertSame(healthyInstance, instances.get(0)); } - + @Test - public void testSelectOneHealthyInstance1() throws NacosException { + void testSelectOneHealthyInstance1() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -644,9 +641,9 @@ public void testSelectOneHealthyInstance1() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, ""); } - + @Test - public void testSelectOneHealthyInstance2() throws NacosException { + void testSelectOneHealthyInstance2() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -664,9 +661,9 @@ public void testSelectOneHealthyInstance2() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, groupName, ""); } - + @Test - public void testSelectOneHealthyInstance3() throws NacosException { + void testSelectOneHealthyInstance3() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -684,9 +681,9 @@ public void testSelectOneHealthyInstance3() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "", false); } - + @Test - public void testSelectOneHealthyInstance4() throws NacosException { + void testSelectOneHealthyInstance4() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -706,9 +703,9 @@ public void testSelectOneHealthyInstance4() throws NacosException { verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "", false); } - + @Test - public void testSelectOneHealthyInstance5() throws NacosException { + void testSelectOneHealthyInstance5() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -726,9 +723,9 @@ public void testSelectOneHealthyInstance5() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } - + @Test - public void testSelectOneHealthyInstance6() throws NacosException { + void testSelectOneHealthyInstance6() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -748,9 +745,9 @@ public void testSelectOneHealthyInstance6() throws NacosException { verify(proxy, times(1)).subscribe(serviceName, groupName, "cluster1,cluster2"); } - + @Test - public void testSelectOneHealthyInstance7() throws NacosException { + void testSelectOneHealthyInstance7() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -770,9 +767,9 @@ public void testSelectOneHealthyInstance7() throws NacosException { verify(proxy, times(1)) .queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false); } - + @Test - public void testSelectOneHealthyInstance8() throws NacosException { + void testSelectOneHealthyInstance8() throws NacosException { //given Instance healthyInstance = new Instance(); healthyInstance.setIp("1.1.1.1"); @@ -792,9 +789,9 @@ public void testSelectOneHealthyInstance8() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "cluster1,cluster2", false); } - + @Test - public void testSubscribe1() throws NacosException { + void testSubscribe1() throws NacosException { //given String serviceName = "service1"; EventListener listener = event -> { @@ -806,9 +803,9 @@ public void testSubscribe1() throws NacosException { verify(changeNotifier, times(1)).registerListener(Constants.DEFAULT_GROUP, serviceName, "", listener); verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, ""); } - + @Test - public void testSubscribe2() throws NacosException { + void testSubscribe2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -821,9 +818,9 @@ public void testSubscribe2() throws NacosException { verify(changeNotifier, times(1)).registerListener(groupName, serviceName, "", listener); verify(proxy, times(1)).subscribe(serviceName, groupName, ""); } - + @Test - public void testSubscribe3() throws NacosException { + void testSubscribe3() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -837,9 +834,9 @@ public void testSubscribe3() throws NacosException { .registerListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", listener); verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } - + @Test - public void testSubscribe4() throws NacosException { + void testSubscribe4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -853,9 +850,9 @@ public void testSubscribe4() throws NacosException { verify(changeNotifier, times(1)).registerListener(groupName, serviceName, "cluster1,cluster2", listener); verify(proxy, times(1)).subscribe(serviceName, groupName, "cluster1,cluster2"); } - + @Test - public void testSubscribeWithNullListener() throws NacosException { + void testSubscribeWithNullListener() throws NacosException { String serviceName = "service1"; String groupName = "group1"; //when @@ -865,9 +862,9 @@ public void testSubscribeWithNullListener() throws NacosException { verify(proxy, never()).subscribe(serviceName, groupName, ""); } - + @Test - public void testUnSubscribe1() throws NacosException { + void testUnSubscribe1() throws NacosException { //given String serviceName = "service1"; EventListener listener = event -> { @@ -878,9 +875,9 @@ public void testUnSubscribe1() throws NacosException { verify(changeNotifier, times(1)).deregisterListener(Constants.DEFAULT_GROUP, serviceName, "", listener); verify(proxy, times(1)).unsubscribe(serviceName, Constants.DEFAULT_GROUP, ""); } - + @Test - public void testUnSubscribe2() throws NacosException { + void testUnSubscribe2() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -892,9 +889,9 @@ public void testUnSubscribe2() throws NacosException { verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, "", listener); verify(proxy, times(1)).unsubscribe(serviceName, groupName, ""); } - + @Test - public void testUnSubscribe3() throws NacosException { + void testUnSubscribe3() throws NacosException { //given String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); @@ -907,9 +904,9 @@ public void testUnSubscribe3() throws NacosException { .deregisterListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", listener); verify(proxy, times(1)).unsubscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } - + @Test - public void testUnSubscribe4() throws NacosException { + void testUnSubscribe4() throws NacosException { //given String serviceName = "service1"; String groupName = "group1"; @@ -922,9 +919,9 @@ public void testUnSubscribe4() throws NacosException { verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, "cluster1,cluster2", listener); verify(proxy, times(1)).unsubscribe(serviceName, groupName, "cluster1,cluster2"); } - + @Test - public void testGetServicesOfServer1() throws NacosException { + void testGetServicesOfServer1() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -933,9 +930,9 @@ public void testGetServicesOfServer1() throws NacosException { //then verify(proxy, times(1)).getServiceList(pageNo, pageSize, Constants.DEFAULT_GROUP, null); } - + @Test - public void testGetServicesOfServer2() throws NacosException { + void testGetServicesOfServer2() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -945,9 +942,9 @@ public void testGetServicesOfServer2() throws NacosException { //then verify(proxy, times(1)).getServiceList(pageNo, pageSize, groupName, null); } - + @Test - public void testGetServicesOfServer3() throws NacosException { + void testGetServicesOfServer3() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -962,9 +959,9 @@ public String getType() { //then verify(proxy, times(1)).getServiceList(pageNo, pageSize, Constants.DEFAULT_GROUP, selector); } - + @Test - public void testGetServicesOfServer4() throws NacosException { + void testGetServicesOfServer4() throws NacosException { //given int pageNo = 1; int pageSize = 10; @@ -981,17 +978,17 @@ public String getType() { //then verify(proxy, times(1)).getServiceList(pageNo, pageSize, groupName, selector); } - + @Test - public void testGetSubscribeServices() { + void testGetSubscribeServices() { //when client.getSubscribeServices(); //then verify(changeNotifier, times(1)).getSubscribeServices(); } - + @Test - public void testGetServerStatus() { + void testGetServerStatus() { //given when(proxy.serverHealthy()).thenReturn(true); //when @@ -999,9 +996,9 @@ public void testGetServerStatus() { //then assertEquals("UP", serverStatus); } - + @Test - public void testGetServerStatusFail() { + void testGetServerStatusFail() { //given when(proxy.serverHealthy()).thenReturn(false); //when @@ -1009,17 +1006,17 @@ public void testGetServerStatusFail() { //then assertEquals("DOWN", serverStatus); } - + @Test - public void testShutDown() throws NacosException { + void testShutDown() throws NacosException { //when client.shutDown(); //then verify(proxy, times(1)).shutdown(); } - + @Test - public void testConstructorWithServerList() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testConstructorWithServerList() throws NacosException, NoSuchFieldException, IllegalAccessException { NacosNamingService namingService = new NacosNamingService("localhost"); try { Field namespaceField = NacosNamingService.class.getDeclaredField("namespace"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java index 26cad59f79a..a74e6c1383b 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java @@ -20,13 +20,12 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder; import com.alibaba.nacos.common.utils.ReflectUtils; -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.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -37,14 +36,15 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class FailoverReactorTest { +@ExtendWith(MockitoExtension.class) +class FailoverReactorTest { @Mock ServiceInfoHolder holder; @@ -53,34 +53,34 @@ public class FailoverReactorTest { FailoverDataSource failoverDataSource; FailoverReactor failoverReactor; - - @Before - public void setUp() throws NoSuchFieldException, IllegalAccessException { + + @BeforeEach + void setUp() throws NoSuchFieldException, IllegalAccessException { failoverReactor = new FailoverReactor(holder, UUID.randomUUID().toString()); Field failoverDataSourceField = FailoverReactor.class.getDeclaredField("failoverDataSource"); failoverDataSourceField.setAccessible(true); failoverDataSourceField.set(failoverReactor, failoverDataSource); } - - @After - public void tearDown() throws NacosException { + + @AfterEach + void tearDown() throws NacosException { failoverReactor.shutdown(); } - + @Test - public void testIsFailoverSwitch() throws NacosException { - Assert.assertFalse(failoverReactor.isFailoverSwitch()); + void testIsFailoverSwitch() throws NacosException { + assertFalse(failoverReactor.isFailoverSwitch()); } - + @Test - public void testGetService() throws NacosException { + void testGetService() throws NacosException { ServiceInfo info = failoverReactor.getService("aa@@bb"); assertEquals(new ServiceInfo("aa@@bb").toString(), info.toString()); } - + @Test - public void testRefreshFromDisabledToEnabled() throws InterruptedException { + void testRefreshFromDisabledToEnabled() throws InterruptedException { // make sure the first no delay refresh thread finished. TimeUnit.MILLISECONDS.sleep(500); FailoverSwitch mockFailoverSwitch = new FailoverSwitch(true); @@ -95,9 +95,9 @@ public void testRefreshFromDisabledToEnabled() throws InterruptedException { ServiceInfo actual = failoverReactor.getService("a@@b"); assertEquals(serviceInfo, actual); } - + @Test - public void testRefreshFromDisabledToEnabledWithException() throws InterruptedException { + void testRefreshFromDisabledToEnabledWithException() throws InterruptedException { // make sure the first no delay refresh thread finished. TimeUnit.MILLISECONDS.sleep(500); FailoverSwitch mockFailoverSwitch = new FailoverSwitch(true); @@ -107,9 +107,9 @@ public void testRefreshFromDisabledToEnabledWithException() throws InterruptedEx TimeUnit.MILLISECONDS.sleep(5500); assertTrue(((Map) ReflectUtils.getFieldValue(failoverDataSource, "serviceMap", new HashMap<>())).isEmpty()); } - + @Test - public void testRefreshFromEnabledToDisabled() + void testRefreshFromEnabledToDisabled() throws InterruptedException, NoSuchFieldException, IllegalAccessException { // make sure the first no delay refresh thread finished. TimeUnit.MILLISECONDS.sleep(500); @@ -131,18 +131,18 @@ public void testRefreshFromEnabledToDisabled() ServiceInfo actual = failoverReactor.getService("a@@b"); assertNotEquals(serviceInfo, actual); } - + @Test - public void testFailoverServiceCntMetrics() + void testFailoverServiceCntMetrics() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method method = FailoverReactor.class.getDeclaredMethod("failoverServiceCntMetrics"); method.setAccessible(true); method.invoke(failoverReactor); // No exception } - + @Test - public void testFailoverServiceCntMetricsClear() + void testFailoverServiceCntMetricsClear() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { Field field = FailoverReactor.class.getDeclaredField("meterMap"); field.setAccessible(true); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java index 7a0b3066610..4a958263e71 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java @@ -19,44 +19,43 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.client.naming.backups.FailoverData; import com.alibaba.nacos.client.naming.backups.FailoverSwitch; -import com.alibaba.nacos.client.naming.cache.DiskCacheTest; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class DiskFailoverDataSourceTest { +class DiskFailoverDataSourceTest { DiskFailoverDataSource dataSource; - - @Before - public void setUp() { + + @BeforeEach + void setUp() { dataSource = new DiskFailoverDataSource(); } - + @Test - public void testGetSwitchWithNonExistFailoverSwitchFile() { + void testGetSwitchWithNonExistFailoverSwitchFile() { FailoverSwitch actual = dataSource.getSwitch(); assertFalse(actual.getEnabled()); } - + @Test - public void testGetSwitchForFailoverDisabled() throws NoSuchFieldException, IllegalAccessException { - String dir = DiskCacheTest.class.getResource("/").getPath() + "/failover_test/disabled"; + void testGetSwitchForFailoverDisabled() throws NoSuchFieldException, IllegalAccessException { + String dir = DiskFailoverDataSourceTest.class.getResource("/").getPath() + "/failover_test/disabled"; injectFailOverDir(dir); assertFalse(dataSource.getSwitch().getEnabled()); Map actual = dataSource.getFailoverData(); assertTrue(actual.isEmpty()); } - + @Test - public void testGetSwitchForFailoverEnabled() throws NoSuchFieldException, IllegalAccessException { - String dir = DiskCacheTest.class.getResource("/").getPath() + "/failover_test/enabled"; + void testGetSwitchForFailoverEnabled() throws NoSuchFieldException, IllegalAccessException { + String dir = DiskFailoverDataSourceTest.class.getResource("/").getPath() + "/failover_test/enabled"; injectFailOverDir(dir); assertTrue(dataSource.getSwitch().getEnabled()); Map actual = dataSource.getFailoverData(); @@ -66,9 +65,9 @@ public void testGetSwitchForFailoverEnabled() throws NoSuchFieldException, Illeg assertEquals("1.1.1.1", ((ServiceInfo) actual.get("legal@@with_name@@file").getData()).getHosts().get(0).getIp()); } - + @Test - public void testGetFailoverDataForFailoverDisabled() { + void testGetFailoverDataForFailoverDisabled() { Map actual = dataSource.getFailoverData(); assertTrue(actual.isEmpty()); } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java index e6f638ef767..31725e23663 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java @@ -18,10 +18,9 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.UnsupportedEncodingException; @@ -29,20 +28,21 @@ import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; -public class DiskCacheTest { +class DiskCacheTest { private static final String CACHE_DIR = DiskCacheTest.class.getResource("/").getPath() + "cache/"; private ServiceInfo serviceInfo; private Instance instance; - - @Before - public void setUp() { + + @BeforeEach + void setUp() { System.out.println(CACHE_DIR); serviceInfo = new ServiceInfo("G@@testName", "testClusters"); instance = new Instance(); @@ -53,9 +53,9 @@ public void setUp() { instance.addMetadata("chinese", "中文"); serviceInfo.setHosts(Collections.singletonList(instance)); } - - @After - public void tearDown() { + + @AfterEach + void tearDown() { File file = new File(CACHE_DIR); if (file.exists() && file.list().length > 0) { for (File each : file.listFiles()) { @@ -64,18 +64,18 @@ public void tearDown() { file.delete(); } } - + @Test - public void testCache() { + void testCache() { DiskCache.write(serviceInfo, CACHE_DIR); Map actual = DiskCache.read(CACHE_DIR); assertEquals(1, actual.size()); assertTrue(actual.containsKey(serviceInfo.getKey())); assertServiceInfo(actual.get(serviceInfo.getKey()), serviceInfo); } - + @Test - public void testWriteCacheWithErrorPath() { + void testWriteCacheWithErrorPath() { File file = new File(CACHE_DIR, serviceInfo.getKeyEncoded()); try { file.mkdirs(); @@ -85,9 +85,9 @@ public void testWriteCacheWithErrorPath() { file.delete(); } } - + @Test - public void testReadCacheForAllSituation() { + void testReadCacheForAllSituation() { String dir = DiskCacheTest.class.getResource("/").getPath() + "/disk_cache_test"; Map actual = DiskCache.read(dir); assertEquals(2, actual.size()); @@ -96,30 +96,34 @@ public void testReadCacheForAllSituation() { assertTrue(actual.containsKey("legal@@with_name@@file")); assertEquals("1.1.1.1", actual.get("legal@@with_name@@file").getHosts().get(0).getIp()); } - + @Test - public void testReadCacheForNullFile() { + void testReadCacheForNullFile() { Map actual = DiskCache.read(null); assertTrue(actual.isEmpty()); } - + @Test - public void testParseServiceInfoFromNonExistFile() throws UnsupportedEncodingException { + void testParseServiceInfoFromNonExistFile() throws UnsupportedEncodingException { File file = new File("non%40%40exist%40%40file"); Map actual = DiskCache.parseServiceInfoFromCache(file); assertTrue(actual.isEmpty()); } - - @Test(expected = IllegalStateException.class) - public void testCreateFileIfAbsentForDir() throws Throwable { - File file = mock(File.class); - DiskCache.createFileIfAbsent(file, true); + + @Test + void testCreateFileIfAbsentForDir() throws Throwable { + assertThrows(IllegalStateException.class, () -> { + File file = mock(File.class); + DiskCache.createFileIfAbsent(file, true); + }); } - - @Test(expected = IllegalStateException.class) - public void testCreateFileIfAbsentForFile() throws Throwable { - File file = mock(File.class); - DiskCache.createFileIfAbsent(file, false); + + @Test + void testCreateFileIfAbsentForFile() throws Throwable { + assertThrows(IllegalStateException.class, () -> { + File file = mock(File.class); + DiskCache.createFileIfAbsent(file, false); + }); } private void assertServiceInfo(ServiceInfo actual, ServiceInfo expected) { @@ -146,10 +150,10 @@ private void assertInstance(Instance actual, Instance expected) { assertEquals(actual.getPort(), expected.getPort()); assertEquals(actual.getMetadata(), expected.getMetadata()); } - + @Test - public void testGetLineSeparator() { + void testGetLineSeparator() { String lineSeparator = DiskCache.getLineSeparator(); - Assert.assertTrue(lineSeparator.length() > 0); + assertTrue(lineSeparator.length() > 0); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java index 9104cb8b0d8..bfa1b694fff 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java @@ -24,46 +24,49 @@ import com.alibaba.nacos.api.naming.pojo.ServiceInfo; import com.alibaba.nacos.client.env.NacosClientProperties; import com.alibaba.nacos.client.naming.backups.FailoverReactor; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ScheduledExecutorService; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ServiceInfoHolderTest { +class ServiceInfoHolderTest { NacosClientProperties nacosClientProperties; ServiceInfoHolder holder; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(); holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties); } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { } - + @Test - public void testGetServiceInfoMap() throws NoSuchFieldException, IllegalAccessException { - Assert.assertEquals(0, holder.getServiceInfoMap().size()); + void testGetServiceInfoMap() throws NoSuchFieldException, IllegalAccessException { + assertEquals(0, holder.getServiceInfoMap().size()); Field fieldNotifierEventScope = ServiceInfoHolder.class.getDeclaredField("notifierEventScope"); fieldNotifierEventScope.setAccessible(true); - Assert.assertEquals("scope-001", fieldNotifierEventScope.get(holder)); + assertEquals("scope-001", fieldNotifierEventScope.get(holder)); } - + @Test - public void testProcessServiceInfo() { + void testProcessServiceInfo() { ServiceInfo info = new ServiceInfo("a@@b@@c"); Instance instance1 = createInstance("1.1.1.1", 1); Instance instance2 = createInstance("1.1.1.2", 2); @@ -73,7 +76,7 @@ public void testProcessServiceInfo() { info.setHosts(hosts); ServiceInfo actual1 = holder.processServiceInfo(info); - Assert.assertEquals(info, actual1); + assertEquals(info, actual1); Instance newInstance1 = createInstance("1.1.1.1", 1); newInstance1.setWeight(2.0); @@ -85,7 +88,7 @@ public void testProcessServiceInfo() { info2.setHosts(hosts2); ServiceInfo actual2 = holder.processServiceInfo(info2); - Assert.assertEquals(info2, actual2); + assertEquals(info2, actual2); } private Instance createInstance(String ip, int port) { @@ -94,19 +97,19 @@ private Instance createInstance(String ip, int port) { instance.setPort(port); return instance; } - + @Test - public void testProcessServiceInfo2() { + void testProcessServiceInfo2() { String json = "{\"groupName\":\"a\",\"name\":\"b\",\"clusters\":\"c\"}"; ServiceInfo actual = holder.processServiceInfo(json); ServiceInfo expect = new ServiceInfo("a@@b@@c"); expect.setJsonFromServer(json); - Assert.assertEquals(expect.getKey(), actual.getKey()); + assertEquals(expect.getKey(), actual.getKey()); } - + @Test - public void testProcessServiceInfoWithPushEmpty() throws NacosException { + void testProcessServiceInfoWithPushEmpty() throws NacosException { ServiceInfo oldInfo = new ServiceInfo("a@@b@@c"); Instance instance1 = createInstance("1.1.1.1", 1); Instance instance2 = createInstance("1.1.1.2", 2); @@ -124,17 +127,17 @@ public void testProcessServiceInfoWithPushEmpty() throws NacosException { final ServiceInfo actual = holder.processServiceInfo(newInfo); - Assert.assertEquals(oldInfo.getKey(), actual.getKey()); - Assert.assertEquals(2, actual.getHosts().size()); + assertEquals(oldInfo.getKey(), actual.getKey()); + assertEquals(2, actual.getHosts().size()); } - + @Test - public void testProcessNullServiceInfo() { - Assert.assertNull(holder.processServiceInfo(new ServiceInfo())); + void testProcessNullServiceInfo() { + assertNull(holder.processServiceInfo(new ServiceInfo())); } - + @Test - public void testProcessServiceInfoForOlder() { + void testProcessServiceInfoForOlder() { ServiceInfo info = new ServiceInfo("a@@b@@c"); Instance instance1 = createInstance("1.1.1.1", 1); Instance instance2 = createInstance("1.1.1.2", 2); @@ -147,11 +150,11 @@ public void testProcessServiceInfoForOlder() { ServiceInfo olderInfo = new ServiceInfo("a@@b@@c"); olderInfo.setLastRefTime(0L); final ServiceInfo actual = holder.processServiceInfo(olderInfo); - Assert.assertEquals(olderInfo, actual); + assertEquals(olderInfo, actual); } - + @Test - public void testGetServiceInfo() { + void testGetServiceInfo() { ServiceInfo info = new ServiceInfo("a@@b@@c"); Instance instance1 = createInstance("1.1.1.1", 1); List hosts = new ArrayList<>(); @@ -163,47 +166,47 @@ public void testGetServiceInfo() { String groupName = "a"; String clusters = "c"; ServiceInfo actual = holder.getServiceInfo(serviceName, groupName, clusters); - Assert.assertEquals(expect.getKey(), actual.getKey()); - Assert.assertEquals(expect.getHosts().size(), actual.getHosts().size()); - Assert.assertEquals(expect.getHosts().get(0), actual.getHosts().get(0)); + assertEquals(expect.getKey(), actual.getKey()); + assertEquals(expect.getHosts().size(), actual.getHosts().size()); + assertEquals(expect.getHosts().get(0), actual.getHosts().get(0)); } - + @Test - public void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException { + void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException { Field field = ServiceInfoHolder.class.getDeclaredField("failoverReactor"); field.setAccessible(true); FailoverReactor reactor = (FailoverReactor) field.get(holder); Field executorService = FailoverReactor.class.getDeclaredField("executorService"); executorService.setAccessible(true); ScheduledExecutorService pool = (ScheduledExecutorService) executorService.get(reactor); - Assert.assertFalse(pool.isShutdown()); + assertFalse(pool.isShutdown()); holder.shutdown(); - Assert.assertTrue(pool.isShutdown()); + assertTrue(pool.isShutdown()); } - + @Test - public void testConstructWithCacheLoad() throws NacosException { + void testConstructWithCacheLoad() throws NacosException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START, "true"); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "non-exist"); holder.shutdown(); holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties); - Assert.assertEquals(System.getProperty("user.home") + "/nacos/non-exist/naming/aa", holder.getCacheDir()); - Assert.assertTrue(holder.getServiceInfoMap().isEmpty()); + assertEquals(System.getProperty("user.home") + "/nacos/non-exist/naming/aa", holder.getCacheDir()); + assertTrue(holder.getServiceInfoMap().isEmpty()); } - + @Test - public void testIsFailoverSwitch() throws IllegalAccessException, NoSuchFieldException, NacosException { + void testIsFailoverSwitch() throws IllegalAccessException, NoSuchFieldException, NacosException { FailoverReactor mock = injectMockFailoverReactor(); when(mock.isFailoverSwitch()).thenReturn(true); - Assert.assertTrue(holder.isFailoverSwitch()); + assertTrue(holder.isFailoverSwitch()); } - + @Test - public void testGetFailoverServiceInfo() throws IllegalAccessException, NoSuchFieldException, NacosException { + void testGetFailoverServiceInfo() throws IllegalAccessException, NoSuchFieldException, NacosException { FailoverReactor mock = injectMockFailoverReactor(); ServiceInfo serviceInfo = new ServiceInfo("a@@b@@c"); when(mock.getService("a@@b@@c")).thenReturn(serviceInfo); - Assert.assertEquals(serviceInfo, holder.getFailoverServiceInfo("b", "a", "c")); + assertEquals(serviceInfo, holder.getFailoverServiceInfo("b", "a", "c")); } private FailoverReactor injectMockFailoverReactor() diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java index cc2801d2e91..542e354eea7 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java @@ -18,36 +18,35 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -public class BalancerTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class BalancerTest { + @Test - public void testGetHostByRandomWeightNull() { - Assert.assertNull(Balancer.getHostByRandomWeight(null)); - Assert.assertNull(Balancer.getHostByRandomWeight(new ArrayList<>())); + void testGetHostByRandomWeightNull() { + assertNull(Balancer.getHostByRandomWeight(null)); + assertNull(Balancer.getHostByRandomWeight(new ArrayList<>())); } - + @Test - public void testGetHostByRandomWeight() { + void testGetHostByRandomWeight() { List list = new ArrayList<>(); Instance instance1 = new Instance(); list.add(instance1); final Instance actual = Balancer.getHostByRandomWeight(list); - Assert.assertEquals(instance1, actual); + assertEquals(instance1, actual); } - + @Test - public void testSelectHost() { + void testSelectHost() { List hosts = new ArrayList<>(); Instance instance1 = new Instance(); hosts.add(instance1); @@ -55,15 +54,16 @@ public void testSelectHost() { serviceInfo.setHosts(hosts); final Instance actual = Balancer.RandomByWeight.selectHost(serviceInfo); - Assert.assertEquals(instance1, actual); + assertEquals(instance1, actual); } - + @Test - public void testSelectHostEmpty() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("no host to srv for serviceInfo: null"); - ServiceInfo serviceInfo = new ServiceInfo(); - - Balancer.RandomByWeight.selectHost(serviceInfo); + void testSelectHostEmpty() { + Throwable exception = assertThrows(IllegalStateException.class, () -> { + ServiceInfo serviceInfo = new ServiceInfo(); + + Balancer.RandomByWeight.selectHost(serviceInfo); + }); + assertTrue(exception.getMessage().contains("no host to srv for serviceInfo: null")); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java index 3954d84c808..76b0d251b01 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java @@ -16,22 +16,23 @@ package com.alibaba.nacos.client.naming.core; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ProtectModeTest { -public class ProtectModeTest { - @Test - public void testProtectThresholdDefault() { + void testProtectThresholdDefault() { final ProtectMode protectMode = new ProtectMode(); - Assert.assertEquals(0.8f, protectMode.getProtectThreshold(), 0.01f); + assertEquals(0.8f, protectMode.getProtectThreshold(), 0.01f); } - + @Test - public void testSetProtectThreshold() { + void testSetProtectThreshold() { final ProtectMode protectMode = new ProtectMode(); float expect = 0.7f; protectMode.setProtectThreshold(expect); - Assert.assertEquals(expect, protectMode.getProtectThreshold(), 0.01f); + assertEquals(expect, protectMode.getProtectThreshold(), 0.01f); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java index 4dbeb9deeec..b74aa685e73 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java @@ -22,14 +22,16 @@ import com.alibaba.nacos.common.http.HttpClientBeanHolder; import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.client.NacosRestTemplate; -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.Assertions; +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.io.IOException; import java.lang.reflect.Field; @@ -39,11 +41,16 @@ import java.util.Map; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -@RunWith(MockitoJUnitRunner.class) -public class ServerListManagerTest { +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class ServerListManagerTest { private static final String NS = "ns"; @@ -57,9 +64,9 @@ public class ServerListManagerTest { HttpRestResult httpRestResult; ServerListManager serverListManager; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { clientProperties = NacosClientProperties.PROTOTYPE.derive(); Field restMapField = HttpClientBeanHolder.class.getDeclaredField("SINGLETON_REST"); restMapField.setAccessible(true); @@ -73,9 +80,9 @@ public void setUp() throws Exception { httpRestResult.setCode(200); Mockito.when(nacosRestTemplate.get(any(), any(), any(), any())).thenReturn(httpRestResult); } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { if (null != cachedNacosRestTemplate) { Field restMapField = HttpClientBeanHolder.class.getDeclaredField("SINGLETON_REST"); restMapField.setAccessible(true); @@ -87,108 +94,110 @@ public void tearDown() throws Exception { serverListManager.shutdown(); } } - - @Test(expected = NacosLoadException.class) - public void testConstructError() { - serverListManager = new ServerListManager(new Properties()); + + @Test + void testConstructError() { + assertThrows(NacosLoadException.class, () -> { + serverListManager = new ServerListManager(new Properties()); + }); } - + @Test - public void testConstructWithAddr() { + void testConstructWithAddr() { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848,127.0.0.1:8849"); serverListManager = new ServerListManager(properties); final List serverList = serverListManager.getServerList(); - Assert.assertEquals(2, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); - Assert.assertEquals("127.0.0.1:8849", serverList.get(1)); + assertEquals(2, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals("127.0.0.1:8849", serverList.get(1)); } - + @Test - public void testConstructWithAddrTryToRefresh() + void testConstructWithAddrTryToRefresh() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848,127.0.0.1:8849"); serverListManager = new ServerListManager(properties); List serverList = serverListManager.getServerList(); - Assert.assertEquals(2, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); - Assert.assertEquals("127.0.0.1:8849", serverList.get(1)); + assertEquals(2, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals("127.0.0.1:8849", serverList.get(1)); mockThreadInvoke(serverListManager, false); serverList = serverListManager.getServerList(); - Assert.assertEquals(2, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); - Assert.assertEquals("127.0.0.1:8849", serverList.get(1)); + assertEquals(2, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals("127.0.0.1:8849", serverList.get(1)); } - + @Test - public void testConstructWithEndpointAndRefresh() throws Exception { + void testConstructWithEndpointAndRefresh() throws Exception { Properties properties = new Properties(); properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1"); serverListManager = new ServerListManager(properties); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); httpRestResult.setData("127.0.0.1:8848\n127.0.0.1:8948"); mockThreadInvoke(serverListManager, true); serverList = serverListManager.getServerList(); - Assert.assertEquals(2, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); - Assert.assertEquals("127.0.0.1:8948", serverList.get(1)); + assertEquals(2, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals("127.0.0.1:8948", serverList.get(1)); } - + @Test - public void testConstructWithEndpointAndTimedNotNeedRefresh() throws Exception { + void testConstructWithEndpointAndTimedNotNeedRefresh() throws Exception { Properties properties = new Properties(); properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1"); serverListManager = new ServerListManager(properties); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); httpRestResult.setData("127.0.0.1:8848\n127.0.0.1:8948"); mockThreadInvoke(serverListManager, false); serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test - public void testConstructWithEndpointAndRefreshEmpty() throws Exception { + void testConstructWithEndpointAndRefreshEmpty() throws Exception { Properties properties = new Properties(); properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1"); serverListManager = new ServerListManager(properties); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); httpRestResult.setData(""); mockThreadInvoke(serverListManager, true); serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test - public void testConstructWithEndpointAndRefreshException() + void testConstructWithEndpointAndRefreshException() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException { Properties properties = new Properties(); properties.put(PropertyKeyConst.ENDPOINT, "127.0.0.1"); serverListManager = new ServerListManager(properties); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); httpRestResult.setCode(500); mockThreadInvoke(serverListManager, true); serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test - public void testConstructWithEndpointWithCustomPathAndName() throws Exception { + void testConstructWithEndpointWithCustomPathAndName() throws Exception { clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "aaa"); clientProperties.setProperty(PropertyKeyConst.CLUSTER_NAME, "bbb"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "127.0.0.1"); @@ -197,12 +206,12 @@ public void testConstructWithEndpointWithCustomPathAndName() throws Exception { .thenReturn(httpRestResult); serverListManager = new ServerListManager(clientProperties, "test"); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test - public void testConstructWithEndpointWithEndpointPathAndName() throws Exception { + void testConstructWithEndpointWithEndpointPathAndName() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, "aaa"); clientProperties.setProperty(PropertyKeyConst.CLUSTER_NAME, "bbb"); clientProperties.setProperty(PropertyKeyConst.ENDPOINT, "127.0.0.1"); @@ -211,12 +220,12 @@ public void testConstructWithEndpointWithEndpointPathAndName() throws Exception .thenReturn(httpRestResult); serverListManager = new ServerListManager(clientProperties, "test"); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test - public void testConstructEndpointContextPathPriority() throws Exception { + void testConstructEndpointContextPathPriority() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, "aaa"); clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "bbb"); clientProperties.setProperty(PropertyKeyConst.CLUSTER_NAME, "ccc"); @@ -226,12 +235,12 @@ public void testConstructEndpointContextPathPriority() throws Exception { .thenReturn(httpRestResult); serverListManager = new ServerListManager(clientProperties, "test"); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test - public void testConstructEndpointContextPathIsEmpty() throws Exception { + void testConstructEndpointContextPathIsEmpty() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, ""); clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "bbb"); clientProperties.setProperty(PropertyKeyConst.CLUSTER_NAME, "ccc"); @@ -241,38 +250,36 @@ public void testConstructEndpointContextPathIsEmpty() throws Exception { .thenReturn(httpRestResult); serverListManager = new ServerListManager(clientProperties, "test"); List serverList = serverListManager.getServerList(); - Assert.assertEquals(1, serverList.size()); - Assert.assertEquals("127.0.0.1:8848", serverList.get(0)); + assertEquals(1, serverList.size()); + assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test - public void testIsDomain() throws IOException { + void testIsDomain() throws IOException { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); serverListManager = new ServerListManager(properties); - Assert.assertTrue(serverListManager.isDomain()); - Assert.assertEquals("127.0.0.1:8848", serverListManager.getNacosDomain()); + assertTrue(serverListManager.isDomain()); + assertEquals("127.0.0.1:8848", serverListManager.getNacosDomain()); } - + @Test - public void testGetCurrentServer() { + void testGetCurrentServer() { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); final ServerListManager serverListManager = new ServerListManager(properties); - Assert.assertEquals("127.0.0.1:8848", serverListManager.getCurrentServer()); - Assert.assertEquals("127.0.0.1:8848", serverListManager.genNextServer()); + assertEquals("127.0.0.1:8848", serverListManager.getCurrentServer()); + assertEquals("127.0.0.1:8848", serverListManager.genNextServer()); } - + @Test - public void testShutdown() { + void testShutdown() { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); final ServerListManager serverListManager = new ServerListManager(properties); - try { + Assertions.assertDoesNotThrow(() -> { serverListManager.shutdown(); - } catch (Exception e) { - Assert.fail(); - } + }); } private void mockThreadInvoke(ServerListManager serverListManager, boolean expectedInvoked) diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java index aaffa64adb4..74e99dbc8ce 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java @@ -24,13 +24,15 @@ import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder; import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier; import com.alibaba.nacos.client.naming.remote.NamingClientProxy; -import org.junit.After; -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 java.lang.reflect.Field; import java.util.Collections; @@ -40,11 +42,13 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class ServiceInfoUpdateServiceTest { +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class ServiceInfoUpdateServiceTest { String serviceName = "aa"; @@ -66,9 +70,9 @@ public class ServiceInfoUpdateServiceTest { ServiceInfo info; ServiceInfoUpdateService serviceInfoUpdateService; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(); info = new ServiceInfo(); info.setName(serviceName); @@ -77,24 +81,24 @@ public void setUp() throws Exception { info.setLastRefTime(System.currentTimeMillis()); when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenReturn(info); } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { if (null != serviceInfoUpdateService) { serviceInfoUpdateService.shutdown(); } } - + @Test - public void testScheduleUpdateWithoutOpen() throws InterruptedException, NacosException { + void testScheduleUpdateWithoutOpen() throws InterruptedException, NacosException { serviceInfoUpdateService = new ServiceInfoUpdateService(null, holder, proxy, notifier); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters); TimeUnit.MILLISECONDS.sleep(1500); Mockito.verify(proxy, Mockito.never()).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test - public void testScheduleUpdateIfAbsent() throws InterruptedException, NacosException { + void testScheduleUpdateIfAbsent() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -102,9 +106,9 @@ public void testScheduleUpdateIfAbsent() throws InterruptedException, NacosExcep TimeUnit.MILLISECONDS.sleep(1500); Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test - public void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, NacosException { + void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -114,9 +118,9 @@ public void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, N // Only once called Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test - public void testScheduleUpdateIfAbsentUpdateOlder() throws InterruptedException, NacosException { + void testScheduleUpdateIfAbsentUpdateOlder() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -127,9 +131,9 @@ public void testScheduleUpdateIfAbsentUpdateOlder() throws InterruptedException, TimeUnit.MILLISECONDS.sleep(1500); Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test - public void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws InterruptedException, NacosException { + void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -141,9 +145,9 @@ public void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws Interrupt TimeUnit.MILLISECONDS.sleep(1500); Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test - public void testScheduleUpdateIfAbsentWith403Exception() + void testScheduleUpdateIfAbsentWith403Exception() throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -153,9 +157,9 @@ public void testScheduleUpdateIfAbsentWith403Exception() TimeUnit.MILLISECONDS.sleep(1500); assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 1000); } - + @Test - public void testScheduleUpdateIfAbsentWith500Exception() + void testScheduleUpdateIfAbsentWith500Exception() throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -165,9 +169,9 @@ public void testScheduleUpdateIfAbsentWith500Exception() TimeUnit.MILLISECONDS.sleep(1500); assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 2000); } - + @Test - public void testScheduleUpdateIfAbsentWithOtherException() + void testScheduleUpdateIfAbsentWithOtherException() throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -177,9 +181,9 @@ public void testScheduleUpdateIfAbsentWithOtherException() TimeUnit.MILLISECONDS.sleep(1500); assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 1000); } - + @Test - public void testStopScheduleUpdateIfAbsent() throws InterruptedException, NacosException { + void testStopScheduleUpdateIfAbsent() throws InterruptedException, NacosException { info.setCacheMillis(10000L); nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); @@ -188,9 +192,9 @@ public void testStopScheduleUpdateIfAbsent() throws InterruptedException, NacosE TimeUnit.MILLISECONDS.sleep(1500); Mockito.verify(proxy, Mockito.never()).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test - public void testStopUpdateIfContainWithoutOpen() throws NacosException, InterruptedException { + void testStopUpdateIfContainWithoutOpen() throws NacosException, InterruptedException { serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters); TimeUnit.MILLISECONDS.sleep(1500); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java index 17cdfff75c4..ba0e869c6ab 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java @@ -17,16 +17,17 @@ package com.alibaba.nacos.client.naming.event; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -public class InstancesChangeEventTest { - +import static org.junit.jupiter.api.Assertions.assertEquals; + +class InstancesChangeEventTest { + @Test - public void testGetServiceName() { + void testGetServiceName() { String eventScope = "scope-001"; String serviceName = "a"; String groupName = "b"; @@ -35,12 +36,12 @@ public void testGetServiceName() { Instance ins = new Instance(); hosts.add(ins); InstancesChangeEvent event = new InstancesChangeEvent(eventScope, serviceName, groupName, clusters, hosts); - Assert.assertEquals(eventScope, event.scope()); - Assert.assertEquals(serviceName, event.getServiceName()); - Assert.assertEquals(clusters, event.getClusters()); - Assert.assertEquals(groupName, event.getGroupName()); + assertEquals(eventScope, event.scope()); + assertEquals(serviceName, event.getServiceName()); + assertEquals(clusters, event.getClusters()); + assertEquals(groupName, event.getGroupName()); List hosts1 = event.getHosts(); - Assert.assertEquals(hosts.size(), hosts1.size()); - Assert.assertEquals(hosts.get(0), hosts1.get(0)); + assertEquals(hosts.size(), hosts1.size()); + assertEquals(hosts.get(0), hosts1.get(0)); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java index 858ac881336..ef9aa6e7b36 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java @@ -20,24 +20,26 @@ import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; +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.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; -public class InstancesChangeNotifierTest { - +class InstancesChangeNotifierTest { + @Test - public void testRegisterListener() { + void testRegisterListener() { String eventScope = "scope-001"; String group = "a"; String name = "b"; @@ -46,20 +48,20 @@ public void testRegisterListener() { EventListener listener = Mockito.mock(EventListener.class); instancesChangeNotifier.registerListener(group, name, clusters, listener); List subscribeServices = instancesChangeNotifier.getSubscribeServices(); - Assert.assertEquals(1, subscribeServices.size()); - Assert.assertEquals(group, subscribeServices.get(0).getGroupName()); - Assert.assertEquals(name, subscribeServices.get(0).getName()); - Assert.assertEquals(clusters, subscribeServices.get(0).getClusters()); + assertEquals(1, subscribeServices.size()); + assertEquals(group, subscribeServices.get(0).getGroupName()); + assertEquals(name, subscribeServices.get(0).getName()); + assertEquals(clusters, subscribeServices.get(0).getClusters()); List hosts = new ArrayList<>(); Instance ins = new Instance(); hosts.add(ins); InstancesChangeEvent event = new InstancesChangeEvent(eventScope, name, group, clusters, hosts); - Assert.assertEquals(true, instancesChangeNotifier.scopeMatches(event)); + assertTrue(instancesChangeNotifier.scopeMatches(event)); } - + @Test - public void testDeregisterListener() { + void testDeregisterListener() { String eventScope = "scope-001"; String group = "a"; String name = "b"; @@ -68,33 +70,33 @@ public void testDeregisterListener() { EventListener listener = Mockito.mock(EventListener.class); instancesChangeNotifier.registerListener(group, name, clusters, listener); List subscribeServices = instancesChangeNotifier.getSubscribeServices(); - Assert.assertEquals(1, subscribeServices.size()); + assertEquals(1, subscribeServices.size()); instancesChangeNotifier.deregisterListener(group, name, clusters, listener); List subscribeServices2 = instancesChangeNotifier.getSubscribeServices(); - Assert.assertEquals(0, subscribeServices2.size()); + assertEquals(0, subscribeServices2.size()); instancesChangeNotifier.deregisterListener(group, name, clusters, listener); - Assert.assertEquals(0, subscribeServices2.size()); + assertEquals(0, subscribeServices2.size()); } - + @Test - public void testIsSubscribed() { + void testIsSubscribed() { String eventScope = "scope-001"; String group = "a"; String name = "b"; String clusters = "c"; InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); EventListener listener = Mockito.mock(EventListener.class); - Assert.assertFalse(instancesChangeNotifier.isSubscribed(group, name, clusters)); + assertFalse(instancesChangeNotifier.isSubscribed(group, name, clusters)); instancesChangeNotifier.registerListener(group, name, clusters, listener); - Assert.assertTrue(instancesChangeNotifier.isSubscribed(group, name, clusters)); + assertTrue(instancesChangeNotifier.isSubscribed(group, name, clusters)); } - + @Test - public void testOnEvent() { + void testOnEvent() { String eventScope = "scope-001"; String group = "a"; String name = "b"; @@ -111,9 +113,9 @@ public void testOnEvent() { instancesChangeNotifier.onEvent(event1); Mockito.verify(listener, times(1)).onEvent(any()); } - + @Test - public void testOnEventWithoutListener() { + void testOnEventWithoutListener() { String eventScope = "scope-001"; String group = "a"; String name = "b"; @@ -128,9 +130,9 @@ public void testOnEventWithoutListener() { instancesChangeNotifier.onEvent(event1); Mockito.verify(listener, never()).onEvent(any()); } - + @Test - public void testOnEventByExecutor() { + void testOnEventByExecutor() { String eventScope = "scope-001"; String group = "a"; String name = "b"; @@ -149,11 +151,11 @@ public void testOnEventByExecutor() { instancesChangeNotifier.onEvent(event1); Mockito.verify(executor).execute(any()); } - + @Test - public void testSubscribeType() { + void testSubscribeType() { String eventScope = "scope-001"; InstancesChangeNotifier instancesChangeNotifier = new InstancesChangeNotifier(eventScope); - Assert.assertEquals(InstancesChangeEvent.class, instancesChangeNotifier.subscribeType()); + assertEquals(InstancesChangeEvent.class, instancesChangeNotifier.subscribeType()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java index 22863f57d92..9dfda183f22 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java @@ -31,48 +31,49 @@ import com.alibaba.nacos.client.utils.AppNameUtils; import com.alibaba.nacos.common.notify.Event; import com.alibaba.nacos.plugin.auth.api.RequestResource; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +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.util.HashMap; import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class AbstractNamingClientProxyTest { +@ExtendWith(MockitoExtension.class) +class AbstractNamingClientProxyTest { @Mock private SecurityProxy sc; - + /** * test get security headers for accessToken. */ @Test - public void testGetSecurityHeadersForAccessToken() { + void testGetSecurityHeadersForAccessToken() { AbstractNamingClientProxy proxy = new MockNamingClientProxy(sc); String token = "aa"; Map keyMap = new HashMap<>(); keyMap.put(Constants.ACCESS_TOKEN, token); when(sc.getIdentityContext(any(RequestResource.class))).thenReturn(keyMap); Map securityHeaders = proxy.getSecurityHeaders("", "", ""); - Assert.assertEquals(2, securityHeaders.size()); - Assert.assertEquals(token, securityHeaders.get(Constants.ACCESS_TOKEN)); - Assert.assertEquals(AppNameUtils.getAppName(), securityHeaders.get("app")); + assertEquals(2, securityHeaders.size()); + assertEquals(token, securityHeaders.get(Constants.ACCESS_TOKEN)); + assertEquals(AppNameUtils.getAppName(), securityHeaders.get("app")); } - + /** * get security headers for ram. * * @throws Exception exception */ @Test - public void testGetSecurityHeadersForRam() throws Exception { + void testGetSecurityHeadersForRam() throws Exception { String ak = "aa"; String sk = "bb"; Map mockIdentityContext = new HashMap<>(); @@ -84,12 +85,12 @@ public void testGetSecurityHeadersForRam() throws Exception { when(sc.getIdentityContext(any(RequestResource.class))).thenReturn(mockIdentityContext); AbstractNamingClientProxy proxy = new MockNamingClientProxy(sc); Map spasHeaders = proxy.getSecurityHeaders("", "", serviceName); - Assert.assertEquals(4, spasHeaders.size()); - Assert.assertEquals(AppNameUtils.getAppName(), spasHeaders.get("app")); - Assert.assertEquals(ak, spasHeaders.get("ak")); - Assert.assertTrue(spasHeaders.get("data").endsWith("@@" + serviceName)); + assertEquals(4, spasHeaders.size()); + assertEquals(AppNameUtils.getAppName(), spasHeaders.get("app")); + assertEquals(ak, spasHeaders.get("ak")); + assertTrue(spasHeaders.get("data").endsWith("@@" + serviceName)); String expectSign = SignUtil.sign(spasHeaders.get("data"), sk); - Assert.assertEquals(expectSign, spasHeaders.get("signature")); + assertEquals(expectSign, spasHeaders.get("signature")); } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java index d1074f93dc3..94a4b887bf5 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java @@ -31,27 +31,31 @@ import com.alibaba.nacos.client.naming.event.InstancesChangeNotifier; import com.alibaba.nacos.client.naming.remote.gprc.NamingGrpcClientProxy; import com.alibaba.nacos.client.naming.remote.http.NamingHttpClientProxy; -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.Assertions; +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 java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NamingClientProxyDelegateTest { +@ExtendWith(MockitoExtension.class) +class NamingClientProxyDelegateTest { private static final String TEST_NAMESPACE = "ns1"; @@ -66,9 +70,9 @@ public class NamingClientProxyDelegateTest { InstancesChangeNotifier notifier; NacosClientProperties nacosClientProperties; - - @Before - public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { + + @BeforeEach + void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties props = new Properties(); props.setProperty("serverAddr", "localhost"); nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props); @@ -78,14 +82,14 @@ public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessEx grpcClientProxyField.setAccessible(true); grpcClientProxyField.set(delegate, mockGrpcClient); } - - @After - public void tearDown() throws NacosException { + + @AfterEach + void tearDown() throws NacosException { delegate.shutdown(); } - + @Test - public void testRegisterEphemeralServiceByGrpc() throws NacosException { + void testRegisterEphemeralServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -97,9 +101,9 @@ public void testRegisterEphemeralServiceByGrpc() throws NacosException { delegate.registerService(serviceName, groupName, instance); verify(mockGrpcClient, times(1)).registerService(serviceName, groupName, instance); } - + @Test - public void testBatchRegisterServiceByGrpc() throws NacosException { + void testBatchRegisterServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -112,9 +116,9 @@ public void testBatchRegisterServiceByGrpc() throws NacosException { delegate.batchRegisterService(serviceName, groupName, instanceList); verify(mockGrpcClient, times(1)).batchRegisterService(serviceName, groupName, instanceList); } - + @Test - public void testBatchDeregisterServiceByGrpc() throws NacosException { + void testBatchDeregisterServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; List instanceList = new ArrayList<>(); @@ -125,9 +129,9 @@ public void testBatchDeregisterServiceByGrpc() throws NacosException { delegate.batchDeregisterService(serviceName, groupName, instanceList); verify(mockGrpcClient, times(1)).batchDeregisterService(serviceName, groupName, instanceList); } - + @Test - public void testRegisterPersistentServiceByGrpc() throws NacosException { + void testRegisterPersistentServiceByGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -143,9 +147,9 @@ public void testRegisterPersistentServiceByGrpc() throws NacosException { delegate.registerService(serviceName, groupName, instance); verify(mockGrpcClient, times(1)).registerService(serviceName, groupName, instance); } - + @Test - public void testRegisterPersistentServiceByHttp() + void testRegisterPersistentServiceByHttp() throws NacosException, NoSuchFieldException, IllegalAccessException { NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class); Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy"); @@ -165,9 +169,9 @@ public void testRegisterPersistentServiceByHttp() delegate.registerService(serviceName, groupName, instance); verify(mockHttpClient, times(1)).registerService(serviceName, groupName, instance); } - + @Test - public void testDeregisterEphemeralServiceGrpc() throws NacosException { + void testDeregisterEphemeralServiceGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -180,9 +184,9 @@ public void testDeregisterEphemeralServiceGrpc() throws NacosException { delegate.deregisterService(serviceName, groupName, instance); verify(mockGrpcClient, times(1)).deregisterService(serviceName, groupName, instance); } - + @Test - public void testDeregisterPersistentServiceGrpc() throws NacosException { + void testDeregisterPersistentServiceGrpc() throws NacosException { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); @@ -198,9 +202,9 @@ public void testDeregisterPersistentServiceGrpc() throws NacosException { delegate.deregisterService(serviceName, groupName, instance); verify(mockGrpcClient, times(1)).deregisterService(serviceName, groupName, instance); } - + @Test - public void testDeregisterPersistentServiceHttp() + void testDeregisterPersistentServiceHttp() throws NacosException, NoSuchFieldException, IllegalAccessException { NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class); Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy"); @@ -219,61 +223,55 @@ public void testDeregisterPersistentServiceHttp() delegate.deregisterService(serviceName, groupName, instance); verify(mockHttpClient, times(1)).deregisterService(serviceName, groupName, instance); } - + @Test - public void testUpdateInstance() { + void testUpdateInstance() { String serviceName = "service1"; String groupName = "group1"; Instance instance = new Instance(); - try { + Assertions.assertDoesNotThrow(() -> { delegate.updateInstance(serviceName, groupName, instance); - } catch (Exception e) { - Assert.fail(); - } + }); } - + @Test - public void testQueryInstancesOfService() throws NacosException { + void testQueryInstancesOfService() throws NacosException { String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; delegate.queryInstancesOfService(serviceName, groupName, clusters, false); verify(mockGrpcClient, times(1)).queryInstancesOfService(serviceName, groupName, clusters, false); } - + @Test - public void testQueryService() throws NacosException { + void testQueryService() throws NacosException { Service service = delegate.queryService("a", "b"); - Assert.assertNull(service); + assertNull(service); } - + @Test - public void testCreateService() { + void testCreateService() { Service service = new Service(); - try { + Assertions.assertDoesNotThrow(() -> { delegate.createService(service, new NoneSelector()); - } catch (Exception e) { - Assert.fail(); - } + }); } - + @Test - public void testDeleteService() throws NacosException { - Assert.assertFalse(delegate.deleteService("service", "group1")); + void testDeleteService() throws NacosException { + assertFalse(delegate.deleteService("service", "group1")); } - + @Test - public void testUpdateService() { + void testUpdateService() { Service service = new Service(); - try { + Assertions.assertDoesNotThrow(() -> { delegate.updateService(service, new ExpressionSelector()); - } catch (Exception e) { - Assert.fail(); - } + }); } - + @Test - public void testGetServiceList() throws NacosException { + void testGetServiceList() throws NacosException { AbstractSelector selector = new ExpressionSelector(); int pageNo = 1; int pageSize = 10; @@ -282,9 +280,9 @@ public void testGetServiceList() throws NacosException { verify(mockGrpcClient, times(1)).getServiceList(pageNo, pageSize, groupName, selector); } - + @Test - public void testSubscribe() throws NacosException { + void testSubscribe() throws NacosException { String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; @@ -295,39 +293,39 @@ public void testSubscribe() throws NacosException { when(mockGrpcClient.subscribe(serviceName, groupName, clusters)).thenReturn(info); ServiceInfo actual = delegate.subscribe(serviceName, groupName, clusters); - Assert.assertEquals(info, actual); + assertEquals(info, actual); verify(mockGrpcClient, times(1)).subscribe(serviceName, groupName, clusters); verify(holder, times(1)).processServiceInfo(info); } - + @Test - public void testUnsubscribe() throws NacosException { + void testUnsubscribe() throws NacosException { String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; delegate.unsubscribe(serviceName, groupName, clusters); verify(mockGrpcClient, times(1)).unsubscribe(serviceName, groupName, clusters); } - + @Test - public void testServerHealthy() { + void testServerHealthy() { Mockito.when(mockGrpcClient.serverHealthy()).thenReturn(true); - Assert.assertTrue(delegate.serverHealthy()); + assertTrue(delegate.serverHealthy()); } - + @Test - public void testIsSubscribed() throws NacosException { + void testIsSubscribed() throws NacosException { String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; - Assert.assertFalse(delegate.isSubscribed(serviceName, groupName, clusters)); + assertFalse(delegate.isSubscribed(serviceName, groupName, clusters)); when(mockGrpcClient.isSubscribed(serviceName, groupName, clusters)).thenReturn(true); - Assert.assertTrue(delegate.isSubscribed(serviceName, groupName, clusters)); + assertTrue(delegate.isSubscribed(serviceName, groupName, clusters)); } - + @Test - public void testShutdown() throws NacosException { + void testShutdown() throws NacosException { delegate.shutdown(); verify(mockGrpcClient, times(1)).shutdown(); } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java index 901d6d4a7b2..34c90fd30cb 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java @@ -60,16 +60,15 @@ import com.alibaba.nacos.common.remote.client.grpc.GrpcClient; import com.alibaba.nacos.common.remote.client.grpc.GrpcClientConfig; import com.alibaba.nacos.common.remote.client.grpc.GrpcConstants; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -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 java.lang.reflect.Field; import java.util.ArrayList; @@ -83,8 +82,13 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doThrow; @@ -92,11 +96,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NamingGrpcClientProxyTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class NamingGrpcClientProxyTest { private static final String NAMESPACE_ID = "ns1"; @@ -131,12 +134,9 @@ public class NamingGrpcClientProxyTest { private Instance persistentInstance; private String uuid; - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { + + @BeforeEach + void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { System.setProperty(GrpcConstants.GRPC_RETRY_TIMES, "1"); System.setProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT, "100"); List serverList = Stream.of(ORIGIN_SERVER, "anotherServer").collect(Collectors.toList()); @@ -151,7 +151,7 @@ public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessEx uuidField.setAccessible(true); uuid = (String) uuidField.get(client); - Assert.assertNotNull(RpcClientFactory.getClient(uuid)); + assertNotNull(RpcClientFactory.getClient(uuid)); Field rpcClientField = NamingGrpcClientProxy.class.getDeclaredField("rpcClient"); rpcClientField.setAccessible(true); ((RpcClient) rpcClientField.get(client)).shutdown(); @@ -170,16 +170,16 @@ public void setUp() throws NacosException, NoSuchFieldException, IllegalAccessEx persistentInstance.setPort(1111); persistentInstance.setEphemeral(false); } - - @After - public void tearDown() throws NacosException { + + @AfterEach + void tearDown() throws NacosException { System.clearProperty(GrpcConstants.GRPC_RETRY_TIMES); System.clearProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT); client.shutdown(); } - + @Test - public void testRegisterService() throws NacosException { + void testRegisterService() throws NacosException { client.registerService(SERVICE_NAME, GROUP_NAME, instance); verify(this.rpcClient, times(1)).request(argThat(request -> { if (request instanceof InstanceRequest) { @@ -189,9 +189,9 @@ public void testRegisterService() throws NacosException { return false; })); } - + @Test - public void testRegisterPersistentService() throws NacosException { + void testRegisterPersistentService() throws NacosException { client.registerService(SERVICE_NAME, GROUP_NAME, persistentInstance); verify(this.rpcClient, times(1)).request(argThat(request -> { if (request instanceof PersistentInstanceRequest) { @@ -201,41 +201,43 @@ public void testRegisterPersistentService() throws NacosException { return false; })); } - + @Test - public void testRegisterServiceThrowsNacosException() throws NacosException { - expectedException.expect(NacosException.class); - expectedException.expectMessage("err args"); - - when(this.rpcClient.request(Mockito.any())).thenReturn(ErrorResponse.build(400, "err args")); - - try { - client.registerService(SERVICE_NAME, GROUP_NAME, instance); - } catch (NacosException ex) { - Assert.assertNull(ex.getCause()); - - throw ex; - } + void testRegisterServiceThrowsNacosException() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + when(this.rpcClient.request(Mockito.any())).thenReturn(ErrorResponse.build(400, "err args")); + + try { + client.registerService(SERVICE_NAME, GROUP_NAME, instance); + } catch (NacosException ex) { + assertNull(ex.getCause()); + + throw ex; + } + }); + assertTrue(exception.getMessage().contains("err args")); } - + @Test - public void testRegisterServiceThrowsException() throws NacosException { - expectedException.expect(NacosException.class); - expectedException.expectMessage("Request nacos server failed: "); - - when(this.rpcClient.request(Mockito.any())).thenReturn(null); - - try { - client.registerService(SERVICE_NAME, GROUP_NAME, instance); - } catch (NacosException ex) { - Assert.assertEquals(NullPointerException.class, ex.getCause().getClass()); - - throw ex; - } + void testRegisterServiceThrowsException() throws NacosException { + Throwable exception = assertThrows(NacosException.class, () -> { + + when(this.rpcClient.request(Mockito.any())).thenReturn(null); + + try { + client.registerService(SERVICE_NAME, GROUP_NAME, instance); + } catch (NacosException ex) { + assertEquals(NullPointerException.class, ex.getCause().getClass()); + + throw ex; + } + }); + assertTrue(exception.getMessage().contains("Request nacos server failed: ")); } - + @Test - public void testDeregisterService() throws NacosException { + void testDeregisterService() throws NacosException { client.deregisterService(SERVICE_NAME, GROUP_NAME, instance); verify(this.rpcClient, times(1)).request(argThat(request -> { if (request instanceof InstanceRequest) { @@ -245,9 +247,9 @@ public void testDeregisterService() throws NacosException { return false; })); } - + @Test - public void testDeregisterPersistentService() throws NacosException { + void testDeregisterPersistentService() throws NacosException { client.deregisterService(SERVICE_NAME, GROUP_NAME, persistentInstance); verify(this.rpcClient, times(1)).request(argThat(request -> { if (request instanceof PersistentInstanceRequest) { @@ -257,9 +259,9 @@ public void testDeregisterPersistentService() throws NacosException { return false; })); } - + @Test - public void testDeregisterServiceForBatchRegistered() throws NacosException { + void testDeregisterServiceForBatchRegistered() throws NacosException { try { List instanceList = new ArrayList<>(); instance.setHealthy(true); @@ -284,9 +286,9 @@ public void testDeregisterServiceForBatchRegistered() throws NacosException { return false; })); } - + @Test - public void testBatchRegisterService() throws NacosException { + void testBatchRegisterService() throws NacosException { List instanceList = new ArrayList<>(); instance.setHealthy(true); instanceList.add(instance); @@ -302,43 +304,51 @@ public void testBatchRegisterService() throws NacosException { return false; })); } - - @Test(expected = NacosException.class) - public void testBatchDeregisterServiceWithEmptyInstances() throws NacosException { - client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST); + + @Test + void testBatchDeregisterServiceWithEmptyInstances() throws NacosException { + assertThrows(NacosException.class, () -> { + client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST); + }); } - - @Test(expected = NacosException.class) - public void testBatchDeregisterServiceWithoutCacheData() throws NacosException { - List instanceList = new ArrayList<>(); - instance.setHealthy(true); - instanceList.add(instance); - client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + + @Test + void testBatchDeregisterServiceWithoutCacheData() throws NacosException { + assertThrows(NacosException.class, () -> { + List instanceList = new ArrayList<>(); + instance.setHealthy(true); + instanceList.add(instance); + client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + }); } - - @Test(expected = NacosException.class) - public void testBatchDeregisterServiceNotBatchData() throws NacosException { - client.registerService(SERVICE_NAME, GROUP_NAME, instance); - List instanceList = new ArrayList<>(); - instance.setHealthy(true); - instanceList.add(instance); - client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + + @Test + void testBatchDeregisterServiceNotBatchData() throws NacosException { + assertThrows(NacosException.class, () -> { + client.registerService(SERVICE_NAME, GROUP_NAME, instance); + List instanceList = new ArrayList<>(); + instance.setHealthy(true); + instanceList.add(instance); + client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + }); } - - @Test(expected = NacosException.class) - public void testBatchDeregisterServiceWithEmptyBatchData() throws NacosException { - try { - client.batchRegisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST); - } catch (Exception ignored) { - } - List instanceList = new ArrayList<>(); - instance.setHealthy(true); - instanceList.add(instance); - client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + + @Test + void testBatchDeregisterServiceWithEmptyBatchData() throws NacosException { + assertThrows(NacosException.class, () -> { + try { + client.batchRegisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST); + } catch (Exception ignored) { + } + List instanceList = new ArrayList<>(); + instance.setHealthy(true); + instanceList.add(instance); + client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); + }); } - + @Test - public void testBatchDeregisterService() throws NacosException { + void testBatchDeregisterService() throws NacosException { try { List instanceList = new ArrayList<>(); instance.setHealthy(true); @@ -363,9 +373,9 @@ public void testBatchDeregisterService() throws NacosException { return false; })); } - + @Test - public void testBatchDeregisterServiceWithOtherPortInstance() throws NacosException { + void testBatchDeregisterServiceWithOtherPortInstance() throws NacosException { try { List instanceList = new ArrayList<>(); instance.setHealthy(true); @@ -393,53 +403,53 @@ public void testBatchDeregisterServiceWithOtherPortInstance() throws NacosExcept return false; })); } - + @Test - public void testUpdateInstance() throws Exception { + void testUpdateInstance() throws Exception { //TODO thrown.expect(UnsupportedOperationException.class); client.updateInstance(SERVICE_NAME, GROUP_NAME, instance); } - + @Test - public void testQueryInstancesOfService() throws Exception { + void testQueryInstancesOfService() throws Exception { QueryServiceResponse res = new QueryServiceResponse(); ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS); res.setServiceInfo(info); when(this.rpcClient.request(any())).thenReturn(res); ServiceInfo actual = client.queryInstancesOfService(SERVICE_NAME, GROUP_NAME, CLUSTERS, false); - Assert.assertEquals(info, actual); + assertEquals(info, actual); } - + @Test - public void testQueryService() throws Exception { + void testQueryService() throws Exception { Service service = client.queryService(SERVICE_NAME, GROUP_NAME); - Assert.assertNull(service); + assertNull(service); } - + @Test - public void testCreateService() throws Exception { + void testCreateService() throws Exception { //TODO thrown.expect(UnsupportedOperationException.class); Service service = new Service(); AbstractSelector selector = new NoneSelector(); client.createService(service, selector); } - + @Test - public void testDeleteService() throws Exception { + void testDeleteService() throws Exception { //TODO thrown.expect(UnsupportedOperationException.class); assertFalse(client.deleteService(SERVICE_NAME, GROUP_NAME)); } - + @Test - public void testUpdateService() throws NacosException { + void testUpdateService() throws NacosException { //TODO thrown.expect(UnsupportedOperationException.class); Service service = new Service(); AbstractSelector selector = new NoneSelector(); client.updateService(service, selector); } - + @Test - public void testGetServiceList() throws Exception { + void testGetServiceList() throws Exception { ServiceListResponse res = new ServiceListResponse(); List services = Arrays.asList("service1", "service2"); res.setServiceNames(services); @@ -447,12 +457,12 @@ public void testGetServiceList() throws Exception { when(this.rpcClient.request(any())).thenReturn(res); AbstractSelector selector = new NoneSelector(); ListView serviceList = client.getServiceList(1, 10, GROUP_NAME, selector); - Assert.assertEquals(5, serviceList.getCount()); - Assert.assertEquals(services, serviceList.getData()); + assertEquals(5, serviceList.getCount()); + assertEquals(services, serviceList.getData()); } - + @Test - public void testGetServiceListForLabelSelector() throws Exception { + void testGetServiceListForLabelSelector() throws Exception { ServiceListResponse res = new ServiceListResponse(); List services = Arrays.asList("service1", "service2"); res.setServiceNames(services); @@ -460,22 +470,22 @@ public void testGetServiceListForLabelSelector() throws Exception { when(this.rpcClient.request(any())).thenReturn(res); AbstractSelector selector = new ExpressionSelector(); ListView serviceList = client.getServiceList(1, 10, GROUP_NAME, selector); - Assert.assertEquals(5, serviceList.getCount()); - Assert.assertEquals(services, serviceList.getData()); + assertEquals(5, serviceList.getCount()); + assertEquals(services, serviceList.getData()); } - + @Test - public void testSubscribe() throws Exception { + void testSubscribe() throws Exception { SubscribeServiceResponse res = new SubscribeServiceResponse(); ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS); res.setServiceInfo(info); when(this.rpcClient.request(any())).thenReturn(res); ServiceInfo actual = client.subscribe(SERVICE_NAME, GROUP_NAME, CLUSTERS); - Assert.assertEquals(info, actual); + assertEquals(info, actual); } - + @Test - public void testUnsubscribe() throws Exception { + void testUnsubscribe() throws Exception { SubscribeServiceResponse res = new SubscribeServiceResponse(); ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS); res.setServiceInfo(info); @@ -493,9 +503,9 @@ public void testUnsubscribe() throws Exception { return false; })); } - + @Test - public void testIsSubscribed() throws NacosException { + void testIsSubscribed() throws NacosException { SubscribeServiceResponse res = new SubscribeServiceResponse(); ServiceInfo info = new ServiceInfo(GROUP_NAME + "@@" + SERVICE_NAME + "@@" + CLUSTERS); res.setServiceInfo(info); @@ -504,55 +514,55 @@ public void testIsSubscribed() throws NacosException { client.subscribe(SERVICE_NAME, GROUP_NAME, CLUSTERS); assertTrue(client.isSubscribed(SERVICE_NAME, GROUP_NAME, CLUSTERS)); } - + @Test - public void testServerHealthy() { + void testServerHealthy() { when(this.rpcClient.isRunning()).thenReturn(true); - Assert.assertTrue(client.serverHealthy()); + assertTrue(client.serverHealthy()); verify(this.rpcClient, times(1)).isRunning(); } - + @Test - public void testIsAbilitySupportedByServer1() { + void testIsAbilitySupportedByServer1() { when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) .thenReturn(AbilityStatus.SUPPORTED); - Assert.assertTrue(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); + assertTrue(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } - + @Test - public void testIsAbilitySupportedByServer2() { + void testIsAbilitySupportedByServer2() { when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) .thenReturn(AbilityStatus.NOT_SUPPORTED); - Assert.assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); + assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } - + @Test - public void testIsAbilitySupportedByServer3() { + void testIsAbilitySupportedByServer3() { when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) .thenReturn(AbilityStatus.UNKNOWN); - Assert.assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); + assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } - + @Test - public void testIsAbilitySupportedByServer4() { + void testIsAbilitySupportedByServer4() { when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) .thenReturn(null); - Assert.assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); + assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } - + @Test - public void testShutdown() throws Exception { + void testShutdown() throws Exception { client.shutdown(); - Assert.assertNull(RpcClientFactory.getClient(uuid)); + assertNull(RpcClientFactory.getClient(uuid)); //verify(this.rpcClient, times(1)).shutdown(); } - + @Test - public void testShutdownWithException() throws NoSuchFieldException, IllegalAccessException, NacosException { + void testShutdownWithException() throws NoSuchFieldException, IllegalAccessException, NacosException { Field field = RpcClientFactory.class.getDeclaredField("CLIENT_MAP"); field.setAccessible(true); Map map = (Map) field.get(RpcClientFactory.class); @@ -564,16 +574,16 @@ public void testShutdownWithException() throws NoSuchFieldException, IllegalAcce map.put(uuid, rpcClient); doThrow(new NacosException()).when(rpcClient).shutdown(); } - + @Test - public void testIsEnable() { + void testIsEnable() { when(this.rpcClient.isRunning()).thenReturn(true); - Assert.assertTrue(client.isEnable()); + assertTrue(client.isEnable()); verify(this.rpcClient, times(1)).isRunning(); } - + @Test - public void testServerListChanged() throws Exception { + void testServerListChanged() throws Exception { RpcClient rpc = new RpcClient(new RpcClientConfig() { @Override @@ -664,11 +674,11 @@ public void close() { while (!rpc.isRunning()) { TimeUnit.MILLISECONDS.sleep(200); if (--retry < 0) { - Assert.fail("rpc is not running"); + fail("rpc is not running"); } } - Assert.assertEquals(ORIGIN_SERVER, rpc.getCurrentServer().getServerIp()); + assertEquals(ORIGIN_SERVER, rpc.getCurrentServer().getServerIp()); String newServer = "www.aliyun.com"; when(factory.genNextServer()).thenReturn(newServer); @@ -679,15 +689,15 @@ public void close() { while (ORIGIN_SERVER.equals(rpc.getCurrentServer().getServerIp())) { TimeUnit.MILLISECONDS.sleep(200); if (--retry < 0) { - Assert.fail("failed to auth switch server"); + fail("failed to auth switch server"); } } - Assert.assertEquals(newServer, rpc.getCurrentServer().getServerIp()); + assertEquals(newServer, rpc.getCurrentServer().getServerIp()); } - + @Test - public void testConfigAppNameLabels() throws Exception { + void testConfigAppNameLabels() throws Exception { final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); client = new NamingGrpcClientProxy(NAMESPACE_ID, proxy, factory, nacosClientProperties, holder); Field rpcClientField = NamingGrpcClientProxy.class.getDeclaredField("rpcClient"); @@ -697,6 +707,6 @@ public void testConfigAppNameLabels() throws Exception { clientConfig.setAccessible(true); GrpcClientConfig config = (GrpcClientConfig) clientConfig.get(rpcClient); String appName = config.labels().get(Constants.APPNAME); - Assert.assertNotNull(appName); + assertNotNull(appName); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java index 791f3c5a540..76c3191fab3 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java @@ -27,17 +27,18 @@ import com.alibaba.nacos.client.naming.cache.ServiceInfoHolder; import com.alibaba.nacos.client.naming.remote.TestConnection; import com.alibaba.nacos.common.remote.client.RpcClient; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class NamingPushRequestHandlerTest { - +class NamingPushRequestHandlerTest { + @Test - public void testRequestReply() { + void testRequestReply() { //given ServiceInfoHolder holder = mock(ServiceInfoHolder.class); NamingPushRequestHandler handler = new NamingPushRequestHandler(holder); @@ -46,15 +47,15 @@ public void testRequestReply() { //when Response response = handler.requestReply(req, new TestConnection(new RpcClient.ServerInfo())); //then - Assert.assertTrue(response instanceof NotifySubscriberResponse); + assertTrue(response instanceof NotifySubscriberResponse); verify(holder, times(1)).processServiceInfo(info); } - + @Test - public void testRequestReplyOtherType() { + void testRequestReplyOtherType() { ServiceInfoHolder holder = mock(ServiceInfoHolder.class); NamingPushRequestHandler handler = new NamingPushRequestHandler(holder); - Assert.assertNull( + assertNull( handler.requestReply(new HealthCheckRequest(), new TestConnection(new RpcClient.ServerInfo()))); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java index 23681502af4..9583af4e086 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java @@ -26,12 +26,12 @@ import com.alibaba.nacos.client.naming.remote.gprc.redo.data.SubscriberRedoData; import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.utils.ReflectUtils; -import org.junit.After; -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.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.lang.reflect.Field; import java.util.ArrayList; @@ -40,12 +40,12 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledExecutorService; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(MockitoJUnitRunner.class) -public class NamingGrpcRedoServiceTest { +@ExtendWith(MockitoExtension.class) +class NamingGrpcRedoServiceTest { private static final String SERVICE = "service"; @@ -57,9 +57,9 @@ public class NamingGrpcRedoServiceTest { private NamingGrpcClientProxy clientProxy; private NamingGrpcRedoService redoService; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { Properties prop = new Properties(); NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); redoService = new NamingGrpcRedoService(clientProxy, nacosClientProperties); @@ -67,14 +67,14 @@ public void setUp() throws Exception { "redoExecutor"); redoExecutor.shutdownNow(); } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { redoService.shutdown(); } - + @Test - public void testDefaultProperties() throws Exception { + void testDefaultProperties() throws Exception { Field redoThreadCountField = NamingGrpcRedoService.class.getDeclaredField("redoThreadCount"); redoThreadCountField.setAccessible(true); @@ -89,7 +89,7 @@ public void testDefaultProperties() throws Exception { } @Test - public void testCustomProperties() throws Exception { + void testCustomProperties() throws Exception { Properties prop = new Properties(); prop.setProperty(PropertyKeyConst.REDO_DELAY_TIME, "4000"); prop.setProperty(PropertyKeyConst.REDO_DELAY_THREAD_COUNT, "2"); @@ -110,14 +110,14 @@ public void testCustomProperties() throws Exception { } @Test - public void testOnConnected() { + void testOnConnected() { assertFalse(redoService.isConnected()); redoService.onConnected(new TestConnection(new RpcClient.ServerInfo())); assertTrue(redoService.isConnected()); } - + @Test - public void testOnDisConnect() { + void testOnDisConnect() { redoService.onConnected(new TestConnection(new RpcClient.ServerInfo())); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceRegistered(SERVICE, GROUP); @@ -131,9 +131,9 @@ public void testOnDisConnect() { assertFalse(redoService.findInstanceRedoData().isEmpty()); assertFalse(redoService.findSubscriberRedoData().isEmpty()); } - + @Test - public void testCacheInstanceForRedo() { + void testCacheInstanceForRedo() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); assertTrue(registeredInstances.isEmpty()); Instance instance = new Instance(); @@ -147,9 +147,9 @@ public void testCacheInstanceForRedo() { assertFalse(actual.isUnregistering()); assertTrue(actual.isExpectedRegistered()); } - + @Test - public void testCacheInstanceForRedoByBatchInstanceRedoData() { + void testCacheInstanceForRedoByBatchInstanceRedoData() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); assertTrue(registeredInstances.isEmpty()); Instance instance = new Instance(); @@ -165,18 +165,18 @@ public void testCacheInstanceForRedoByBatchInstanceRedoData() { assertFalse(actual.isRegistered()); assertFalse(actual.isUnregistering()); } - + @Test - public void testInstanceRegistered() { + void testInstanceRegistered() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceRegistered(SERVICE, GROUP); InstanceRedoData actual = registeredInstances.entrySet().iterator().next().getValue(); assertTrue(actual.isRegistered()); } - + @Test - public void testInstanceDeregister() { + void testInstanceDeregister() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceDeregister(SERVICE, GROUP); @@ -184,9 +184,9 @@ public void testInstanceDeregister() { assertTrue(actual.isUnregistering()); assertFalse(actual.isExpectedRegistered()); } - + @Test - public void testInstanceDeregistered() { + void testInstanceDeregistered() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); redoService.instanceDeregistered(SERVICE, GROUP); @@ -194,9 +194,9 @@ public void testInstanceDeregistered() { assertFalse(actual.isRegistered()); assertTrue(actual.isUnregistering()); } - + @Test - public void testRemoveInstanceForRedo() { + void testRemoveInstanceForRedo() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); assertTrue(registeredInstances.isEmpty()); redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); @@ -205,9 +205,9 @@ public void testRemoveInstanceForRedo() { redoService.removeInstanceForRedo(SERVICE, GROUP); assertTrue(registeredInstances.isEmpty()); } - + @Test - public void testFindInstanceRedoData() { + void testFindInstanceRedoData() { redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); assertFalse(redoService.findInstanceRedoData().isEmpty()); redoService.instanceRegistered(SERVICE, GROUP); @@ -220,9 +220,9 @@ public void testFindInstanceRedoData() { private ConcurrentMap getInstanceRedoDataMap() { return (ConcurrentMap) ReflectUtils.getFieldValue(redoService, "registeredInstances"); } - + @Test - public void testCacheSubscriberForRedo() { + void testCacheSubscriberForRedo() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); assertTrue(subscribes.isEmpty()); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); @@ -234,35 +234,35 @@ public void testCacheSubscriberForRedo() { assertFalse(actual.isRegistered()); assertFalse(actual.isUnregistering()); } - + @Test - public void testSubscriberRegistered() { + void testSubscriberRegistered() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER); SubscriberRedoData actual = subscribes.entrySet().iterator().next().getValue(); assertTrue(actual.isRegistered()); } - + @Test - public void testSubscriberDeregister() { + void testSubscriberDeregister() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); redoService.subscriberDeregister(SERVICE, GROUP, CLUSTER); SubscriberRedoData actual = subscribes.entrySet().iterator().next().getValue(); assertTrue(actual.isUnregistering()); } - + @Test - public void testIsSubscriberRegistered() { + void testIsSubscriberRegistered() { assertFalse(redoService.isSubscriberRegistered(SERVICE, GROUP, CLUSTER)); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER); assertTrue(redoService.isSubscriberRegistered(SERVICE, GROUP, CLUSTER)); } - + @Test - public void testRemoveSubscriberForRedo() { + void testRemoveSubscriberForRedo() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); assertTrue(subscribes.isEmpty()); redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); @@ -271,9 +271,9 @@ public void testRemoveSubscriberForRedo() { redoService.removeSubscriberForRedo(SERVICE, GROUP, CLUSTER); assertTrue(subscribes.isEmpty()); } - + @Test - public void testFindSubscriberRedoData() { + void testFindSubscriberRedoData() { redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); assertFalse(redoService.findSubscriberRedoData().isEmpty()); redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java index 2df4d75207c..287b09db51a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java @@ -22,11 +22,13 @@ import com.alibaba.nacos.client.naming.remote.gprc.redo.data.BatchInstanceRedoData; import com.alibaba.nacos.client.naming.remote.gprc.redo.data.InstanceRedoData; import com.alibaba.nacos.client.naming.remote.gprc.redo.data.SubscriberRedoData; -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.util.Collections; import java.util.HashSet; @@ -37,8 +39,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class RedoScheduledTaskTest { +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class RedoScheduledTaskTest { private static final String SERVICE = "service"; @@ -55,24 +59,24 @@ public class RedoScheduledTaskTest { private NamingGrpcRedoService redoService; private RedoScheduledTask redoTask; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { redoTask = new RedoScheduledTask(clientProxy, redoService); when(clientProxy.isEnable()).thenReturn(true); when(redoService.isConnected()).thenReturn(true); } - + @Test - public void testRunRedoRegisterInstance() throws NacosException { + void testRunRedoRegisterInstance() throws NacosException { Set mockData = generateMockInstanceData(false, false, true); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); verify(clientProxy).doRegisterService(SERVICE, GROUP, INSTANCE); } - + @Test - public void testRunRedoRegisterBatchInstance() throws NacosException { + void testRunRedoRegisterBatchInstance() throws NacosException { BatchInstanceRedoData redoData = BatchInstanceRedoData .build(SERVICE, GROUP, Collections.singletonList(INSTANCE)); redoData.setRegistered(false); @@ -84,52 +88,52 @@ public void testRunRedoRegisterBatchInstance() throws NacosException { redoTask.run(); verify(clientProxy).doBatchRegisterService(SERVICE, GROUP, redoData.getInstances()); } - + @Test - public void testRunRedoDeregisterInstance() throws NacosException { + void testRunRedoDeregisterInstance() throws NacosException { Set mockData = generateMockInstanceData(true, true, false); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); verify(clientProxy).doDeregisterService(SERVICE, GROUP, INSTANCE); } - + @Test - public void testRunRedoRemoveInstanceRedoData() throws NacosException { + void testRunRedoRemoveInstanceRedoData() throws NacosException { Set mockData = generateMockInstanceData(false, true, false); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); verify(redoService).removeInstanceForRedo(SERVICE, GROUP); } - + @Test - public void testRunRedoRegisterInstanceWithClientDisabled() throws NacosException { + void testRunRedoRegisterInstanceWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); Set mockData = generateMockInstanceData(false, false, true); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); verify(clientProxy, never()).doRegisterService(SERVICE, GROUP, INSTANCE); } - + @Test - public void testRunRedoDeregisterInstanceWithClientDisabled() throws NacosException { + void testRunRedoDeregisterInstanceWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); Set mockData = generateMockInstanceData(true, true, false); when(redoService.findInstanceRedoData()).thenReturn(mockData); redoTask.run(); verify(clientProxy, never()).doRegisterService(SERVICE, GROUP, INSTANCE); } - + @Test - public void testRunRedoRegisterInstanceWithNacosException() throws NacosException { + void testRunRedoRegisterInstanceWithNacosException() throws NacosException { Set mockData = generateMockInstanceData(false, false, true); when(redoService.findInstanceRedoData()).thenReturn(mockData); doThrow(new NacosException()).when(clientProxy).doRegisterService(SERVICE, GROUP, INSTANCE); redoTask.run(); // Not any exception thrown } - + @Test - public void testRunRedoRegisterInstanceWithOtherException() throws NacosException { + void testRunRedoRegisterInstanceWithOtherException() throws NacosException { Set mockData = generateMockInstanceData(false, false, true); when(redoService.findInstanceRedoData()).thenReturn(mockData); doThrow(new RuntimeException("test")).when(clientProxy).doRegisterService(SERVICE, GROUP, INSTANCE); @@ -147,51 +151,51 @@ private Set generateMockInstanceData(boolean registered, boole result.add(redoData); return result; } - + @Test - public void testRunRedoRegisterSubscriber() throws NacosException { + void testRunRedoRegisterSubscriber() throws NacosException { Set mockData = generateMockSubscriberData(false, false, true); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); verify(clientProxy).doSubscribe(SERVICE, GROUP, CLUSTER); } - + @Test - public void testRunRedoDeregisterSubscriber() throws NacosException { + void testRunRedoDeregisterSubscriber() throws NacosException { Set mockData = generateMockSubscriberData(true, true, false); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); verify(clientProxy).doUnsubscribe(SERVICE, GROUP, CLUSTER); } - + @Test - public void testRunRedoRemoveSubscriberRedoData() throws NacosException { + void testRunRedoRemoveSubscriberRedoData() throws NacosException { Set mockData = generateMockSubscriberData(false, true, false); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); verify(redoService).removeSubscriberForRedo(SERVICE, GROUP, CLUSTER); } - + @Test - public void testRunRedoRegisterSubscriberWithClientDisabled() throws NacosException { + void testRunRedoRegisterSubscriberWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); Set mockData = generateMockSubscriberData(false, false, true); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); verify(clientProxy, never()).doSubscribe(SERVICE, GROUP, CLUSTER); } - + @Test - public void testRunRedoDeRegisterSubscriberWithClientDisabled() throws NacosException { + void testRunRedoDeRegisterSubscriberWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); Set mockData = generateMockSubscriberData(true, true, false); when(redoService.findSubscriberRedoData()).thenReturn(mockData); redoTask.run(); verify(clientProxy, never()).doUnsubscribe(SERVICE, GROUP, CLUSTER); } - + @Test - public void testRunRedoRegisterSubscriberWithNacosException() throws NacosException { + void testRunRedoRegisterSubscriberWithNacosException() throws NacosException { Set mockData = generateMockSubscriberData(false, false, true); when(redoService.findSubscriberRedoData()).thenReturn(mockData); doThrow(new NacosException()).when(clientProxy).doSubscribe(SERVICE, GROUP, CLUSTER); @@ -209,9 +213,9 @@ private Set generateMockSubscriberData(boolean registered, b result.add(redoData); return result; } - + @Test - public void testRunRedoWithDisconnection() { + void testRunRedoWithDisconnection() { when(redoService.isConnected()).thenReturn(false); redoTask.run(); verify(redoService, never()).findInstanceRedoData(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java index e9f033e1031..fbe1801624c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java @@ -17,36 +17,34 @@ package com.alibaba.nacos.client.naming.remote.gprc.redo.data; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +class BatchInstanceRedoDataTest { -public class BatchInstanceRedoDataTest { - @Test @SuppressWarnings("all") - public void testEquals() { + void testEquals() { BatchInstanceRedoData redoData1 = new BatchInstanceRedoData("a", "b"); redoData1.setInstances(Collections.singletonList(new Instance())); BatchInstanceRedoData redoData2 = new BatchInstanceRedoData("a", "b"); redoData2.setInstances(Collections.singletonList(new Instance())); - assertTrue(redoData1.equals(redoData1)); - assertTrue(redoData1.equals(redoData2)); + assertEquals(redoData1, redoData1); + assertEquals(redoData1, redoData2); redoData2.getInstances().get(0).setIp("1.1.1.1"); - assertFalse(redoData1.equals(null)); - assertFalse(redoData1.equals(redoData2)); - assertFalse(redoData1.equals(redoData2)); + assertNotEquals(null, redoData1); + assertNotEquals(redoData1, redoData2); + assertNotEquals(redoData1, redoData2); BatchInstanceRedoData redoData3 = new BatchInstanceRedoData("c", "b"); - assertFalse(redoData1.equals(redoData3)); + assertNotEquals(redoData1, redoData3); } - + @Test - public void testHashCode() { + void testHashCode() { BatchInstanceRedoData redoData1 = new BatchInstanceRedoData("a", "b"); redoData1.setInstances(Collections.singletonList(new Instance())); BatchInstanceRedoData redoData2 = new BatchInstanceRedoData("a", "b"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java index ddbc79b05c4..f3ee6fee6bc 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java @@ -17,28 +17,26 @@ package com.alibaba.nacos.client.naming.remote.gprc.redo.data; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +class InstanceRedoDataTest { -public class InstanceRedoDataTest { - @Test - public void testEquals() { + void testEquals() { InstanceRedoData redoData1 = new InstanceRedoData("a", "b"); - assertTrue(redoData1.equals(redoData1)); - assertFalse(redoData1.equals(null)); + assertEquals(redoData1, redoData1); + assertNotEquals(null, redoData1); BatchInstanceRedoData redoData2 = new BatchInstanceRedoData("a", "b"); - assertFalse(redoData1.equals(redoData2)); + assertNotEquals(redoData1, redoData2); InstanceRedoData redoData3 = new InstanceRedoData("a", "b"); - assertTrue(redoData1.equals(redoData3)); + assertEquals(redoData1, redoData3); } - + @Test - public void testHashCode() { + void testHashCode() { InstanceRedoData redoData1 = new InstanceRedoData("a", "b"); redoData1.set(new Instance()); InstanceRedoData redoData2 = new InstanceRedoData("a", "b"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java index ac318b86a99..1cf4e60e373 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java @@ -22,8 +22,7 @@ import com.alibaba.nacos.common.http.HttpClientBeanHolder; import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.http.client.request.HttpClientRequest; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.IOException; @@ -31,31 +30,32 @@ import java.util.Map; import static com.alibaba.nacos.common.constant.RequestUrlConstants.HTTP_PREFIX; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class NamingHttpClientManagerTest { - +class NamingHttpClientManagerTest { + @Test - public void testGetInstance() { - Assert.assertNotNull(NamingHttpClientManager.getInstance()); + void testGetInstance() { + assertNotNull(NamingHttpClientManager.getInstance()); } - + @Test - public void testGetPrefix() { + void testGetPrefix() { assertEquals(HTTP_PREFIX, NamingHttpClientManager.getInstance().getPrefix()); } - + @Test - public void testGetNacosRestTemplate() { - Assert.assertNotNull(NamingHttpClientManager.getInstance().getNacosRestTemplate()); + void testGetNacosRestTemplate() { + assertNotNull(NamingHttpClientManager.getInstance().getNacosRestTemplate()); } - + @Test - public void testShutdown() throws NoSuchFieldException, IllegalAccessException, NacosException, IOException { + void testShutdown() throws NoSuchFieldException, IllegalAccessException, NacosException, IOException { //given NamingHttpClientManager instance = NamingHttpClientManager.getInstance(); @@ -68,9 +68,9 @@ public void testShutdown() throws NoSuchFieldException, IllegalAccessException, // then verify(mockHttpClientRequest, times(1)).close(); } - + @Test - public void testShutdownWithException() throws Exception { + void testShutdownWithException() throws Exception { String key = "com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory"; try { HttpClientBeanHolder.shutdownNacosSyncRest(key); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java index 3ffcc78f423..3e8ae64cece 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java @@ -34,15 +34,14 @@ import com.alibaba.nacos.common.http.client.NacosRestTemplate; import com.alibaba.nacos.common.utils.HttpMethod; import com.alibaba.nacos.common.utils.ReflectUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -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.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.Arrays; @@ -52,9 +51,11 @@ import java.util.Map; import java.util.Properties; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.endsWith; import static org.mockito.ArgumentMatchers.eq; @@ -64,11 +65,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class NamingHttpClientProxyTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class NamingHttpClientProxyTest { @Mock private SecurityProxy proxy; @@ -79,34 +79,34 @@ public class NamingHttpClientProxyTest { private Properties props; private NamingHttpClientProxy clientProxy; - - @Before - public void setUp() { + + @BeforeEach + void setUp() { when(mgr.getServerList()).thenReturn(Arrays.asList("localhost")); props = new Properties(); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props); clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, nacosClientProperties); } - - @After - public void tearDown() throws NacosException { + + @AfterEach + void tearDown() throws NacosException { clientProxy.shutdown(); System.clearProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT); } - + @Test - public void testOnEvent() { + void testOnEvent() { clientProxy.onEvent(new ServerListChangedEvent()); // Do nothing } - + @Test - public void testSubscribeType() { + void testSubscribeType() { assertEquals(ServerListChangedEvent.class, clientProxy.subscribeType()); } - + @Test - public void testRegisterService() throws Exception { + void testRegisterService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -127,82 +127,89 @@ public void testRegisterService() throws Exception { //then verify(nacosRestTemplate, times(1)).exchangeForm(any(), any(), any(), any(), any(), any()); } - - @Test(expected = UnsupportedOperationException.class) - public void testRegisterEphemeralInstance() throws NacosException { - Instance instance = new Instance(); - clientProxy.registerService("a", "b", instance); + + @Test + void testRegisterEphemeralInstance() throws NacosException { + assertThrows(UnsupportedOperationException.class, () -> { + Instance instance = new Instance(); + clientProxy.registerService("a", "b", instance); + }); } - + @Test - public void testRegisterServiceThrowsNacosException() throws Exception { - thrown.expect(NacosException.class); - thrown.expectMessage("failed to req API"); - - NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); - HttpRestResult a = new HttpRestResult(); - a.setCode(503); - when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a); - - final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); - nacosRestTemplateField.setAccessible(true); - nacosRestTemplateField.set(clientProxy, nacosRestTemplate); - String serviceName = "service1"; - String groupName = "group1"; - Instance instance = new Instance(); - instance.setEphemeral(false); - try { - clientProxy.registerService(serviceName, groupName, instance); - } catch (NacosException ex) { - // verify the `NacosException` is directly thrown - assertEquals(null, ex.getCause()); - - throw ex; - } + void testRegisterServiceThrowsNacosException() throws Exception { + Throwable exception = assertThrows(NacosException.class, () -> { + + NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); + HttpRestResult a = new HttpRestResult(); + a.setCode(503); + when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a); + + final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); + nacosRestTemplateField.setAccessible(true); + nacosRestTemplateField.set(clientProxy, nacosRestTemplate); + String serviceName = "service1"; + String groupName = "group1"; + Instance instance = new Instance(); + instance.setEphemeral(false); + try { + clientProxy.registerService(serviceName, groupName, instance); + } catch (NacosException ex) { + // verify the `NacosException` is directly thrown + assertNull(ex.getCause()); + + throw ex; + } + }); + assertTrue(exception.getMessage().contains("failed to req API")); } - + @Test - public void testRegisterServiceThrowsException() throws Exception { - // assert throw NacosException - thrown.expect(NacosException.class); - - NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); - HttpRestResult a = new HttpRestResult(); - a.setCode(503); - // makes exchangeForm failed with a NullPointerException - when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(null); - - final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); - nacosRestTemplateField.setAccessible(true); - nacosRestTemplateField.set(clientProxy, nacosRestTemplate); - String serviceName = "service1"; - String groupName = "group1"; - Instance instance = new Instance(); - instance.setEphemeral(false); - - try { - clientProxy.registerService(serviceName, groupName, instance); - } catch (NacosException ex) { - // verify the `NacosException` is directly thrown - Assert.assertTrue(ex.getErrMsg().contains("java.lang.NullPointerException")); - assertEquals(NacosException.SERVER_ERROR, ex.getErrCode()); - - throw ex; - } + void testRegisterServiceThrowsException() throws Exception { + assertThrows(NacosException.class, () -> { + + NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); + HttpRestResult a = new HttpRestResult(); + a.setCode(503); + // makes exchangeForm failed with a NullPointerException + when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(null); + + final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); + nacosRestTemplateField.setAccessible(true); + nacosRestTemplateField.set(clientProxy, nacosRestTemplate); + String serviceName = "service1"; + String groupName = "group1"; + Instance instance = new Instance(); + instance.setEphemeral(false); + + try { + clientProxy.registerService(serviceName, groupName, instance); + } catch (NacosException ex) { + // verify the `NacosException` is directly thrown + assertTrue(ex.getErrMsg().contains("java.lang.NullPointerException")); + assertEquals(NacosException.SERVER_ERROR, ex.getErrCode()); + + throw ex; + } + }); } - - @Test(expected = UnsupportedOperationException.class) - public void testBatchRegisterService() { - clientProxy.batchRegisterService("a", "b", null); + + @Test + void testBatchRegisterService() { + assertThrows(UnsupportedOperationException.class, () -> { + clientProxy.batchRegisterService("a", "b", null); + }); } - - @Test(expected = UnsupportedOperationException.class) - public void testBatchDeregisterService() { - clientProxy.batchDeregisterService("a", "b", null); + + @Test + void testBatchDeregisterService() { + assertThrows(UnsupportedOperationException.class, () -> { + clientProxy.batchDeregisterService("a", "b", null); + }); } - + @Test - public void testDeregisterService() throws Exception { + void testDeregisterService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -223,9 +230,9 @@ public void testDeregisterService() throws Exception { //then verify(nacosRestTemplate, times(1)).exchangeForm(any(), any(), any(), any(), eq(HttpMethod.DELETE), any()); } - + @Test - public void testDeregisterServiceForEphemeral() throws Exception { + void testDeregisterServiceForEphemeral() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); nacosRestTemplateField.setAccessible(true); @@ -235,9 +242,9 @@ public void testDeregisterServiceForEphemeral() throws Exception { verify(nacosRestTemplate, never()).exchangeForm(any(), any(), any(), any(), eq(HttpMethod.DELETE), any()); } - + @Test - public void testUpdateInstance() throws Exception { + void testUpdateInstance() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -257,19 +264,19 @@ public void testUpdateInstance() throws Exception { //then verify(nacosRestTemplate, times(1)).exchangeForm(any(), any(), any(), any(), eq(HttpMethod.PUT), any()); } - + @Test - public void testQueryInstancesOfServiceThrowsException() { + void testQueryInstancesOfServiceThrowsException() { //assert exception String serviceName = "service1"; String groupName = "group1"; String clusters = "cluster1"; - Assert.assertThrows(UnsupportedOperationException.class, + assertThrows(UnsupportedOperationException.class, () -> clientProxy.queryInstancesOfService(serviceName, groupName, clusters, false)); } - + @Test - public void testQueryService() throws Exception { + void testQueryService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -292,9 +299,9 @@ public void testQueryService() throws Exception { assertEquals(serviceName, service.getName()); assertEquals(groupName, service.getGroupName()); } - + @Test - public void testCreateService() throws Exception { + void testCreateService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -312,9 +319,9 @@ public void testCreateService() throws Exception { verify(nacosRestTemplate, times(1)) .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.POST), any()); } - + @Test - public void testDeleteService() throws Exception { + void testDeleteService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -334,9 +341,9 @@ public void testDeleteService() throws Exception { verify(nacosRestTemplate, times(1)) .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.DELETE), any()); } - + @Test - public void testUpdateService() throws Exception { + void testUpdateService() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -357,9 +364,9 @@ public void testUpdateService() throws Exception { .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.PUT), any()); } - + @Test - public void testServerHealthy() throws Exception { + void testServerHealthy() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -376,11 +383,11 @@ public void testServerHealthy() throws Exception { //then verify(nacosRestTemplate, times(1)) .exchangeForm(endsWith("/operator/metrics"), any(), any(), any(), eq(HttpMethod.GET), any()); - Assert.assertTrue(serverHealthy); + assertTrue(serverHealthy); } - + @Test - public void testServerHealthyForException() throws Exception { + void testServerHealthyForException() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())) .thenThrow(new RuntimeException("test")); @@ -389,9 +396,9 @@ public void testServerHealthyForException() throws Exception { nacosRestTemplateField.set(clientProxy, nacosRestTemplate); assertFalse(clientProxy.serverHealthy()); } - + @Test - public void testGetServiceList() throws Exception { + void testGetServiceList() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -413,9 +420,9 @@ public void testGetServiceList() throws Exception { assertEquals("aaa", serviceList.getData().get(0)); assertEquals("bbb", serviceList.getData().get(1)); } - + @Test - public void testGetServiceListWithLabelSelector() throws Exception { + void testGetServiceListWithLabelSelector() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); @@ -437,19 +444,21 @@ public void testGetServiceListWithLabelSelector() throws Exception { assertEquals("aaa", serviceList.getData().get(0)); assertEquals("bbb", serviceList.getData().get(1)); } - - @Test(expected = UnsupportedOperationException.class) - public void testSubscribe() throws Exception { - String groupName = "group1"; - String serviceName = "serviceName"; - String clusters = "clusters"; - - //when - clientProxy.subscribe(serviceName, groupName, clusters); + + @Test + void testSubscribe() throws Exception { + assertThrows(UnsupportedOperationException.class, () -> { + String groupName = "group1"; + String serviceName = "serviceName"; + String clusters = "clusters"; + + //when + clientProxy.subscribe(serviceName, groupName, clusters); + }); } - + @Test - public void testUnsubscribe() throws Exception { + void testUnsubscribe() throws Exception { String groupName = "group1"; String serviceName = "serviceName"; String clusters = "clusters"; @@ -458,14 +467,14 @@ public void testUnsubscribe() throws Exception { clientProxy.unsubscribe(serviceName, groupName, clusters); // do nothing } - + @Test - public void testIsSubscribed() throws NacosException { + void testIsSubscribed() throws NacosException { assertTrue(clientProxy.isSubscribed("serviceName", "group1", "clusters")); } - + @Test - public void testReqApi() throws Exception { + void testReqApi() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -489,9 +498,9 @@ public void testReqApi() throws Exception { assertEquals("http://localhost:8848/api", res); } - + @Test - public void testReqApi2() throws Exception { + void testReqApi2() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -515,9 +524,9 @@ public void testReqApi2() throws Exception { //then assertEquals("http://localhost:8848/api", res); } - + @Test - public void testReqApi3() throws Exception { + void testReqApi3() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -542,38 +551,39 @@ public void testReqApi3() throws Exception { //then assertEquals("http://127.0.0.1:8848/api", res); } - + @Test - public void testCallServerFail() throws Exception { - //then - thrown.expect(NacosException.class); - - //given - NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); - - when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenAnswer(invocationOnMock -> { - //return url - HttpRestResult res = new HttpRestResult(); - res.setMessage("fail"); - res.setCode(400); - return res; + void testCallServerFail() throws Exception { + assertThrows(NacosException.class, () -> { + + //given + NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); + + when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenAnswer(invocationOnMock -> { + //return url + HttpRestResult res = new HttpRestResult(); + res.setMessage("fail"); + res.setCode(400); + return res; + }); + + final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); + nacosRestTemplateField.setAccessible(true); + nacosRestTemplateField.set(clientProxy, nacosRestTemplate); + String api = "/api"; + Map params = new HashMap<>(); + Map body = new HashMap<>(); + String method = HttpMethod.GET; + String curServer = "127.0.0.1"; + //when + clientProxy.callServer(api, params, body, curServer, method); + }); - - final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); - nacosRestTemplateField.setAccessible(true); - nacosRestTemplateField.set(clientProxy, nacosRestTemplate); - String api = "/api"; - Map params = new HashMap<>(); - Map body = new HashMap<>(); - String method = HttpMethod.GET; - String curServer = "127.0.0.1"; - //when - clientProxy.callServer(api, params, body, curServer, method); - + } - + @Test - public void testCallServerFail304() throws Exception { + void testCallServerFail304() throws Exception { //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -598,39 +608,44 @@ public void testCallServerFail304() throws Exception { //then assertEquals("", s); } - + @Test - public void testGetNamespaceId() { + void testGetNamespaceId() { String namespaceId = "aaa"; final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props); NamingHttpClientProxy clientProxy = new NamingHttpClientProxy(namespaceId, proxy, mgr, nacosClientProperties); String actualNamespaceId = clientProxy.getNamespaceId(); assertEquals(namespaceId, actualNamespaceId); } - + @Test - public void testSetServerPort() { + void testSetServerPort() { clientProxy.setServerPort(1234); assertEquals(1234, ReflectUtils.getFieldValue(clientProxy, "serverPort")); System.setProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT, "1111"); clientProxy.setServerPort(1234); assertEquals(1111, ReflectUtils.getFieldValue(clientProxy, "serverPort")); } - - @Test(expected = NacosException.class) - public void testReqApiForEmptyServer() throws NacosException { - Map params = new HashMap<>(); - clientProxy - .reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); + + @Test + void testReqApiForEmptyServer() throws NacosException { + assertThrows(NacosException.class, () -> { + Map params = new HashMap<>(); + clientProxy + .reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); + }); } - - @Test(expected = NacosException.class) - public void testRegApiForDomain() throws NacosException { - Map params = new HashMap<>(); - when(mgr.isDomain()).thenReturn(true); - when(mgr.getNacosDomain()).thenReturn("http://test.nacos.domain"); - clientProxy - .reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); - + + @Test + void testRegApiForDomain() throws NacosException { + assertThrows(NacosException.class, () -> { + Map params = new HashMap<>(); + when(mgr.isDomain()).thenReturn(true); + when(mgr.getNacosDomain()).thenReturn("http://test.nacos.domain"); + clientProxy + .reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); + + }); + } } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java index 32a8599037c..6e591957f9a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java @@ -18,44 +18,44 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.client.env.NacosClientProperties; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class CacheDirUtilTest { - - @After - public void tearDown() throws Exception { +class CacheDirUtilTest { + + @AfterEach + void tearDown() throws Exception { System.clearProperty("user.home"); System.clearProperty("JM.SNAPSHOT.PATH"); } - + @Test - public void testInitCacheDirWithDefaultRootAndWithoutCache() { + void testInitCacheDirWithDefaultRootAndWithoutCache() { System.setProperty("user.home", "/home/admin"); String actual = CacheDirUtil.initCacheDir("test", NacosClientProperties.PROTOTYPE.derive()); assertEquals("/home/admin/nacos/naming/test", actual); } - + @Test - public void testInitCacheDirWithDefaultRootAndWithCache() { + void testInitCacheDirWithDefaultRootAndWithCache() { System.setProperty("user.home", "/home/admin"); NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "custom"); String actual = CacheDirUtil.initCacheDir("test", properties); assertEquals("/home/admin/nacos/custom/naming/test", actual); } - + @Test - public void testInitCacheDirWithJmSnapshotPathRootAndWithoutCache() { + void testInitCacheDirWithJmSnapshotPathRootAndWithoutCache() { System.setProperty("JM.SNAPSHOT.PATH", "/home/snapshot"); String actual = CacheDirUtil.initCacheDir("test", NacosClientProperties.PROTOTYPE.derive()); assertEquals("/home/snapshot/nacos/naming/test", actual); } - + @Test - public void testInitCacheDirWithJmSnapshotPathRootAndWithCache() { + void testInitCacheDirWithJmSnapshotPathRootAndWithCache() { System.setProperty("user.home", "/home/snapshot"); NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.NAMING_CACHE_REGISTRY_DIR, "custom"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java index 8f62917f88a..9e0e3580ff1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.client.naming.utils; import com.alibaba.nacos.api.naming.pojo.Instance; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; @@ -25,31 +25,32 @@ import java.util.List; import java.util.concurrent.ThreadLocalRandom; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ChooserTest { -public class ChooserTest { - @Test - public void testChooser() { + void testChooser() { //Test the correctness of Chooser, the weight of the final selected instance must be greater than 0 List hosts = getInstanceList(); Instance target = getRandomInstance(hosts); assertTrue(hosts.contains(target) && target.getWeight() > 0); } - + @Test - public void testChooserRandomForEmptyList() { + void testChooserRandomForEmptyList() { Chooser chooser = new Chooser<>("test"); assertEquals("test", chooser.getUniqueKey()); assertNull(chooser.random()); } - + @Test - public void testChooserRandomForOneSizeList() { + void testChooserRandomForOneSizeList() { List> list = new LinkedList<>(); list.add(new Pair<>("test", 1)); Chooser chooser = new Chooser<>("test", list); @@ -57,9 +58,9 @@ public void testChooserRandomForOneSizeList() { assertNotNull(actual); assertEquals("test", actual); } - + @Test - public void testChooserRandom() { + void testChooserRandom() { List> list = new LinkedList<>(); list.add(new Pair<>("test", 1)); list.add(new Pair<>("test2", 1)); @@ -68,18 +69,18 @@ public void testChooserRandom() { assertNotNull(actual); assertTrue(actual.equals("test") || actual.equals("test2")); } - + @Test - public void testOnlyOneInstanceWeightIsNotZero() { + void testOnlyOneInstanceWeightIsNotZero() { // If there is only one instance whose weight is not zero, it will be selected List hosts = getOneInstanceNotZeroList(); Instance target = getRandomInstance(hosts); assertTrue(target.getWeight() > 0); } - + @Test - public void testInstanceWeightAllZero() { + void testInstanceWeightAllZero() { // Throw an IllegalStateException when all instances have a weight of zero. List hosts = getInstanceWeightAllZero(); @@ -89,17 +90,19 @@ public void testInstanceWeightAllZero() { assertTrue(e instanceof IllegalStateException); } } - - @Test(expected = IllegalStateException.class) - public void testRandomWithWeightForNaNAndInfinity() { - List> list = new LinkedList<>(); - list.add(new Pair<>("test", Double.NaN)); - list.add(new Pair<>("test2", Double.POSITIVE_INFINITY)); - new Chooser<>("test", list); + + @Test + void testRandomWithWeightForNaNAndInfinity() { + assertThrows(IllegalStateException.class, () -> { + List> list = new LinkedList<>(); + list.add(new Pair<>("test", Double.NaN)); + list.add(new Pair<>("test2", Double.POSITIVE_INFINITY)); + new Chooser<>("test", list); + }); } - + @Test - public void testRefresh() { + void testRefresh() { Chooser chooser = new Chooser<>("test"); assertEquals("test", chooser.getUniqueKey()); assertNull(chooser.random()); @@ -110,45 +113,45 @@ public void testRefresh() { assertNotNull(actual); assertEquals("test", actual); } - + @Test - public void testEqualsHashCode() { + void testEqualsHashCode() { List> list = new LinkedList<>(); list.add(new Pair<>("test", 1)); list.add(new Pair<>("test2", 1)); Chooser chooser = new Chooser<>("test", list); assertEquals("test".hashCode(), chooser.hashCode()); - assertTrue(chooser.equals(chooser)); - assertFalse(chooser.equals(null)); - assertFalse(chooser.equals("test")); + assertEquals(chooser, chooser); + assertNotEquals(null, chooser); + assertNotEquals("test", chooser); Chooser chooser1 = new Chooser<>(null, null); - assertFalse(chooser.equals(chooser1)); - assertFalse(chooser1.equals(chooser)); + assertNotEquals(chooser, chooser1); + assertNotEquals(chooser1, chooser); Chooser chooser2 = new Chooser<>("test", Collections.emptyList()); - assertFalse(chooser.equals(chooser2)); - assertFalse(chooser2.equals(chooser)); + assertNotEquals(chooser, chooser2); + assertNotEquals(chooser2, chooser); Chooser chooser3 = new Chooser<>("test1", list); - assertFalse(chooser.equals(chooser3)); + assertNotEquals(chooser, chooser3); Chooser chooser4 = new Chooser<>("test", list); - assertTrue(chooser.equals(chooser4)); + assertEquals(chooser, chooser4); } - + @Test - public void testRefEqualsHashCode() { + void testRefEqualsHashCode() { List> list = new LinkedList<>(); list.add(new Pair<>("test", 1)); list.add(new Pair<>("test2", 1)); Chooser chooser = new Chooser<>("test", list); Chooser.Ref ref = chooser.getRef(); assertEquals(list.hashCode(), ref.hashCode()); - assertTrue(ref.equals(ref)); - assertFalse(ref.equals(null)); - assertFalse(ref.equals(chooser)); + assertEquals(ref, ref); + assertNotEquals(null, ref); + assertNotEquals(ref, chooser); Chooser.Ref ref1 = new Chooser<>("test", null).getRef(); - assertFalse(ref.equals(ref1)); - assertFalse(ref1.equals(ref)); + assertNotEquals(ref, ref1); + assertNotEquals(ref1, ref); Chooser.Ref ref2 = new Chooser<>("test", list).getRef(); - assertTrue(ref.equals(ref2)); + assertEquals(ref, ref2); } private List getInstanceList() { diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java index fdcb20993d9..e7b3cd7bf55 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java @@ -16,53 +16,56 @@ package com.alibaba.nacos.client.naming.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; -public class CollectionUtilsTest { - +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 CollectionUtilsTest { + @Test - public void testSubtract() { + void testSubtract() { List subtract = (List) CollectionUtils .subtract(Arrays.asList("a", "b"), Arrays.asList("b", "c")); - Assert.assertEquals(1, subtract.size()); - Assert.assertEquals("a", subtract.get(0)); + assertEquals(1, subtract.size()); + assertEquals("a", subtract.get(0)); } - + @Test - public void testGetCardinalityMap() { + void testGetCardinalityMap() { List list1 = Arrays.asList("2", "2", "3"); Map map1 = CollectionUtils.getCardinalityMap(list1); - Assert.assertEquals(2, map1.size()); - Assert.assertEquals(2, map1.get("2").intValue()); - Assert.assertEquals(1, map1.get("3").intValue()); + assertEquals(2, map1.size()); + assertEquals(2, map1.get("2").intValue()); + assertEquals(1, map1.get("3").intValue()); } - + @Test - public void testIsEqualCollection() { + void testIsEqualCollection() { List list1 = Arrays.asList("2", "2", "3"); List list2 = Arrays.asList("3", "2", "2"); List list3 = Arrays.asList("3", "2", "3"); List list4 = Arrays.asList("3", "2"); List list5 = Arrays.asList("3", "2", "1"); List list6 = Arrays.asList("2", "2", "1"); - Assert.assertTrue(CollectionUtils.isEqualCollection(list1, list2)); - Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list3)); - Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list4)); - Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list5)); - Assert.assertFalse(CollectionUtils.isEqualCollection(list1, list6)); + assertTrue(CollectionUtils.isEqualCollection(list1, list2)); + assertFalse(CollectionUtils.isEqualCollection(list1, list3)); + assertFalse(CollectionUtils.isEqualCollection(list1, list4)); + assertFalse(CollectionUtils.isEqualCollection(list1, list5)); + assertFalse(CollectionUtils.isEqualCollection(list1, list6)); } - + @Test - public void testIsEmpty() { - Assert.assertTrue(CollectionUtils.isEmpty(null)); - Assert.assertTrue(CollectionUtils.isEmpty(new ArrayList())); - Assert.assertFalse(CollectionUtils.isEmpty(Arrays.asList("aa"))); + void testIsEmpty() { + assertTrue(CollectionUtils.isEmpty(null)); + assertTrue(CollectionUtils.isEmpty(new ArrayList())); + assertFalse(CollectionUtils.isEmpty(Arrays.asList("aa"))); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java index 545df8d0d5f..5d58c861e66 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java @@ -17,8 +17,7 @@ package com.alibaba.nacos.client.naming.utils; import com.alibaba.nacos.client.utils.ConcurrentDiskUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -28,76 +27,83 @@ import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ConcurrentDiskUtilTest { - +class ConcurrentDiskUtilTest { + @Test - public void testReadAndWrite() throws IOException { + void testReadAndWrite() throws IOException { File tempFile = File.createTempFile("aaa", "bbb"); String fileName = tempFile.getAbsolutePath(); String content = "hello"; String charset = "UTF-8"; ConcurrentDiskUtil.writeFileContent(fileName, content, charset); String actualContent = ConcurrentDiskUtil.getFileContent(fileName, charset); - Assert.assertEquals(content, actualContent); + assertEquals(content, actualContent); } - + @Test - public void testReadAndWrite2() throws IOException { + void testReadAndWrite2() throws IOException { File tempFile = File.createTempFile("aaa", "bbb"); String content = "hello"; String charset = "UTF-8"; ConcurrentDiskUtil.writeFileContent(tempFile, content, charset); String actualContent = ConcurrentDiskUtil.getFileContent(tempFile, charset); - Assert.assertEquals(content, actualContent); + assertEquals(content, actualContent); } - + @Test - public void testByteBufferToString() throws IOException { + void testByteBufferToString() throws IOException { String msg = "test buff to string"; ByteBuffer buff = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)); String actual = ConcurrentDiskUtil.byteBufferToString(buff, "UTF-8"); - Assert.assertEquals(msg, actual); + assertEquals(msg, actual); } - + @Test - public void testWriteFileContent() throws IOException { + void testWriteFileContent() throws IOException { File file = mock(File.class); - Assert.assertFalse(ConcurrentDiskUtil.writeFileContent(file, "hello", "UTF-8")); + assertFalse(ConcurrentDiskUtil.writeFileContent(file, "hello", "UTF-8")); } - - @Test(expected = IOException.class) - public void testTryLockFailure() throws Throwable { - Method method = ConcurrentDiskUtil.class - .getDeclaredMethod("tryLock", File.class, FileChannel.class, boolean.class); - method.setAccessible(true); - File file = new File("non-exist"); - FileChannel channel = mock(FileChannel.class); - when(channel.tryLock(anyLong(), anyLong(), anyBoolean())).thenThrow(new RuntimeException()); - try { - method.invoke(null, file, channel, true); - } catch (InvocationTargetException e) { - throw e.getCause(); - } + + @Test + void testTryLockFailure() throws Throwable { + assertThrows(IOException.class, () -> { + Method method = ConcurrentDiskUtil.class + .getDeclaredMethod("tryLock", File.class, FileChannel.class, boolean.class); + method.setAccessible(true); + File file = new File("non-exist"); + FileChannel channel = mock(FileChannel.class); + when(channel.tryLock(anyLong(), anyLong(), anyBoolean())).thenThrow(new RuntimeException()); + try { + method.invoke(null, file, channel, true); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); } - - @Test(expected = IOException.class) - public void testTryLockFailureForIntercept() throws Throwable { - Method method = ConcurrentDiskUtil.class - .getDeclaredMethod("tryLock", File.class, FileChannel.class, boolean.class); - method.setAccessible(true); - File file = new File("non-exist"); - FileChannel channel = mock(FileChannel.class); - Thread.currentThread().interrupt(); - when(channel.tryLock(anyLong(), anyLong(), anyBoolean())).thenThrow(new RuntimeException()); - try { - method.invoke(null, file, channel, true); - } catch (InvocationTargetException e) { - throw e.getCause(); - } + + @Test + void testTryLockFailureForIntercept() throws Throwable { + assertThrows(IOException.class, () -> { + Method method = ConcurrentDiskUtil.class + .getDeclaredMethod("tryLock", File.class, FileChannel.class, boolean.class); + method.setAccessible(true); + File file = new File("non-exist"); + FileChannel channel = mock(FileChannel.class); + Thread.currentThread().interrupt(); + when(channel.tryLock(anyLong(), anyLong(), anyBoolean())).thenThrow(new RuntimeException()); + try { + method.invoke(null, file, channel, true); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java index b081427fbfc..8a1feafca30 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java @@ -16,29 +16,30 @@ package com.alibaba.nacos.client.naming.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; -public class GenericPollerTest { - +import static org.junit.jupiter.api.Assertions.assertEquals; + +class GenericPollerTest { + @Test - public void testNext() { + void testNext() { String item1 = "item1"; String item2 = "item2"; GenericPoller poller = new GenericPoller<>(Arrays.asList(item1, item2)); - Assert.assertEquals(item1, poller.next()); - Assert.assertEquals(item2, poller.next()); - Assert.assertEquals(item1, poller.next()); + assertEquals(item1, poller.next()); + assertEquals(item2, poller.next()); + assertEquals(item1, poller.next()); } - + @Test - public void testRefresh() { + void testRefresh() { String item1 = "item1"; String item2 = "item2"; GenericPoller poller = new GenericPoller<>(Arrays.asList(item1, item2)); Poller poller1 = poller.refresh(Arrays.asList(item2)); - Assert.assertEquals(item2, poller1.next()); + assertEquals(item2, poller1.next()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java index b64cca489f0..d8e441baf9b 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java @@ -19,14 +19,15 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.SystemPropertyKeyConst; import com.alibaba.nacos.client.env.NacosClientProperties; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -public class InitUtilsTest { - - @After - public void tearDown() { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class InitUtilsTest { + + @AfterEach + void tearDown() { System.clearProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING); System.clearProperty(SystemPropertyKeyConst.ANS_NAMESPACE); System.clearProperty(PropertyKeyConst.NAMESPACE); @@ -37,130 +38,130 @@ public void tearDown() { UtilAndComs.nacosUrlBase = "/nacos/v1/ns"; UtilAndComs.nacosUrlInstance = "/nacos/v1/ns/instance"; } - + /** * current namespace priority 1. system.Properties 2. user.Properties 3. default value */ @Test - public void testInitNamespaceForDefault() { + void testInitNamespaceForDefault() { //DEFAULT final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String actual = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); + assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); } - + @Test - public void testInitNamespaceFromAnsWithCloudParsing() { + void testInitNamespaceFromAnsWithCloudParsing() { String expect = "ans"; System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, expect); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "true"); String actual = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } - + @Test - public void testInitNamespaceFromAliwareWithCloudParsing() { + void testInitNamespaceFromAliwareWithCloudParsing() { String expect = "aliware"; System.setProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "true"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE, expect); String actual = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } - + @Test - public void testInitNamespaceFromJvmNamespaceWithCloudParsing() { + void testInitNamespaceFromJvmNamespaceWithCloudParsing() { String expect = "jvm_namespace"; System.setProperty(PropertyKeyConst.NAMESPACE, expect); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String ns = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, ns); + assertEquals(expect, ns); } - + @Test - public void testInitNamespaceFromPropNamespaceWithCloudParsing() { + void testInitNamespaceFromPropNamespaceWithCloudParsing() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String expect = "ns1"; properties.setProperty(PropertyKeyConst.NAMESPACE, expect); String ns = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, ns); + assertEquals(expect, ns); } - + @Test - public void testInitNamespaceFromDefaultNamespaceWithCloudParsing() { + void testInitNamespaceFromDefaultNamespaceWithCloudParsing() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "true"); String actual = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); + assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); } - + @Test - public void testInitNamespaceFromJvmNamespaceWithoutCloudParsing() { + void testInitNamespaceFromJvmNamespaceWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, "ans"); String expect = "jvm_namespace"; System.setProperty(PropertyKeyConst.NAMESPACE, expect); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "false"); String ns = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, ns); + assertEquals(expect, ns); } - + @Test - public void testInitNamespaceFromPropNamespaceWithoutCloudParsing() { + void testInitNamespaceFromPropNamespaceWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, "ans"); System.setProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "false"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String expect = "ns1"; properties.setProperty(PropertyKeyConst.NAMESPACE, expect); String ns = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(expect, ns); + assertEquals(expect, ns); } - + @Test - public void testInitNamespaceFromDefaultNamespaceWithoutCloudParsing() { + void testInitNamespaceFromDefaultNamespaceWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, "ans"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING, "false"); String actual = InitUtils.initNamespaceForNaming(properties); - Assert.assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); + assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); } - + @Test - public void testInitWebRootContext() { + void testInitWebRootContext() { String ctx = "/aaa"; final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.CONTEXT_PATH, ctx); InitUtils.initWebRootContext(properties); - Assert.assertEquals(ctx, UtilAndComs.webContext); - Assert.assertEquals(ctx + "/v1/ns", UtilAndComs.nacosUrlBase); - Assert.assertEquals(ctx + "/v1/ns/instance", UtilAndComs.nacosUrlInstance); + assertEquals(ctx, UtilAndComs.webContext); + assertEquals(ctx + "/v1/ns", UtilAndComs.nacosUrlBase); + assertEquals(ctx + "/v1/ns/instance", UtilAndComs.nacosUrlInstance); } - + @Test - public void testInitWebRootContextWithoutValue() { + void testInitWebRootContextWithoutValue() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); InitUtils.initWebRootContext(properties); - Assert.assertEquals("/nacos", UtilAndComs.webContext); - Assert.assertEquals("/nacos/v1/ns", UtilAndComs.nacosUrlBase); - Assert.assertEquals("/nacos/v1/ns/instance", UtilAndComs.nacosUrlInstance); + assertEquals("/nacos", UtilAndComs.webContext); + assertEquals("/nacos/v1/ns", UtilAndComs.nacosUrlBase); + assertEquals("/nacos/v1/ns/instance", UtilAndComs.nacosUrlInstance); } - + @Test - public void testInitEndpointForNullProperties() { - Assert.assertEquals("", InitUtils.initEndpoint(null)); + void testInitEndpointForNullProperties() { + assertEquals("", InitUtils.initEndpoint(null)); } - + @Test - public void testInitEndpointFromDefaultWithoutCloudParsing() { + void testInitEndpointFromDefaultWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "false"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals("", actual); + assertEquals("", actual); } - + @Test - public void testInitEndpointFromPropertiesWithoutCloudParsing() { + void testInitEndpointFromPropertiesWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "false"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String endpoint = "1.1.1.1"; @@ -168,11 +169,11 @@ public void testInitEndpointFromPropertiesWithoutCloudParsing() { properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, endpointPort); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals(endpoint + ":" + endpointPort, actual); + assertEquals(endpoint + ":" + endpointPort, actual); } - + @Test - public void testInitEndpointFromAliwareWithoutCloudParsing() { + void testInitEndpointFromAliwareWithoutCloudParsing() { String endpoint = "aliware_endpoint"; String endpointPort = "1234"; System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "false"); @@ -181,19 +182,19 @@ public void testInitEndpointFromAliwareWithoutCloudParsing() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, endpointPort + "1"); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals("", actual); + assertEquals("", actual); } - + @Test - public void testInitEndpointFromDefaultWithCloudParsing() { + void testInitEndpointFromDefaultWithCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals("", actual); + assertEquals("", actual); } - + @Test - public void testInitEndpointFromPropertiesWithCloudParsing() { + void testInitEndpointFromPropertiesWithCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); String endpoint = "1.1.1.1"; @@ -201,11 +202,11 @@ public void testInitEndpointFromPropertiesWithCloudParsing() { properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, endpointPort); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals(endpoint + ":" + endpointPort, actual); + assertEquals(endpoint + ":" + endpointPort, actual); } - + @Test - public void testInitEndpointFromAliwareWithCloudParsing() { + void testInitEndpointFromAliwareWithCloudParsing() { String endpoint = "aliware_endpoint"; String endpointPort = "1234"; System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); @@ -214,11 +215,11 @@ public void testInitEndpointFromAliwareWithCloudParsing() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); properties.setProperty(PropertyKeyConst.ENDPOINT_PORT, endpointPort + "1"); String actual = InitUtils.initEndpoint(properties); - Assert.assertEquals(endpoint + ":" + endpointPort, actual); + assertEquals(endpoint + ":" + endpointPort, actual); } - + @Test - public void testInitEndpointAns() { + void testInitEndpointAns() { try { System.setProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); @@ -226,7 +227,7 @@ public void testInitEndpointAns() { properties.setProperty(PropertyKeyConst.ENDPOINT, endpoint); String actual = InitUtils.initEndpoint(properties); //defaultEndpointPort is "8080"; - Assert.assertEquals("test.com:8080", actual); + assertEquals("test.com:8080", actual); } finally { System.clearProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE); } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java index eda626ba41b..1ad588ae07e 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java @@ -19,20 +19,22 @@ import com.alibaba.nacos.common.constant.HttpHeaderConsts; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.utils.VersionUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class NamingHttpUtilTest { -public class NamingHttpUtilTest { - @Test - public void testBuilderHeader() { + void testBuilderHeader() { Header header = NamingHttpUtil.builderHeader(); - Assert.assertNotNull(header); - Assert.assertEquals(header.getValue(HttpHeaderConsts.CLIENT_VERSION_HEADER), VersionUtils.version); - Assert.assertEquals(header.getValue(HttpHeaderConsts.USER_AGENT_HEADER), VersionUtils.getFullClientVersion()); - Assert.assertEquals(header.getValue(HttpHeaderConsts.ACCEPT_ENCODING), "gzip,deflate,sdch"); - Assert.assertEquals(header.getValue(HttpHeaderConsts.CONNECTION), "Keep-Alive"); - Assert.assertNotNull(header.getValue(HttpHeaderConsts.REQUEST_ID)); - Assert.assertEquals(header.getValue(HttpHeaderConsts.REQUEST_MODULE), "Naming"); + assertNotNull(header); + assertEquals(header.getValue(HttpHeaderConsts.CLIENT_VERSION_HEADER), VersionUtils.version); + assertEquals(header.getValue(HttpHeaderConsts.USER_AGENT_HEADER), VersionUtils.getFullClientVersion()); + assertEquals("gzip,deflate,sdch", header.getValue(HttpHeaderConsts.ACCEPT_ENCODING)); + assertEquals("Keep-Alive", header.getValue(HttpHeaderConsts.CONNECTION)); + assertNotNull(header.getValue(HttpHeaderConsts.REQUEST_ID)); + assertEquals("Naming", header.getValue(HttpHeaderConsts.REQUEST_MODULE)); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java index bbdf66b5dc5..f4ceaa64cf6 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java @@ -16,17 +16,18 @@ package com.alibaba.nacos.client.naming.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PairTest { -public class PairTest { - @Test - public void testItem() { + void testItem() { String item = "aa"; double weight = 1.0; Pair pair = new Pair<>(item, weight); - Assert.assertEquals(weight, pair.weight(), 0.01); - Assert.assertEquals(item, pair.item()); + assertEquals(weight, pair.weight(), 0.01); + assertEquals(item, pair.item()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java index ee75d48914a..efe413f06c5 100644 --- a/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java @@ -23,12 +23,13 @@ import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.plugin.auth.api.RequestResource; import com.alibaba.nacos.plugin.auth.spi.client.ClientAuthPluginManager; -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.ArrayList; @@ -37,21 +38,25 @@ import java.util.Map; import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class SecurityProxyTest { +@ExtendWith(MockitoExtension.class) +// todo remove strictness lenient +@MockitoSettings(strictness = Strictness.LENIENT) +class SecurityProxyTest { private SecurityProxy securityProxy; @Mock private NacosRestTemplate nacosRestTemplate; - - @Before - public void setUp() throws Exception { + + @BeforeEach + void setUp() throws Exception { //given HttpRestResult result = new HttpRestResult<>(); result.setData("{\"accessToken\":\"ttttttttttttttttt\",\"tokenTtl\":1000}"); @@ -62,18 +67,18 @@ public void setUp() throws Exception { serverList.add("localhost"); securityProxy = new SecurityProxy(serverList, nacosRestTemplate); } - + @Test - public void testLoginClientAuthService() throws Exception { + void testLoginClientAuthService() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); securityProxy.login(properties); verify(nacosRestTemplate).postForm(any(), (Header) any(), any(), any(), any()); } - + @Test - public void testGetIdentityContext() { + void testGetIdentityContext() { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); @@ -81,11 +86,11 @@ public void testGetIdentityContext() { //when Map keyMap = securityProxy.getIdentityContext(null); //then - Assert.assertEquals("ttttttttttttttttt", keyMap.get(NacosAuthLoginConstant.ACCESSTOKEN)); + assertEquals("ttttttttttttttttt", keyMap.get(NacosAuthLoginConstant.ACCESSTOKEN)); } - + @Test - public void testLoginWithoutAnyPlugin() throws NoSuchFieldException, IllegalAccessException { + void testLoginWithoutAnyPlugin() throws NoSuchFieldException, IllegalAccessException { Field clientAuthPluginManagerField = SecurityProxy.class.getDeclaredField("clientAuthPluginManager"); clientAuthPluginManagerField.setAccessible(true); ClientAuthPluginManager clientAuthPluginManager = mock(ClientAuthPluginManager.class); @@ -93,6 +98,6 @@ public void testLoginWithoutAnyPlugin() throws NoSuchFieldException, IllegalAcce when(clientAuthPluginManager.getAuthServiceSpiImplSet()).thenReturn(Collections.emptySet()); securityProxy.login(new Properties()); Map header = securityProxy.getIdentityContext(new RequestResource()); - Assert.assertTrue(header.isEmpty()); + assertTrue(header.isEmpty()); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java index 95ddb0265c9..bd96dc68deb 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java @@ -19,55 +19,55 @@ package com.alibaba.nacos.client.utils; import com.alibaba.nacos.client.constant.Constants; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AppNameUtilsTest { - - @Before - public void setUp() throws Exception { +class AppNameUtilsTest { + + @BeforeEach + void setUp() throws Exception { } - - @After - public void tearDown() throws Exception { + + @AfterEach + void tearDown() throws Exception { System.clearProperty(Constants.SysEnv.PROJECT_NAME); System.clearProperty("jboss.server.home.dir"); System.clearProperty("jetty.home"); System.clearProperty("catalina.base"); } - + @Test - public void testGetAppNameByDefault() { + void testGetAppNameByDefault() { String appName = AppNameUtils.getAppName(); assertEquals("unknown", appName); } - + @Test - public void testGetAppNameByProjectName() { + void testGetAppNameByProjectName() { System.setProperty(Constants.SysEnv.PROJECT_NAME, "testAppName"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); } - + @Test - public void testGetAppNameByServerTypeForJboss() { + void testGetAppNameByServerTypeForJboss() { System.setProperty("jboss.server.home.dir", "/home/admin/testAppName/"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); } - + @Test - public void testGetAppNameByServerTypeForJetty() { + void testGetAppNameByServerTypeForJetty() { System.setProperty("jetty.home", "/home/admin/testAppName/"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); } - + @Test - public void testGetAppNameByServerTypeForTomcat() { + void testGetAppNameByServerTypeForTomcat() { System.setProperty("catalina.base", "/home/admin/testAppName/"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java index c1953d8b1e7..5afdc1c3caa 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java @@ -16,9 +16,9 @@ package com.alibaba.nacos.client.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * ContextPathUtil test. @@ -26,10 +26,10 @@ * @author Wei.Wang * @date 2020/11/26 3:13 PM */ -public class ContextPathUtilTest { - +class ContextPathUtilTest { + @Test - public void testNormalizeContextPath() { + void testNormalizeContextPath() { assertEquals("/nacos", ContextPathUtil.normalizeContextPath("/nacos")); assertEquals("/nacos", ContextPathUtil.normalizeContextPath("nacos")); assertEquals("", ContextPathUtil.normalizeContextPath("/")); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java index 1be9575ef4e..07214276f70 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java @@ -19,8 +19,7 @@ package com.alibaba.nacos.client.utils; import com.alibaba.nacos.api.common.Constants; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; @@ -28,45 +27,48 @@ import java.util.List; import java.util.Map; -public class EnvUtilTest { - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class EnvUtilTest { + @Test - public void testSetSelfEnv() { + void testSetSelfEnv() { Map> headers = new HashMap<>(); headers.put(Constants.AMORY_TAG, Arrays.asList("a", "1")); headers.put(Constants.VIPSERVER_TAG, Arrays.asList("b", "2")); headers.put(Constants.LOCATION_TAG, Arrays.asList("c", "3")); EnvUtil.setSelfEnv(headers); - Assert.assertEquals("a,1", EnvUtil.getSelfAmoryTag()); - Assert.assertEquals("b,2", EnvUtil.getSelfVipserverTag()); - Assert.assertEquals("c,3", EnvUtil.getSelfLocationTag()); + assertEquals("a,1", EnvUtil.getSelfAmoryTag()); + assertEquals("b,2", EnvUtil.getSelfVipserverTag()); + assertEquals("c,3", EnvUtil.getSelfLocationTag()); // reset by empty list headers.put(Constants.AMORY_TAG, Collections.emptyList()); headers.put(Constants.VIPSERVER_TAG, Collections.emptyList()); headers.put(Constants.LOCATION_TAG, Collections.emptyList()); EnvUtil.setSelfEnv(headers); - Assert.assertNull(EnvUtil.getSelfAmoryTag()); - Assert.assertNull(EnvUtil.getSelfVipserverTag()); - Assert.assertNull(EnvUtil.getSelfLocationTag()); + assertNull(EnvUtil.getSelfAmoryTag()); + assertNull(EnvUtil.getSelfVipserverTag()); + assertNull(EnvUtil.getSelfLocationTag()); } - + @Test - public void testSetSelfEnv2() { + void testSetSelfEnv2() { Map> headers = new HashMap<>(); headers.put(Constants.AMORY_TAG, Arrays.asList("a", "1")); headers.put(Constants.VIPSERVER_TAG, Arrays.asList("b", "2")); headers.put(Constants.LOCATION_TAG, Arrays.asList("c", "3")); EnvUtil.setSelfEnv(headers); - Assert.assertEquals("a,1", EnvUtil.getSelfAmoryTag()); - Assert.assertEquals("b,2", EnvUtil.getSelfVipserverTag()); - Assert.assertEquals("c,3", EnvUtil.getSelfLocationTag()); + assertEquals("a,1", EnvUtil.getSelfAmoryTag()); + assertEquals("b,2", EnvUtil.getSelfVipserverTag()); + assertEquals("c,3", EnvUtil.getSelfLocationTag()); // reset headers.put(Constants.AMORY_TAG, null); headers.put(Constants.VIPSERVER_TAG, null); headers.put(Constants.LOCATION_TAG, null); EnvUtil.setSelfEnv(headers); - Assert.assertNull(EnvUtil.getSelfAmoryTag()); - Assert.assertNull(EnvUtil.getSelfVipserverTag()); - Assert.assertNull(EnvUtil.getSelfLocationTag()); + assertNull(EnvUtil.getSelfAmoryTag()); + assertNull(EnvUtil.getSelfVipserverTag()); + assertNull(EnvUtil.getSelfLocationTag()); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java index ec04b5a4e7b..5120ee88ec7 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java @@ -16,16 +16,17 @@ package com.alibaba.nacos.client.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; -public class LogUtilsTest { - +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class LogUtilsTest { + @Test - public void testLogger() { + void testLogger() { Logger logger = LogUtils.logger(LogUtilsTest.class); - Assert.assertNotNull(logger); + assertNotNull(logger); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java index 7f16b04f607..129f3722bb7 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java @@ -22,17 +22,18 @@ import com.alibaba.nacos.client.env.NacosClientProperties; import com.alibaba.nacos.common.utils.MD5Utils; import com.alibaba.nacos.common.utils.VersionUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class ParamUtilTest { +class ParamUtilTest { private String defaultAppKey; @@ -47,9 +48,9 @@ public class ParamUtilTest { private double defaultPerTaskConfigSize; private String defaultNodesPath; - - @Before - public void before() { + + @BeforeEach + void before() { defaultAppKey = ""; defaultAppName = "unknown"; defaultContextPath = "nacos"; @@ -58,9 +59,9 @@ public void before() { defaultPerTaskConfigSize = 3000.0; defaultNodesPath = "serverlist"; } - - @After - public void after() { + + @AfterEach + void after() { ParamUtil.setAppKey(defaultAppKey); ParamUtil.setAppName(defaultAppName); ParamUtil.setDefaultContextPath(defaultContextPath); @@ -72,9 +73,9 @@ public void after() { System.clearProperty("PER_TASK_CONFIG_SIZE"); System.clearProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL); } - + @Test - public void testGetAppKey() { + void testGetAppKey() { String defaultVal = ParamUtil.getAppKey(); assertEquals(defaultAppKey, defaultVal); @@ -82,9 +83,9 @@ public void testGetAppKey() { ParamUtil.setAppKey(expect); assertEquals(expect, ParamUtil.getAppKey()); } - + @Test - public void testGetAppName() { + void testGetAppName() { String defaultVal = ParamUtil.getAppName(); assertEquals(defaultAppName, defaultVal); @@ -92,9 +93,9 @@ public void testGetAppName() { ParamUtil.setAppName(expect); assertEquals(expect, ParamUtil.getAppName()); } - + @Test - public void testGetDefaultContextPath() { + void testGetDefaultContextPath() { String defaultVal = ParamUtil.getDefaultContextPath(); assertEquals(defaultContextPath, defaultVal); @@ -102,9 +103,9 @@ public void testGetDefaultContextPath() { ParamUtil.setDefaultContextPath(expect); assertEquals(expect, ParamUtil.getDefaultContextPath()); } - + @Test - public void testGetClientVersion() { + void testGetClientVersion() { String defaultVal = ParamUtil.getClientVersion(); assertEquals(defaultVersion, defaultVal); @@ -112,9 +113,9 @@ public void testGetClientVersion() { ParamUtil.setClientVersion(expect); assertEquals(expect, ParamUtil.getClientVersion()); } - + @Test - public void testSetConnectTimeout() { + void testSetConnectTimeout() { int defaultVal = ParamUtil.getConnectTimeout(); assertEquals(defaultConnectTimeout, defaultVal); @@ -122,9 +123,9 @@ public void testSetConnectTimeout() { ParamUtil.setConnectTimeout(expect); assertEquals(expect, ParamUtil.getConnectTimeout()); } - + @Test - public void testGetPerTaskConfigSize() { + void testGetPerTaskConfigSize() { double defaultVal = ParamUtil.getPerTaskConfigSize(); assertEquals(defaultPerTaskConfigSize, defaultVal, 0.01); @@ -132,15 +133,15 @@ public void testGetPerTaskConfigSize() { ParamUtil.setPerTaskConfigSize(expect); assertEquals(expect, ParamUtil.getPerTaskConfigSize(), 0.01); } - + @Test - public void testGetDefaultServerPort() { + void testGetDefaultServerPort() { String actual = ParamUtil.getDefaultServerPort(); assertEquals("8848", actual); } - + @Test - public void testGetDefaultNodesPath() { + void testGetDefaultNodesPath() { String defaultVal = ParamUtil.getDefaultNodesPath(); assertEquals("serverlist", defaultVal); @@ -148,9 +149,9 @@ public void testGetDefaultNodesPath() { ParamUtil.setDefaultNodesPath(expect); assertEquals(expect, ParamUtil.getDefaultNodesPath()); } - + @Test - public void testParseNamespace() { + void testParseNamespace() { String expect = "test"; Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.NAMESPACE, expect); @@ -159,52 +160,56 @@ public void testParseNamespace() { String actual = ParamUtil.parseNamespace(nacosClientProperties); assertEquals(expect, actual); } - + @Test - public void testParsingEndpointRule() { + void testParsingEndpointRule() { String url = "${test:www.example.com}"; String actual = ParamUtil.parsingEndpointRule(url); assertEquals("www.example.com", actual); } - - @Test(expected = IllegalArgumentException.class) - public void testInitConnectionTimeoutWithException() throws Throwable { - Method method = ParamUtil.class.getDeclaredMethod("initConnectionTimeout"); - method.setAccessible(true); - System.setProperty("NACOS.CONNECT.TIMEOUT", "test"); - try { - method.invoke(null); - } catch (InvocationTargetException e) { - throw e.getCause(); - } + + @Test + void testInitConnectionTimeoutWithException() throws Throwable { + assertThrows(IllegalArgumentException.class, () -> { + Method method = ParamUtil.class.getDeclaredMethod("initConnectionTimeout"); + method.setAccessible(true); + System.setProperty("NACOS.CONNECT.TIMEOUT", "test"); + try { + method.invoke(null); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); } - - @Test(expected = IllegalArgumentException.class) - public void testInitPerTaskConfigSizeWithException() throws Throwable { - Method method = ParamUtil.class.getDeclaredMethod("initPerTaskConfigSize"); - method.setAccessible(true); - System.setProperty("PER_TASK_CONFIG_SIZE", "test"); - try { - method.invoke(null); - } catch (InvocationTargetException e) { - throw e.getCause(); - } + + @Test + void testInitPerTaskConfigSizeWithException() throws Throwable { + assertThrows(IllegalArgumentException.class, () -> { + Method method = ParamUtil.class.getDeclaredMethod("initPerTaskConfigSize"); + method.setAccessible(true); + System.setProperty("PER_TASK_CONFIG_SIZE", "test"); + try { + method.invoke(null); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + }); } - + @Test - public void testParsingEndpointRuleFromSystem() { + void testParsingEndpointRuleFromSystem() { System.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL, "alibaba_aliware_endpoint_url"); assertEquals("alibaba_aliware_endpoint_url", ParamUtil.parsingEndpointRule(null)); } - + @Test - public void testParsingEndpointRuleFromSystemWithParam() { + void testParsingEndpointRuleFromSystemWithParam() { System.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL, "alibaba_aliware_endpoint_url"); assertEquals("alibaba_aliware_endpoint_url", ParamUtil.parsingEndpointRule("${abc:xxx}")); } - + @Test - public void testSimplyEnvNameIfOverLimit() { + void testSimplyEnvNameIfOverLimit() { StringBuilder envNameOverLimitBuilder = new StringBuilder("test"); for (int i = 0; i < 50; i++) { envNameOverLimitBuilder.append(i); @@ -214,8 +219,9 @@ public void testSimplyEnvNameIfOverLimit() { String expect = envName.substring(0, 50) + MD5Utils.md5Hex(envName, "UTF-8"); assertEquals(expect, actual); } - - @Test public void testSimplyEnvNameNotOverLimit() { + + @Test + void testSimplyEnvNameNotOverLimit() { String expect = "test"; assertEquals(expect, ParamUtil.simplyEnvNameIfOverLimit(expect)); } diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java index 67969c8ef48..3ad06e11d1f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java @@ -16,14 +16,14 @@ package com.alibaba.nacos.client.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; -public class PreInitUtilsTest { - +class PreInitUtilsTest { + @Test - public void testAsyncPreLoadCostComponent() throws InterruptedException { + void testAsyncPreLoadCostComponent() throws InterruptedException { // There is no things need to be assert. // The method will called when nacos-client init to async to load some components to reduce the sync load time. PreInitUtils.asyncPreLoadCostComponent(); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java index 1550888822b..ecf5064b222 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.client.utils; import com.alibaba.nacos.common.utils.StringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collection; @@ -27,54 +27,54 @@ import static com.alibaba.nacos.common.utils.StringUtils.isNotEmpty; import static com.alibaba.nacos.common.utils.StringUtils.join; import static com.alibaba.nacos.common.utils.StringUtils.substringBetween; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class StringUtilsTest { -public class StringUtilsTest { - @Test - public void testisNotBlank() { + void testisNotBlank() { assertTrue(isNotBlank("foo")); assertFalse(isNotBlank(" ")); assertFalse(isNotBlank(null)); } - + @Test - public void testIsNotEmpty() { + void testIsNotEmpty() { assertFalse(isNotEmpty("")); assertTrue(isNotEmpty("foo")); } - + @Test - public void testDefaultIfEmpty() { + void testDefaultIfEmpty() { assertEquals("foo", defaultIfEmpty("", "foo")); assertEquals("bar", defaultIfEmpty("bar", "foo")); } - + @Test - public void testEquals() { + void testEquals() { assertTrue(StringUtils.equals("foo", "foo")); assertFalse(StringUtils.equals("bar", "foo")); assertFalse(StringUtils.equals(" ", "foo")); assertFalse(StringUtils.equals("foo", null)); } - + @Test - public void testSubstringBetween() { + void testSubstringBetween() { assertNull(substringBetween(null, null, null)); assertNull(substringBetween("", "foo", "")); assertNull(substringBetween("foo", "bar", "baz")); assertEquals("", substringBetween("foo", "foo", "")); } - + @Test - public void testJoin() { + void testJoin() { assertNull(join(null, "")); Collection collection = new ArrayList(); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java index 0af54f40bd6..06db16289db 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java @@ -18,37 +18,37 @@ package com.alibaba.nacos.client.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.concurrent.Callable; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class TemplateUtilsTest { - +class TemplateUtilsTest { + @Test - public void testStringNotEmptyAndThenExecuteSuccess() { + void testStringNotEmptyAndThenExecuteSuccess() { String word = "run"; Runnable task = Mockito.mock(Runnable.class); TemplateUtils.stringNotEmptyAndThenExecute(word, task); Mockito.verify(task, Mockito.times(1)).run(); } - + @Test - public void testStringNotEmptyAndThenExecuteFail() { + void testStringNotEmptyAndThenExecuteFail() { String word = ""; Runnable task = Mockito.mock(Runnable.class); TemplateUtils.stringNotEmptyAndThenExecute(word, task); Mockito.verify(task, Mockito.times(0)).run(); } - + @Test - public void testStringNotEmptyAndThenExecuteException() { + void testStringNotEmptyAndThenExecuteException() { String word = "run"; Runnable task = Mockito.mock(Runnable.class); doThrow(new RuntimeException("test")).when(task).run(); @@ -56,47 +56,47 @@ public void testStringNotEmptyAndThenExecuteException() { Mockito.verify(task, Mockito.times(1)).run(); // NO exception thrown } - + @Test - public void testStringEmptyAndThenExecuteSuccess() { + void testStringEmptyAndThenExecuteSuccess() { String word = " "; String actual = TemplateUtils.stringEmptyAndThenExecute(word, () -> "call"); - Assert.assertEquals("", actual); + assertEquals("", actual); } - + @Test - public void testStringEmptyAndThenExecuteFail() { + void testStringEmptyAndThenExecuteFail() { String word = ""; final String expect = "call"; String actual = TemplateUtils.stringEmptyAndThenExecute(word, () -> expect); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } - + @Test - public void testStringEmptyAndThenExecuteException() throws Exception { + void testStringEmptyAndThenExecuteException() throws Exception { Callable callable = mock(Callable.class); when(callable.call()).thenThrow(new RuntimeException("test")); String actual = TemplateUtils.stringEmptyAndThenExecute(null, callable); assertNull(actual); } - + @Test - public void testStringBlankAndThenExecuteSuccess() { + void testStringBlankAndThenExecuteSuccess() { String word = "success"; String actual = TemplateUtils.stringBlankAndThenExecute(word, () -> "call"); - Assert.assertEquals(word, actual); + assertEquals(word, actual); } - + @Test - public void testStringBlankAndThenExecuteFail() { + void testStringBlankAndThenExecuteFail() { String word = " "; final String expect = "call"; String actual = TemplateUtils.stringBlankAndThenExecute(word, () -> expect); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } - + @Test - public void testStringBlankAndThenExecuteException() throws Exception { + void testStringBlankAndThenExecuteException() throws Exception { Callable callable = mock(Callable.class); when(callable.call()).thenThrow(new RuntimeException("test")); String actual = TemplateUtils.stringBlankAndThenExecute(null, callable); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java index 4b00504bc3a..a5a7e1a817f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java @@ -18,32 +18,33 @@ package com.alibaba.nacos.client.utils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -public class TenantUtilTest { - - @After - public void tearDown() { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TenantUtilTest { + + @AfterEach + void tearDown() { System.clearProperty("acm.namespace"); System.clearProperty("ans.namespace"); } - + @Test - public void testGetUserTenantForAcm() { + void testGetUserTenantForAcm() { String expect = "test"; System.setProperty("acm.namespace", expect); String actual = TenantUtil.getUserTenantForAcm(); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } - + @Test - public void testGetUserTenantForAns() { + void testGetUserTenantForAns() { String expect = "test"; System.setProperty("ans.namespace", expect); String actual = TenantUtil.getUserTenantForAns(); - Assert.assertEquals(expect, actual); + assertEquals(expect, actual); } } diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java index a14536facc1..280794d01a1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java @@ -17,17 +17,18 @@ package com.alibaba.nacos.client.utils; import com.alibaba.nacos.api.PropertyKeyConst; -import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.client.env.NacosClientProperties; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Properties; -public class ValidatorUtilsTest { - +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ValidatorUtilsTest { + @Test - public void testContextPathLegal() { + void testContextPathLegal() { String contextPath1 = "/nacos"; ValidatorUtils.checkContextPath(contextPath1); String contextPath2 = "nacos"; @@ -39,40 +40,46 @@ public void testContextPathLegal() { // allow null ValidatorUtils.checkContextPath(null); } - - @Test(expected = IllegalArgumentException.class) - public void testContextPathIllegal1() { - String contextPath1 = "//nacos/"; - ValidatorUtils.checkContextPath(contextPath1); + + @Test + void testContextPathIllegal1() { + assertThrows(IllegalArgumentException.class, () -> { + String contextPath1 = "//nacos/"; + ValidatorUtils.checkContextPath(contextPath1); + }); } - - @Test(expected = IllegalArgumentException.class) - public void testContextPathIllegal2() { - String contextPath2 = "/nacos//"; - ValidatorUtils.checkContextPath(contextPath2); + + @Test + void testContextPathIllegal2() { + assertThrows(IllegalArgumentException.class, () -> { + String contextPath2 = "/nacos//"; + ValidatorUtils.checkContextPath(contextPath2); + }); } - - @Test(expected = IllegalArgumentException.class) - public void testContextPathIllegal3() { - String contextPath3 = "///"; - ValidatorUtils.checkContextPath(contextPath3); + + @Test + void testContextPathIllegal3() { + assertThrows(IllegalArgumentException.class, () -> { + String contextPath3 = "///"; + ValidatorUtils.checkContextPath(contextPath3); + }); } - - @Test(expected = IllegalArgumentException.class) - public void testContextPathIllegal4() { - String contextPath4 = "//"; - ValidatorUtils.checkContextPath(contextPath4); + + @Test + void testContextPathIllegal4() { + assertThrows(IllegalArgumentException.class, () -> { + String contextPath4 = "//"; + ValidatorUtils.checkContextPath(contextPath4); + }); } - + @Test - public void testCheckInitParam() { - try { + void testCheckInitParam() { + Assertions.assertDoesNotThrow(() -> { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.CONTEXT_PATH, "test"); final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties); ValidatorUtils.checkInitParam(nacosClientProperties); - } catch (NacosException e) { - Assert.fail(); - } + }); } } From e23b784b93af4ae5dd388236ca0257c9cf46670c Mon Sep 17 00:00:00 2001 From: "shalk(xiao kun)" Date: Fri, 10 May 2024 20:55:25 +0800 Subject: [PATCH 2/5] fix code style --- .../injector/NamingResourceInjectorTest.java | 22 +++++++++---------- .../naming/utils/CollectionUtilsTest.java | 4 ++-- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java index ad721cd4436..33b8b473e6a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/NamingResourceInjectorTest.java @@ -43,7 +43,7 @@ class NamingResourceInjectorTest { private RequestResource resource; private StsCredential stsCredential; - + @BeforeEach void setUp() throws Exception { namingResourceInjector = new NamingResourceInjector(); @@ -53,21 +53,21 @@ void setUp() throws Exception { stsCredential = new StsCredential(); StsConfig.getInstance().setRamRoleName(null); } - + @AfterEach void tearDown() throws NoSuchFieldException, IllegalAccessException { clearForSts(); } - + @Test void testDoInjectWithEmpty() throws Exception { resource = RequestResource.namingBuilder().setResource("").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); - String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); assertEquals(3, actual.getAllKey().size()); assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); assertTrue(Long.parseLong(actual.getParameter("data")) - System.currentTimeMillis() < 100); + String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); assertEquals(expectSign, actual.getParameter("signature")); } @@ -76,13 +76,13 @@ void testDoInjectWithGroup() throws Exception { resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); - String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); assertEquals(3, actual.getAllKey().size()); assertEquals(PropertyKeyConst.ACCESS_KEY, actual.getParameter("ak")); assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); + String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); assertEquals(expectSign, actual.getParameter("signature")); } - + @Test void testDoInjectWithoutGroup() throws Exception { resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build(); @@ -94,33 +94,33 @@ void testDoInjectWithoutGroup() throws Exception { String expectSign = SignUtil.sign(actual.getParameter("data"), PropertyKeyConst.SECRET_KEY); assertEquals(expectSign, actual.getParameter("signature")); } - + @Test void testDoInjectWithGroupForSts() throws Exception { prepareForSts(); resource = RequestResource.namingBuilder().setResource("test@@aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); - String expectSign = SignUtil.sign(actual.getParameter("data"), "test-sts-sk"); assertEquals(4, actual.getAllKey().size()); assertEquals("test-sts-ak", actual.getParameter("ak")); assertTrue(actual.getParameter("data").endsWith("@@test@@aaa")); + String expectSign = SignUtil.sign(actual.getParameter("data"), "test-sts-sk"); assertEquals(expectSign, actual.getParameter("signature")); } - + @Test void testDoInjectWithoutGroupForSts() throws Exception { prepareForSts(); resource = RequestResource.namingBuilder().setResource("aaa").setGroup("group").build(); LoginIdentityContext actual = new LoginIdentityContext(); namingResourceInjector.doInject(resource, ramContext, actual); - String expectSign = SignUtil.sign(actual.getParameter("data"), "test-sts-sk"); assertEquals(4, actual.getAllKey().size()); assertEquals("test-sts-ak", actual.getParameter("ak")); assertTrue(actual.getParameter("data").endsWith("@@group@@aaa")); + String expectSign = SignUtil.sign(actual.getParameter("data"), "test-sts-sk"); assertEquals(expectSign, actual.getParameter("signature")); } - + @Test void testDoInjectForStsWithException() throws Exception { prepareForSts(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java index e7b3cd7bf55..2bae52a81bc 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java @@ -53,12 +53,12 @@ void testIsEqualCollection() { List list2 = Arrays.asList("3", "2", "2"); List list3 = Arrays.asList("3", "2", "3"); List list4 = Arrays.asList("3", "2"); - List list5 = Arrays.asList("3", "2", "1"); - List list6 = Arrays.asList("2", "2", "1"); assertTrue(CollectionUtils.isEqualCollection(list1, list2)); assertFalse(CollectionUtils.isEqualCollection(list1, list3)); assertFalse(CollectionUtils.isEqualCollection(list1, list4)); + List list5 = Arrays.asList("3", "2", "1"); assertFalse(CollectionUtils.isEqualCollection(list1, list5)); + List list6 = Arrays.asList("2", "2", "1"); assertFalse(CollectionUtils.isEqualCollection(list1, list6)); } From e6b412b2369701f191fa2fe5e7a6507c3dba4e92 Mon Sep 17 00:00:00 2001 From: "shalk(xiao kun)" Date: Wed, 15 May 2024 11:32:16 +0800 Subject: [PATCH 3/5] format with code style --- .../nacos/client/ability/AbilityTest.java | 49 ++--- .../ClientAbilityControlManagerTest.java | 6 +- .../impl/NacosClientAuthServiceImplTest.java | 45 ++--- .../ram/RamClientAuthServiceImplTest.java | 20 +-- .../ram/identify/CredentialServiceTest.java | 24 +-- .../ram/identify/CredentialWatcherTest.java | 25 ++- .../auth/ram/identify/CredentialsTest.java | 8 +- .../ram/identify/StsCredentialHolderTest.java | 14 +- .../AbstractResourceInjectorTest.java | 7 +- .../injector/ConfigResourceInjectorTest.java | 14 +- .../client/auth/ram/utils/SignUtilTest.java | 6 +- .../auth/ram/utils/SpasAdapterTest.java | 13 +- .../client/config/NacosConfigServiceTest.java | 40 ++--- .../client/config/common/GroupKeyTest.java | 18 +- .../config/filter/impl/ConfigContextTest.java | 2 +- .../impl/ConfigEncryptionFilterTest1.java | 35 ++-- .../impl/ConfigFilterChainManagerTest.java | 94 +++++----- .../filter/impl/ConfigFilterChainTest.java | 2 +- .../config/filter/impl/ConfigRequestTest.java | 6 +- .../filter/impl/ConfigResponseTest.java | 6 +- .../config/http/MetricsHttpAgentTest.java | 104 +++++------ .../config/http/ServerHttpAgentTest.java | 78 ++++---- .../client/config/impl/CacheDataTest.java | 16 +- .../client/config/impl/ClientWorkerTest.java | 55 +++--- .../config/impl/ConfigChangeHandlerTest.java | 4 +- .../impl/ConfigHttpClientManagerTest.java | 10 +- .../nacos/client/config/impl/LimiterTest.java | 2 +- .../impl/PropertiesChangeParserTest.java | 8 +- .../config/impl/ServerListManagerTest.java | 36 ++-- .../config/impl/YmlChangeParserTest.java | 12 +- .../AbstractConfigChangeListenerTest.java | 2 +- .../listener/impl/PropertiesListenerTest.java | 8 +- .../client/config/utils/ContentUtilsTest.java | 24 +-- .../client/config/utils/JvmUtilTest.java | 8 +- .../client/config/utils/ParamUtilsTest.java | 46 ++--- .../config/utils/SnapShotSwitchTest.java | 2 +- .../client/env/NacosClientPropertiesTest.java | 55 +++--- .../client/env/SearchablePropertiesTest.java | 24 +-- .../env/SystemEnvPropertySourceTest.java | 18 +- .../env/convert/CompositeConverterTest.java | 32 ++-- .../client/logging/NacosLoggingTest.java | 8 +- .../NacosNamingMaintainServiceTest.java | 40 ++--- .../client/naming/NacosNamingServiceTest.java | 169 +++++++++--------- .../naming/backups/FailoverReactorTest.java | 21 ++- .../DiskFailoverDataSourceTest.java | 10 +- .../client/naming/cache/DiskCacheTest.java | 20 +-- .../naming/cache/ServiceInfoHolderTest.java | 26 +-- .../client/naming/core/BalancerTest.java | 10 +- .../client/naming/core/ProtectModeTest.java | 4 +- .../naming/core/ServerListManagerTest.java | 36 ++-- .../core/ServiceInfoUpdateServiceTest.java | 36 ++-- .../event/InstancesChangeEventTest.java | 2 +- .../event/InstancesChangeNotifierTest.java | 14 +- .../remote/AbstractNamingClientProxyTest.java | 4 +- .../remote/NamingClientProxyDelegateTest.java | 58 +++--- .../gprc/NamingGrpcClientProxyTest.java | 108 +++++------ .../gprc/NamingPushRequestHandlerTest.java | 7 +- .../gprc/redo/NamingGrpcRedoServiceTest.java | 54 +++--- .../gprc/redo/RedoScheduledTaskTest.java | 36 ++-- .../redo/data/BatchInstanceRedoDataTest.java | 4 +- .../gprc/redo/data/InstanceRedoDataTest.java | 4 +- .../http/NamingHttpClientManagerTest.java | 10 +- .../http/NamingHttpClientProxyTest.java | 151 ++++++++-------- .../client/naming/utils/CacheDirUtilTest.java | 10 +- .../client/naming/utils/ChooserTest.java | 20 +-- .../naming/utils/CollectionUtilsTest.java | 12 +- .../naming/utils/ConcurrentDiskUtilTest.java | 20 +-- .../naming/utils/GenericPollerTest.java | 4 +- .../client/naming/utils/InitUtilsTest.java | 40 ++--- .../naming/utils/NamingHttpUtilTest.java | 2 +- .../nacos/client/naming/utils/PairTest.java | 2 +- .../client/security/SecurityProxyTest.java | 8 +- .../nacos/client/utils/AppNameUtilsTest.java | 14 +- .../client/utils/ContextPathUtilTest.java | 2 +- .../nacos/client/utils/EnvUtilTest.java | 4 +- .../nacos/client/utils/LogUtilsTest.java | 2 +- .../nacos/client/utils/ParamUtilTest.java | 36 ++-- .../nacos/client/utils/PreInitUtilsTest.java | 2 +- .../nacos/client/utils/StringUtilsTest.java | 12 +- .../nacos/client/utils/TemplateUtilsTest.java | 18 +- .../nacos/client/utils/TenantUtilTest.java | 6 +- .../client/utils/ValidatorUtilsTest.java | 12 +- 82 files changed, 1020 insertions(+), 1016 deletions(-) diff --git a/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java b/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java index dbfe68b2db2..302cd0e278d 100644 --- a/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/ability/AbilityTest.java @@ -25,8 +25,8 @@ import com.alibaba.nacos.api.remote.response.Response; import com.alibaba.nacos.client.naming.remote.TestConnection; import com.alibaba.nacos.common.remote.ConnectionType; -import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.Connection; +import com.alibaba.nacos.common.remote.client.RpcClient; import com.alibaba.nacos.common.remote.client.RpcClientConfig; import com.alibaba.nacos.common.remote.client.ServerListFactory; import com.alibaba.nacos.common.remote.client.ServerRequestHandler; @@ -45,7 +45,7 @@ class AbilityTest { private RpcClient rpcClient; private Connection connection; - + @Test void testReceive() throws Exception { rpcClient = new RpcClient(new RpcClientConfig() { @@ -53,32 +53,32 @@ void testReceive() throws Exception { public String name() { return "test"; } - + @Override public int retryTimes() { return 1; } - + @Override public long timeOutMills() { return 3000L; } - + @Override public long connectionKeepAlive() { return 5000L; } - + @Override public int healthCheckRetryTimes() { return 1; } - + @Override public long healthCheckTimeOut() { return 3000L; } - + @Override public Map labels() { return new HashMap<>(); @@ -89,12 +89,12 @@ public Map labels() { public ConnectionType getConnectionType() { return null; } - + @Override public int rpcPortOffset() { return 0; } - + @Override public Connection connectToServer(ServerInfo serverInfo) throws Exception { connection = new Connection(new RpcClient.ServerInfo()) { @@ -104,27 +104,28 @@ public Connection connectToServer(ServerInfo serverInfo) throws Exception { super.abilityTable.put(AbilityKey.SERVER_TEST_1.getName(), true); super.abilityTable.put(AbilityKey.SERVER_TEST_2.getName(), false); } - + @Override public Response request(Request request, long timeoutMills) throws NacosException { return null; } - + @Override public RequestFuture requestFuture(Request request) throws NacosException { return null; } - + @Override public void asyncRequest(Request request, RequestCallBack requestCallBack) throws NacosException { - + } - + @Override public void close() { - + } - };; + }; + ; return connection; } }; @@ -139,12 +140,12 @@ public void close() { public String genNextServer() { return "localhost:8848"; } - + @Override public String getCurrentServer() { return "localhost:8848"; } - + @Override public List getServerList() { return null; @@ -155,21 +156,23 @@ public List getServerList() { assertEquals(AbilityStatus.SUPPORTED, rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_1)); assertEquals(AbilityStatus.NOT_SUPPORTED, rpcClient.getConnectionAbility(AbilityKey.SERVER_TEST_2)); } - + @AfterEach void testServerRequestAbility() { //test support ServerRequestHandler serverRequestHandler = (request, connection) -> { assertEquals(AbilityStatus.SUPPORTED, connection.getConnectionAbility(AbilityKey.SERVER_TEST_1)); assertEquals(AbilityStatus.NOT_SUPPORTED, connection.getConnectionAbility(AbilityKey.SERVER_TEST_2)); - return new Response() { }; + return new Response() { + }; }; serverRequestHandler.requestReply(null, connection); - + // test no ability table serverRequestHandler = (request, connection) -> { assertEquals(AbilityStatus.UNKNOWN, connection.getConnectionAbility(AbilityKey.SERVER_TEST_1)); - return new Response() { }; + return new Response() { + }; }; serverRequestHandler.requestReply(null, new TestConnection(new RpcClient.ServerInfo())); } diff --git a/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java index e82426bdd1f..c0473dcc8d3 100644 --- a/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/ability/ClientAbilityControlManagerTest.java @@ -29,12 +29,12 @@ class ClientAbilityControlManagerTest { ClientAbilityControlManager clientAbilityControlManager; - + @BeforeEach void setUp() { clientAbilityControlManager = new ClientAbilityControlManager(); } - + @Test void testInitCurrentNodeAbilities() { Map> actual = clientAbilityControlManager.initCurrentNodeAbilities(); @@ -43,7 +43,7 @@ void testInitCurrentNodeAbilities() { // Current not define sdk ability. assertEquals(0, actual.get(AbilityMode.SDK_CLIENT).size()); } - + @Test void testGetPriority() { assertEquals(0, clientAbilityControlManager.getPriority()); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java index 17f05311078..a2312d8b984 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImplTest.java @@ -35,7 +35,7 @@ import static org.mockito.Mockito.when; class NacosClientAuthServiceImplTest { - + @Test void testLoginSuccess() throws Exception { //given @@ -58,7 +58,7 @@ void testLoginSuccess() throws Exception { //then assertTrue(ret); } - + @Test void testTestLoginFailCode() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -70,14 +70,14 @@ void testTestLoginFailCode() throws Exception { properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); List serverList = new ArrayList<>(); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); boolean ret = nacosClientAuthService.login(properties); assertFalse(ret); } - + @Test void testTestLoginFailHttp() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -87,7 +87,7 @@ void testTestLoginFailHttp() throws Exception { properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); List serverList = new ArrayList<>(); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); @@ -95,7 +95,7 @@ void testTestLoginFailHttp() throws Exception { assertFalse(ret); } - + @Test void testTestLoginServerListSuccess() throws Exception { //given @@ -110,14 +110,14 @@ void testTestLoginServerListSuccess() throws Exception { List serverList = new ArrayList<>(); serverList.add("localhost"); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); boolean ret = nacosClientAuthService.login(properties); assertTrue(ret); } - + @Test void testTestLoginServerListLoginInWindow() throws Exception { //given @@ -142,7 +142,7 @@ void testTestLoginServerListLoginInWindow() throws Exception { assertTrue(ret); } - + @Test void testGetAccessToken() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -153,19 +153,20 @@ void testGetAccessToken() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); - + List serverList = new ArrayList<>(); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); //when assertTrue(nacosClientAuthService.login(properties)); //then - assertEquals("abc", nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); + assertEquals("abc", + nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); } - + @Test void testGetAccessEmptyToken() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -186,9 +187,10 @@ void testGetAccessEmptyToken() throws Exception { //when assertTrue(nacosClientAuthService.login(properties)); //then - assertEquals("", nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); + assertEquals("", + nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); } - + @Test void testGetAccessTokenWithoutToken() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -199,19 +201,20 @@ void testGetAccessTokenWithoutToken() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); - + List serverList = new ArrayList<>(); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); //when assertTrue(nacosClientAuthService.login(properties)); //then - assertNull(nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); + assertNull( + nacosClientAuthService.getLoginIdentityContext(null).getParameter(NacosAuthLoginConstant.ACCESSTOKEN)); } - + @Test void testGetAccessTokenWithInvalidTtl() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -222,10 +225,10 @@ void testGetAccessTokenWithInvalidTtl() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.USERNAME, "aaa"); properties.setProperty(PropertyKeyConst.PASSWORD, "123456"); - + List serverList = new ArrayList<>(); serverList.add("localhost"); - + NacosClientAuthServiceImpl nacosClientAuthService = new NacosClientAuthServiceImpl(); nacosClientAuthService.setServerList(serverList); nacosClientAuthService.setNacosRestTemplate(nacosRestTemplate); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java index 9cf1c7dda6d..a7a577af4c4 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/RamClientAuthServiceImplTest.java @@ -17,10 +17,10 @@ package com.alibaba.nacos.client.auth.ram; import com.alibaba.nacos.api.PropertyKeyConst; -import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; import com.alibaba.nacos.client.auth.ram.injector.AbstractResourceInjector; -import com.alibaba.nacos.plugin.auth.api.RequestResource; import com.alibaba.nacos.common.utils.ReflectUtils; +import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; +import com.alibaba.nacos.plugin.auth.api.RequestResource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -53,12 +53,12 @@ class RamClientAuthServiceImplTest { private RamContext ramContext; private RequestResource resource; - + @BeforeEach void setUp() throws Exception { ramClientAuthService = new RamClientAuthServiceImpl(); - Map resourceInjectors = (Map) ReflectUtils - .getFieldValue(ramClientAuthService, "resourceInjectors"); + Map resourceInjectors = (Map) ReflectUtils.getFieldValue( + ramClientAuthService, "resourceInjectors"); resourceInjectors.clear(); resourceInjectors.put(MOCK, mockResourceInjector); ramContext = (RamContext) ReflectUtils.getFieldValue(ramClientAuthService, "ramContext"); @@ -69,7 +69,7 @@ void setUp() throws Exception { roleProperties.setProperty(PropertyKeyConst.RAM_ROLE_NAME, PropertyKeyConst.RAM_ROLE_NAME); resource = new RequestResource(); } - + @Test void testLoginWithAkSk() { assertTrue(ramClientAuthService.login(akSkProperties)); @@ -81,7 +81,7 @@ void testLoginWithAkSk() { assertEquals(PropertyKeyConst.SECRET_KEY, ramContext.getSecretKey()); assertNull(ramContext.getRamRoleName()); } - + @Test void testLoginWithRoleName() { assertTrue(ramClientAuthService.login(roleProperties)); @@ -93,14 +93,14 @@ void testLoginWithRoleName() { assertNull(ramContext.getSecretKey(), PropertyKeyConst.SECRET_KEY); assertEquals(PropertyKeyConst.RAM_ROLE_NAME, ramContext.getRamRoleName()); } - + @Test void testGetLoginIdentityContextWithoutLogin() { LoginIdentityContext actual = ramClientAuthService.getLoginIdentityContext(resource); assertTrue(actual.getAllKey().isEmpty()); verify(mockResourceInjector, never()).doInject(resource, ramContext, actual); } - + @Test void testGetLoginIdentityContextWithoutInjector() { ramClientAuthService.login(akSkProperties); @@ -108,7 +108,7 @@ void testGetLoginIdentityContextWithoutInjector() { assertTrue(actual.getAllKey().isEmpty()); verify(mockResourceInjector, never()).doInject(resource, ramContext, actual); } - + @Test void testGetLoginIdentityContextWithInjector() { ramClientAuthService.login(akSkProperties); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java index 0eb3b1a3965..4f56bcb77c8 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialServiceTest.java @@ -33,32 +33,32 @@ class CredentialServiceTest { private static final String APP_NAME = "app"; - + @BeforeEach void setUp() throws Exception { } - + @AfterEach void tearDown() throws Exception { System.clearProperty(IdentifyConstants.PROJECT_NAME_PROPERTY); CredentialService.freeInstance(); CredentialService.freeInstance(APP_NAME); } - + @Test void testGetInstance() { CredentialService credentialService1 = CredentialService.getInstance(); CredentialService credentialService2 = CredentialService.getInstance(); assertEquals(credentialService1, credentialService2); } - + @Test void testGetInstance2() { CredentialService credentialService1 = CredentialService.getInstance(APP_NAME); CredentialService credentialService2 = CredentialService.getInstance(APP_NAME); assertEquals(credentialService1, credentialService2); } - + @Test void testGetInstance3() throws NoSuchFieldException, IllegalAccessException { System.setProperty(IdentifyConstants.PROJECT_NAME_PROPERTY, APP_NAME); @@ -68,21 +68,21 @@ void testGetInstance3() throws NoSuchFieldException, IllegalAccessException { String appName = (String) appNameField.get(credentialService1); assertEquals(APP_NAME, appName); } - + @Test void testFreeInstance() { CredentialService credentialService1 = CredentialService.getInstance(); CredentialService credentialService2 = CredentialService.freeInstance(); assertEquals(credentialService1, credentialService2); } - + @Test void testFreeInstance2() { CredentialService credentialService1 = CredentialService.getInstance(); CredentialService credentialService2 = CredentialService.freeInstance(); assertEquals(credentialService1, credentialService2); } - + @Test void testFree() throws NoSuchFieldException, IllegalAccessException { CredentialService credentialService1 = CredentialService.getInstance(); @@ -95,14 +95,14 @@ void testFree() throws NoSuchFieldException, IllegalAccessException { //then verify(mockWatcher, times(1)).stop(); } - + @Test void testGetCredential() { CredentialService credentialService1 = CredentialService.getInstance(); Credentials credential = credentialService1.getCredential(); assertNotNull(credential); } - + @Test void testSetCredential() { CredentialService credentialService1 = CredentialService.getInstance(); @@ -112,7 +112,7 @@ void testSetCredential() { //then assertEquals(credential, credentialService1.getCredential()); } - + @Test void testSetStaticCredential() throws NoSuchFieldException, IllegalAccessException { CredentialService credentialService1 = CredentialService.getInstance(); @@ -127,7 +127,7 @@ void testSetStaticCredential() throws NoSuchFieldException, IllegalAccessExcepti assertEquals(credential, credentialService1.getCredential()); verify(mockWatcher, times(1)).stop(); } - + @Test void testRegisterCredentialListener() { CredentialListener expect = mock(CredentialListener.class); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java index 6e3a11d559b..11d51d9f474 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialWatcherTest.java @@ -58,17 +58,17 @@ class CredentialWatcherTest { private Method loadCredentialMethod; private Method loadCredentialFromPropertiesMethod; - + @BeforeEach void setUp() throws Exception { credentialWatcher = new CredentialWatcher("testApp", credentialService); loadCredentialMethod = CredentialWatcher.class.getDeclaredMethod("loadCredential", boolean.class); loadCredentialMethod.setAccessible(true); - loadCredentialFromPropertiesMethod = CredentialWatcher.class - .getDeclaredMethod("loadCredentialFromProperties", InputStream.class, boolean.class, Credentials.class); + loadCredentialFromPropertiesMethod = CredentialWatcher.class.getDeclaredMethod("loadCredentialFromProperties", + InputStream.class, boolean.class, Credentials.class); loadCredentialFromPropertiesMethod.setAccessible(true); } - + @AfterEach void tearDown() throws Exception { credentialWatcher.stop(); @@ -77,7 +77,7 @@ void tearDown() throws Exception { System.clearProperty(IdentifyConstants.ENV_SECRET_KEY); CredentialService.freeInstance(); } - + @Test void testStop() throws NoSuchFieldException, IllegalAccessException { credentialWatcher.stop(); @@ -86,7 +86,7 @@ void testStop() throws NoSuchFieldException, IllegalAccessException { ScheduledExecutorService executor = (ScheduledExecutorService) executorField.get(credentialWatcher); assertTrue(executor.isShutdown()); } - + @Test void testLoadCredentialByEnv() throws InvocationTargetException, IllegalAccessException { System.setProperty(IdentifyConstants.ENV_ACCESS_KEY, "testAk"); @@ -106,7 +106,7 @@ void testLoadCredentialByEnv() throws InvocationTargetException, IllegalAccessEx assertEquals("testSk", readSK.get()); assertNull(readTenantId.get()); } - + @Test void testLoadCredentialByIdentityFile() throws InvocationTargetException, IllegalAccessException { URL url = CredentialWatcherTest.class.getResource("/spas.identity"); @@ -126,7 +126,7 @@ void testLoadCredentialByIdentityFile() throws InvocationTargetException, Illega assertEquals("testSk", readSK.get()); assertEquals("testTenantId", readTenantId.get()); } - + @Test void testLoadCredentialByInvalidIdentityFile() throws InvocationTargetException, IllegalAccessException { URL url = CredentialWatcherTest.class.getResource("/spas_invalid.identity"); @@ -146,7 +146,7 @@ void testLoadCredentialByInvalidIdentityFile() throws InvocationTargetException, assertEquals("testSk", readSK.get()); assertEquals("testTenantId", readTenantId.get()); } - + /** * The docker file is need /etc permission, which depend environment. So use mock InputStream to test. */ @@ -164,7 +164,7 @@ void testLoadCredentialByDockerFile() assertEquals("testSk", actual.getSecretKey()); assertEquals("testTenantId", actual.getTenantId()); } - + @Test void testLoadCredentialByFileWithIoException() throws IOException, InvocationTargetException, IllegalAccessException { @@ -177,10 +177,9 @@ void testLoadCredentialByFileWithIoException() assertNull(actual.getSecretKey()); assertNull(actual.getTenantId()); } - + @Test - void testReLoadCredential() - throws InvocationTargetException, IllegalAccessException, InterruptedException { + void testReLoadCredential() throws InvocationTargetException, IllegalAccessException, InterruptedException { URL url = CredentialWatcherTest.class.getResource("/spas_modified.identity"); modifiedFile(url, true); System.setProperty("spas.identity", url.getPath()); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java index bf236ee0422..51f831e11c1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/CredentialsTest.java @@ -24,7 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class CredentialsTest { - + @Test void testGetter() { // given @@ -37,7 +37,7 @@ void testGetter() { assertEquals(sk, credentials.getSecretKey()); assertEquals(tenantId, credentials.getTenantId()); } - + @Test void testSetter() { //given @@ -54,7 +54,7 @@ void testSetter() { assertEquals(sk, credentials.getSecretKey()); assertEquals(tenantId, credentials.getTenantId()); } - + @Test void testValid() { //given @@ -67,7 +67,7 @@ void testValid() { //then assertTrue(actual); } - + @Test void testIdentical() { //given diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java index ef3641baf16..4ca79c2be36 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/identify/StsCredentialHolderTest.java @@ -49,7 +49,7 @@ class StsCredentialHolderTest { @Mock private HttpClientRequest mockRest; - + @BeforeEach void setUp() throws Exception { securityCredentialsUrl = StsConfig.getInstance().getSecurityCredentialsUrl(); @@ -59,7 +59,7 @@ void setUp() throws Exception { httpClient = (HttpClientRequest) field.get(ConfigHttpClientManager.getInstance().getNacosRestTemplate()); field.set(ConfigHttpClientManager.getInstance().getNacosRestTemplate(), mockRest); } - + @AfterEach void tearDown() throws Exception { StsConfig.getInstance().setSecurityCredentials(null); @@ -76,7 +76,7 @@ private void clearForSts() throws NoSuchFieldException, IllegalAccessException { field.setAccessible(true); field.set(StsCredentialHolder.getInstance(), null); } - + @Test void testGetStsCredentialFromCache() throws NoSuchFieldException, IllegalAccessException { StsCredential stsCredential = buildMockStsCredential(); @@ -89,14 +89,14 @@ private void setStsCredential(StsCredential stsCredential) throws NoSuchFieldExc field.setAccessible(true); field.set(StsCredentialHolder.getInstance(), stsCredential); } - + @Test void testGetStsCredentialFromStringCache() throws NoSuchFieldException, IllegalAccessException { StsCredential stsCredential = buildMockStsCredential(); StsConfig.getInstance().setSecurityCredentials(JacksonUtils.toJson(stsCredential)); assertEquals(stsCredential.toString(), StsCredentialHolder.getInstance().getStsCredential().toString()); } - + @Test void testGetStsCredentialFromRequest() throws Exception { StsCredential stsCredential = buildMockStsCredential(); @@ -107,7 +107,7 @@ void testGetStsCredentialFromRequest() throws Exception { when(mockRest.execute(any(), any(), any())).thenReturn(response); assertEquals(stsCredential.toString(), StsCredentialHolder.getInstance().getStsCredential().toString()); } - + @Test void testGetStsCredentialFromRequestFailure() throws Exception { assertThrows(NacosRuntimeException.class, () -> { @@ -119,7 +119,7 @@ void testGetStsCredentialFromRequestFailure() throws Exception { StsCredentialHolder.getInstance().getStsCredential(); }); } - + @Test void testGetStsCredentialFromRequestException() throws Exception { assertThrows(NacosRuntimeException.class, () -> { diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java index 94d6721023a..4af02b0a162 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/AbstractResourceInjectorTest.java @@ -22,12 +22,13 @@ class AbstractResourceInjectorTest { AbstractResourceInjector injector; - + @BeforeEach void setUp() { - injector = new AbstractResourceInjector() { }; + injector = new AbstractResourceInjector() { + }; } - + /** * TODO, fill test case after AbstractResourceInjector include default logic. */ diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java index 41402273f80..fdd780f71f3 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjectorTest.java @@ -48,7 +48,7 @@ class ConfigResourceInjectorTest { private String cachedSecurityCredentials; private StsCredential stsCredential; - + @BeforeEach void setUp() throws Exception { configResourceInjector = new ConfigResourceInjector(); @@ -65,14 +65,14 @@ void setUp() throws Exception { StsConfig.getInstance().setSecurityCredentials(""); stsCredential = new StsCredential(); } - + @AfterEach void tearDown() throws NoSuchFieldException, IllegalAccessException { StsConfig.getInstance().setSecurityCredentialsUrl(cachedSecurityCredentialsUrl); StsConfig.getInstance().setSecurityCredentials(cachedSecurityCredentials); clearForSts(); } - + @Test void testDoInjectWithFullResource() throws Exception { LoginIdentityContext actual = new LoginIdentityContext(); @@ -82,7 +82,7 @@ void testDoInjectWithFullResource() throws Exception { assertTrue(actual.getAllKey().contains("Timestamp")); assertTrue(actual.getAllKey().contains("Spas-Signature")); } - + @Test void testDoInjectWithTenant() throws Exception { resource.setGroup(""); @@ -93,7 +93,7 @@ void testDoInjectWithTenant() throws Exception { assertTrue(actual.getAllKey().contains("Timestamp")); assertTrue(actual.getAllKey().contains("Spas-Signature")); } - + @Test void testDoInjectWithGroup() throws Exception { resource.setNamespace(""); @@ -104,7 +104,7 @@ void testDoInjectWithGroup() throws Exception { assertTrue(actual.getAllKey().contains("Timestamp")); assertTrue(actual.getAllKey().contains("Spas-Signature")); } - + @Test void testDoInjectWithoutResource() throws Exception { resource = new RequestResource(); @@ -115,7 +115,7 @@ void testDoInjectWithoutResource() throws Exception { assertTrue(actual.getAllKey().contains("Timestamp")); assertTrue(actual.getAllKey().contains("Spas-Signature")); } - + @Test void testDoInjectForSts() throws NoSuchFieldException, IllegalAccessException { prepareForSts(); diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java index dc130aeacdf..a9eef88a8fd 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SignUtilTest.java @@ -24,20 +24,20 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class SignUtilTest { - + @Test void testSign() throws Exception { String actual = SignUtil.sign("aaa", "b"); assertEquals("DxyaKScrqL26yXYOuHXE3OwfQ0Y=", actual); } - + @Test void testSignWithException() throws Exception { assertThrows(Exception.class, () -> { SignUtil.sign(null, "b"); }); } - + @Test void testSignWithException2() throws Exception { assertThrows(Exception.class, () -> { diff --git a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java index b60abfb46e9..eb19570bedf 100644 --- a/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/auth/ram/utils/SpasAdapterTest.java @@ -27,7 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class SpasAdapterTest { - + @Test void test() { assertNull(SpasAdapter.getAk()); @@ -37,7 +37,7 @@ void test() { }); } - + @Test void testSign() { @@ -55,10 +55,9 @@ void testSign() { final Map map3 = SpasAdapter.getSignHeaders("", "bb", "123"); assertEquals(2, map3.size()); - assertEquals(SpasAdapter.signWithHmacSha1Encrypt(map3.get("Timestamp"), "123"), - map3.get("Spas-Signature")); + assertEquals(SpasAdapter.signWithHmacSha1Encrypt(map3.get("Timestamp"), "123"), map3.get("Spas-Signature")); } - + @Test void testSign2() { @@ -72,7 +71,7 @@ void testSign2() { assertEquals(SpasAdapter.signWithHmacSha1Encrypt("bb+aa+" + map1.get("Timestamp"), "123"), map1.get("Spas-Signature")); } - + @Test void testGetSignHeadersWithoutTenant() { Map param1 = new HashMap<>(); @@ -82,7 +81,7 @@ void testGetSignHeadersWithoutTenant() { assertEquals(SpasAdapter.signWithHmacSha1Encrypt("aa+" + map1.get("Timestamp"), "123"), map1.get("Spas-Signature")); } - + @Test void testSignWithHmacSha1EncryptWithException() { assertThrows(Exception.class, () -> { diff --git a/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java index fe55ce53b4c..f56ef44877f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java @@ -57,7 +57,7 @@ private void setFinal(Field field, Object ins, Object newValue) throws Exception field.setAccessible(false); } - + @BeforeEach void mock() throws Exception { final Properties properties = new Properties(); @@ -66,12 +66,12 @@ void mock() throws Exception { mockWoker = Mockito.mock(ClientWorker.class); setFinal(NacosConfigService.class.getDeclaredField("worker"), nacosConfigService, mockWoker); } - + @AfterEach void clean() { LocalConfigInfoProcessor.cleanAllSnapshot(); } - + @Test void testGetConfigFromServer() throws NacosException { final String dataId = "1"; @@ -87,7 +87,7 @@ void testGetConfigFromServer() throws NacosException { Mockito.verify(mockWoker, Mockito.times(1)).getServerConfig(dataId, group, tenant, timeout, false); } - + @Test void testGetConfigFromFailOver() throws NacosException { final String dataId = "1failover"; @@ -99,7 +99,7 @@ void testGetConfigFromFailOver() throws NacosException { try { String contentFailOver = "failOverContent" + System.currentTimeMillis(); localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) + () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(contentFailOver); final int timeout = 3000; @@ -109,7 +109,7 @@ void testGetConfigFromFailOver() throws NacosException { localConfigInfoProcessorMockedStatic.close(); } } - + @Test void testGetConfigFromLocalCache() throws NacosException { final String dataId = "1localcache"; @@ -122,11 +122,11 @@ void testGetConfigFromLocalCache() throws NacosException { String contentFailOver = "localCacheContent" + System.currentTimeMillis(); //fail over null localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) + () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(null); //snapshot content localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getSnapshot(any(), eq(dataId), eq(group), eq(tenant))) + () -> LocalConfigInfoProcessor.getSnapshot(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(contentFailOver); //form server error. final int timeout = 3000; @@ -139,7 +139,7 @@ void testGetConfigFromLocalCache() throws NacosException { } } - + @Test void testGetConfig403() throws NacosException { final String dataId = "1localcache403"; @@ -151,7 +151,7 @@ void testGetConfig403() throws NacosException { try { //fail over null localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) + () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(null); //form server error. @@ -168,7 +168,7 @@ void testGetConfig403() throws NacosException { localConfigInfoProcessorMockedStatic.close(); } } - + @Test void testGetConfigAndSignListener() throws NacosException { final String dataId = "1"; @@ -245,7 +245,7 @@ public boolean removeConfig(String dataId, String group, String tenant, String t Mockito.verify(mockWoker, Mockito.times(1)) .addTenantListenersWithContent(dataId, group, content, null, Arrays.asList(listener)); } - + @Test void testAddListener() throws NacosException { String dataId = "1"; @@ -265,7 +265,7 @@ public void receiveConfigInfo(String configInfo) { nacosConfigService.addListener(dataId, group, listener); Mockito.verify(mockWoker, Mockito.times(1)).addTenantListeners(dataId, group, Arrays.asList(listener)); } - + @Test void testPublishConfig() throws NacosException { String dataId = "1"; @@ -282,7 +282,7 @@ void testPublishConfig() throws NacosException { Mockito.verify(mockWoker, Mockito.times(1)) .publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); } - + @Test void testPublishConfig2() throws NacosException { String dataId = "1"; @@ -300,7 +300,7 @@ void testPublishConfig2() throws NacosException { Mockito.verify(mockWoker, Mockito.times(1)) .publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); } - + @Test void testPublishConfigCas() throws NacosException { String dataId = "1"; @@ -319,7 +319,7 @@ void testPublishConfigCas() throws NacosException { Mockito.verify(mockWoker, Mockito.times(1)) .publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); } - + @Test void testPublishConfigCas2() throws NacosException { String dataId = "1"; @@ -338,7 +338,7 @@ void testPublishConfigCas2() throws NacosException { Mockito.verify(mockWoker, Mockito.times(1)) .publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); } - + @Test void testRemoveConfig() throws NacosException { String dataId = "1"; @@ -352,7 +352,7 @@ void testRemoveConfig() throws NacosException { Mockito.verify(mockWoker, Mockito.times(1)).removeConfig(dataId, group, tenant, null); } - + @Test void testRemoveListener() { String dataId = "1"; @@ -372,7 +372,7 @@ public void receiveConfigInfo(String configInfo) { nacosConfigService.removeListener(dataId, group, listener); Mockito.verify(mockWoker, Mockito.times(1)).removeTenantListener(dataId, group, listener); } - + @Test void testGetServerStatus() { Mockito.when(mockWoker.isHealthServer()).thenReturn(true); @@ -384,7 +384,7 @@ void testGetServerStatus() { Mockito.verify(mockWoker, Mockito.times(2)).isHealthServer(); } - + @Test void testShutDown() { Assertions.assertDoesNotThrow(() -> { diff --git a/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java b/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java index 276cf09c883..e5bfd1992ac 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/common/GroupKeyTest.java @@ -23,61 +23,61 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class GroupKeyTest { - + @Test void testGetKey() { assertEquals("1+foo", GroupKey.getKey("1", "foo")); assertEquals("1+foo+bar", GroupKey.getKey("1", "foo", "bar")); assertEquals("1+f%2Boo+b%25ar", GroupKey.getKey("1", "f+oo", "b%ar")); } - + @Test void testGetKeyTenant() { assertEquals("1+foo+bar", GroupKey.getKeyTenant("1", "foo", "bar")); } - + @Test void testParseKey() { assertArrayEquals(new String[] {"a", "f+oo", null}, GroupKey.parseKey("a+f%2Boo")); assertArrayEquals(new String[] {"b", "f%oo", null}, GroupKey.parseKey("b+f%25oo")); assertArrayEquals(new String[] {"a", "b", "c"}, GroupKey.parseKey("a+b+c")); } - + @Test void testParseKeyIllegalArgumentException1() { assertThrows(IllegalArgumentException.class, () -> { GroupKey.parseKey(""); }); } - + @Test void testParseKeyIllegalArgumentException2() { assertThrows(IllegalArgumentException.class, () -> { GroupKey.parseKey("f%oo"); }); } - + @Test void testParseKeyIllegalArgumentException3() { assertThrows(IllegalArgumentException.class, () -> { GroupKey.parseKey("f+o+o+bar"); }); } - + @Test void testParseKeyIllegalArgumentException4() { assertThrows(IllegalArgumentException.class, () -> { GroupKey.parseKey("f++bar"); }); } - + @Test void testGetKeyDatIdParam() { assertThrows(IllegalArgumentException.class, () -> { GroupKey.getKey("", "a"); }); } - + @Test void testGetKeyGroupParam() { assertThrows(IllegalArgumentException.class, () -> { diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java index 8ec8c4fd9bd..5796a000427 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigContextTest.java @@ -21,7 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class ConfigContextTest { - + @Test void testParameter() { ConfigContext context = new ConfigContext(); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java index a3d906940c7..c4685baed5a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigEncryptionFilterTest1.java @@ -21,17 +21,6 @@ import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.encryption.EncryptionPluginManager; import com.alibaba.nacos.plugin.encryption.spi.EncryptionPluginService; - -import java.nio.charset.StandardCharsets; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import javax.crypto.Cipher; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - import org.apache.commons.codec.binary.Base64; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -39,6 +28,16 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * AES encryption algorithm testing dataId with prefix cipher. * @@ -55,7 +54,7 @@ class ConfigEncryptionFilterTest1 { @Mock private IConfigFilterChain iConfigFilterChain; - + @BeforeEach void setUp() throws Exception { mockEncryptionPluginService = new EncryptionPluginService() { @@ -149,13 +148,15 @@ private String aesDecrypt(String content, String key) { configEncryptionFilter = new ConfigEncryptionFilter(); } - + @Test void testDoFilterEncryptedData() throws NacosException { String dataId = "cipher-aes-test"; String content = "nacos"; - final String encryptionContent = mockEncryptionPluginService.encrypt(mockEncryptionPluginService.generateSecretKey(), content); - final String theKeyOfContentKey = mockEncryptionPluginService.encryptSecretKey(mockEncryptionPluginService.generateSecretKey()); + final String encryptionContent = mockEncryptionPluginService.encrypt( + mockEncryptionPluginService.generateSecretKey(), content); + final String theKeyOfContentKey = mockEncryptionPluginService.encryptSecretKey( + mockEncryptionPluginService.generateSecretKey()); ConfigRequest configRequest = new ConfigRequest(); configRequest.setDataId(dataId); @@ -172,7 +173,7 @@ void testDoFilterEncryptedData() throws NacosException { assertEquals(configResponse.getContent(), content); assertEquals(configResponse.getEncryptedDataKey(), mockEncryptionPluginService.generateSecretKey()); } - + @Test void testDoFilter() throws NacosException { String dataId = "test"; @@ -193,7 +194,7 @@ void testDoFilter() throws NacosException { assertEquals(configResponse.getContent(), content); assertEquals("", configResponse.getEncryptedDataKey()); } - + @Test void testGetOrder() { int order = configEncryptionFilter.getOrder(); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java index 46cfda2d8fb..b610c72c6aa 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainManagerTest.java @@ -33,6 +33,53 @@ class ConfigFilterChainManagerTest { + @Test + void testAddFilterOrder() throws NacosException { + final ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(new Properties()); + MyIConfigFilter filter1 = new MyIConfigFilter("filter1", 1); + MyIConfigFilter filter2 = new MyIConfigFilter("filter2", 2); + MyIConfigFilter filter3 = new MyIConfigFilter("filter3", 3); + + //random order + configFilterChainManager.addFilter(filter2); + configFilterChainManager.addFilter(filter1); + configFilterChainManager.addFilter(filter3); + + ConfigRequest configRequest = new ConfigRequest(); + + configFilterChainManager.doFilter(configRequest, new ConfigResponse()); + + IConfigContext configContext = configRequest.getConfigContext(); + + // doFilter works + assertEquals(1, configContext.getParameter("filter1")); + assertEquals(2, configContext.getParameter("filter2")); + assertEquals(3, configContext.getParameter("filter3")); + + //order + List orders = (List) configContext.getParameter("orders"); + assertEquals(Arrays.asList(1, 2, 3), orders); + } + + @Test + void testAddFilterNotRepeat() throws NacosException { + final ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(new Properties()); + MyIConfigFilter filter1 = new MyIConfigFilter("filter1", 1); + MyIConfigFilter filter2 = new MyIConfigFilter("filter2", 2); + MyIConfigFilter repeatFilter = new MyIConfigFilter("filter1", 1); + + configFilterChainManager.addFilter(filter2); + configFilterChainManager.addFilter(filter1); + configFilterChainManager.addFilter(repeatFilter); + + ConfigRequest configRequest = new ConfigRequest(); + configFilterChainManager.doFilter(configRequest, new ConfigResponse()); + + IConfigContext configContext = configRequest.getConfigContext(); + + assertEquals(2, configContext.getParameter("filterCount")); + } + private static class MyIConfigFilter implements IConfigFilter { private String name; @@ -84,51 +131,4 @@ public String getFilterName() { return name; } } - - @Test - void testAddFilterOrder() throws NacosException { - final ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(new Properties()); - MyIConfigFilter filter1 = new MyIConfigFilter("filter1", 1); - MyIConfigFilter filter2 = new MyIConfigFilter("filter2", 2); - MyIConfigFilter filter3 = new MyIConfigFilter("filter3", 3); - - //random order - configFilterChainManager.addFilter(filter2); - configFilterChainManager.addFilter(filter1); - configFilterChainManager.addFilter(filter3); - - ConfigRequest configRequest = new ConfigRequest(); - - configFilterChainManager.doFilter(configRequest, new ConfigResponse()); - - IConfigContext configContext = configRequest.getConfigContext(); - - // doFilter works - assertEquals(1, configContext.getParameter("filter1")); - assertEquals(2, configContext.getParameter("filter2")); - assertEquals(3, configContext.getParameter("filter3")); - - //order - List orders = (List) configContext.getParameter("orders"); - assertEquals(Arrays.asList(1, 2, 3), orders); - } - - @Test - void testAddFilterNotRepeat() throws NacosException { - final ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(new Properties()); - MyIConfigFilter filter1 = new MyIConfigFilter("filter1", 1); - MyIConfigFilter filter2 = new MyIConfigFilter("filter2", 2); - MyIConfigFilter repeatFilter = new MyIConfigFilter("filter1", 1); - - configFilterChainManager.addFilter(filter2); - configFilterChainManager.addFilter(filter1); - configFilterChainManager.addFilter(repeatFilter); - - ConfigRequest configRequest = new ConfigRequest(); - configFilterChainManager.doFilter(configRequest, new ConfigResponse()); - - IConfigContext configContext = configRequest.getConfigContext(); - - assertEquals(2, configContext.getParameter("filterCount")); - } } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java index c177e81ab92..e831c796439 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigFilterChainTest.java @@ -22,7 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class ConfigFilterChainTest { - + @Test void testConfigFilterChain() { ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager(null); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java index 76f17db7edf..a2e58bd7512 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigRequestTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; class ConfigRequestTest { - + @Test void testGetterAndSetter() { ConfigRequest configRequest = new ConfigRequest(); @@ -46,7 +46,7 @@ void testGetterAndSetter() { assertEquals(type, configRequest.getType()); } - + @Test void testGetParameter() { ConfigRequest configRequest = new ConfigRequest(); @@ -65,7 +65,7 @@ void testGetParameter() { assertEquals(tenant, configRequest.getParameter("tenant")); assertEquals(content, configRequest.getParameter("content")); } - + @Test void testGetConfigContext() { ConfigRequest configRequest = new ConfigRequest(); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java index 0450e0d41c2..ae49404fa88 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/filter/impl/ConfigResponseTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; class ConfigResponseTest { - + @Test void testGetterAndSetter() { ConfigResponse configResponse = new ConfigResponse(); @@ -45,7 +45,7 @@ void testGetterAndSetter() { assertEquals(content, configResponse.getContent()); assertEquals(type, configResponse.getConfigType()); } - + @Test void getParameter() { ConfigResponse configResponse = new ConfigResponse(); @@ -67,7 +67,7 @@ void getParameter() { assertEquals(content, configResponse.getParameter("content")); assertEquals(custom, configResponse.getParameter("custom")); } - + @Test void getConfigContext() { ConfigResponse configResponse = new ConfigResponse(); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java b/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java index 548f50716ef..cc048de9354 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/http/MetricsHttpAgentTest.java @@ -29,6 +29,58 @@ class MetricsHttpAgentTest { + @Test + void testGetter() { + String name = "name"; + String encode = "UTF-8"; + String tenant = "aaa"; + String namespace = "aaa"; + final HttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); + final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); + + assertEquals(name, metricsHttpAgent.getName()); + assertEquals(encode, metricsHttpAgent.getEncode()); + assertEquals(tenant, metricsHttpAgent.getTenant()); + assertEquals(namespace, metricsHttpAgent.getNamespace()); + } + + @Test + void testLifeCycle() throws NacosException { + String name = "name"; + String encode = "UTF-8"; + String tenant = "aaa"; + String namespace = "aaa"; + final MockHttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); + final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); + + metricsHttpAgent.start(); + assertTrue(mockHttpAgent.isStart()); + + metricsHttpAgent.shutdown(); + assertTrue(mockHttpAgent.isShutdown()); + } + + @Test + void testHttpMethod() throws Exception { + String name = "name"; + String encode = "UTF-8"; + String tenant = "aaa"; + String namespace = "aaa"; + final MockHttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); + final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); + + final HttpRestResult result1 = metricsHttpAgent.httpGet("/aa", new HashMap(), + new HashMap(), "UTF-8", 1L); + assertEquals("get /aa", result1.getMessage()); + final HttpRestResult result2 = metricsHttpAgent.httpPost("/aa", new HashMap(), + new HashMap(), "UTF-8", 1L); + assertEquals("post /aa", result2.getMessage()); + + final HttpRestResult result3 = metricsHttpAgent.httpDelete("/aa", new HashMap(), + new HashMap(), "UTF-8", 1L); + assertEquals("delete /aa", result3.getMessage()); + } + private static class MockHttpAgent implements HttpAgent { private String name; @@ -106,56 +158,4 @@ public boolean isShutdown() { return shutdown; } } - - @Test - void testGetter() { - String name = "name"; - String encode = "UTF-8"; - String tenant = "aaa"; - String namespace = "aaa"; - final HttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); - final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); - - assertEquals(name, metricsHttpAgent.getName()); - assertEquals(encode, metricsHttpAgent.getEncode()); - assertEquals(tenant, metricsHttpAgent.getTenant()); - assertEquals(namespace, metricsHttpAgent.getNamespace()); - } - - @Test - void testLifeCycle() throws NacosException { - String name = "name"; - String encode = "UTF-8"; - String tenant = "aaa"; - String namespace = "aaa"; - final MockHttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); - final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); - - metricsHttpAgent.start(); - assertTrue(mockHttpAgent.isStart()); - - metricsHttpAgent.shutdown(); - assertTrue(mockHttpAgent.isShutdown()); - } - - @Test - void testHttpMethod() throws Exception { - String name = "name"; - String encode = "UTF-8"; - String tenant = "aaa"; - String namespace = "aaa"; - final MockHttpAgent mockHttpAgent = new MockHttpAgent(name, encode, tenant, namespace); - final MetricsHttpAgent metricsHttpAgent = new MetricsHttpAgent(mockHttpAgent); - - final HttpRestResult result1 = metricsHttpAgent - .httpGet("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - assertEquals("get /aa", result1.getMessage()); - final HttpRestResult result2 = metricsHttpAgent - .httpPost("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - assertEquals("post /aa", result2.getMessage()); - - final HttpRestResult result3 = metricsHttpAgent - .httpDelete("/aa", new HashMap(), new HashMap(), "UTF-8", 1L); - assertEquals("delete /aa", result3.getMessage()); - } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java b/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java index 51594fa98b9..6f512437222 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/http/ServerHttpAgentTest.java @@ -74,7 +74,7 @@ class ServerHttpAgentTest { NacosRestTemplate nacosRestTemplate; ServerHttpAgent serverHttpAgent; - + @BeforeEach void setUp() throws NoSuchFieldException, IllegalAccessException { serverHttpAgent = new ServerHttpAgent(serverListManager, new Properties()); @@ -89,12 +89,12 @@ private void injectRestTemplate() throws NoSuchFieldException, IllegalAccessExce restTemplateField.setAccessible(true); restTemplateField.set(serverHttpAgent, nacosRestTemplate); } - + @AfterEach void tearDown() throws NacosException { serverHttpAgent.shutdown(); } - + @Test void testConstruct() throws NacosException { ServerListManager server = new ServerListManager(); @@ -110,7 +110,7 @@ void testConstruct() throws NacosException { assertNotNull(serverHttpAgent3); } - + @Test void testGetterAndSetter() throws NacosException { ServerListManager server = new ServerListManager("aaa", "namespace1"); @@ -130,7 +130,7 @@ void testGetterAndSetter() throws NacosException { assertEquals("custom-aaa_8080_nacos_serverlist_namespace1", name); } - + @Test void testLifCycle() throws NacosException { Properties properties = new Properties(); @@ -140,22 +140,22 @@ void testLifCycle() throws NacosException { serverHttpAgent.start(); Mockito.verify(server).start(); - + Assertions.assertDoesNotThrow(() -> { serverHttpAgent.shutdown(); }); } - + @Test void testHttpGetSuccess() throws Exception { when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + HttpRestResult actual = serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), + "UTF-8", 1000); assertEquals(mockResult, actual); } - + @Test void testHttpGetFailed() throws Exception { assertThrows(ConnectException.class, () -> { @@ -165,17 +165,17 @@ void testHttpGetFailed() throws Exception { serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); }); } - + @Test void testHttpWithRequestException() throws Exception { assertThrows(NacosException.class, () -> { when(nacosRestTemplate.get(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))) - .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); + any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException(), + new SocketTimeoutException(), new NacosException()); serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); }); } - + @Test void testRetryWithNewServer() throws Exception { when(mockIterator.hasNext()).thenReturn(true); @@ -184,11 +184,11 @@ void testRetryWithNewServer() throws Exception { when(nacosRestTemplate.get(eq(SERVER_ADDRESS_2 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + HttpRestResult actual = serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), + "UTF-8", 1000); assertEquals(mockResult, actual); } - + @Test void testRetryTimeout() throws Exception { assertThrows(ConnectException.class, () -> { @@ -197,17 +197,17 @@ void testRetryTimeout() throws Exception { serverHttpAgent.httpGet("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); }); } - + @Test void testHttpPostSuccess() throws Exception { when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + HttpRestResult actual = serverHttpAgent.httpPost("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); assertEquals(mockResult, actual); } - + @Test void testHttpPostFailed() throws Exception { assertThrows(ConnectException.class, () -> { @@ -217,17 +217,17 @@ void testHttpPostFailed() throws Exception { serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); }); } - + @Test void testHttpPostWithRequestException() throws Exception { assertThrows(NacosException.class, () -> { when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), anyMap(), eq(String.class))) - .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); + any(Header.class), anyMap(), eq(String.class))).thenThrow(new ConnectException(), + new SocketTimeoutException(), new NacosException()); serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); }); } - + @Test void testRetryPostWithNewServer() throws Exception { when(mockIterator.hasNext()).thenReturn(true); @@ -236,11 +236,11 @@ void testRetryPostWithNewServer() throws Exception { when(nacosRestTemplate.postForm(eq(SERVER_ADDRESS_2 + "/test"), any(HttpClientConfig.class), any(Header.class), anyMap(), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + HttpRestResult actual = serverHttpAgent.httpPost("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); assertEquals(mockResult, actual); } - + @Test void testRetryPostTimeout() throws Exception { assertThrows(ConnectException.class, () -> { @@ -249,17 +249,17 @@ void testRetryPostTimeout() throws Exception { serverHttpAgent.httpPost("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 0); }); } - + @Test void testHttpDeleteSuccess() throws Exception { when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + HttpRestResult actual = serverHttpAgent.httpDelete("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); assertEquals(mockResult, actual); } - + @Test void testHttpDeleteFailed() throws Exception { assertThrows(ConnectException.class, () -> { @@ -269,17 +269,17 @@ void testHttpDeleteFailed() throws Exception { serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); }); } - + @Test void testHttpDeleteWithRequestException() throws Exception { assertThrows(NacosException.class, () -> { when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_1 + "/test"), any(HttpClientConfig.class), - any(Header.class), any(Query.class), eq(String.class))) - .thenThrow(new ConnectException(), new SocketTimeoutException(), new NacosException()); + any(Header.class), any(Query.class), eq(String.class))).thenThrow(new ConnectException(), + new SocketTimeoutException(), new NacosException()); serverHttpAgent.httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); }); } - + @Test void testRetryDeleteWithNewServer() throws Exception { when(mockIterator.hasNext()).thenReturn(true); @@ -288,11 +288,11 @@ void testRetryDeleteWithNewServer() throws Exception { when(nacosRestTemplate.delete(eq(SERVER_ADDRESS_2 + "/test"), any(HttpClientConfig.class), any(Header.class), any(Query.class), eq(String.class))).thenReturn(mockResult); when(mockResult.getCode()).thenReturn(HttpURLConnection.HTTP_OK); - HttpRestResult actual = serverHttpAgent - .httpDelete("/test", Collections.emptyMap(), Collections.emptyMap(), "UTF-8", 1000); + HttpRestResult actual = serverHttpAgent.httpDelete("/test", Collections.emptyMap(), + Collections.emptyMap(), "UTF-8", 1000); assertEquals(mockResult, actual); } - + @Test void testRetryDeleteTimeout() throws Exception { assertThrows(ConnectException.class, () -> { diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java index 632b319441f..3d0fb134393 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/CacheDataTest.java @@ -43,7 +43,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class CacheDataTest { - + @Test void testConstructorAndEquals() { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); @@ -57,7 +57,7 @@ void testConstructorAndEquals() { final CacheData cacheData3 = new CacheData(filter, "name2", "key3", "group", "tenant"); assertNotEquals(cacheData1, cacheData3); } - + @Test void testGetter() { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); @@ -92,7 +92,7 @@ void testGetter() { assertEquals(timeStamp, cacheData1.getLastModifiedTs().longValue()); assertEquals(timeStamp, cacheData1.getLocalConfigInfoVersion()); } - + @Test void testNotifyWarnTimeout() { System.setProperty("nacos.listener.notify.warn.timeout", "5000"); @@ -102,7 +102,7 @@ void testNotifyWarnTimeout() { long notifyWarnTimeout2 = CacheData.initNotifyWarnTimeout(); assertEquals(60000, notifyWarnTimeout2); } - + @Test void testListener() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); @@ -126,7 +126,7 @@ public void receiveConfigInfo(String configInfo) { assertEquals(0, cacheData1.getListeners().size()); } - + @Test void testCheckListenerMd5() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); @@ -155,7 +155,7 @@ public void receiveConfigInfo(String configInfo) { assertEquals("new", list.get(0)); } - + @Test void testCheckListenerMd5NotifyTimeouts() throws NacosException { System.setProperty("nacos.listener.notify.warn.timeout", "1000"); @@ -200,7 +200,7 @@ public Class subscribeType() { assertTrue(data.checkListenersMd5Consistent()); assertEquals("keytimeouts", dataIdNotifyTimeouts.get()); } - + @Test void testAbstractSharedListener() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); @@ -233,7 +233,7 @@ public void innerReceive(String dataId, String group, String configInfo) { assertEquals("group", groupReceive[0]); assertEquals(contentReceive[0], content); } - + @Test void testAbstractConfigChangeListener() throws NacosException { ConfigFilterChainManager filter = new ConfigFilterChainManager(new Properties()); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java index 6c811e6d48e..eaaba3e6e5f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java @@ -81,19 +81,19 @@ @ExtendWith(MockitoExtension.class) class ClientWorkerTest { + private static final String TEST_NAMESPACE = "TEST_NAMESPACE"; + MockedStatic rpcClientFactoryMockedStatic; MockedStatic localConfigInfoProcessorMockedStatic; - private static final String TEST_NAMESPACE = "TEST_NAMESPACE"; + @Mock + RpcClient rpcClient; private ClientWorker clientWorker; private ClientWorker clientWorkerSpy; - @Mock - RpcClient rpcClient; - @BeforeEach void before() { rpcClientFactoryMockedStatic = Mockito.mockStatic(RpcClientFactory.class); @@ -117,13 +117,13 @@ void before() { } clientWorkerSpy = Mockito.spy(clientWorker); } - + @AfterEach void after() { rpcClientFactoryMockedStatic.close(); localConfigInfoProcessorMockedStatic.close(); } - + @Test void testConstruct() throws NacosException { Properties prop = new Properties(); @@ -134,7 +134,7 @@ void testConstruct() throws NacosException { ClientWorker clientWorker = new ClientWorker(filter, agent, nacosClientProperties); assertNotNull(clientWorker); } - + @Test void testAddListenerWithoutTenant() throws NacosException { Properties prop = new Properties(); @@ -164,7 +164,7 @@ public void receiveConfigInfo(String configInfo) { CacheData cacheData = clientWorker.addCacheDataIfAbsent(dataId, group); assertEquals(cacheData, clientWorker.getCache(dataId, group)); } - + @Test void testListenerWithTenant() throws NacosException { Properties prop = new Properties(); @@ -210,7 +210,7 @@ public void receiveConfigInfo(String configInfo) { assertNull(clientWorker.getCache(dataId, group, tenant)); } - + @Test void testPublishConfigSuccess() throws NacosException { Properties prop = new Properties(); @@ -239,7 +239,7 @@ void testPublishConfigSuccess() throws NacosException { assertTrue(b); } - + @Test void testPublishConfigFail() throws NacosException { Properties prop = new Properties(); @@ -268,7 +268,7 @@ void testPublishConfigFail() throws NacosException { assertFalse(b); } - + @Test void testPublishConfigException() throws NacosException { Properties prop = new Properties(); @@ -296,7 +296,7 @@ void testPublishConfigException() throws NacosException { assertFalse(b); } - + @Test void testRemoveConfig() throws NacosException { @@ -324,7 +324,7 @@ void testRemoveConfig() throws NacosException { } } - + @Test void testGeConfigConfigSuccess() throws NacosException { @@ -347,7 +347,7 @@ void testGeConfigConfigSuccess() throws NacosException { () -> LocalConfigInfoProcessor.saveSnapshot(eq(clientWorker.getAgentName()), eq(dataId), eq(group), eq(tenant), eq(content)), times(1)); } - + @Test void testHandleConfigChangeReqeust() throws Exception { @@ -377,7 +377,7 @@ void testHandleConfigChangeReqeust() throws Exception { Mockito.verify(cacheDataMocked, times(1)).setConsistentWithServer(false); Mockito.verify(atomicBoolean, times(1)).set(true); } - + @Test void testHandleClientMetricsReqeust() throws Exception { @@ -426,7 +426,7 @@ void testHandleClientMetricsReqeust() throws Exception { assertEquals(md5, metricValues.substring(colonIndex + 1, metricValues.length())); } - + @Test void testGeConfigConfigNotFound() throws NacosException { @@ -449,7 +449,7 @@ void testGeConfigConfigNotFound() throws NacosException { eq(tenant), eq(null)), times(1)); } - + @Test void testGeConfigConfigConflict() throws NacosException { @@ -472,7 +472,7 @@ void testGeConfigConfigConflict() throws NacosException { assertEquals(NacosException.CONFLICT, e.getErrCode()); } } - + @Test void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties prop = new Properties(); @@ -487,10 +487,10 @@ void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessEx ConfigTransportClient o = (ConfigTransportClient) agent1.get(clientWorker); assertTrue(o.executor.isShutdown()); agent1.setAccessible(false); - + assertNull(clientWorker.getAgentName()); } - + @Test void testExecuteConfigListen() throws Exception { Properties prop = new Properties(); @@ -616,7 +616,7 @@ private CacheData useLocalCache(ConfigFilterChainManager filter, String envName, () -> LocalConfigInfoProcessor.getFailover(envName, dataId, group, tenant)).thenReturn(failOverContent); return cacheData; } - + @Test void testIsHealthServer() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties prop = new Properties(); @@ -631,13 +631,13 @@ void testIsHealthServer() throws NacosException, NoSuchFieldException, IllegalAc Field declaredField = ClientWorker.class.getDeclaredField("agent"); declaredField.setAccessible(true); declaredField.set(clientWorker, client); - + assertTrue(clientWorker.isHealthServer()); Mockito.when(client.isHealthServer()).thenReturn(Boolean.FALSE); assertFalse(clientWorker.isHealthServer()); } - + @Test void testPutCache() throws Exception { // 反射调用私有方法putCacheIfAbsent @@ -664,10 +664,9 @@ void testPutCache() throws Exception { // 检查key对应的value是否改变为newCacheData assertEquals(newCacheData, cacheMapRef.get().get(key)); } - + @Test - void testAddListenersEnsureCacheDataSafe() - throws NacosException, IllegalAccessException, NoSuchFieldException { + void testAddListenersEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { String dataId = "testDataId"; String group = "testGroup"; // 将key-cacheData插入到cacheMap中 @@ -696,7 +695,7 @@ void testAddListenersEnsureCacheDataSafe() assertFalse(cacheDataFromCache2.isDiscard()); assertFalse(cacheDataFromCache2.isConsistentWithServer()); } - + @Test void testAddTenantListenersEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { @@ -729,7 +728,7 @@ void testAddTenantListenersEnsureCacheDataSafe() assertFalse(cacheDataFromCache2.isDiscard()); assertFalse(cacheDataFromCache2.isConsistentWithServer()); } - + @Test void testAddTenantListenersWithContentEnsureCacheDataSafe() throws NacosException, IllegalAccessException, NoSuchFieldException { diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java index 6b08e9a83c9..520d7725c2a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigChangeHandlerTest.java @@ -25,13 +25,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class ConfigChangeHandlerTest { - + @Test void testParseProperties() throws IOException { Map properties = ConfigChangeHandler.getInstance().parseChangeData("", "app.name = nacos", "properties"); assertEquals("nacos", ((ConfigChangeItem) properties.get("app.name")).getNewValue()); } - + @Test void testParseYaml() throws IOException { Map properties = ConfigChangeHandler.getInstance().parseChangeData("", "app:\n name: nacos", "yaml"); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java index a4dc38223cc..2ca8c0a0775 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ConfigHttpClientManagerTest.java @@ -24,25 +24,25 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; class ConfigHttpClientManagerTest { - + @Test void test() { final ConfigHttpClientManager instance1 = ConfigHttpClientManager.getInstance(); final ConfigHttpClientManager instance2 = ConfigHttpClientManager.getInstance(); assertEquals(instance1, instance2); - + final NacosRestTemplate nacosRestTemplate = instance1.getNacosRestTemplate(); assertNotNull(nacosRestTemplate); - + final int time1 = instance1.getConnectTimeoutOrDefault(10); assertEquals(1000, time1); final int time2 = instance1.getConnectTimeoutOrDefault(2000); assertEquals(2000, time2); - + Assertions.assertDoesNotThrow(() -> { instance1.shutdown(); }); } - + } diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java index c933e17a660..d48bdecd25e 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/LimiterTest.java @@ -22,7 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class LimiterTest { - + @Test void testIsLimit() { String keyId = "a"; diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java index 48c299667b1..e667fd0f15d 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/PropertiesChangeParserTest.java @@ -31,26 +31,26 @@ class PropertiesChangeParserTest { private final PropertiesChangeParser parser = new PropertiesChangeParser(); private final String type = "properties"; - + @Test void testType() { assertTrue(parser.isResponsibleFor(type)); } - + @Test void testAddKey() throws IOException { Map map = parser.doParse("", "app.name = nacos", type); assertNull(map.get("app.name").getOldValue()); assertEquals("nacos", map.get("app.name").getNewValue()); } - + @Test void testRemoveKey() throws IOException { Map map = parser.doParse("app.name = nacos", "", type); assertEquals("nacos", map.get("app.name").getOldValue()); assertNull(map.get("app.name").getNewValue()); } - + @Test void testModifyKey() throws IOException { Map map = parser.doParse("app.name = rocketMQ", "app.name = nacos", type); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java index db2cc367025..c38f620cd5c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ServerListManagerTest.java @@ -36,7 +36,7 @@ import static org.junit.jupiter.api.Assertions.fail; class ServerListManagerTest { - + @Test void testStart() throws NacosException { final ServerListManager mgr = new ServerListManager("localhost", 0); @@ -50,7 +50,7 @@ void testStart() throws NacosException { } mgr.shutdown(); } - + @Test void testGetter() throws NacosException { { @@ -66,12 +66,12 @@ void testGetter() throws NacosException { Properties properties = new Properties(); properties.put(PropertyKeyConst.CONTEXT_PATH, "aaa"); properties.put(PropertyKeyConst.ENDPOINT, "endpoint"); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties); final ServerListManager mgr2 = new ServerListManager(nacosClientProperties); assertEquals("aaa", mgr2.getContentPath()); } - + // Test https { Properties properties = new Properties(); @@ -87,7 +87,7 @@ void testGetter() throws NacosException { Properties properties2 = new Properties(); properties2.put(PropertyKeyConst.CONTEXT_PATH, "aaa"); properties2.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1:8848"); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties2); final ServerListManager mgr3 = new ServerListManager(nacosClientProperties); assertEquals(1, mgr3.getServerUrls().size()); @@ -96,37 +96,39 @@ void testGetter() throws NacosException { assertTrue(mgr3.contain("http://1.1.1.1:8848")); assertEquals("ServerManager-fixed-1.1.1.1_8848-[http://1.1.1.1:8848]", mgr3.toString()); } - + { Properties properties3 = new Properties(); properties3.put(PropertyKeyConst.CONTEXT_PATH, "aaa"); properties3.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1:8848,2.2.2.2:8848"); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties3); final ServerListManager mgr4 = new ServerListManager(nacosClientProperties); assertEquals(2, mgr4.getServerUrls().size()); assertEquals("http://1.1.1.1:8848", mgr4.getServerUrls().get(0)); assertEquals("http://2.2.2.2:8848", mgr4.getServerUrls().get(1)); assertTrue(mgr4.contain("http://1.1.1.1:8848")); - assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", mgr4.toString()); + assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", + mgr4.toString()); } - + { Properties properties4 = new Properties(); properties4.put(PropertyKeyConst.CONTEXT_PATH, "aaa"); properties4.put(PropertyKeyConst.SERVER_ADDR, "1.1.1.1:8848;2.2.2.2:8848"); - + final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(properties4); final ServerListManager mgr5 = new ServerListManager(nacosClientProperties); assertEquals(2, mgr5.getServerUrls().size()); assertEquals("http://1.1.1.1:8848", mgr5.getServerUrls().get(0)); assertEquals("http://2.2.2.2:8848", mgr5.getServerUrls().get(1)); assertTrue(mgr5.contain("http://1.1.1.1:8848")); - assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", mgr5.toString()); + assertEquals("ServerManager-fixed-1.1.1.1_8848-2.2.2.2_8848-[http://1.1.1.1:8848, http://2.2.2.2:8848]", + mgr5.toString()); } } - + @Test void testIterator() { List addrs = new ArrayList<>(); @@ -153,7 +155,7 @@ void testIterator() { assertTrue(iterator1.hasNext()); } - + @Test void testAddressServerBaseServerAddrsStr() throws NacosException { Properties properties = new Properties(); @@ -166,7 +168,7 @@ void testAddressServerBaseServerAddrsStr() throws NacosException { assertEquals(1, serverListManager.serverUrls.size()); assertTrue(serverListManager.serverUrls.contains(HTTP_PREFIX + serverAddrStr)); } - + @Test void testAddressServerBaseEndpoint() throws NacosException { Properties properties = new Properties(); @@ -181,7 +183,7 @@ void testAddressServerBaseEndpoint() throws NacosException { assertTrue(serverListManager.addressServerUrl.startsWith( HTTP_PREFIX + endpoint + ":" + endpointPort + endpointContextPath)); } - + @Test void testInitParam() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties properties = new Properties(); @@ -215,7 +217,7 @@ void testInitParam() throws NacosException, NoSuchFieldException, IllegalAccessE String fieldContentPath = String.valueOf(contentPathField.get(serverListManager)); assertEquals(fieldContentPath, contextPath); } - + @Test void testWithEndpointContextPath() throws NacosException { Properties properties = new Properties(); @@ -232,7 +234,7 @@ void testWithEndpointContextPath() throws NacosException { assertTrue(serverListManager.addressServerUrl.contains(endpointContextPath)); assertTrue(serverListManager.getName().contains("endpointContextPath")); } - + @Test void testWithoutEndpointContextPath() throws NacosException { Properties properties = new Properties(); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java index 4504a060805..b0157672a38 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/YmlChangeParserTest.java @@ -33,33 +33,33 @@ class YmlChangeParserTest { private final YmlChangeParser parser = new YmlChangeParser(); private final String type = "yaml"; - + @Test void testType() { assertTrue(parser.isResponsibleFor(type)); } - + @Test void testAddKey() throws IOException { Map map = parser.doParse("", "app:\n name: nacos", type); assertNull(map.get("app.name").getOldValue()); assertEquals("nacos", map.get("app.name").getNewValue()); } - + @Test void testRemoveKey() throws IOException { Map map = parser.doParse("app:\n name: nacos", "", type); assertEquals("nacos", map.get("app.name").getOldValue()); assertNull(map.get("app.name").getNewValue()); } - + @Test void testModifyKey() throws IOException { Map map = parser.doParse("app:\n name: rocketMQ", "app:\n name: nacos", type); assertEquals("rocketMQ", map.get("app.name").getOldValue()); assertEquals("nacos", map.get("app.name").getNewValue()); } - + @Test void testComplexYaml() throws IOException { /* @@ -76,7 +76,7 @@ void testComplexYaml() throws IOException { Map map = parser.doParse(s, s, type); assertEquals(0, map.size()); } - + @Test void testChangeInvalidKey() { assertThrows(NacosRuntimeException.class, () -> { diff --git a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java index 742c9a9e884..e57f270dee9 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/AbstractConfigChangeListenerTest.java @@ -25,7 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class AbstractConfigChangeListenerTest { - + @Test void receiveConfigInfo() { final Deque data = new ArrayDeque(); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java index 6c93762fc03..490224544f3 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/listener/impl/PropertiesListenerTest.java @@ -26,7 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; class PropertiesListenerTest { - + @Test void testReceiveConfigInfo() { final Deque q2 = new ArrayDeque(); @@ -42,7 +42,7 @@ public void innerReceive(Properties properties) { assertEquals("bar", actual.getProperty("foo")); } - + @Test void testReceiveConfigInfoEmpty() { final Deque q2 = new ArrayDeque(); @@ -56,7 +56,7 @@ public void innerReceive(Properties properties) { final Properties actual = q2.poll(); assertNull(actual); } - + @Test void testReceiveConfigInfoIsNotProperties() { final Deque q2 = new ArrayDeque(); @@ -70,7 +70,7 @@ public void innerReceive(Properties properties) { final Properties actual = q2.poll(); assertNull(actual); } - + @Test void testInnerReceive() { final Deque q2 = new ArrayDeque(); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java index 66b2d4f18c2..bc2c12b3f19 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/ContentUtilsTest.java @@ -28,13 +28,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class ContentUtilsTest { - + @Test void testVerifyIncrementPubContent() { String content = "aabbb"; ContentUtils.verifyIncrementPubContent(content); } - + @Test void testVerifyIncrementPubContentFail1() { Throwable exception = assertThrows(IllegalArgumentException.class, () -> { @@ -43,7 +43,7 @@ void testVerifyIncrementPubContentFail1() { }); assertTrue(exception.getMessage().contains("publish/delete content can not be null")); } - + @Test void testVerifyIncrementPubContentFail2() { Throwable exception = assertThrows(IllegalArgumentException.class, () -> { @@ -52,7 +52,7 @@ void testVerifyIncrementPubContentFail2() { }); assertTrue(exception.getMessage().contains("publish/delete content can not contain return and linefeed")); } - + @Test void testVerifyIncrementPubContentFail3() { Throwable exception = assertThrows(IllegalArgumentException.class, () -> { @@ -61,7 +61,7 @@ void testVerifyIncrementPubContentFail3() { }); assertTrue(exception.getMessage().contains("publish/delete content can not be null")); } - + @Test void testVerifyIncrementPubContentFail4() { Throwable exception = assertThrows(IllegalArgumentException.class, () -> { @@ -70,14 +70,14 @@ void testVerifyIncrementPubContentFail4() { }); assertTrue(exception.getMessage().contains("publish/delete content can not contain(char)2")); } - + @Test void testGetContentIdentity() { String content = "aa" + WORD_SEPARATOR + "bbb"; String content1 = ContentUtils.getContentIdentity(content); assertEquals("aa", content1); } - + @Test void testGetContentIdentityFail() { assertThrows(IllegalArgumentException.class, () -> { @@ -85,14 +85,14 @@ void testGetContentIdentityFail() { ContentUtils.getContentIdentity(content); }); } - + @Test void testGetContent() { String content = "aa" + WORD_SEPARATOR + "bbb"; String content1 = ContentUtils.getContent(content); assertEquals("bbb", content1); } - + @Test void testGetContentFail() { assertThrows(IllegalArgumentException.class, () -> { @@ -100,14 +100,14 @@ void testGetContentFail() { ContentUtils.getContent(content); }); } - + @Test void testTruncateContent() { String content = "aa"; String actual = ContentUtils.truncateContent(content); assertEquals(content, actual); } - + @Test void testTruncateLongContent() { char[] arr = new char[101]; @@ -116,7 +116,7 @@ void testTruncateLongContent() { String actual = ContentUtils.truncateContent(content); assertEquals(content.substring(0, 100) + "...", actual); } - + @Test void testTruncateContentNull() { String actual = ContentUtils.truncateContent(null); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java index 2ffa632ee05..a5966243778 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/JvmUtilTest.java @@ -32,13 +32,13 @@ class JvmUtilTest { Method initMethod; - + @BeforeEach void setUp() throws NoSuchMethodException { initMethod = JvmUtil.class.getDeclaredMethod("init"); initMethod.setAccessible(true); } - + @AfterEach void tearDown() throws NoSuchFieldException, IllegalAccessException { System.clearProperty("isMultiInstance"); @@ -46,14 +46,14 @@ void tearDown() throws NoSuchFieldException, IllegalAccessException { field.setAccessible(true); field.set(JvmUtil.class, false); } - + @Test void testIsMultiInstance() throws InvocationTargetException, IllegalAccessException { initMethod.invoke(JvmUtil.class); Boolean multiInstance = JvmUtil.isMultiInstance(); assertFalse(multiInstance); } - + @Test void testIsMultiInstance2() throws InvocationTargetException, IllegalAccessException { System.setProperty("isMultiInstance", "true"); diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java index 0b41c9ee49e..f28bfe4fd5f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/ParamUtilsTest.java @@ -31,7 +31,7 @@ import static org.junit.jupiter.api.Assertions.fail; class ParamUtilsTest { - + @Test void testIsValid() { String content = "abcABC09.:_-"; @@ -49,7 +49,7 @@ void testIsValid() { content = "/"; assertFalse(ParamUtils.isValid(content)); } - + @Test void testCheckTdg() throws NacosException { String tenant = "a"; @@ -57,11 +57,11 @@ void testCheckTdg() throws NacosException { String group = "c"; ParamUtils.checkTdg(tenant, dataId, group); } - + @Test void testCheckTdgFail1() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { - + String tenant = "a"; String dataId = ""; String group = "c"; @@ -69,11 +69,11 @@ void testCheckTdgFail1() throws NacosException { }); assertTrue(exception.getMessage().contains("dataId invalid")); } - + @Test void testCheckTdgFail2() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { - + String tenant = "a"; String dataId = "b"; String group = ""; @@ -81,7 +81,7 @@ void testCheckTdgFail2() throws NacosException { }); assertTrue(exception.getMessage().contains("group invalid")); } - + @Test void testCheckKeyParam1() throws NacosException { String dataId = "b"; @@ -106,7 +106,7 @@ void testCheckKeyParam1() throws NacosException { assertEquals("group invalid", e.getMessage()); } } - + @Test void testCheckKeyParam2() throws NacosException { String dataId = "b"; @@ -145,7 +145,7 @@ void testCheckKeyParam2() throws NacosException { assertEquals("datumId invalid", e.getMessage()); } } - + @Test void testCheckKeyParam3() throws NacosException { String dataId = "b"; @@ -181,7 +181,7 @@ void testCheckKeyParam3() throws NacosException { assertEquals("group invalid", e.getMessage()); } } - + @Test void testCheckParam() throws NacosException { String dataId = "b"; @@ -189,11 +189,11 @@ void testCheckParam() throws NacosException { String content = "a"; ParamUtils.checkParam(dataId, group, content); } - + @Test void testCheckParamFail() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { - + String dataId = "b"; String group = "c"; String content = ""; @@ -201,7 +201,7 @@ void testCheckParamFail() throws NacosException { }); assertTrue(exception.getMessage().contains("content invalid")); } - + @Test void testCheckParam2() throws NacosException { String dataId = "b"; @@ -210,11 +210,11 @@ void testCheckParam2() throws NacosException { String content = "a"; ParamUtils.checkParam(dataId, group, datumId, content); } - + @Test void testCheckParam2Fail() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { - + String dataId = "b"; String group = "c"; String datumId = "d"; @@ -223,13 +223,13 @@ void testCheckParam2Fail() throws NacosException { }); assertTrue(exception.getMessage().contains("content invalid")); } - + @Test void testCheckTenant() throws NacosException { String tenant = "a"; ParamUtils.checkTenant(tenant); } - + @Test void testCheckTenantFail() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { @@ -238,21 +238,21 @@ void testCheckTenantFail() throws NacosException { }); assertTrue(exception.getMessage().contains("tenant invalid")); } - + @Test void testCheckBetaIps() throws NacosException { ParamUtils.checkBetaIps("127.0.0.1"); } - + @Test void testCheckBetaIpsFail1() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { - + ParamUtils.checkBetaIps(""); }); assertTrue(exception.getMessage().contains("betaIps invalid")); } - + @Test void testCheckBetaIpsFail2() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { @@ -260,12 +260,12 @@ void testCheckBetaIpsFail2() throws NacosException { }); assertTrue(exception.getMessage().contains("betaIps invalid")); } - + @Test void testCheckContent() throws NacosException { ParamUtils.checkContent("aaa"); } - + @Test void testCheckContentFail() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { diff --git a/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java b/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java index ae2d583cf4a..2e0990db99f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/utils/SnapShotSwitchTest.java @@ -24,7 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class SnapShotSwitchTest { - + @Test void testGetIsSnapShot() { Boolean isSnapShot = SnapShotSwitch.getIsSnapShot(); diff --git a/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java b/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java index 8d6a4c352c7..ce047577211 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/NacosClientPropertiesTest.java @@ -29,24 +29,24 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class NacosClientPropertiesTest { - + @BeforeAll static void init() { System.setProperty("nacos.env.first", "jvm"); } - + @AfterAll static void teardown() { System.clearProperty("nacos.env.first"); } - + @Test void testGetProperty() { NacosClientProperties.PROTOTYPE.setProperty("nacos.home", "/home/nacos"); final String value = NacosClientProperties.PROTOTYPE.getProperty("nacos.home"); assertEquals("/home/nacos", value); } - + @Test void testGetPropertyMultiLayer() { @@ -73,59 +73,59 @@ void testGetPropertyMultiLayer() { value = layerCEnv.getProperty("top.layer"); assertEquals("top", value); } - + @Test void testGetPropertyDefaultValue() { final String value = NacosClientProperties.PROTOTYPE.getProperty("nacos.home.default", "/home/default_value"); assertEquals("/home/default_value", value); } - + @Test void testGetBoolean() { NacosClientProperties.PROTOTYPE.setProperty("use.cluster", "true"); final Boolean value = NacosClientProperties.PROTOTYPE.getBoolean("use.cluster"); assertTrue(value); } - + @Test void testGetBooleanDefaultValue() { final Boolean value = NacosClientProperties.PROTOTYPE.getBoolean("use.cluster.default", false); assertFalse(value); } - + @Test void testGetInteger() { NacosClientProperties.PROTOTYPE.setProperty("max.timeout", "200"); final Integer value = NacosClientProperties.PROTOTYPE.getInteger("max.timeout"); assertEquals(200, value.intValue()); } - + @Test void testGetIntegerDefaultValue() { final Integer value = NacosClientProperties.PROTOTYPE.getInteger("max.timeout.default", 400); assertEquals(400, value.intValue()); } - + @Test void testGetLong() { NacosClientProperties.PROTOTYPE.setProperty("connection.timeout", "200"); final Long value = NacosClientProperties.PROTOTYPE.getLong("connection.timeout"); assertEquals(200L, value.longValue()); } - + @Test void testGetLongDefault() { final Long value = NacosClientProperties.PROTOTYPE.getLong("connection.timeout.default", 400L); assertEquals(400L, value.longValue()); } - + @Test void setProperty() { NacosClientProperties.PROTOTYPE.setProperty("nacos.set.property", "true"); final String ret = NacosClientProperties.PROTOTYPE.getProperty("nacos.set.property"); assertEquals("true", ret); } - + @Test void setPropertyWithScope() { @@ -138,7 +138,7 @@ void setPropertyWithScope() { ret = properties.getProperty("nacos.set.property.scope"); assertEquals("config", ret); } - + @Test void testAddProperties() { Properties properties = new Properties(); @@ -150,7 +150,7 @@ void testAddProperties() { assertEquals("true", ret); } - + @Test void testAddPropertiesWithScope() { @@ -167,7 +167,7 @@ void testAddPropertiesWithScope() { assertEquals("config", ret); } - + @Test void testTestDerive() { Properties properties = new Properties(); @@ -180,7 +180,7 @@ void testTestDerive() { assertEquals("derive", value); } - + @Test void testContainsKey() { NacosClientProperties.PROTOTYPE.setProperty("nacos.contains.key", "true"); @@ -191,7 +191,7 @@ void testContainsKey() { ret = NacosClientProperties.PROTOTYPE.containsKey("nacos.contains.key.in.sys"); assertFalse(ret); } - + @Test void testContainsKeyMultiLayers() { @@ -219,7 +219,7 @@ void testContainsKeyMultiLayers() { assertTrue(exist); } - + @Test void testContainsKeyWithScope() { NacosClientProperties.PROTOTYPE.setProperty("nacos.contains.global.scope", "global"); @@ -239,7 +239,7 @@ void testContainsKeyWithScope() { assertTrue(ret); } - + @Test void testAsProperties() { NacosClientProperties.PROTOTYPE.setProperty("nacos.as.properties", "true"); @@ -247,7 +247,7 @@ void testAsProperties() { assertNotNull(properties); assertEquals("true", properties.getProperty("nacos.as.properties")); } - + @Test void testAsPropertiesWithScope() { @@ -266,7 +266,7 @@ void testAsPropertiesWithScope() { ret = properties.getProperty("nacos.server.addr.scope"); assertEquals("config", ret); } - + @Test void testGetPropertyWithScope() { @@ -302,16 +302,15 @@ void testGetPropertyWithScope() { assertNull(ret); } - + @Test void testGetPropertyFrom() { System.setProperty("nacos.home.default.test", "/home/jvm_args"); NacosClientProperties.PROTOTYPE.setProperty("nacos.home.default.test", "/home/properties_args"); - - assertEquals( - "/home/jvm_args", NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.JVM, "nacos.home.default.test")); - assertEquals( - "/home/properties_args", + + assertEquals("/home/jvm_args", + NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.JVM, "nacos.home.default.test")); + assertEquals("/home/properties_args", NacosClientProperties.PROTOTYPE.getPropertyFrom(SourceType.PROPERTIES, "nacos.home.default.test")); assertEquals(NacosClientProperties.PROTOTYPE.getPropertyFrom(null, "nacos.home.default.test"), NacosClientProperties.PROTOTYPE.getProperty("nacos.home.default.test")); diff --git a/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java b/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java index e7fb2f3eb3e..d4f52428fbb 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/SearchablePropertiesTest.java @@ -38,36 +38,36 @@ class SearchablePropertiesTest { Method initMethod; - + @BeforeAll static void init() { System.setProperty(Constants.SysEnv.NACOS_ENV_FIRST, "jvm"); } - + + @AfterAll + static void teardown() { + System.clearProperty(Constants.SysEnv.NACOS_ENV_FIRST); + } + @BeforeEach void setUp() throws Exception { initMethod = SearchableProperties.class.getDeclaredMethod("init"); initMethod.setAccessible(true); } - + @AfterEach void tearDown() throws Exception { init(); initMethod.invoke(null); } - - @AfterAll - static void teardown() { - System.clearProperty(Constants.SysEnv.NACOS_ENV_FIRST); - } - + @Test void testInitWithInvalidOrder() throws IllegalAccessException, InvocationTargetException { System.setProperty(Constants.SysEnv.NACOS_ENV_FIRST, "invalid"); List order = (List) initMethod.invoke(null); assertOrder(order, SourceType.PROPERTIES, SourceType.JVM, SourceType.ENV); } - + @Test void testInitWithoutSpecifiedOrder() throws IllegalAccessException, InvocationTargetException { System.clearProperty(Constants.SysEnv.NACOS_ENV_FIRST); @@ -81,7 +81,7 @@ private void assertOrder(List order, SourceType... sourceTypes) { assertEquals(sourceTypes[i], order.get(i)); } } - + @Test void testGetPropertyFromEnv() { System.setProperty("testFromSource", "jvm"); @@ -89,7 +89,7 @@ void testGetPropertyFromEnv() { properties.setProperty("testFromSource", "properties"); assertNull(properties.getPropertyFrom(SourceType.ENV, "testFromSource")); } - + @Test void testGetPropertyFromUnknown() { System.setProperty("testFromSource", "jvm"); diff --git a/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java b/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java index 669363c63b6..89d1ad6604b 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/SystemEnvPropertySourceTest.java @@ -35,7 +35,7 @@ class SystemEnvPropertySourceTest { SystemEnvPropertySource systemEnvPropertySource; private Map mockEnvMap; - + @BeforeEach void setUp() throws Exception { systemEnvPropertySource = new SystemEnvPropertySource(); @@ -48,42 +48,42 @@ void setUp() throws Exception { mockEnvMap.put("TESTCASE3", "value3"); mockEnvMap.put("TEST_CASE_4", "value4"); } - + @Test void testGetEnvForLowerCaseKey() { assertEquals("value1", systemEnvPropertySource.getProperty("testcase1")); } - + @Test void testGetEnvForLowerCaseKeyWithDot() { assertEquals("value2", systemEnvPropertySource.getProperty("test.case.2")); } - + @Test void testGetEnvForLowerCaseKeyWithHyphen() { assertEquals("value2", systemEnvPropertySource.getProperty("test-case-2")); } - + @Test void testGetEnvForLowerCaseKeyWithHyphenAndDot() { assertEquals("value2", systemEnvPropertySource.getProperty("test.case-2")); } - + @Test void testGetEnvForUpperCaseKey() { assertEquals("value3", systemEnvPropertySource.getProperty("TESTCASE3")); } - + @Test void testGetEnvForUpperCaseKeyWithDot() { assertEquals("value4", systemEnvPropertySource.getProperty("TEST.CASE.4")); } - + @Test void testGetEnvForUpperCaseKeyWithHyphen() { assertEquals("value4", systemEnvPropertySource.getProperty("TEST-CASE-4")); } - + @Test void testGetEnvForUpperCaseKeyWithHyphenAndDot() { assertEquals("value4", systemEnvPropertySource.getProperty("TEST_CASE.4")); diff --git a/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java b/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java index 4358018482c..8d200e29a29 100644 --- a/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/env/convert/CompositeConverterTest.java @@ -31,28 +31,28 @@ class CompositeConverterTest { CompositeConverter compositeConverter; - + @BeforeEach void setUp() throws Exception { compositeConverter = new CompositeConverter(); } - + @AfterEach void tearDown() throws Exception { } - + @Test void testConvertNotSupportType() { assertThrows(MissingFormatArgumentException.class, () -> { compositeConverter.convert("test", CompositeConverter.class); }); } - + @Test void testConvertBooleanForEmptyProperty() { assertNull(compositeConverter.convert(null, Boolean.class)); } - + @Test void testConvertBooleanTrue() { assertTrue(compositeConverter.convert("true", Boolean.class)); @@ -60,7 +60,7 @@ void testConvertBooleanTrue() { assertTrue(compositeConverter.convert("yes", Boolean.class)); assertTrue(compositeConverter.convert("1", Boolean.class)); } - + @Test void testConvertBooleanFalse() { assertFalse(compositeConverter.convert("false", Boolean.class)); @@ -68,45 +68,47 @@ void testConvertBooleanFalse() { assertFalse(compositeConverter.convert("no", Boolean.class)); assertFalse(compositeConverter.convert("0", Boolean.class)); } - + @Test void testConvertBooleanIllegal() { assertThrows(IllegalArgumentException.class, () -> { compositeConverter.convert("aaa", Boolean.class); }); } - + @Test void testConvertIntegerForEmptyProperty() { assertNull(compositeConverter.convert(null, Integer.class)); } - + @Test void testConvertInteger() { assertEquals(100, (int) compositeConverter.convert("100", Integer.class)); - assertEquals(Integer.MAX_VALUE, (int) compositeConverter.convert(String.valueOf(Integer.MAX_VALUE), Integer.class)); - assertEquals(Integer.MIN_VALUE, (int) compositeConverter.convert(String.valueOf(Integer.MIN_VALUE), Integer.class)); + assertEquals(Integer.MAX_VALUE, + (int) compositeConverter.convert(String.valueOf(Integer.MAX_VALUE), Integer.class)); + assertEquals(Integer.MIN_VALUE, + (int) compositeConverter.convert(String.valueOf(Integer.MIN_VALUE), Integer.class)); } - + @Test void testConvertIntegerIllegal() { assertThrows(IllegalArgumentException.class, () -> { compositeConverter.convert("aaa", Integer.class); }); } - + @Test void testConvertLongForEmptyProperty() { assertNull(compositeConverter.convert(null, Long.class)); } - + @Test void testConvertLong() { assertEquals(100L, (long) compositeConverter.convert("100", Long.class)); assertEquals(Long.MAX_VALUE, (long) compositeConverter.convert(String.valueOf(Long.MAX_VALUE), Long.class)); assertEquals(Long.MIN_VALUE, (long) compositeConverter.convert(String.valueOf(Long.MIN_VALUE), Long.class)); } - + @Test void testConvertLongIllegal() { assertThrows(IllegalArgumentException.class, () -> { diff --git a/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java b/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java index 38d857e8796..bdd3f4d9701 100644 --- a/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/logging/NacosLoggingTest.java @@ -42,7 +42,7 @@ class NacosLoggingTest { NacosLoggingProperties loggingProperties; NacosLogging instance; - + @BeforeEach void setUp() throws NoSuchFieldException, IllegalAccessException { loggingProperties = new NacosLoggingProperties("", new Properties()); @@ -51,13 +51,13 @@ void setUp() throws NoSuchFieldException, IllegalAccessException { loggingPropertiesField.setAccessible(true); loggingPropertiesField.set(instance, loggingProperties); } - + @Test void testGetInstance() { NacosLogging instance = NacosLogging.getInstance(); assertNotNull(instance); } - + @Test void testLoadConfiguration() throws NoSuchFieldException, IllegalAccessException { instance = NacosLogging.getInstance(); @@ -67,7 +67,7 @@ void testLoadConfiguration() throws NoSuchFieldException, IllegalAccessException instance.loadConfiguration(); Mockito.verify(loggingAdapter, Mockito.times(1)).loadConfiguration(loggingProperties); } - + @Test void testLoadConfigurationWithException() throws NoSuchFieldException, IllegalAccessException { instance = NacosLogging.getInstance(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java index 020d80e316f..50580d0e526 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingMaintainServiceTest.java @@ -57,19 +57,19 @@ class NacosNamingMaintainServiceTest { private SecurityProxy securityProxy; private ScheduledExecutorService executorService; - + @BeforeEach void setUp() throws Exception { Properties prop = new Properties(); prop.setProperty(PropertyKeyConst.NAMESPACE, "public"); prop.setProperty("serverAddr", "localhost"); - + nacosNamingMaintainService = new NacosNamingMaintainService(prop); serverProxy = mock(NamingHttpClientProxy.class); serverListManager = mock(ServerListManager.class); securityProxy = mock(SecurityProxy.class); executorService = mock(ScheduledExecutorService.class); - + Field serverProxyField = NacosNamingMaintainService.class.getDeclaredField("serverProxy"); serverProxyField.setAccessible(true); serverProxyField.set(nacosNamingMaintainService, serverProxy); @@ -83,17 +83,17 @@ void setUp() throws Exception { executorServiceField.setAccessible(true); executorServiceField.set(nacosNamingMaintainService, executorService); } - + @AfterEach void tearDown() throws Exception { } - + @Test void testConstructor() throws NacosException { NacosNamingMaintainService client = new NacosNamingMaintainService("localhost"); assertNotNull(client); } - + @Test void testUpdateInstance1() throws NacosException { //given @@ -105,7 +105,7 @@ void testUpdateInstance1() throws NacosException { //then verify(serverProxy, times(1)).updateInstance(serviceName, groupName, instance); } - + @Test void testUpdateInstance2() throws NacosException { //given @@ -116,7 +116,7 @@ void testUpdateInstance2() throws NacosException { //then verify(serverProxy, times(1)).updateInstance(serviceName, Constants.DEFAULT_GROUP, instance); } - + @Test void testQueryService1() throws NacosException { //given @@ -127,7 +127,7 @@ void testQueryService1() throws NacosException { //then verify(serverProxy, times(1)).queryService(serviceName, groupName); } - + @Test void testQueryService2() throws NacosException { //given @@ -138,7 +138,7 @@ void testQueryService2() throws NacosException { //then verify(serverProxy, times(1)).queryService(serviceName, Constants.DEFAULT_GROUP); } - + @Test void testCreateService1() throws NacosException { //given @@ -155,7 +155,7 @@ public boolean matches(Service service) { } }), argThat(o -> o instanceof NoneSelector)); } - + @Test void testCreateService2() throws NacosException { //given @@ -173,7 +173,7 @@ public boolean matches(Service service) { } }), argThat(o -> o instanceof NoneSelector)); } - + @Test void testCreateService3() throws NacosException { //given @@ -192,7 +192,7 @@ public boolean matches(Service service) { } }), argThat(o -> o instanceof NoneSelector)); } - + @Test void testCreateService5() throws NacosException { //given @@ -212,7 +212,7 @@ public boolean matches(Service service) { } }), argThat(o -> ((ExpressionSelector) o).getExpression().equals(expression))); } - + @Test void testCreateService4() throws NacosException { //given @@ -223,7 +223,7 @@ void testCreateService4() throws NacosException { //then verify(serverProxy, times(1)).createService(service, selector); } - + @Test void testDeleteService1() throws NacosException { //given @@ -233,7 +233,7 @@ void testDeleteService1() throws NacosException { //then verify(serverProxy, times(1)).deleteService(serviceName, Constants.DEFAULT_GROUP); } - + @Test void testDeleteService2() throws NacosException { //given @@ -244,7 +244,7 @@ void testDeleteService2() throws NacosException { //then verify(serverProxy, times(1)).deleteService(serviceName, groupName); } - + @Test void testUpdateService1() throws NacosException { //given @@ -263,7 +263,7 @@ public boolean matches(Service service) { } }), argThat(o -> o instanceof NoneSelector)); } - + @Test void testUpdateService2() throws NacosException { //given @@ -285,7 +285,7 @@ public boolean matches(Service service) { } }), argThat(o -> o instanceof NoneSelector)); } - + @Test void testUpdateService3() throws NacosException { //given @@ -296,7 +296,7 @@ void testUpdateService3() throws NacosException { //then verify(serverProxy, times(1)).updateService(service, selector); } - + @Test void testShutDown() throws NacosException { //when diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java index d02e1c2233d..02fa6ce13f3 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/NacosNamingServiceTest.java @@ -73,7 +73,7 @@ class NacosNamingServiceTest { private ServiceInfoHolder serviceInfoHolder; private NacosNamingService client; - + @BeforeEach void before() throws NoSuchFieldException, NacosException, IllegalAccessException { Properties prop = new Properties(); @@ -82,7 +82,7 @@ void before() throws NoSuchFieldException, NacosException, IllegalAccessExceptio client = new NacosNamingService(prop); injectMocks(client); } - + @AfterEach void tearDown() throws NacosException { client.shutDown(); @@ -113,7 +113,7 @@ private void injectMocks(NacosNamingService client) throws NoSuchFieldException, } serviceInfoHolderField.set(client, serviceInfoHolder); } - + @Test void testRegisterInstance1() throws NacosException { //given @@ -128,7 +128,7 @@ void testRegisterInstance1() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(Constants.DEFAULT_CLUSTER_NAME))); } - + @Test void testBatchRegisterInstance() throws NacosException { Instance instance = new Instance(); @@ -147,7 +147,7 @@ void testBatchRegisterInstance() throws NacosException { verify(proxy, times(1)).batchRegisterService(eq(serviceName), eq(Constants.DEFAULT_GROUP), argThat(instances -> CollectionUtils.isEqualCollection(instanceList, instances))); } - + @Test void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException { Instance instance = new Instance(); @@ -166,7 +166,7 @@ void testBatchRegisterInstanceWithGroupNamePrefix() throws NacosException { verify(proxy, times(1)).batchRegisterService(eq(serviceName), eq(Constants.DEFAULT_GROUP), argThat(instances -> CollectionUtils.isEqualCollection(instanceList, instances))); } - + @Test void testBatchRegisterInstanceWithWrongGroupNamePrefix() throws NacosException { Instance instance = new Instance(); @@ -187,7 +187,7 @@ void testBatchRegisterInstanceWithWrongGroupNamePrefix() throws NacosException { assertTrue(e.getMessage().contains("wrong group name prefix of instance service name")); } } - + @Test void testBatchDeRegisterInstance() throws NacosException { Instance instance = new Instance(); @@ -208,7 +208,7 @@ void testBatchDeRegisterInstance() throws NacosException { assertTrue(e.getMessage().contains("not found")); } } - + @Test void testRegisterInstance2() throws NacosException { //given @@ -224,7 +224,7 @@ void testRegisterInstance2() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(Constants.DEFAULT_CLUSTER_NAME))); } - + @Test void testRegisterInstance3() throws NacosException { //given @@ -240,7 +240,7 @@ void testRegisterInstance3() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(clusterName))); } - + @Test void testRegisterInstance4() throws NacosException { //given @@ -257,7 +257,7 @@ void testRegisterInstance4() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(clusterName))); } - + @Test void testRegisterInstance5() throws NacosException { //given @@ -268,7 +268,7 @@ void testRegisterInstance5() throws NacosException { //then verify(proxy, times(1)).registerService(serviceName, Constants.DEFAULT_GROUP, instance); } - + @Test void testRegisterInstance6() throws NacosException { //given @@ -280,11 +280,11 @@ void testRegisterInstance6() throws NacosException { //then verify(proxy, times(1)).registerService(serviceName, groupName, instance); } - + @Test void testRegisterInstance7() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { - + //given String serviceName = "service1"; String groupName = "group1"; @@ -293,9 +293,10 @@ void testRegisterInstance7() throws NacosException { //when client.registerInstance(serviceName, groupName, instance); }); - assertTrue(exception.getMessage().contains("Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)")); + assertTrue(exception.getMessage().contains( + "Instance 'clusterName' should be characters with only 0-9a-zA-Z-. (current: cluster1,cluster2)")); } - + @Test void testDeregisterInstance1() throws NacosException { //given @@ -310,7 +311,7 @@ void testDeregisterInstance1() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(Constants.DEFAULT_CLUSTER_NAME))); } - + @Test void testDeregisterInstance2() throws NacosException { //given @@ -326,7 +327,7 @@ void testDeregisterInstance2() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(Constants.DEFAULT_CLUSTER_NAME))); } - + @Test void testDeregisterInstance3() throws NacosException { //given @@ -342,7 +343,7 @@ void testDeregisterInstance3() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(clusterName))); } - + @Test void testDeregisterInstance4() throws NacosException { //given @@ -359,7 +360,7 @@ void testDeregisterInstance4() throws NacosException { && Math.abs(instance.getWeight() - 1.0) < 0.01f && instance.getClusterName() .equals(clusterName))); } - + @Test void testDeregisterInstance5() throws NacosException { //given @@ -370,7 +371,7 @@ void testDeregisterInstance5() throws NacosException { //then verify(proxy, times(1)).deregisterService(serviceName, Constants.DEFAULT_GROUP, instance); } - + @Test void testDeregisterInstance6() throws NacosException { //given @@ -382,7 +383,7 @@ void testDeregisterInstance6() throws NacosException { //then verify(proxy, times(1)).deregisterService(serviceName, groupName, instance); } - + @Test void testGetAllInstances1() throws NacosException { //given @@ -392,7 +393,7 @@ void testGetAllInstances1() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, ""); } - + @Test void testGetAllInstances2() throws NacosException { //given @@ -403,7 +404,7 @@ void testGetAllInstances2() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, groupName, ""); } - + @Test void testGetAllInstances3() throws NacosException { //given @@ -413,7 +414,7 @@ void testGetAllInstances3() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "", false); } - + @Test void testGetAllInstances4() throws NacosException { //given @@ -425,7 +426,7 @@ void testGetAllInstances4() throws NacosException { verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "", false); } - + @Test void testGetAllInstances5() throws NacosException { //given @@ -436,7 +437,7 @@ void testGetAllInstances5() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } - + @Test void testGetAllInstances6() throws NacosException { //given @@ -449,7 +450,7 @@ void testGetAllInstances6() throws NacosException { verify(proxy, times(1)).subscribe(serviceName, groupName, "cluster1,cluster2"); } - + @Test void testGetAllInstances7() throws NacosException { //given @@ -458,10 +459,10 @@ void testGetAllInstances7() throws NacosException { //when client.getAllInstances(serviceName, clusterList, false); //then - verify(proxy, times(1)) - .queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false); + verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", + false); } - + @Test void testGetAllInstances8() throws NacosException { //given @@ -473,7 +474,7 @@ void testGetAllInstances8() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "cluster1,cluster2", false); } - + @Test void testGetAllInstanceFromFailover() throws NacosException { when(serviceInfoHolder.isFailoverSwitch()).thenReturn(true); @@ -485,7 +486,7 @@ void testGetAllInstanceFromFailover() throws NacosException { assertEquals(1, actual.size()); assertEquals(new Instance(), actual.get(0)); } - + @Test void testGetAllInstanceFromFailoverEmpty() throws NacosException { when(serviceInfoHolder.isFailoverSwitch()).thenReturn(true); @@ -495,7 +496,7 @@ void testGetAllInstanceFromFailoverEmpty() throws NacosException { verify(proxy).queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean()); assertEquals(0, actual.size()); } - + @Test void testSelectInstances1() throws NacosException { //given @@ -505,7 +506,7 @@ void testSelectInstances1() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, ""); } - + @Test void testSelectInstances2() throws NacosException { //given @@ -516,7 +517,7 @@ void testSelectInstances2() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, groupName, ""); } - + @Test void testSelectInstances3() throws NacosException { //given @@ -526,7 +527,7 @@ void testSelectInstances3() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "", false); } - + @Test void testSelectInstances4() throws NacosException { //given @@ -538,7 +539,7 @@ void testSelectInstances4() throws NacosException { verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "", false); } - + @Test void testSelectInstances5() throws NacosException { //given @@ -549,7 +550,7 @@ void testSelectInstances5() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } - + @Test void testSelectInstances6() throws NacosException { //given @@ -562,7 +563,7 @@ void testSelectInstances6() throws NacosException { verify(proxy, times(1)).subscribe(serviceName, groupName, "cluster1,cluster2"); } - + @Test void testSelectInstances7() throws NacosException { //given @@ -571,10 +572,10 @@ void testSelectInstances7() throws NacosException { //when client.selectInstances(serviceName, clusterList, true, false); //then - verify(proxy, times(1)) - .queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false); + verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", + false); } - + @Test void testSelectInstances8() throws NacosException { //given @@ -586,7 +587,7 @@ void testSelectInstances8() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "cluster1,cluster2", false); } - + @Test void testSelectInstancesWithHealthyFlag() throws NacosException { //given @@ -622,7 +623,7 @@ void testSelectInstancesWithHealthyFlag() throws NacosException { assertEquals(1, instances.size()); assertSame(healthyInstance, instances.get(0)); } - + @Test void testSelectOneHealthyInstance1() throws NacosException { //given @@ -641,7 +642,7 @@ void testSelectOneHealthyInstance1() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, ""); } - + @Test void testSelectOneHealthyInstance2() throws NacosException { //given @@ -661,7 +662,7 @@ void testSelectOneHealthyInstance2() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, groupName, ""); } - + @Test void testSelectOneHealthyInstance3() throws NacosException { //given @@ -672,8 +673,8 @@ void testSelectOneHealthyInstance3() throws NacosException { hosts.add(healthyInstance); ServiceInfo infoWithHealthyInstance = new ServiceInfo(); infoWithHealthyInstance.setHosts(hosts); - when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())) - .thenReturn(infoWithHealthyInstance); + when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn( + infoWithHealthyInstance); String serviceName = "service1"; //when @@ -681,7 +682,7 @@ void testSelectOneHealthyInstance3() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "", false); } - + @Test void testSelectOneHealthyInstance4() throws NacosException { //given @@ -692,8 +693,8 @@ void testSelectOneHealthyInstance4() throws NacosException { hosts.add(healthyInstance); ServiceInfo infoWithHealthyInstance = new ServiceInfo(); infoWithHealthyInstance.setHosts(hosts); - when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())) - .thenReturn(infoWithHealthyInstance); + when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn( + infoWithHealthyInstance); String serviceName = "service1"; String groupName = "group1"; @@ -703,7 +704,7 @@ void testSelectOneHealthyInstance4() throws NacosException { verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "", false); } - + @Test void testSelectOneHealthyInstance5() throws NacosException { //given @@ -723,7 +724,7 @@ void testSelectOneHealthyInstance5() throws NacosException { //then verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } - + @Test void testSelectOneHealthyInstance6() throws NacosException { //given @@ -745,7 +746,7 @@ void testSelectOneHealthyInstance6() throws NacosException { verify(proxy, times(1)).subscribe(serviceName, groupName, "cluster1,cluster2"); } - + @Test void testSelectOneHealthyInstance7() throws NacosException { //given @@ -756,18 +757,18 @@ void testSelectOneHealthyInstance7() throws NacosException { hosts.add(healthyInstance); ServiceInfo infoWithHealthyInstance = new ServiceInfo(); infoWithHealthyInstance.setHosts(hosts); - when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())) - .thenReturn(infoWithHealthyInstance); + when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn( + infoWithHealthyInstance); String serviceName = "service1"; List clusterList = Arrays.asList("cluster1", "cluster2"); //when client.selectOneHealthyInstance(serviceName, clusterList, false); //then - verify(proxy, times(1)) - .queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", false); + verify(proxy, times(1)).queryInstancesOfService(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2", + false); } - + @Test void testSelectOneHealthyInstance8() throws NacosException { //given @@ -778,8 +779,8 @@ void testSelectOneHealthyInstance8() throws NacosException { hosts.add(healthyInstance); ServiceInfo infoWithHealthyInstance = new ServiceInfo(); infoWithHealthyInstance.setHosts(hosts); - when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())) - .thenReturn(infoWithHealthyInstance); + when(proxy.queryInstancesOfService(anyString(), anyString(), anyString(), anyBoolean())).thenReturn( + infoWithHealthyInstance); String serviceName = "service1"; String groupName = "group1"; @@ -789,7 +790,7 @@ void testSelectOneHealthyInstance8() throws NacosException { //then verify(proxy, times(1)).queryInstancesOfService(serviceName, groupName, "cluster1,cluster2", false); } - + @Test void testSubscribe1() throws NacosException { //given @@ -803,7 +804,7 @@ void testSubscribe1() throws NacosException { verify(changeNotifier, times(1)).registerListener(Constants.DEFAULT_GROUP, serviceName, "", listener); verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, ""); } - + @Test void testSubscribe2() throws NacosException { //given @@ -818,7 +819,7 @@ void testSubscribe2() throws NacosException { verify(changeNotifier, times(1)).registerListener(groupName, serviceName, "", listener); verify(proxy, times(1)).subscribe(serviceName, groupName, ""); } - + @Test void testSubscribe3() throws NacosException { //given @@ -830,11 +831,11 @@ void testSubscribe3() throws NacosException { //when client.subscribe(serviceName, clusterList, listener); //then - verify(changeNotifier, times(1)) - .registerListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", listener); + verify(changeNotifier, times(1)).registerListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", + listener); verify(proxy, times(1)).subscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } - + @Test void testSubscribe4() throws NacosException { //given @@ -850,7 +851,7 @@ void testSubscribe4() throws NacosException { verify(changeNotifier, times(1)).registerListener(groupName, serviceName, "cluster1,cluster2", listener); verify(proxy, times(1)).subscribe(serviceName, groupName, "cluster1,cluster2"); } - + @Test void testSubscribeWithNullListener() throws NacosException { String serviceName = "service1"; @@ -862,7 +863,7 @@ void testSubscribeWithNullListener() throws NacosException { verify(proxy, never()).subscribe(serviceName, groupName, ""); } - + @Test void testUnSubscribe1() throws NacosException { //given @@ -875,7 +876,7 @@ void testUnSubscribe1() throws NacosException { verify(changeNotifier, times(1)).deregisterListener(Constants.DEFAULT_GROUP, serviceName, "", listener); verify(proxy, times(1)).unsubscribe(serviceName, Constants.DEFAULT_GROUP, ""); } - + @Test void testUnSubscribe2() throws NacosException { //given @@ -889,7 +890,7 @@ void testUnSubscribe2() throws NacosException { verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, "", listener); verify(proxy, times(1)).unsubscribe(serviceName, groupName, ""); } - + @Test void testUnSubscribe3() throws NacosException { //given @@ -900,11 +901,11 @@ void testUnSubscribe3() throws NacosException { }; client.unsubscribe(serviceName, clusterList, listener); //then - verify(changeNotifier, times(1)) - .deregisterListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", listener); + verify(changeNotifier, times(1)).deregisterListener(Constants.DEFAULT_GROUP, serviceName, "cluster1,cluster2", + listener); verify(proxy, times(1)).unsubscribe(serviceName, Constants.DEFAULT_GROUP, "cluster1,cluster2"); } - + @Test void testUnSubscribe4() throws NacosException { //given @@ -919,7 +920,7 @@ void testUnSubscribe4() throws NacosException { verify(changeNotifier, times(1)).deregisterListener(groupName, serviceName, "cluster1,cluster2", listener); verify(proxy, times(1)).unsubscribe(serviceName, groupName, "cluster1,cluster2"); } - + @Test void testGetServicesOfServer1() throws NacosException { //given @@ -930,7 +931,7 @@ void testGetServicesOfServer1() throws NacosException { //then verify(proxy, times(1)).getServiceList(pageNo, pageSize, Constants.DEFAULT_GROUP, null); } - + @Test void testGetServicesOfServer2() throws NacosException { //given @@ -942,7 +943,7 @@ void testGetServicesOfServer2() throws NacosException { //then verify(proxy, times(1)).getServiceList(pageNo, pageSize, groupName, null); } - + @Test void testGetServicesOfServer3() throws NacosException { //given @@ -959,7 +960,7 @@ public String getType() { //then verify(proxy, times(1)).getServiceList(pageNo, pageSize, Constants.DEFAULT_GROUP, selector); } - + @Test void testGetServicesOfServer4() throws NacosException { //given @@ -978,7 +979,7 @@ public String getType() { //then verify(proxy, times(1)).getServiceList(pageNo, pageSize, groupName, selector); } - + @Test void testGetSubscribeServices() { //when @@ -986,7 +987,7 @@ void testGetSubscribeServices() { //then verify(changeNotifier, times(1)).getSubscribeServices(); } - + @Test void testGetServerStatus() { //given @@ -996,7 +997,7 @@ void testGetServerStatus() { //then assertEquals("UP", serverStatus); } - + @Test void testGetServerStatusFail() { //given @@ -1006,7 +1007,7 @@ void testGetServerStatusFail() { //then assertEquals("DOWN", serverStatus); } - + @Test void testShutDown() throws NacosException { //when @@ -1014,7 +1015,7 @@ void testShutDown() throws NacosException { //then verify(proxy, times(1)).shutdown(); } - + @Test void testConstructorWithServerList() throws NacosException, NoSuchFieldException, IllegalAccessException { NacosNamingService namingService = new NacosNamingService("localhost"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java index a74e6c1383b..8c480ada321 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/backups/FailoverReactorTest.java @@ -53,7 +53,7 @@ class FailoverReactorTest { FailoverDataSource failoverDataSource; FailoverReactor failoverReactor; - + @BeforeEach void setUp() throws NoSuchFieldException, IllegalAccessException { failoverReactor = new FailoverReactor(holder, UUID.randomUUID().toString()); @@ -61,24 +61,24 @@ void setUp() throws NoSuchFieldException, IllegalAccessException { failoverDataSourceField.setAccessible(true); failoverDataSourceField.set(failoverReactor, failoverDataSource); } - + @AfterEach void tearDown() throws NacosException { failoverReactor.shutdown(); } - + @Test void testIsFailoverSwitch() throws NacosException { assertFalse(failoverReactor.isFailoverSwitch()); } - + @Test void testGetService() throws NacosException { ServiceInfo info = failoverReactor.getService("aa@@bb"); assertEquals(new ServiceInfo("aa@@bb").toString(), info.toString()); } - + @Test void testRefreshFromDisabledToEnabled() throws InterruptedException { // make sure the first no delay refresh thread finished. @@ -95,7 +95,7 @@ void testRefreshFromDisabledToEnabled() throws InterruptedException { ServiceInfo actual = failoverReactor.getService("a@@b"); assertEquals(serviceInfo, actual); } - + @Test void testRefreshFromDisabledToEnabledWithException() throws InterruptedException { // make sure the first no delay refresh thread finished. @@ -107,10 +107,9 @@ void testRefreshFromDisabledToEnabledWithException() throws InterruptedException TimeUnit.MILLISECONDS.sleep(5500); assertTrue(((Map) ReflectUtils.getFieldValue(failoverDataSource, "serviceMap", new HashMap<>())).isEmpty()); } - + @Test - void testRefreshFromEnabledToDisabled() - throws InterruptedException, NoSuchFieldException, IllegalAccessException { + void testRefreshFromEnabledToDisabled() throws InterruptedException, NoSuchFieldException, IllegalAccessException { // make sure the first no delay refresh thread finished. TimeUnit.MILLISECONDS.sleep(500); FailoverSwitch mockFailoverSwitch = new FailoverSwitch(false); @@ -131,7 +130,7 @@ void testRefreshFromEnabledToDisabled() ServiceInfo actual = failoverReactor.getService("a@@b"); assertNotEquals(serviceInfo, actual); } - + @Test void testFailoverServiceCntMetrics() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { @@ -140,7 +139,7 @@ void testFailoverServiceCntMetrics() method.invoke(failoverReactor); // No exception } - + @Test void testFailoverServiceCntMetricsClear() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException { diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java index 4a958263e71..e839e815b79 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/backups/datasource/DiskFailoverDataSourceTest.java @@ -32,18 +32,18 @@ class DiskFailoverDataSourceTest { DiskFailoverDataSource dataSource; - + @BeforeEach void setUp() { dataSource = new DiskFailoverDataSource(); } - + @Test void testGetSwitchWithNonExistFailoverSwitchFile() { FailoverSwitch actual = dataSource.getSwitch(); assertFalse(actual.getEnabled()); } - + @Test void testGetSwitchForFailoverDisabled() throws NoSuchFieldException, IllegalAccessException { String dir = DiskFailoverDataSourceTest.class.getResource("/").getPath() + "/failover_test/disabled"; @@ -52,7 +52,7 @@ void testGetSwitchForFailoverDisabled() throws NoSuchFieldException, IllegalAcce Map actual = dataSource.getFailoverData(); assertTrue(actual.isEmpty()); } - + @Test void testGetSwitchForFailoverEnabled() throws NoSuchFieldException, IllegalAccessException { String dir = DiskFailoverDataSourceTest.class.getResource("/").getPath() + "/failover_test/enabled"; @@ -65,7 +65,7 @@ void testGetSwitchForFailoverEnabled() throws NoSuchFieldException, IllegalAcces assertEquals("1.1.1.1", ((ServiceInfo) actual.get("legal@@with_name@@file").getData()).getHosts().get(0).getIp()); } - + @Test void testGetFailoverDataForFailoverDisabled() { Map actual = dataSource.getFailoverData(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java index 31725e23663..a99fdda69de 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/cache/DiskCacheTest.java @@ -40,7 +40,7 @@ class DiskCacheTest { private ServiceInfo serviceInfo; private Instance instance; - + @BeforeEach void setUp() { System.out.println(CACHE_DIR); @@ -53,7 +53,7 @@ void setUp() { instance.addMetadata("chinese", "中文"); serviceInfo.setHosts(Collections.singletonList(instance)); } - + @AfterEach void tearDown() { File file = new File(CACHE_DIR); @@ -64,7 +64,7 @@ void tearDown() { file.delete(); } } - + @Test void testCache() { DiskCache.write(serviceInfo, CACHE_DIR); @@ -73,7 +73,7 @@ void testCache() { assertTrue(actual.containsKey(serviceInfo.getKey())); assertServiceInfo(actual.get(serviceInfo.getKey()), serviceInfo); } - + @Test void testWriteCacheWithErrorPath() { File file = new File(CACHE_DIR, serviceInfo.getKeyEncoded()); @@ -85,7 +85,7 @@ void testWriteCacheWithErrorPath() { file.delete(); } } - + @Test void testReadCacheForAllSituation() { String dir = DiskCacheTest.class.getResource("/").getPath() + "/disk_cache_test"; @@ -96,20 +96,20 @@ void testReadCacheForAllSituation() { assertTrue(actual.containsKey("legal@@with_name@@file")); assertEquals("1.1.1.1", actual.get("legal@@with_name@@file").getHosts().get(0).getIp()); } - + @Test void testReadCacheForNullFile() { Map actual = DiskCache.read(null); assertTrue(actual.isEmpty()); } - + @Test void testParseServiceInfoFromNonExistFile() throws UnsupportedEncodingException { File file = new File("non%40%40exist%40%40file"); Map actual = DiskCache.parseServiceInfoFromCache(file); assertTrue(actual.isEmpty()); } - + @Test void testCreateFileIfAbsentForDir() throws Throwable { assertThrows(IllegalStateException.class, () -> { @@ -117,7 +117,7 @@ void testCreateFileIfAbsentForDir() throws Throwable { DiskCache.createFileIfAbsent(file, true); }); } - + @Test void testCreateFileIfAbsentForFile() throws Throwable { assertThrows(IllegalStateException.class, () -> { @@ -150,7 +150,7 @@ private void assertInstance(Instance actual, Instance expected) { assertEquals(actual.getPort(), expected.getPort()); assertEquals(actual.getMetadata(), expected.getMetadata()); } - + @Test void testGetLineSeparator() { String lineSeparator = DiskCache.getLineSeparator(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java index bfa1b694fff..ebfd6ec3c55 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/cache/ServiceInfoHolderTest.java @@ -45,18 +45,18 @@ class ServiceInfoHolderTest { NacosClientProperties nacosClientProperties; ServiceInfoHolder holder; - + @BeforeEach void setUp() throws Exception { nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(); holder = new ServiceInfoHolder("aa", "scope-001", nacosClientProperties); } - + @AfterEach void tearDown() throws Exception { } - + @Test void testGetServiceInfoMap() throws NoSuchFieldException, IllegalAccessException { assertEquals(0, holder.getServiceInfoMap().size()); @@ -64,7 +64,7 @@ void testGetServiceInfoMap() throws NoSuchFieldException, IllegalAccessException fieldNotifierEventScope.setAccessible(true); assertEquals("scope-001", fieldNotifierEventScope.get(holder)); } - + @Test void testProcessServiceInfo() { ServiceInfo info = new ServiceInfo("a@@b@@c"); @@ -97,7 +97,7 @@ private Instance createInstance(String ip, int port) { instance.setPort(port); return instance; } - + @Test void testProcessServiceInfo2() { String json = "{\"groupName\":\"a\",\"name\":\"b\",\"clusters\":\"c\"}"; @@ -107,7 +107,7 @@ void testProcessServiceInfo2() { expect.setJsonFromServer(json); assertEquals(expect.getKey(), actual.getKey()); } - + @Test void testProcessServiceInfoWithPushEmpty() throws NacosException { ServiceInfo oldInfo = new ServiceInfo("a@@b@@c"); @@ -130,12 +130,12 @@ void testProcessServiceInfoWithPushEmpty() throws NacosException { assertEquals(oldInfo.getKey(), actual.getKey()); assertEquals(2, actual.getHosts().size()); } - + @Test void testProcessNullServiceInfo() { assertNull(holder.processServiceInfo(new ServiceInfo())); } - + @Test void testProcessServiceInfoForOlder() { ServiceInfo info = new ServiceInfo("a@@b@@c"); @@ -152,7 +152,7 @@ void testProcessServiceInfoForOlder() { final ServiceInfo actual = holder.processServiceInfo(olderInfo); assertEquals(olderInfo, actual); } - + @Test void testGetServiceInfo() { ServiceInfo info = new ServiceInfo("a@@b@@c"); @@ -170,7 +170,7 @@ void testGetServiceInfo() { assertEquals(expect.getHosts().size(), actual.getHosts().size()); assertEquals(expect.getHosts().get(0), actual.getHosts().get(0)); } - + @Test void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessException { Field field = ServiceInfoHolder.class.getDeclaredField("failoverReactor"); @@ -183,7 +183,7 @@ void testShutdown() throws NacosException, NoSuchFieldException, IllegalAccessEx holder.shutdown(); assertTrue(pool.isShutdown()); } - + @Test void testConstructWithCacheLoad() throws NacosException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START, "true"); @@ -193,14 +193,14 @@ void testConstructWithCacheLoad() throws NacosException { assertEquals(System.getProperty("user.home") + "/nacos/non-exist/naming/aa", holder.getCacheDir()); assertTrue(holder.getServiceInfoMap().isEmpty()); } - + @Test void testIsFailoverSwitch() throws IllegalAccessException, NoSuchFieldException, NacosException { FailoverReactor mock = injectMockFailoverReactor(); when(mock.isFailoverSwitch()).thenReturn(true); assertTrue(holder.isFailoverSwitch()); } - + @Test void testGetFailoverServiceInfo() throws IllegalAccessException, NoSuchFieldException, NacosException { FailoverReactor mock = injectMockFailoverReactor(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java index 542e354eea7..a26652cfe3a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/BalancerTest.java @@ -29,13 +29,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class BalancerTest { - + @Test void testGetHostByRandomWeightNull() { assertNull(Balancer.getHostByRandomWeight(null)); assertNull(Balancer.getHostByRandomWeight(new ArrayList<>())); } - + @Test void testGetHostByRandomWeight() { List list = new ArrayList<>(); @@ -44,7 +44,7 @@ void testGetHostByRandomWeight() { final Instance actual = Balancer.getHostByRandomWeight(list); assertEquals(instance1, actual); } - + @Test void testSelectHost() { List hosts = new ArrayList<>(); @@ -56,12 +56,12 @@ void testSelectHost() { final Instance actual = Balancer.RandomByWeight.selectHost(serviceInfo); assertEquals(instance1, actual); } - + @Test void testSelectHostEmpty() { Throwable exception = assertThrows(IllegalStateException.class, () -> { ServiceInfo serviceInfo = new ServiceInfo(); - + Balancer.RandomByWeight.selectHost(serviceInfo); }); assertTrue(exception.getMessage().contains("no host to srv for serviceInfo: null")); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java index 76b0d251b01..23951d6d5ff 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/ProtectModeTest.java @@ -21,13 +21,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class ProtectModeTest { - + @Test void testProtectThresholdDefault() { final ProtectMode protectMode = new ProtectMode(); assertEquals(0.8f, protectMode.getProtectThreshold(), 0.01f); } - + @Test void testSetProtectThreshold() { final ProtectMode protectMode = new ProtectMode(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java index b74aa685e73..3fadc114998 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServerListManagerTest.java @@ -64,15 +64,15 @@ class ServerListManagerTest { HttpRestResult httpRestResult; ServerListManager serverListManager; - + @BeforeEach void setUp() throws Exception { clientProperties = NacosClientProperties.PROTOTYPE.derive(); Field restMapField = HttpClientBeanHolder.class.getDeclaredField("SINGLETON_REST"); restMapField.setAccessible(true); Map restMap = (Map) restMapField.get(null); - cachedNacosRestTemplate = restMap - .get("com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory"); + cachedNacosRestTemplate = restMap.get( + "com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory"); restMap.put("com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory", nacosRestTemplate); httpRestResult = new HttpRestResult<>(); @@ -80,7 +80,7 @@ void setUp() throws Exception { httpRestResult.setCode(200); Mockito.when(nacosRestTemplate.get(any(), any(), any(), any())).thenReturn(httpRestResult); } - + @AfterEach void tearDown() throws Exception { if (null != cachedNacosRestTemplate) { @@ -94,14 +94,14 @@ void tearDown() throws Exception { serverListManager.shutdown(); } } - + @Test void testConstructError() { assertThrows(NacosLoadException.class, () -> { serverListManager = new ServerListManager(new Properties()); }); } - + @Test void testConstructWithAddr() { Properties properties = new Properties(); @@ -112,7 +112,7 @@ void testConstructWithAddr() { assertEquals("127.0.0.1:8848", serverList.get(0)); assertEquals("127.0.0.1:8849", serverList.get(1)); } - + @Test void testConstructWithAddrTryToRefresh() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException { @@ -129,7 +129,7 @@ void testConstructWithAddrTryToRefresh() assertEquals("127.0.0.1:8848", serverList.get(0)); assertEquals("127.0.0.1:8849", serverList.get(1)); } - + @Test void testConstructWithEndpointAndRefresh() throws Exception { Properties properties = new Properties(); @@ -146,7 +146,7 @@ void testConstructWithEndpointAndRefresh() throws Exception { assertEquals("127.0.0.1:8848", serverList.get(0)); assertEquals("127.0.0.1:8948", serverList.get(1)); } - + @Test void testConstructWithEndpointAndTimedNotNeedRefresh() throws Exception { Properties properties = new Properties(); @@ -162,7 +162,7 @@ void testConstructWithEndpointAndTimedNotNeedRefresh() throws Exception { assertEquals(1, serverList.size()); assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test void testConstructWithEndpointAndRefreshEmpty() throws Exception { Properties properties = new Properties(); @@ -178,7 +178,7 @@ void testConstructWithEndpointAndRefreshEmpty() throws Exception { assertEquals(1, serverList.size()); assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test void testConstructWithEndpointAndRefreshException() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException { @@ -195,7 +195,7 @@ void testConstructWithEndpointAndRefreshException() assertEquals(1, serverList.size()); assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test void testConstructWithEndpointWithCustomPathAndName() throws Exception { clientProperties.setProperty(PropertyKeyConst.CONTEXT_PATH, "aaa"); @@ -209,7 +209,7 @@ void testConstructWithEndpointWithCustomPathAndName() throws Exception { assertEquals(1, serverList.size()); assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test void testConstructWithEndpointWithEndpointPathAndName() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, "aaa"); @@ -223,7 +223,7 @@ void testConstructWithEndpointWithEndpointPathAndName() throws Exception { assertEquals(1, serverList.size()); assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test void testConstructEndpointContextPathPriority() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, "aaa"); @@ -238,7 +238,7 @@ void testConstructEndpointContextPathPriority() throws Exception { assertEquals(1, serverList.size()); assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test void testConstructEndpointContextPathIsEmpty() throws Exception { clientProperties.setProperty(PropertyKeyConst.ENDPOINT_CONTEXT_PATH, ""); @@ -253,7 +253,7 @@ void testConstructEndpointContextPathIsEmpty() throws Exception { assertEquals(1, serverList.size()); assertEquals("127.0.0.1:8848", serverList.get(0)); } - + @Test void testIsDomain() throws IOException { Properties properties = new Properties(); @@ -262,7 +262,7 @@ void testIsDomain() throws IOException { assertTrue(serverListManager.isDomain()); assertEquals("127.0.0.1:8848", serverListManager.getNacosDomain()); } - + @Test void testGetCurrentServer() { Properties properties = new Properties(); @@ -271,7 +271,7 @@ void testGetCurrentServer() { assertEquals("127.0.0.1:8848", serverListManager.getCurrentServer()); assertEquals("127.0.0.1:8848", serverListManager.genNextServer()); } - + @Test void testShutdown() { Properties properties = new Properties(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java index 74e99dbc8ce..f6833d7d5ef 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/core/ServiceInfoUpdateServiceTest.java @@ -70,7 +70,7 @@ class ServiceInfoUpdateServiceTest { ServiceInfo info; ServiceInfoUpdateService serviceInfoUpdateService; - + @BeforeEach void setUp() throws Exception { nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(); @@ -81,14 +81,14 @@ void setUp() throws Exception { info.setLastRefTime(System.currentTimeMillis()); when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenReturn(info); } - + @AfterEach void tearDown() throws Exception { if (null != serviceInfoUpdateService) { serviceInfoUpdateService.shutdown(); } } - + @Test void testScheduleUpdateWithoutOpen() throws InterruptedException, NacosException { serviceInfoUpdateService = new ServiceInfoUpdateService(null, holder, proxy, notifier); @@ -96,7 +96,7 @@ void testScheduleUpdateWithoutOpen() throws InterruptedException, NacosException TimeUnit.MILLISECONDS.sleep(1500); Mockito.verify(proxy, Mockito.never()).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test void testScheduleUpdateIfAbsent() throws InterruptedException, NacosException { info.setCacheMillis(10000L); @@ -106,7 +106,7 @@ void testScheduleUpdateIfAbsent() throws InterruptedException, NacosException { TimeUnit.MILLISECONDS.sleep(1500); Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, NacosException { info.setCacheMillis(10000L); @@ -118,7 +118,7 @@ void testScheduleUpdateIfAbsentDuplicate() throws InterruptedException, NacosExc // Only once called Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test void testScheduleUpdateIfAbsentUpdateOlder() throws InterruptedException, NacosException { info.setCacheMillis(10000L); @@ -131,7 +131,7 @@ void testScheduleUpdateIfAbsentUpdateOlder() throws InterruptedException, NacosE TimeUnit.MILLISECONDS.sleep(1500); Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws InterruptedException, NacosException { info.setCacheMillis(10000L); @@ -145,43 +145,43 @@ void testScheduleUpdateIfAbsentUpdateOlderWithInstance() throws InterruptedExcep TimeUnit.MILLISECONDS.sleep(1500); Mockito.verify(proxy).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test void testScheduleUpdateIfAbsentWith403Exception() throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters); - when(proxy.queryInstancesOfService(serviceName, group, clusters, false)) - .thenThrow(new NacosException(403, "test")); + when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenThrow( + new NacosException(403, "test")); TimeUnit.MILLISECONDS.sleep(1500); assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 1000); } - + @Test void testScheduleUpdateIfAbsentWith500Exception() throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters); - when(proxy.queryInstancesOfService(serviceName, group, clusters, false)) - .thenThrow(new NacosException(500, "test")); + when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenThrow( + new NacosException(500, "test")); TimeUnit.MILLISECONDS.sleep(1500); assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 2000); } - + @Test void testScheduleUpdateIfAbsentWithOtherException() throws InterruptedException, NacosException, NoSuchFieldException, IllegalAccessException { nacosClientProperties.setProperty(PropertyKeyConst.NAMING_ASYNC_QUERY_SUBSCRIBE_SERVICE, "true"); serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); serviceInfoUpdateService.scheduleUpdateIfAbsent(serviceName, group, clusters); - when(proxy.queryInstancesOfService(serviceName, group, clusters, false)) - .thenThrow(new RuntimeException("test")); + when(proxy.queryInstancesOfService(serviceName, group, clusters, false)).thenThrow( + new RuntimeException("test")); TimeUnit.MILLISECONDS.sleep(1500); assertTrue(getScheduleFuture().getDelay(TimeUnit.MILLISECONDS) > 1000); } - + @Test void testStopScheduleUpdateIfAbsent() throws InterruptedException, NacosException { info.setCacheMillis(10000L); @@ -192,7 +192,7 @@ void testStopScheduleUpdateIfAbsent() throws InterruptedException, NacosExceptio TimeUnit.MILLISECONDS.sleep(1500); Mockito.verify(proxy, Mockito.never()).queryInstancesOfService(serviceName, group, clusters, false); } - + @Test void testStopUpdateIfContainWithoutOpen() throws NacosException, InterruptedException { serviceInfoUpdateService = new ServiceInfoUpdateService(nacosClientProperties, holder, proxy, notifier); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java index ba0e869c6ab..4f22b4af69b 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeEventTest.java @@ -25,7 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class InstancesChangeEventTest { - + @Test void testGetServiceName() { String eventScope = "scope-001"; diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java index ef9aa6e7b36..b8eeb9496e4 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/event/InstancesChangeNotifierTest.java @@ -37,7 +37,7 @@ import static org.mockito.Mockito.when; class InstancesChangeNotifierTest { - + @Test void testRegisterListener() { String eventScope = "scope-001"; @@ -59,7 +59,7 @@ void testRegisterListener() { InstancesChangeEvent event = new InstancesChangeEvent(eventScope, name, group, clusters, hosts); assertTrue(instancesChangeNotifier.scopeMatches(event)); } - + @Test void testDeregisterListener() { String eventScope = "scope-001"; @@ -80,7 +80,7 @@ void testDeregisterListener() { instancesChangeNotifier.deregisterListener(group, name, clusters, listener); assertEquals(0, subscribeServices2.size()); } - + @Test void testIsSubscribed() { String eventScope = "scope-001"; @@ -94,7 +94,7 @@ void testIsSubscribed() { instancesChangeNotifier.registerListener(group, name, clusters, listener); assertTrue(instancesChangeNotifier.isSubscribed(group, name, clusters)); } - + @Test void testOnEvent() { String eventScope = "scope-001"; @@ -113,7 +113,7 @@ void testOnEvent() { instancesChangeNotifier.onEvent(event1); Mockito.verify(listener, times(1)).onEvent(any()); } - + @Test void testOnEventWithoutListener() { String eventScope = "scope-001"; @@ -130,7 +130,7 @@ void testOnEventWithoutListener() { instancesChangeNotifier.onEvent(event1); Mockito.verify(listener, never()).onEvent(any()); } - + @Test void testOnEventByExecutor() { String eventScope = "scope-001"; @@ -151,7 +151,7 @@ void testOnEventByExecutor() { instancesChangeNotifier.onEvent(event1); Mockito.verify(executor).execute(any()); } - + @Test void testSubscribeType() { String eventScope = "scope-001"; diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java index 9dfda183f22..b2b60a68d30 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java @@ -50,7 +50,7 @@ class AbstractNamingClientProxyTest { @Mock private SecurityProxy sc; - + /** * test get security headers for accessToken. */ @@ -66,7 +66,7 @@ void testGetSecurityHeadersForAccessToken() { assertEquals(token, securityHeaders.get(Constants.ACCESS_TOKEN)); assertEquals(AppNameUtils.getAppName(), securityHeaders.get("app")); } - + /** * get security headers for ram. * diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java index 94a4b887bf5..bdc3ac6cec1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/NamingClientProxyDelegateTest.java @@ -70,7 +70,7 @@ class NamingClientProxyDelegateTest { InstancesChangeNotifier notifier; NacosClientProperties nacosClientProperties; - + @BeforeEach void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { Properties props = new Properties(); @@ -82,12 +82,12 @@ void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException grpcClientProxyField.setAccessible(true); grpcClientProxyField.set(delegate, mockGrpcClient); } - + @AfterEach void tearDown() throws NacosException { delegate.shutdown(); } - + @Test void testRegisterEphemeralServiceByGrpc() throws NacosException { String serviceName = "service1"; @@ -101,7 +101,7 @@ void testRegisterEphemeralServiceByGrpc() throws NacosException { delegate.registerService(serviceName, groupName, instance); verify(mockGrpcClient, times(1)).registerService(serviceName, groupName, instance); } - + @Test void testBatchRegisterServiceByGrpc() throws NacosException { String serviceName = "service1"; @@ -116,7 +116,7 @@ void testBatchRegisterServiceByGrpc() throws NacosException { delegate.batchRegisterService(serviceName, groupName, instanceList); verify(mockGrpcClient, times(1)).batchRegisterService(serviceName, groupName, instanceList); } - + @Test void testBatchDeregisterServiceByGrpc() throws NacosException { String serviceName = "service1"; @@ -129,7 +129,7 @@ void testBatchDeregisterServiceByGrpc() throws NacosException { delegate.batchDeregisterService(serviceName, groupName, instanceList); verify(mockGrpcClient, times(1)).batchDeregisterService(serviceName, groupName, instanceList); } - + @Test void testRegisterPersistentServiceByGrpc() throws NacosException { String serviceName = "service1"; @@ -142,15 +142,14 @@ void testRegisterPersistentServiceByGrpc() throws NacosException { // persistent instance instance.setEphemeral(false); // when server support register persistent instance by grpc, will use grpc to register - when(mockGrpcClient.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(true); + when(mockGrpcClient.isAbilitySupportedByServer( + AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn(true); delegate.registerService(serviceName, groupName, instance); verify(mockGrpcClient, times(1)).registerService(serviceName, groupName, instance); } - + @Test - void testRegisterPersistentServiceByHttp() - throws NacosException, NoSuchFieldException, IllegalAccessException { + void testRegisterPersistentServiceByHttp() throws NacosException, NoSuchFieldException, IllegalAccessException { NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class); Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy"); mockHttpClientField.setAccessible(true); @@ -169,7 +168,7 @@ void testRegisterPersistentServiceByHttp() delegate.registerService(serviceName, groupName, instance); verify(mockHttpClient, times(1)).registerService(serviceName, groupName, instance); } - + @Test void testDeregisterEphemeralServiceGrpc() throws NacosException { String serviceName = "service1"; @@ -184,7 +183,7 @@ void testDeregisterEphemeralServiceGrpc() throws NacosException { delegate.deregisterService(serviceName, groupName, instance); verify(mockGrpcClient, times(1)).deregisterService(serviceName, groupName, instance); } - + @Test void testDeregisterPersistentServiceGrpc() throws NacosException { String serviceName = "service1"; @@ -197,15 +196,14 @@ void testDeregisterPersistentServiceGrpc() throws NacosException { // persistent instance instance.setEphemeral(false); // when server support deregister persistent instance by grpc, will use grpc to deregister - when(mockGrpcClient.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(true); + when(mockGrpcClient.isAbilitySupportedByServer( + AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn(true); delegate.deregisterService(serviceName, groupName, instance); verify(mockGrpcClient, times(1)).deregisterService(serviceName, groupName, instance); } - + @Test - void testDeregisterPersistentServiceHttp() - throws NacosException, NoSuchFieldException, IllegalAccessException { + void testDeregisterPersistentServiceHttp() throws NacosException, NoSuchFieldException, IllegalAccessException { NamingHttpClientProxy mockHttpClient = Mockito.mock(NamingHttpClientProxy.class); Field mockHttpClientField = NamingClientProxyDelegate.class.getDeclaredField("httpClientProxy"); mockHttpClientField.setAccessible(true); @@ -223,7 +221,7 @@ void testDeregisterPersistentServiceHttp() delegate.deregisterService(serviceName, groupName, instance); verify(mockHttpClient, times(1)).deregisterService(serviceName, groupName, instance); } - + @Test void testUpdateInstance() { String serviceName = "service1"; @@ -233,7 +231,7 @@ void testUpdateInstance() { delegate.updateInstance(serviceName, groupName, instance); }); } - + @Test void testQueryInstancesOfService() throws NacosException { String serviceName = "service1"; @@ -242,13 +240,13 @@ void testQueryInstancesOfService() throws NacosException { delegate.queryInstancesOfService(serviceName, groupName, clusters, false); verify(mockGrpcClient, times(1)).queryInstancesOfService(serviceName, groupName, clusters, false); } - + @Test void testQueryService() throws NacosException { Service service = delegate.queryService("a", "b"); assertNull(service); } - + @Test void testCreateService() { Service service = new Service(); @@ -256,12 +254,12 @@ void testCreateService() { delegate.createService(service, new NoneSelector()); }); } - + @Test void testDeleteService() throws NacosException { assertFalse(delegate.deleteService("service", "group1")); } - + @Test void testUpdateService() { Service service = new Service(); @@ -269,7 +267,7 @@ void testUpdateService() { delegate.updateService(service, new ExpressionSelector()); }); } - + @Test void testGetServiceList() throws NacosException { AbstractSelector selector = new ExpressionSelector(); @@ -280,7 +278,7 @@ void testGetServiceList() throws NacosException { verify(mockGrpcClient, times(1)).getServiceList(pageNo, pageSize, groupName, selector); } - + @Test void testSubscribe() throws NacosException { String serviceName = "service1"; @@ -298,7 +296,7 @@ void testSubscribe() throws NacosException { verify(holder, times(1)).processServiceInfo(info); } - + @Test void testUnsubscribe() throws NacosException { String serviceName = "service1"; @@ -307,13 +305,13 @@ void testUnsubscribe() throws NacosException { delegate.unsubscribe(serviceName, groupName, clusters); verify(mockGrpcClient, times(1)).unsubscribe(serviceName, groupName, clusters); } - + @Test void testServerHealthy() { Mockito.when(mockGrpcClient.serverHealthy()).thenReturn(true); assertTrue(delegate.serverHealthy()); } - + @Test void testIsSubscribed() throws NacosException { String serviceName = "service1"; @@ -323,7 +321,7 @@ void testIsSubscribed() throws NacosException { when(mockGrpcClient.isSubscribed(serviceName, groupName, clusters)).thenReturn(true); assertTrue(delegate.isSubscribed(serviceName, groupName, clusters)); } - + @Test void testShutdown() throws NacosException { delegate.shutdown(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java index 34c90fd30cb..18b7f6ef3a1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingGrpcClientProxyTest.java @@ -134,7 +134,7 @@ class NamingGrpcClientProxyTest { private Instance persistentInstance; private String uuid; - + @BeforeEach void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { System.setProperty(GrpcConstants.GRPC_RETRY_TIMES, "1"); @@ -170,14 +170,14 @@ void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException persistentInstance.setPort(1111); persistentInstance.setEphemeral(false); } - + @AfterEach void tearDown() throws NacosException { System.clearProperty(GrpcConstants.GRPC_RETRY_TIMES); System.clearProperty(GrpcConstants.GRPC_SERVER_CHECK_TIMEOUT); client.shutdown(); } - + @Test void testRegisterService() throws NacosException { client.registerService(SERVICE_NAME, GROUP_NAME, instance); @@ -189,7 +189,7 @@ void testRegisterService() throws NacosException { return false; })); } - + @Test void testRegisterPersistentService() throws NacosException { client.registerService(SERVICE_NAME, GROUP_NAME, persistentInstance); @@ -201,41 +201,41 @@ void testRegisterPersistentService() throws NacosException { return false; })); } - + @Test void testRegisterServiceThrowsNacosException() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { - + when(this.rpcClient.request(Mockito.any())).thenReturn(ErrorResponse.build(400, "err args")); - + try { client.registerService(SERVICE_NAME, GROUP_NAME, instance); } catch (NacosException ex) { assertNull(ex.getCause()); - + throw ex; } }); assertTrue(exception.getMessage().contains("err args")); } - + @Test void testRegisterServiceThrowsException() throws NacosException { Throwable exception = assertThrows(NacosException.class, () -> { - + when(this.rpcClient.request(Mockito.any())).thenReturn(null); - + try { client.registerService(SERVICE_NAME, GROUP_NAME, instance); } catch (NacosException ex) { assertEquals(NullPointerException.class, ex.getCause().getClass()); - + throw ex; } }); assertTrue(exception.getMessage().contains("Request nacos server failed: ")); } - + @Test void testDeregisterService() throws NacosException { client.deregisterService(SERVICE_NAME, GROUP_NAME, instance); @@ -247,7 +247,7 @@ void testDeregisterService() throws NacosException { return false; })); } - + @Test void testDeregisterPersistentService() throws NacosException { client.deregisterService(SERVICE_NAME, GROUP_NAME, persistentInstance); @@ -259,7 +259,7 @@ void testDeregisterPersistentService() throws NacosException { return false; })); } - + @Test void testDeregisterServiceForBatchRegistered() throws NacosException { try { @@ -286,7 +286,7 @@ void testDeregisterServiceForBatchRegistered() throws NacosException { return false; })); } - + @Test void testBatchRegisterService() throws NacosException { List instanceList = new ArrayList<>(); @@ -304,14 +304,14 @@ void testBatchRegisterService() throws NacosException { return false; })); } - + @Test void testBatchDeregisterServiceWithEmptyInstances() throws NacosException { assertThrows(NacosException.class, () -> { client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, Collections.EMPTY_LIST); }); } - + @Test void testBatchDeregisterServiceWithoutCacheData() throws NacosException { assertThrows(NacosException.class, () -> { @@ -321,7 +321,7 @@ void testBatchDeregisterServiceWithoutCacheData() throws NacosException { client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); }); } - + @Test void testBatchDeregisterServiceNotBatchData() throws NacosException { assertThrows(NacosException.class, () -> { @@ -332,7 +332,7 @@ void testBatchDeregisterServiceNotBatchData() throws NacosException { client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); }); } - + @Test void testBatchDeregisterServiceWithEmptyBatchData() throws NacosException { assertThrows(NacosException.class, () -> { @@ -346,7 +346,7 @@ void testBatchDeregisterServiceWithEmptyBatchData() throws NacosException { client.batchDeregisterService(SERVICE_NAME, GROUP_NAME, instanceList); }); } - + @Test void testBatchDeregisterService() throws NacosException { try { @@ -373,7 +373,7 @@ void testBatchDeregisterService() throws NacosException { return false; })); } - + @Test void testBatchDeregisterServiceWithOtherPortInstance() throws NacosException { try { @@ -403,13 +403,13 @@ void testBatchDeregisterServiceWithOtherPortInstance() throws NacosException { return false; })); } - + @Test void testUpdateInstance() throws Exception { //TODO thrown.expect(UnsupportedOperationException.class); client.updateInstance(SERVICE_NAME, GROUP_NAME, instance); } - + @Test void testQueryInstancesOfService() throws Exception { QueryServiceResponse res = new QueryServiceResponse(); @@ -419,13 +419,13 @@ void testQueryInstancesOfService() throws Exception { ServiceInfo actual = client.queryInstancesOfService(SERVICE_NAME, GROUP_NAME, CLUSTERS, false); assertEquals(info, actual); } - + @Test void testQueryService() throws Exception { Service service = client.queryService(SERVICE_NAME, GROUP_NAME); assertNull(service); } - + @Test void testCreateService() throws Exception { //TODO thrown.expect(UnsupportedOperationException.class); @@ -433,13 +433,13 @@ void testCreateService() throws Exception { AbstractSelector selector = new NoneSelector(); client.createService(service, selector); } - + @Test void testDeleteService() throws Exception { //TODO thrown.expect(UnsupportedOperationException.class); assertFalse(client.deleteService(SERVICE_NAME, GROUP_NAME)); } - + @Test void testUpdateService() throws NacosException { //TODO thrown.expect(UnsupportedOperationException.class); @@ -447,7 +447,7 @@ void testUpdateService() throws NacosException { AbstractSelector selector = new NoneSelector(); client.updateService(service, selector); } - + @Test void testGetServiceList() throws Exception { ServiceListResponse res = new ServiceListResponse(); @@ -460,7 +460,7 @@ void testGetServiceList() throws Exception { assertEquals(5, serviceList.getCount()); assertEquals(services, serviceList.getData()); } - + @Test void testGetServiceListForLabelSelector() throws Exception { ServiceListResponse res = new ServiceListResponse(); @@ -473,7 +473,7 @@ void testGetServiceListForLabelSelector() throws Exception { assertEquals(5, serviceList.getCount()); assertEquals(services, serviceList.getData()); } - + @Test void testSubscribe() throws Exception { SubscribeServiceResponse res = new SubscribeServiceResponse(); @@ -483,7 +483,7 @@ void testSubscribe() throws Exception { ServiceInfo actual = client.subscribe(SERVICE_NAME, GROUP_NAME, CLUSTERS); assertEquals(info, actual); } - + @Test void testUnsubscribe() throws Exception { SubscribeServiceResponse res = new SubscribeServiceResponse(); @@ -496,14 +496,14 @@ void testUnsubscribe() throws Exception { SubscribeServiceRequest request1 = (SubscribeServiceRequest) request; // verify request fields - return !request1.isSubscribe() && SERVICE_NAME.equals(request1.getServiceName()) && GROUP_NAME - .equals(request1.getGroupName()) && CLUSTERS.equals(request1.getClusters()) && NAMESPACE_ID - .equals(request1.getNamespace()); + return !request1.isSubscribe() && SERVICE_NAME.equals(request1.getServiceName()) && GROUP_NAME.equals( + request1.getGroupName()) && CLUSTERS.equals(request1.getClusters()) && NAMESPACE_ID.equals( + request1.getNamespace()); } return false; })); } - + @Test void testIsSubscribed() throws NacosException { SubscribeServiceResponse res = new SubscribeServiceResponse(); @@ -514,53 +514,53 @@ void testIsSubscribed() throws NacosException { client.subscribe(SERVICE_NAME, GROUP_NAME, CLUSTERS); assertTrue(client.isSubscribed(SERVICE_NAME, GROUP_NAME, CLUSTERS)); } - + @Test void testServerHealthy() { when(this.rpcClient.isRunning()).thenReturn(true); assertTrue(client.serverHealthy()); verify(this.rpcClient, times(1)).isRunning(); } - + @Test void testIsAbilitySupportedByServer1() { - when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(AbilityStatus.SUPPORTED); + when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn( + AbilityStatus.SUPPORTED); assertTrue(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } - + @Test void testIsAbilitySupportedByServer2() { - when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(AbilityStatus.NOT_SUPPORTED); + when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn( + AbilityStatus.NOT_SUPPORTED); assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } - + @Test void testIsAbilitySupportedByServer3() { - when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(AbilityStatus.UNKNOWN); + when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn( + AbilityStatus.UNKNOWN); assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } - + @Test void testIsAbilitySupportedByServer4() { - when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)) - .thenReturn(null); + when(this.rpcClient.getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)).thenReturn( + null); assertFalse(client.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC)); verify(this.rpcClient, times(1)).getConnectionAbility(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC); } - + @Test void testShutdown() throws Exception { client.shutdown(); assertNull(RpcClientFactory.getClient(uuid)); //verify(this.rpcClient, times(1)).shutdown(); } - + @Test void testShutdownWithException() throws NoSuchFieldException, IllegalAccessException, NacosException { Field field = RpcClientFactory.class.getDeclaredField("CLIENT_MAP"); @@ -574,14 +574,14 @@ void testShutdownWithException() throws NoSuchFieldException, IllegalAccessExcep map.put(uuid, rpcClient); doThrow(new NacosException()).when(rpcClient).shutdown(); } - + @Test void testIsEnable() { when(this.rpcClient.isRunning()).thenReturn(true); assertTrue(client.isEnable()); verify(this.rpcClient, times(1)).isRunning(); } - + @Test void testServerListChanged() throws Exception { @@ -695,7 +695,7 @@ public void close() { assertEquals(newServer, rpc.getCurrentServer().getServerIp()); } - + @Test void testConfigAppNameLabels() throws Exception { final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java index 76c3191fab3..341c26e1dcd 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/NamingPushRequestHandlerTest.java @@ -36,7 +36,7 @@ import static org.mockito.Mockito.verify; class NamingPushRequestHandlerTest { - + @Test void testRequestReply() { //given @@ -50,12 +50,11 @@ void testRequestReply() { assertTrue(response instanceof NotifySubscriberResponse); verify(holder, times(1)).processServiceInfo(info); } - + @Test void testRequestReplyOtherType() { ServiceInfoHolder holder = mock(ServiceInfoHolder.class); NamingPushRequestHandler handler = new NamingPushRequestHandler(holder); - assertNull( - handler.requestReply(new HealthCheckRequest(), new TestConnection(new RpcClient.ServerInfo()))); + assertNull(handler.requestReply(new HealthCheckRequest(), new TestConnection(new RpcClient.ServerInfo()))); } } \ No newline at end of file diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java index 9583af4e086..61c31fc51ef 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/NamingGrpcRedoServiceTest.java @@ -18,8 +18,8 @@ import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.naming.pojo.Instance; -import com.alibaba.nacos.client.naming.remote.TestConnection; import com.alibaba.nacos.client.env.NacosClientProperties; +import com.alibaba.nacos.client.naming.remote.TestConnection; import com.alibaba.nacos.client.naming.remote.gprc.NamingGrpcClientProxy; import com.alibaba.nacos.client.naming.remote.gprc.redo.data.BatchInstanceRedoData; import com.alibaba.nacos.client.naming.remote.gprc.redo.data.InstanceRedoData; @@ -57,7 +57,7 @@ class NamingGrpcRedoServiceTest { private NamingGrpcClientProxy clientProxy; private NamingGrpcRedoService redoService; - + @BeforeEach void setUp() throws Exception { Properties prop = new Properties(); @@ -67,55 +67,55 @@ void setUp() throws Exception { "redoExecutor"); redoExecutor.shutdownNow(); } - + @AfterEach void tearDown() throws Exception { redoService.shutdown(); } - + @Test void testDefaultProperties() throws Exception { Field redoThreadCountField = NamingGrpcRedoService.class.getDeclaredField("redoThreadCount"); redoThreadCountField.setAccessible(true); - + Field redoDelayTimeField = NamingGrpcRedoService.class.getDeclaredField("redoDelayTime"); redoDelayTimeField.setAccessible(true); - + Long redoDelayTimeValue = (Long) redoDelayTimeField.get(redoService); Integer redoThreadCountValue = (Integer) redoThreadCountField.get(redoService); - + assertEquals(Long.valueOf(3000L), redoDelayTimeValue); assertEquals(Integer.valueOf(1), redoThreadCountValue); } - + @Test void testCustomProperties() throws Exception { Properties prop = new Properties(); prop.setProperty(PropertyKeyConst.REDO_DELAY_TIME, "4000"); prop.setProperty(PropertyKeyConst.REDO_DELAY_THREAD_COUNT, "2"); NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(prop); - + NamingGrpcRedoService redoService = new NamingGrpcRedoService(clientProxy, nacosClientProperties); - + Field redoThreadCountField = NamingGrpcRedoService.class.getDeclaredField("redoThreadCount"); redoThreadCountField.setAccessible(true); - + Field redoDelayTimeField = NamingGrpcRedoService.class.getDeclaredField("redoDelayTime"); redoDelayTimeField.setAccessible(true); - + Long redoDelayTimeValue = (Long) redoDelayTimeField.get(redoService); Integer redoThreadCountValue = (Integer) redoThreadCountField.get(redoService); assertEquals(Long.valueOf(4000L), redoDelayTimeValue); assertEquals(Integer.valueOf(2), redoThreadCountValue); } - + @Test void testOnConnected() { assertFalse(redoService.isConnected()); redoService.onConnected(new TestConnection(new RpcClient.ServerInfo())); assertTrue(redoService.isConnected()); } - + @Test void testOnDisConnect() { redoService.onConnected(new TestConnection(new RpcClient.ServerInfo())); @@ -131,7 +131,7 @@ void testOnDisConnect() { assertFalse(redoService.findInstanceRedoData().isEmpty()); assertFalse(redoService.findSubscriberRedoData().isEmpty()); } - + @Test void testCacheInstanceForRedo() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); @@ -147,7 +147,7 @@ void testCacheInstanceForRedo() { assertFalse(actual.isUnregistering()); assertTrue(actual.isExpectedRegistered()); } - + @Test void testCacheInstanceForRedoByBatchInstanceRedoData() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); @@ -165,7 +165,7 @@ void testCacheInstanceForRedoByBatchInstanceRedoData() { assertFalse(actual.isRegistered()); assertFalse(actual.isUnregistering()); } - + @Test void testInstanceRegistered() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); @@ -174,7 +174,7 @@ void testInstanceRegistered() { InstanceRedoData actual = registeredInstances.entrySet().iterator().next().getValue(); assertTrue(actual.isRegistered()); } - + @Test void testInstanceDeregister() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); @@ -184,7 +184,7 @@ void testInstanceDeregister() { assertTrue(actual.isUnregistering()); assertFalse(actual.isExpectedRegistered()); } - + @Test void testInstanceDeregistered() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); @@ -194,7 +194,7 @@ void testInstanceDeregistered() { assertFalse(actual.isRegistered()); assertTrue(actual.isUnregistering()); } - + @Test void testRemoveInstanceForRedo() { ConcurrentMap registeredInstances = getInstanceRedoDataMap(); @@ -205,7 +205,7 @@ void testRemoveInstanceForRedo() { redoService.removeInstanceForRedo(SERVICE, GROUP); assertTrue(registeredInstances.isEmpty()); } - + @Test void testFindInstanceRedoData() { redoService.cacheInstanceForRedo(SERVICE, GROUP, new Instance()); @@ -220,7 +220,7 @@ void testFindInstanceRedoData() { private ConcurrentMap getInstanceRedoDataMap() { return (ConcurrentMap) ReflectUtils.getFieldValue(redoService, "registeredInstances"); } - + @Test void testCacheSubscriberForRedo() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); @@ -234,7 +234,7 @@ void testCacheSubscriberForRedo() { assertFalse(actual.isRegistered()); assertFalse(actual.isUnregistering()); } - + @Test void testSubscriberRegistered() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); @@ -243,7 +243,7 @@ void testSubscriberRegistered() { SubscriberRedoData actual = subscribes.entrySet().iterator().next().getValue(); assertTrue(actual.isRegistered()); } - + @Test void testSubscriberDeregister() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); @@ -252,7 +252,7 @@ void testSubscriberDeregister() { SubscriberRedoData actual = subscribes.entrySet().iterator().next().getValue(); assertTrue(actual.isUnregistering()); } - + @Test void testIsSubscriberRegistered() { assertFalse(redoService.isSubscriberRegistered(SERVICE, GROUP, CLUSTER)); @@ -260,7 +260,7 @@ void testIsSubscriberRegistered() { redoService.subscriberRegistered(SERVICE, GROUP, CLUSTER); assertTrue(redoService.isSubscriberRegistered(SERVICE, GROUP, CLUSTER)); } - + @Test void testRemoveSubscriberForRedo() { ConcurrentMap subscribes = getSubscriberRedoDataMap(); @@ -271,7 +271,7 @@ void testRemoveSubscriberForRedo() { redoService.removeSubscriberForRedo(SERVICE, GROUP, CLUSTER); assertTrue(subscribes.isEmpty()); } - + @Test void testFindSubscriberRedoData() { redoService.cacheSubscriberForRedo(SERVICE, GROUP, CLUSTER); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java index 287b09db51a..de86b8bd5db 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/RedoScheduledTaskTest.java @@ -59,14 +59,14 @@ class RedoScheduledTaskTest { private NamingGrpcRedoService redoService; private RedoScheduledTask redoTask; - + @BeforeEach void setUp() throws Exception { redoTask = new RedoScheduledTask(clientProxy, redoService); when(clientProxy.isEnable()).thenReturn(true); when(redoService.isConnected()).thenReturn(true); } - + @Test void testRunRedoRegisterInstance() throws NacosException { Set mockData = generateMockInstanceData(false, false, true); @@ -74,11 +74,11 @@ void testRunRedoRegisterInstance() throws NacosException { redoTask.run(); verify(clientProxy).doRegisterService(SERVICE, GROUP, INSTANCE); } - + @Test void testRunRedoRegisterBatchInstance() throws NacosException { - BatchInstanceRedoData redoData = BatchInstanceRedoData - .build(SERVICE, GROUP, Collections.singletonList(INSTANCE)); + BatchInstanceRedoData redoData = BatchInstanceRedoData.build(SERVICE, GROUP, + Collections.singletonList(INSTANCE)); redoData.setRegistered(false); redoData.setUnregistering(false); redoData.setExpectedRegistered(true); @@ -88,7 +88,7 @@ void testRunRedoRegisterBatchInstance() throws NacosException { redoTask.run(); verify(clientProxy).doBatchRegisterService(SERVICE, GROUP, redoData.getInstances()); } - + @Test void testRunRedoDeregisterInstance() throws NacosException { Set mockData = generateMockInstanceData(true, true, false); @@ -96,7 +96,7 @@ void testRunRedoDeregisterInstance() throws NacosException { redoTask.run(); verify(clientProxy).doDeregisterService(SERVICE, GROUP, INSTANCE); } - + @Test void testRunRedoRemoveInstanceRedoData() throws NacosException { Set mockData = generateMockInstanceData(false, true, false); @@ -104,7 +104,7 @@ void testRunRedoRemoveInstanceRedoData() throws NacosException { redoTask.run(); verify(redoService).removeInstanceForRedo(SERVICE, GROUP); } - + @Test void testRunRedoRegisterInstanceWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); @@ -113,7 +113,7 @@ void testRunRedoRegisterInstanceWithClientDisabled() throws NacosException { redoTask.run(); verify(clientProxy, never()).doRegisterService(SERVICE, GROUP, INSTANCE); } - + @Test void testRunRedoDeregisterInstanceWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); @@ -122,7 +122,7 @@ void testRunRedoDeregisterInstanceWithClientDisabled() throws NacosException { redoTask.run(); verify(clientProxy, never()).doRegisterService(SERVICE, GROUP, INSTANCE); } - + @Test void testRunRedoRegisterInstanceWithNacosException() throws NacosException { Set mockData = generateMockInstanceData(false, false, true); @@ -131,7 +131,7 @@ void testRunRedoRegisterInstanceWithNacosException() throws NacosException { redoTask.run(); // Not any exception thrown } - + @Test void testRunRedoRegisterInstanceWithOtherException() throws NacosException { Set mockData = generateMockInstanceData(false, false, true); @@ -151,7 +151,7 @@ private Set generateMockInstanceData(boolean registered, boole result.add(redoData); return result; } - + @Test void testRunRedoRegisterSubscriber() throws NacosException { Set mockData = generateMockSubscriberData(false, false, true); @@ -159,7 +159,7 @@ void testRunRedoRegisterSubscriber() throws NacosException { redoTask.run(); verify(clientProxy).doSubscribe(SERVICE, GROUP, CLUSTER); } - + @Test void testRunRedoDeregisterSubscriber() throws NacosException { Set mockData = generateMockSubscriberData(true, true, false); @@ -167,7 +167,7 @@ void testRunRedoDeregisterSubscriber() throws NacosException { redoTask.run(); verify(clientProxy).doUnsubscribe(SERVICE, GROUP, CLUSTER); } - + @Test void testRunRedoRemoveSubscriberRedoData() throws NacosException { Set mockData = generateMockSubscriberData(false, true, false); @@ -175,7 +175,7 @@ void testRunRedoRemoveSubscriberRedoData() throws NacosException { redoTask.run(); verify(redoService).removeSubscriberForRedo(SERVICE, GROUP, CLUSTER); } - + @Test void testRunRedoRegisterSubscriberWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); @@ -184,7 +184,7 @@ void testRunRedoRegisterSubscriberWithClientDisabled() throws NacosException { redoTask.run(); verify(clientProxy, never()).doSubscribe(SERVICE, GROUP, CLUSTER); } - + @Test void testRunRedoDeRegisterSubscriberWithClientDisabled() throws NacosException { when(clientProxy.isEnable()).thenReturn(false); @@ -193,7 +193,7 @@ void testRunRedoDeRegisterSubscriberWithClientDisabled() throws NacosException { redoTask.run(); verify(clientProxy, never()).doUnsubscribe(SERVICE, GROUP, CLUSTER); } - + @Test void testRunRedoRegisterSubscriberWithNacosException() throws NacosException { Set mockData = generateMockSubscriberData(false, false, true); @@ -213,7 +213,7 @@ private Set generateMockSubscriberData(boolean registered, b result.add(redoData); return result; } - + @Test void testRunRedoWithDisconnection() { when(redoService.isConnected()).thenReturn(false); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java index fbe1801624c..2dee36e902a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/BatchInstanceRedoDataTest.java @@ -25,7 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; class BatchInstanceRedoDataTest { - + @Test @SuppressWarnings("all") void testEquals() { @@ -42,7 +42,7 @@ void testEquals() { BatchInstanceRedoData redoData3 = new BatchInstanceRedoData("c", "b"); assertNotEquals(redoData1, redoData3); } - + @Test void testHashCode() { BatchInstanceRedoData redoData1 = new BatchInstanceRedoData("a", "b"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java index f3ee6fee6bc..46b2d070218 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoDataTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; class InstanceRedoDataTest { - + @Test void testEquals() { InstanceRedoData redoData1 = new InstanceRedoData("a", "b"); @@ -34,7 +34,7 @@ void testEquals() { InstanceRedoData redoData3 = new InstanceRedoData("a", "b"); assertEquals(redoData1, redoData3); } - + @Test void testHashCode() { InstanceRedoData redoData1 = new InstanceRedoData("a", "b"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java index 1cf4e60e373..5b4a44bdc2c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientManagerTest.java @@ -38,22 +38,22 @@ import static org.mockito.Mockito.verify; class NamingHttpClientManagerTest { - + @Test void testGetInstance() { assertNotNull(NamingHttpClientManager.getInstance()); } - + @Test void testGetPrefix() { assertEquals(HTTP_PREFIX, NamingHttpClientManager.getInstance().getPrefix()); } - + @Test void testGetNacosRestTemplate() { assertNotNull(NamingHttpClientManager.getInstance().getNacosRestTemplate()); } - + @Test void testShutdown() throws NoSuchFieldException, IllegalAccessException, NacosException, IOException { //given @@ -68,7 +68,7 @@ void testShutdown() throws NoSuchFieldException, IllegalAccessException, NacosEx // then verify(mockHttpClientRequest, times(1)).close(); } - + @Test void testShutdownWithException() throws Exception { String key = "com.alibaba.nacos.client.naming.remote.http.NamingHttpClientManager$NamingHttpClientFactory"; diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java index 3e8ae64cece..28e09582226 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxyTest.java @@ -79,7 +79,7 @@ class NamingHttpClientProxyTest { private Properties props; private NamingHttpClientProxy clientProxy; - + @BeforeEach void setUp() { when(mgr.getServerList()).thenReturn(Arrays.asList("localhost")); @@ -87,24 +87,24 @@ void setUp() { final NacosClientProperties nacosClientProperties = NacosClientProperties.PROTOTYPE.derive(props); clientProxy = new NamingHttpClientProxy("namespaceId", proxy, mgr, nacosClientProperties); } - + @AfterEach void tearDown() throws NacosException { clientProxy.shutdown(); System.clearProperty(SystemPropertyKeyConst.NAMING_SERVER_PORT); } - + @Test void testOnEvent() { clientProxy.onEvent(new ServerListChangedEvent()); // Do nothing } - + @Test void testSubscribeType() { assertEquals(ServerListChangedEvent.class, clientProxy.subscribeType()); } - + @Test void testRegisterService() throws Exception { //given @@ -127,7 +127,7 @@ void testRegisterService() throws Exception { //then verify(nacosRestTemplate, times(1)).exchangeForm(any(), any(), any(), any(), any(), any()); } - + @Test void testRegisterEphemeralInstance() throws NacosException { assertThrows(UnsupportedOperationException.class, () -> { @@ -135,16 +135,16 @@ void testRegisterEphemeralInstance() throws NacosException { clientProxy.registerService("a", "b", instance); }); } - + @Test void testRegisterServiceThrowsNacosException() throws Exception { Throwable exception = assertThrows(NacosException.class, () -> { - + NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); a.setCode(503); when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(a); - + final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); nacosRestTemplateField.setAccessible(true); nacosRestTemplateField.set(clientProxy, nacosRestTemplate); @@ -157,23 +157,23 @@ void testRegisterServiceThrowsNacosException() throws Exception { } catch (NacosException ex) { // verify the `NacosException` is directly thrown assertNull(ex.getCause()); - + throw ex; } }); assertTrue(exception.getMessage().contains("failed to req API")); } - + @Test void testRegisterServiceThrowsException() throws Exception { assertThrows(NacosException.class, () -> { - + NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); HttpRestResult a = new HttpRestResult(); a.setCode(503); // makes exchangeForm failed with a NullPointerException when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenReturn(null); - + final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); nacosRestTemplateField.setAccessible(true); nacosRestTemplateField.set(clientProxy, nacosRestTemplate); @@ -181,33 +181,33 @@ void testRegisterServiceThrowsException() throws Exception { String groupName = "group1"; Instance instance = new Instance(); instance.setEphemeral(false); - + try { clientProxy.registerService(serviceName, groupName, instance); } catch (NacosException ex) { // verify the `NacosException` is directly thrown assertTrue(ex.getErrMsg().contains("java.lang.NullPointerException")); assertEquals(NacosException.SERVER_ERROR, ex.getErrCode()); - + throw ex; } }); } - + @Test void testBatchRegisterService() { assertThrows(UnsupportedOperationException.class, () -> { clientProxy.batchRegisterService("a", "b", null); }); } - + @Test void testBatchDeregisterService() { assertThrows(UnsupportedOperationException.class, () -> { clientProxy.batchDeregisterService("a", "b", null); }); } - + @Test void testDeregisterService() throws Exception { //given @@ -230,7 +230,7 @@ void testDeregisterService() throws Exception { //then verify(nacosRestTemplate, times(1)).exchangeForm(any(), any(), any(), any(), eq(HttpMethod.DELETE), any()); } - + @Test void testDeregisterServiceForEphemeral() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); @@ -242,7 +242,7 @@ void testDeregisterServiceForEphemeral() throws Exception { verify(nacosRestTemplate, never()).exchangeForm(any(), any(), any(), any(), eq(HttpMethod.DELETE), any()); } - + @Test void testUpdateInstance() throws Exception { //given @@ -264,7 +264,7 @@ void testUpdateInstance() throws Exception { //then verify(nacosRestTemplate, times(1)).exchangeForm(any(), any(), any(), any(), eq(HttpMethod.PUT), any()); } - + @Test void testQueryInstancesOfServiceThrowsException() { //assert exception @@ -274,7 +274,7 @@ void testQueryInstancesOfServiceThrowsException() { assertThrows(UnsupportedOperationException.class, () -> clientProxy.queryInstancesOfService(serviceName, groupName, clusters, false)); } - + @Test void testQueryService() throws Exception { //given @@ -294,12 +294,12 @@ void testQueryService() throws Exception { //when Service service = clientProxy.queryService(serviceName, groupName); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.GET), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), + eq(HttpMethod.GET), any()); assertEquals(serviceName, service.getName()); assertEquals(groupName, service.getGroupName()); } - + @Test void testCreateService() throws Exception { //given @@ -316,10 +316,10 @@ void testCreateService() throws Exception { //when clientProxy.createService(new Service(), new NoneSelector()); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.POST), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), + eq(HttpMethod.POST), any()); } - + @Test void testDeleteService() throws Exception { //given @@ -338,10 +338,10 @@ void testDeleteService() throws Exception { //when clientProxy.deleteService(serviceName, groupName); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.DELETE), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), + eq(HttpMethod.DELETE), any()); } - + @Test void testUpdateService() throws Exception { //given @@ -360,11 +360,11 @@ void testUpdateService() throws Exception { //when clientProxy.updateService(new Service(), new NoneSelector()); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), eq(HttpMethod.PUT), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith(UtilAndComs.nacosUrlService), any(), any(), any(), + eq(HttpMethod.PUT), any()); } - + @Test void testServerHealthy() throws Exception { //given @@ -381,22 +381,22 @@ void testServerHealthy() throws Exception { //when boolean serverHealthy = clientProxy.serverHealthy(); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith("/operator/metrics"), any(), any(), any(), eq(HttpMethod.GET), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/operator/metrics"), any(), any(), any(), + eq(HttpMethod.GET), any()); assertTrue(serverHealthy); } - + @Test void testServerHealthyForException() throws Exception { NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); - when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())) - .thenThrow(new RuntimeException("test")); + when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenThrow( + new RuntimeException("test")); final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); nacosRestTemplateField.setAccessible(true); nacosRestTemplateField.set(clientProxy, nacosRestTemplate); assertFalse(clientProxy.serverHealthy()); } - + @Test void testGetServiceList() throws Exception { //given @@ -414,13 +414,13 @@ void testGetServiceList() throws Exception { //when ListView serviceList = clientProxy.getServiceList(1, 10, groupName, new NoneSelector()); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith("/service/list"), any(), any(), any(), eq(HttpMethod.GET), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/service/list"), any(), any(), any(), + eq(HttpMethod.GET), any()); assertEquals(2, serviceList.getCount()); assertEquals("aaa", serviceList.getData().get(0)); assertEquals("bbb", serviceList.getData().get(1)); } - + @Test void testGetServiceListWithLabelSelector() throws Exception { //given @@ -438,25 +438,25 @@ void testGetServiceListWithLabelSelector() throws Exception { //when ListView serviceList = clientProxy.getServiceList(1, 10, groupName, new ExpressionSelector()); //then - verify(nacosRestTemplate, times(1)) - .exchangeForm(endsWith("/service/list"), any(), any(), any(), eq(HttpMethod.GET), any()); + verify(nacosRestTemplate, times(1)).exchangeForm(endsWith("/service/list"), any(), any(), any(), + eq(HttpMethod.GET), any()); assertEquals(2, serviceList.getCount()); assertEquals("aaa", serviceList.getData().get(0)); assertEquals("bbb", serviceList.getData().get(1)); } - + @Test void testSubscribe() throws Exception { assertThrows(UnsupportedOperationException.class, () -> { String groupName = "group1"; String serviceName = "serviceName"; String clusters = "clusters"; - + //when clientProxy.subscribe(serviceName, groupName, clusters); }); } - + @Test void testUnsubscribe() throws Exception { String groupName = "group1"; @@ -467,12 +467,12 @@ void testUnsubscribe() throws Exception { clientProxy.unsubscribe(serviceName, groupName, clusters); // do nothing } - + @Test void testIsSubscribed() throws NacosException { assertTrue(clientProxy.isSubscribed("serviceName", "group1", "clusters")); } - + @Test void testReqApi() throws Exception { //given @@ -498,7 +498,7 @@ void testReqApi() throws Exception { assertEquals("http://localhost:8848/api", res); } - + @Test void testReqApi2() throws Exception { //given @@ -524,7 +524,7 @@ void testReqApi2() throws Exception { //then assertEquals("http://localhost:8848/api", res); } - + @Test void testReqApi3() throws Exception { //given @@ -551,22 +551,23 @@ void testReqApi3() throws Exception { //then assertEquals("http://127.0.0.1:8848/api", res); } - + @Test void testCallServerFail() throws Exception { assertThrows(NacosException.class, () -> { - + //given NacosRestTemplate nacosRestTemplate = mock(NacosRestTemplate.class); - - when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenAnswer(invocationOnMock -> { - //return url - HttpRestResult res = new HttpRestResult(); - res.setMessage("fail"); - res.setCode(400); - return res; - }); - + + when(nacosRestTemplate.exchangeForm(any(), any(), any(), any(), any(), any())).thenAnswer( + invocationOnMock -> { + //return url + HttpRestResult res = new HttpRestResult(); + res.setMessage("fail"); + res.setCode(400); + return res; + }); + final Field nacosRestTemplateField = NamingHttpClientProxy.class.getDeclaredField("nacosRestTemplate"); nacosRestTemplateField.setAccessible(true); nacosRestTemplateField.set(clientProxy, nacosRestTemplate); @@ -577,11 +578,11 @@ void testCallServerFail() throws Exception { String curServer = "127.0.0.1"; //when clientProxy.callServer(api, params, body, curServer, method); - + }); - + } - + @Test void testCallServerFail304() throws Exception { //given @@ -608,7 +609,7 @@ void testCallServerFail304() throws Exception { //then assertEquals("", s); } - + @Test void testGetNamespaceId() { String namespaceId = "aaa"; @@ -617,7 +618,7 @@ void testGetNamespaceId() { String actualNamespaceId = clientProxy.getNamespaceId(); assertEquals(namespaceId, actualNamespaceId); } - + @Test void testSetServerPort() { clientProxy.setServerPort(1234); @@ -626,26 +627,24 @@ void testSetServerPort() { clientProxy.setServerPort(1234); assertEquals(1111, ReflectUtils.getFieldValue(clientProxy, "serverPort")); } - + @Test void testReqApiForEmptyServer() throws NacosException { assertThrows(NacosException.class, () -> { Map params = new HashMap<>(); - clientProxy - .reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); + clientProxy.reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); }); } - + @Test void testRegApiForDomain() throws NacosException { assertThrows(NacosException.class, () -> { Map params = new HashMap<>(); when(mgr.isDomain()).thenReturn(true); when(mgr.getNacosDomain()).thenReturn("http://test.nacos.domain"); - clientProxy - .reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); - + clientProxy.reqApi("api", params, Collections.emptyMap(), Collections.emptyList(), HttpMethod.GET); + }); - + } } diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java index 6e591957f9a..5abbc54a57c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CacheDirUtilTest.java @@ -24,20 +24,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class CacheDirUtilTest { - + @AfterEach void tearDown() throws Exception { System.clearProperty("user.home"); System.clearProperty("JM.SNAPSHOT.PATH"); } - + @Test void testInitCacheDirWithDefaultRootAndWithoutCache() { System.setProperty("user.home", "/home/admin"); String actual = CacheDirUtil.initCacheDir("test", NacosClientProperties.PROTOTYPE.derive()); assertEquals("/home/admin/nacos/naming/test", actual); } - + @Test void testInitCacheDirWithDefaultRootAndWithCache() { System.setProperty("user.home", "/home/admin"); @@ -46,14 +46,14 @@ void testInitCacheDirWithDefaultRootAndWithCache() { String actual = CacheDirUtil.initCacheDir("test", properties); assertEquals("/home/admin/nacos/custom/naming/test", actual); } - + @Test void testInitCacheDirWithJmSnapshotPathRootAndWithoutCache() { System.setProperty("JM.SNAPSHOT.PATH", "/home/snapshot"); String actual = CacheDirUtil.initCacheDir("test", NacosClientProperties.PROTOTYPE.derive()); assertEquals("/home/snapshot/nacos/naming/test", actual); } - + @Test void testInitCacheDirWithJmSnapshotPathRootAndWithCache() { System.setProperty("user.home", "/home/snapshot"); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java index 9e0e3580ff1..30b4e24a952 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ChooserTest.java @@ -33,7 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class ChooserTest { - + @Test void testChooser() { //Test the correctness of Chooser, the weight of the final selected instance must be greater than 0 @@ -41,14 +41,14 @@ void testChooser() { Instance target = getRandomInstance(hosts); assertTrue(hosts.contains(target) && target.getWeight() > 0); } - + @Test void testChooserRandomForEmptyList() { Chooser chooser = new Chooser<>("test"); assertEquals("test", chooser.getUniqueKey()); assertNull(chooser.random()); } - + @Test void testChooserRandomForOneSizeList() { List> list = new LinkedList<>(); @@ -58,7 +58,7 @@ void testChooserRandomForOneSizeList() { assertNotNull(actual); assertEquals("test", actual); } - + @Test void testChooserRandom() { List> list = new LinkedList<>(); @@ -69,7 +69,7 @@ void testChooserRandom() { assertNotNull(actual); assertTrue(actual.equals("test") || actual.equals("test2")); } - + @Test void testOnlyOneInstanceWeightIsNotZero() { // If there is only one instance whose weight is not zero, it will be selected @@ -78,7 +78,7 @@ void testOnlyOneInstanceWeightIsNotZero() { Instance target = getRandomInstance(hosts); assertTrue(target.getWeight() > 0); } - + @Test void testInstanceWeightAllZero() { // Throw an IllegalStateException when all instances have a weight of zero. @@ -90,7 +90,7 @@ void testInstanceWeightAllZero() { assertTrue(e instanceof IllegalStateException); } } - + @Test void testRandomWithWeightForNaNAndInfinity() { assertThrows(IllegalStateException.class, () -> { @@ -100,7 +100,7 @@ void testRandomWithWeightForNaNAndInfinity() { new Chooser<>("test", list); }); } - + @Test void testRefresh() { Chooser chooser = new Chooser<>("test"); @@ -113,7 +113,7 @@ void testRefresh() { assertNotNull(actual); assertEquals("test", actual); } - + @Test void testEqualsHashCode() { List> list = new LinkedList<>(); @@ -135,7 +135,7 @@ void testEqualsHashCode() { Chooser chooser4 = new Chooser<>("test", list); assertEquals(chooser, chooser4); } - + @Test void testRefEqualsHashCode() { List> list = new LinkedList<>(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java index 2bae52a81bc..433c4cb5d8a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/CollectionUtilsTest.java @@ -28,15 +28,15 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class CollectionUtilsTest { - + @Test void testSubtract() { - List subtract = (List) CollectionUtils - .subtract(Arrays.asList("a", "b"), Arrays.asList("b", "c")); + List subtract = (List) CollectionUtils.subtract(Arrays.asList("a", "b"), + Arrays.asList("b", "c")); assertEquals(1, subtract.size()); assertEquals("a", subtract.get(0)); } - + @Test void testGetCardinalityMap() { List list1 = Arrays.asList("2", "2", "3"); @@ -46,7 +46,7 @@ void testGetCardinalityMap() { assertEquals(1, map1.get("3").intValue()); } - + @Test void testIsEqualCollection() { List list1 = Arrays.asList("2", "2", "3"); @@ -61,7 +61,7 @@ void testIsEqualCollection() { List list6 = Arrays.asList("2", "2", "1"); assertFalse(CollectionUtils.isEqualCollection(list1, list6)); } - + @Test void testIsEmpty() { assertTrue(CollectionUtils.isEmpty(null)); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java index 5d58c861e66..467f3146687 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/ConcurrentDiskUtilTest.java @@ -36,7 +36,7 @@ import static org.mockito.Mockito.when; class ConcurrentDiskUtilTest { - + @Test void testReadAndWrite() throws IOException { File tempFile = File.createTempFile("aaa", "bbb"); @@ -47,7 +47,7 @@ void testReadAndWrite() throws IOException { String actualContent = ConcurrentDiskUtil.getFileContent(fileName, charset); assertEquals(content, actualContent); } - + @Test void testReadAndWrite2() throws IOException { File tempFile = File.createTempFile("aaa", "bbb"); @@ -57,7 +57,7 @@ void testReadAndWrite2() throws IOException { String actualContent = ConcurrentDiskUtil.getFileContent(tempFile, charset); assertEquals(content, actualContent); } - + @Test void testByteBufferToString() throws IOException { String msg = "test buff to string"; @@ -65,18 +65,18 @@ void testByteBufferToString() throws IOException { String actual = ConcurrentDiskUtil.byteBufferToString(buff, "UTF-8"); assertEquals(msg, actual); } - + @Test void testWriteFileContent() throws IOException { File file = mock(File.class); assertFalse(ConcurrentDiskUtil.writeFileContent(file, "hello", "UTF-8")); } - + @Test void testTryLockFailure() throws Throwable { assertThrows(IOException.class, () -> { - Method method = ConcurrentDiskUtil.class - .getDeclaredMethod("tryLock", File.class, FileChannel.class, boolean.class); + Method method = ConcurrentDiskUtil.class.getDeclaredMethod("tryLock", File.class, FileChannel.class, + boolean.class); method.setAccessible(true); File file = new File("non-exist"); FileChannel channel = mock(FileChannel.class); @@ -88,12 +88,12 @@ void testTryLockFailure() throws Throwable { } }); } - + @Test void testTryLockFailureForIntercept() throws Throwable { assertThrows(IOException.class, () -> { - Method method = ConcurrentDiskUtil.class - .getDeclaredMethod("tryLock", File.class, FileChannel.class, boolean.class); + Method method = ConcurrentDiskUtil.class.getDeclaredMethod("tryLock", File.class, FileChannel.class, + boolean.class); method.setAccessible(true); File file = new File("non-exist"); FileChannel channel = mock(FileChannel.class); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java index 8a1feafca30..6a4d02ab9bf 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/GenericPollerTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class GenericPollerTest { - + @Test void testNext() { String item1 = "item1"; @@ -33,7 +33,7 @@ void testNext() { assertEquals(item2, poller.next()); assertEquals(item1, poller.next()); } - + @Test void testRefresh() { String item1 = "item1"; diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java index d8e441baf9b..e69d56df043 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/InitUtilsTest.java @@ -25,7 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class InitUtilsTest { - + @AfterEach void tearDown() { System.clearProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING); @@ -38,7 +38,7 @@ void tearDown() { UtilAndComs.nacosUrlBase = "/nacos/v1/ns"; UtilAndComs.nacosUrlInstance = "/nacos/v1/ns/instance"; } - + /** * current namespace priority 1. system.Properties 2. user.Properties 3. default value */ @@ -49,7 +49,7 @@ void testInitNamespaceForDefault() { String actual = InitUtils.initNamespaceForNaming(properties); assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); } - + @Test void testInitNamespaceFromAnsWithCloudParsing() { String expect = "ans"; @@ -59,7 +59,7 @@ void testInitNamespaceFromAnsWithCloudParsing() { String actual = InitUtils.initNamespaceForNaming(properties); assertEquals(expect, actual); } - + @Test void testInitNamespaceFromAliwareWithCloudParsing() { String expect = "aliware"; @@ -69,7 +69,7 @@ void testInitNamespaceFromAliwareWithCloudParsing() { String actual = InitUtils.initNamespaceForNaming(properties); assertEquals(expect, actual); } - + @Test void testInitNamespaceFromJvmNamespaceWithCloudParsing() { String expect = "jvm_namespace"; @@ -78,7 +78,7 @@ void testInitNamespaceFromJvmNamespaceWithCloudParsing() { String ns = InitUtils.initNamespaceForNaming(properties); assertEquals(expect, ns); } - + @Test void testInitNamespaceFromPropNamespaceWithCloudParsing() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); @@ -87,7 +87,7 @@ void testInitNamespaceFromPropNamespaceWithCloudParsing() { String ns = InitUtils.initNamespaceForNaming(properties); assertEquals(expect, ns); } - + @Test void testInitNamespaceFromDefaultNamespaceWithCloudParsing() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); @@ -95,7 +95,7 @@ void testInitNamespaceFromDefaultNamespaceWithCloudParsing() { String actual = InitUtils.initNamespaceForNaming(properties); assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); } - + @Test void testInitNamespaceFromJvmNamespaceWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, "ans"); @@ -106,7 +106,7 @@ void testInitNamespaceFromJvmNamespaceWithoutCloudParsing() { String ns = InitUtils.initNamespaceForNaming(properties); assertEquals(expect, ns); } - + @Test void testInitNamespaceFromPropNamespaceWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, "ans"); @@ -117,7 +117,7 @@ void testInitNamespaceFromPropNamespaceWithoutCloudParsing() { String ns = InitUtils.initNamespaceForNaming(properties); assertEquals(expect, ns); } - + @Test void testInitNamespaceFromDefaultNamespaceWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.ANS_NAMESPACE, "ans"); @@ -126,7 +126,7 @@ void testInitNamespaceFromDefaultNamespaceWithoutCloudParsing() { String actual = InitUtils.initNamespaceForNaming(properties); assertEquals(UtilAndComs.DEFAULT_NAMESPACE_ID, actual); } - + @Test void testInitWebRootContext() { String ctx = "/aaa"; @@ -137,7 +137,7 @@ void testInitWebRootContext() { assertEquals(ctx + "/v1/ns", UtilAndComs.nacosUrlBase); assertEquals(ctx + "/v1/ns/instance", UtilAndComs.nacosUrlInstance); } - + @Test void testInitWebRootContextWithoutValue() { final NacosClientProperties properties = NacosClientProperties.PROTOTYPE.derive(); @@ -146,12 +146,12 @@ void testInitWebRootContextWithoutValue() { assertEquals("/nacos/v1/ns", UtilAndComs.nacosUrlBase); assertEquals("/nacos/v1/ns/instance", UtilAndComs.nacosUrlInstance); } - + @Test void testInitEndpointForNullProperties() { assertEquals("", InitUtils.initEndpoint(null)); } - + @Test void testInitEndpointFromDefaultWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "false"); @@ -159,7 +159,7 @@ void testInitEndpointFromDefaultWithoutCloudParsing() { String actual = InitUtils.initEndpoint(properties); assertEquals("", actual); } - + @Test void testInitEndpointFromPropertiesWithoutCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "false"); @@ -171,7 +171,7 @@ void testInitEndpointFromPropertiesWithoutCloudParsing() { String actual = InitUtils.initEndpoint(properties); assertEquals(endpoint + ":" + endpointPort, actual); } - + @Test void testInitEndpointFromAliwareWithoutCloudParsing() { String endpoint = "aliware_endpoint"; @@ -184,7 +184,7 @@ void testInitEndpointFromAliwareWithoutCloudParsing() { String actual = InitUtils.initEndpoint(properties); assertEquals("", actual); } - + @Test void testInitEndpointFromDefaultWithCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); @@ -192,7 +192,7 @@ void testInitEndpointFromDefaultWithCloudParsing() { String actual = InitUtils.initEndpoint(properties); assertEquals("", actual); } - + @Test void testInitEndpointFromPropertiesWithCloudParsing() { System.setProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE, "true"); @@ -204,7 +204,7 @@ void testInitEndpointFromPropertiesWithCloudParsing() { String actual = InitUtils.initEndpoint(properties); assertEquals(endpoint + ":" + endpointPort, actual); } - + @Test void testInitEndpointFromAliwareWithCloudParsing() { String endpoint = "aliware_endpoint"; @@ -217,7 +217,7 @@ void testInitEndpointFromAliwareWithCloudParsing() { String actual = InitUtils.initEndpoint(properties); assertEquals(endpoint + ":" + endpointPort, actual); } - + @Test void testInitEndpointAns() { try { diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java index 1ad588ae07e..c28d634a04f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/NamingHttpUtilTest.java @@ -25,7 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; class NamingHttpUtilTest { - + @Test void testBuilderHeader() { Header header = NamingHttpUtil.builderHeader(); diff --git a/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java b/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java index f4ceaa64cf6..069f27a91d1 100644 --- a/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/naming/utils/PairTest.java @@ -21,7 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class PairTest { - + @Test void testItem() { String item = "aa"; diff --git a/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java b/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java index efe413f06c5..24288008357 100644 --- a/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/security/SecurityProxyTest.java @@ -54,7 +54,7 @@ class SecurityProxyTest { @Mock private NacosRestTemplate nacosRestTemplate; - + @BeforeEach void setUp() throws Exception { //given @@ -67,7 +67,7 @@ void setUp() throws Exception { serverList.add("localhost"); securityProxy = new SecurityProxy(serverList, nacosRestTemplate); } - + @Test void testLoginClientAuthService() throws Exception { Properties properties = new Properties(); @@ -76,7 +76,7 @@ void testLoginClientAuthService() throws Exception { securityProxy.login(properties); verify(nacosRestTemplate).postForm(any(), (Header) any(), any(), any(), any()); } - + @Test void testGetIdentityContext() { Properties properties = new Properties(); @@ -88,7 +88,7 @@ void testGetIdentityContext() { //then assertEquals("ttttttttttttttttt", keyMap.get(NacosAuthLoginConstant.ACCESSTOKEN)); } - + @Test void testLoginWithoutAnyPlugin() throws NoSuchFieldException, IllegalAccessException { Field clientAuthPluginManagerField = SecurityProxy.class.getDeclaredField("clientAuthPluginManager"); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java index bd96dc68deb..1d41c1ee44f 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/AppNameUtilsTest.java @@ -26,11 +26,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class AppNameUtilsTest { - + @BeforeEach void setUp() throws Exception { } - + @AfterEach void tearDown() throws Exception { System.clearProperty(Constants.SysEnv.PROJECT_NAME); @@ -38,34 +38,34 @@ void tearDown() throws Exception { System.clearProperty("jetty.home"); System.clearProperty("catalina.base"); } - + @Test void testGetAppNameByDefault() { String appName = AppNameUtils.getAppName(); assertEquals("unknown", appName); } - + @Test void testGetAppNameByProjectName() { System.setProperty(Constants.SysEnv.PROJECT_NAME, "testAppName"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); } - + @Test void testGetAppNameByServerTypeForJboss() { System.setProperty("jboss.server.home.dir", "/home/admin/testAppName/"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); } - + @Test void testGetAppNameByServerTypeForJetty() { System.setProperty("jetty.home", "/home/admin/testAppName/"); String appName = AppNameUtils.getAppName(); assertEquals("testAppName", appName); } - + @Test void testGetAppNameByServerTypeForTomcat() { System.setProperty("catalina.base", "/home/admin/testAppName/"); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java index 5afdc1c3caa..3692872939e 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/ContextPathUtilTest.java @@ -27,7 +27,7 @@ * @date 2020/11/26 3:13 PM */ class ContextPathUtilTest { - + @Test void testNormalizeContextPath() { assertEquals("/nacos", ContextPathUtil.normalizeContextPath("/nacos")); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java index 07214276f70..8a8185ed9fc 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/EnvUtilTest.java @@ -31,7 +31,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; class EnvUtilTest { - + @Test void testSetSelfEnv() { Map> headers = new HashMap<>(); @@ -51,7 +51,7 @@ void testSetSelfEnv() { assertNull(EnvUtil.getSelfVipserverTag()); assertNull(EnvUtil.getSelfLocationTag()); } - + @Test void testSetSelfEnv2() { Map> headers = new HashMap<>(); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java index 5120ee88ec7..d158de997fa 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/LogUtilsTest.java @@ -22,7 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; class LogUtilsTest { - + @Test void testLogger() { Logger logger = LogUtils.logger(LogUtilsTest.class); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java index 129f3722bb7..5fa229bf58c 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/ParamUtilTest.java @@ -48,7 +48,7 @@ class ParamUtilTest { private double defaultPerTaskConfigSize; private String defaultNodesPath; - + @BeforeEach void before() { defaultAppKey = ""; @@ -59,7 +59,7 @@ void before() { defaultPerTaskConfigSize = 3000.0; defaultNodesPath = "serverlist"; } - + @AfterEach void after() { ParamUtil.setAppKey(defaultAppKey); @@ -73,7 +73,7 @@ void after() { System.clearProperty("PER_TASK_CONFIG_SIZE"); System.clearProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL); } - + @Test void testGetAppKey() { String defaultVal = ParamUtil.getAppKey(); @@ -83,7 +83,7 @@ void testGetAppKey() { ParamUtil.setAppKey(expect); assertEquals(expect, ParamUtil.getAppKey()); } - + @Test void testGetAppName() { String defaultVal = ParamUtil.getAppName(); @@ -93,7 +93,7 @@ void testGetAppName() { ParamUtil.setAppName(expect); assertEquals(expect, ParamUtil.getAppName()); } - + @Test void testGetDefaultContextPath() { String defaultVal = ParamUtil.getDefaultContextPath(); @@ -103,7 +103,7 @@ void testGetDefaultContextPath() { ParamUtil.setDefaultContextPath(expect); assertEquals(expect, ParamUtil.getDefaultContextPath()); } - + @Test void testGetClientVersion() { String defaultVal = ParamUtil.getClientVersion(); @@ -113,7 +113,7 @@ void testGetClientVersion() { ParamUtil.setClientVersion(expect); assertEquals(expect, ParamUtil.getClientVersion()); } - + @Test void testSetConnectTimeout() { int defaultVal = ParamUtil.getConnectTimeout(); @@ -123,7 +123,7 @@ void testSetConnectTimeout() { ParamUtil.setConnectTimeout(expect); assertEquals(expect, ParamUtil.getConnectTimeout()); } - + @Test void testGetPerTaskConfigSize() { double defaultVal = ParamUtil.getPerTaskConfigSize(); @@ -133,13 +133,13 @@ void testGetPerTaskConfigSize() { ParamUtil.setPerTaskConfigSize(expect); assertEquals(expect, ParamUtil.getPerTaskConfigSize(), 0.01); } - + @Test void testGetDefaultServerPort() { String actual = ParamUtil.getDefaultServerPort(); assertEquals("8848", actual); } - + @Test void testGetDefaultNodesPath() { String defaultVal = ParamUtil.getDefaultNodesPath(); @@ -149,7 +149,7 @@ void testGetDefaultNodesPath() { ParamUtil.setDefaultNodesPath(expect); assertEquals(expect, ParamUtil.getDefaultNodesPath()); } - + @Test void testParseNamespace() { String expect = "test"; @@ -160,14 +160,14 @@ void testParseNamespace() { String actual = ParamUtil.parseNamespace(nacosClientProperties); assertEquals(expect, actual); } - + @Test void testParsingEndpointRule() { String url = "${test:www.example.com}"; String actual = ParamUtil.parsingEndpointRule(url); assertEquals("www.example.com", actual); } - + @Test void testInitConnectionTimeoutWithException() throws Throwable { assertThrows(IllegalArgumentException.class, () -> { @@ -181,7 +181,7 @@ void testInitConnectionTimeoutWithException() throws Throwable { } }); } - + @Test void testInitPerTaskConfigSizeWithException() throws Throwable { assertThrows(IllegalArgumentException.class, () -> { @@ -195,19 +195,19 @@ void testInitPerTaskConfigSizeWithException() throws Throwable { } }); } - + @Test void testParsingEndpointRuleFromSystem() { System.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL, "alibaba_aliware_endpoint_url"); assertEquals("alibaba_aliware_endpoint_url", ParamUtil.parsingEndpointRule(null)); } - + @Test void testParsingEndpointRuleFromSystemWithParam() { System.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL, "alibaba_aliware_endpoint_url"); assertEquals("alibaba_aliware_endpoint_url", ParamUtil.parsingEndpointRule("${abc:xxx}")); } - + @Test void testSimplyEnvNameIfOverLimit() { StringBuilder envNameOverLimitBuilder = new StringBuilder("test"); @@ -219,7 +219,7 @@ void testSimplyEnvNameIfOverLimit() { String expect = envName.substring(0, 50) + MD5Utils.md5Hex(envName, "UTF-8"); assertEquals(expect, actual); } - + @Test void testSimplyEnvNameNotOverLimit() { String expect = "test"; diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java index 3ad06e11d1f..19b6c6f0b8e 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/PreInitUtilsTest.java @@ -21,7 +21,7 @@ import java.util.concurrent.TimeUnit; class PreInitUtilsTest { - + @Test void testAsyncPreLoadCostComponent() throws InterruptedException { // There is no things need to be assert. diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java index ecf5064b222..95d13c20c20 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/StringUtilsTest.java @@ -33,7 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; class StringUtilsTest { - + @Test void testisNotBlank() { assertTrue(isNotBlank("foo")); @@ -41,20 +41,20 @@ void testisNotBlank() { assertFalse(isNotBlank(" ")); assertFalse(isNotBlank(null)); } - + @Test void testIsNotEmpty() { assertFalse(isNotEmpty("")); assertTrue(isNotEmpty("foo")); } - + @Test void testDefaultIfEmpty() { assertEquals("foo", defaultIfEmpty("", "foo")); assertEquals("bar", defaultIfEmpty("bar", "foo")); } - + @Test void testEquals() { assertTrue(StringUtils.equals("foo", "foo")); @@ -63,7 +63,7 @@ void testEquals() { assertFalse(StringUtils.equals(" ", "foo")); assertFalse(StringUtils.equals("foo", null)); } - + @Test void testSubstringBetween() { assertNull(substringBetween(null, null, null)); @@ -72,7 +72,7 @@ void testSubstringBetween() { assertEquals("", substringBetween("foo", "foo", "")); } - + @Test void testJoin() { assertNull(join(null, "")); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java index 06db16289db..497a3cb2462 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/TemplateUtilsTest.java @@ -30,7 +30,7 @@ import static org.mockito.Mockito.when; class TemplateUtilsTest { - + @Test void testStringNotEmptyAndThenExecuteSuccess() { String word = "run"; @@ -38,7 +38,7 @@ void testStringNotEmptyAndThenExecuteSuccess() { TemplateUtils.stringNotEmptyAndThenExecute(word, task); Mockito.verify(task, Mockito.times(1)).run(); } - + @Test void testStringNotEmptyAndThenExecuteFail() { String word = ""; @@ -46,7 +46,7 @@ void testStringNotEmptyAndThenExecuteFail() { TemplateUtils.stringNotEmptyAndThenExecute(word, task); Mockito.verify(task, Mockito.times(0)).run(); } - + @Test void testStringNotEmptyAndThenExecuteException() { String word = "run"; @@ -56,14 +56,14 @@ void testStringNotEmptyAndThenExecuteException() { Mockito.verify(task, Mockito.times(1)).run(); // NO exception thrown } - + @Test void testStringEmptyAndThenExecuteSuccess() { String word = " "; String actual = TemplateUtils.stringEmptyAndThenExecute(word, () -> "call"); assertEquals("", actual); } - + @Test void testStringEmptyAndThenExecuteFail() { String word = ""; @@ -71,7 +71,7 @@ void testStringEmptyAndThenExecuteFail() { String actual = TemplateUtils.stringEmptyAndThenExecute(word, () -> expect); assertEquals(expect, actual); } - + @Test void testStringEmptyAndThenExecuteException() throws Exception { Callable callable = mock(Callable.class); @@ -79,14 +79,14 @@ void testStringEmptyAndThenExecuteException() throws Exception { String actual = TemplateUtils.stringEmptyAndThenExecute(null, callable); assertNull(actual); } - + @Test void testStringBlankAndThenExecuteSuccess() { String word = "success"; String actual = TemplateUtils.stringBlankAndThenExecute(word, () -> "call"); assertEquals(word, actual); } - + @Test void testStringBlankAndThenExecuteFail() { String word = " "; @@ -94,7 +94,7 @@ void testStringBlankAndThenExecuteFail() { String actual = TemplateUtils.stringBlankAndThenExecute(word, () -> expect); assertEquals(expect, actual); } - + @Test void testStringBlankAndThenExecuteException() throws Exception { Callable callable = mock(Callable.class); diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java index a5a7e1a817f..a64f3396fbc 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/TenantUtilTest.java @@ -24,13 +24,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class TenantUtilTest { - + @AfterEach void tearDown() { System.clearProperty("acm.namespace"); System.clearProperty("ans.namespace"); } - + @Test void testGetUserTenantForAcm() { String expect = "test"; @@ -38,7 +38,7 @@ void testGetUserTenantForAcm() { String actual = TenantUtil.getUserTenantForAcm(); assertEquals(expect, actual); } - + @Test void testGetUserTenantForAns() { String expect = "test"; diff --git a/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java b/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java index 280794d01a1..5cefb91b3cf 100644 --- a/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/utils/ValidatorUtilsTest.java @@ -26,7 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class ValidatorUtilsTest { - + @Test void testContextPathLegal() { String contextPath1 = "/nacos"; @@ -40,7 +40,7 @@ void testContextPathLegal() { // allow null ValidatorUtils.checkContextPath(null); } - + @Test void testContextPathIllegal1() { assertThrows(IllegalArgumentException.class, () -> { @@ -48,7 +48,7 @@ void testContextPathIllegal1() { ValidatorUtils.checkContextPath(contextPath1); }); } - + @Test void testContextPathIllegal2() { assertThrows(IllegalArgumentException.class, () -> { @@ -56,7 +56,7 @@ void testContextPathIllegal2() { ValidatorUtils.checkContextPath(contextPath2); }); } - + @Test void testContextPathIllegal3() { assertThrows(IllegalArgumentException.class, () -> { @@ -64,7 +64,7 @@ void testContextPathIllegal3() { ValidatorUtils.checkContextPath(contextPath3); }); } - + @Test void testContextPathIllegal4() { assertThrows(IllegalArgumentException.class, () -> { @@ -72,7 +72,7 @@ void testContextPathIllegal4() { ValidatorUtils.checkContextPath(contextPath4); }); } - + @Test void testCheckInitParam() { Assertions.assertDoesNotThrow(() -> { From cf6a011b48a8cf5b2a4f4772035d49132677688c Mon Sep 17 00:00:00 2001 From: "shalk(xiao kun)" Date: Thu, 16 May 2024 16:09:56 +0800 Subject: [PATCH 4/5] fix code style --- .../alibaba/nacos/client/config/impl/ClientWorkerTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java b/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java index eaaba3e6e5f..0b60d704224 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/impl/ClientWorkerTest.java @@ -151,7 +151,7 @@ void testAddListenerWithoutTenant() throws NacosException { public void receiveConfigInfo(String configInfo) { } }; - + clientWorker.addListeners(dataId, group, Collections.singletonList(listener)); List listeners = clientWorker.getCache(dataId, group).getListeners(); assertEquals(1, listeners.size()); @@ -182,7 +182,7 @@ public void receiveConfigInfo(String configInfo) { String dataId = "a"; String group = "b"; - + clientWorker.addTenantListeners(dataId, group, Collections.singletonList(listener)); List listeners = clientWorker.getCache(dataId, group).getListeners(); assertEquals(1, listeners.size()); From b49db59287fdf2cac94ea4fc0aba70dd30e04b87 Mon Sep 17 00:00:00 2001 From: "shalk(xiao kun)" Date: Mon, 20 May 2024 11:17:24 +0800 Subject: [PATCH 5/5] fix codestyle --- .../client/config/NacosConfigServiceTest.java | 57 +++++++------------ 1 file changed, 20 insertions(+), 37 deletions(-) diff --git a/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java b/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java index f56ef44877f..3cc54107c4a 100644 --- a/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java +++ b/client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java @@ -94,12 +94,10 @@ void testGetConfigFromFailOver() throws NacosException { final String group = "2"; final String tenant = ""; - MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic( - LocalConfigInfoProcessor.class); + MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic(LocalConfigInfoProcessor.class); try { String contentFailOver = "failOverContent" + System.currentTimeMillis(); - localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) + localConfigInfoProcessorMockedStatic.when(() -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(contentFailOver); final int timeout = 3000; @@ -116,17 +114,14 @@ void testGetConfigFromLocalCache() throws NacosException { final String group = "2"; final String tenant = ""; - MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic( - LocalConfigInfoProcessor.class); + MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic(LocalConfigInfoProcessor.class); try { String contentFailOver = "localCacheContent" + System.currentTimeMillis(); //fail over null - localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) + localConfigInfoProcessorMockedStatic.when(() -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(null); //snapshot content - localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getSnapshot(any(), eq(dataId), eq(group), eq(tenant))) + localConfigInfoProcessorMockedStatic.when(() -> LocalConfigInfoProcessor.getSnapshot(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(contentFailOver); //form server error. final int timeout = 3000; @@ -146,12 +141,10 @@ void testGetConfig403() throws NacosException { final String group = "2"; final String tenant = ""; - MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic( - LocalConfigInfoProcessor.class); + MockedStatic localConfigInfoProcessorMockedStatic = Mockito.mockStatic(LocalConfigInfoProcessor.class); try { //fail over null - localConfigInfoProcessorMockedStatic.when( - () -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) + localConfigInfoProcessorMockedStatic.when(() -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant))) .thenReturn(null); //form server error. @@ -216,8 +209,8 @@ public void removeCache(String dataId, String group) { } @Override - public ConfigResponse queryConfig(String dataId, String group, String tenant, long readTimeous, - boolean notify) throws NacosException { + public ConfigResponse queryConfig(String dataId, String group, String tenant, long readTimeous, boolean notify) + throws NacosException { ConfigResponse configResponse = new ConfigResponse(); configResponse.setContent(content); configResponse.setDataId(dataId); @@ -227,9 +220,8 @@ public ConfigResponse queryConfig(String dataId, String group, String tenant, lo } @Override - public boolean publishConfig(String dataId, String group, String tenant, String appName, String tag, - String betaIps, String content, String encryptedDataKey, String casMd5, String type) - throws NacosException { + public boolean publishConfig(String dataId, String group, String tenant, String appName, String tag, String betaIps, + String content, String encryptedDataKey, String casMd5, String type) throws NacosException { return false; } @@ -242,8 +234,7 @@ public boolean removeConfig(String dataId, String group, String tenant, String t final String config = nacosConfigService.getConfigAndSignListener(dataId, group, timeout, listener); assertEquals(content, config); - Mockito.verify(mockWoker, Mockito.times(1)) - .addTenantListenersWithContent(dataId, group, content, null, Arrays.asList(listener)); + Mockito.verify(mockWoker, Mockito.times(1)).addTenantListenersWithContent(dataId, group, content, null, Arrays.asList(listener)); } @Test @@ -273,14 +264,12 @@ void testPublishConfig() throws NacosException { String content = "123"; String namespace = ""; String type = ConfigType.getDefaultType().getType(); - Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type)) - .thenReturn(true); + Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type)).thenReturn(true); final boolean b = nacosConfigService.publishConfig(dataId, group, content); assertTrue(b); - Mockito.verify(mockWoker, Mockito.times(1)) - .publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); + Mockito.verify(mockWoker, Mockito.times(1)).publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); } @Test @@ -291,14 +280,12 @@ void testPublishConfig2() throws NacosException { String namespace = ""; String type = ConfigType.PROPERTIES.getType(); - Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type)) - .thenReturn(true); + Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type)).thenReturn(true); final boolean b = nacosConfigService.publishConfig(dataId, group, content, type); assertTrue(b); - Mockito.verify(mockWoker, Mockito.times(1)) - .publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); + Mockito.verify(mockWoker, Mockito.times(1)).publishConfig(dataId, group, namespace, null, null, null, content, "", null, type); } @Test @@ -310,14 +297,12 @@ void testPublishConfigCas() throws NacosException { String casMd5 = "96147704e3cb8be8597d55d75d244a02"; String type = ConfigType.getDefaultType().getType(); - Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type)) - .thenReturn(true); + Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type)).thenReturn(true); final boolean b = nacosConfigService.publishConfigCas(dataId, group, content, casMd5); assertTrue(b); - Mockito.verify(mockWoker, Mockito.times(1)) - .publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); + Mockito.verify(mockWoker, Mockito.times(1)).publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); } @Test @@ -329,14 +314,12 @@ void testPublishConfigCas2() throws NacosException { String casMd5 = "96147704e3cb8be8597d55d75d244a02"; String type = ConfigType.PROPERTIES.getType(); - Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type)) - .thenReturn(true); + Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type)).thenReturn(true); final boolean b = nacosConfigService.publishConfigCas(dataId, group, content, casMd5, type); assertTrue(b); - Mockito.verify(mockWoker, Mockito.times(1)) - .publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); + Mockito.verify(mockWoker, Mockito.times(1)).publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type); } @Test